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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/poplib.py | python | POP3.noop | (self) | return self._shortcmd('NOOP') | Does nothing.
One supposes the response indicates the server is alive. | Does nothing. | [
"Does",
"nothing",
"."
] | def noop(self):
"""Does nothing.
One supposes the response indicates the server is alive.
"""
return self._shortcmd('NOOP') | [
"def",
"noop",
"(",
"self",
")",
":",
"return",
"self",
".",
"_shortcmd",
"(",
"'NOOP'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/poplib.py#L264-L269 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/dist.py | python | check_requirements | (dist, attr, value) | Verify that install_requires is a valid requirements list | Verify that install_requires is a valid requirements list | [
"Verify",
"that",
"install_requires",
"is",
"a",
"valid",
"requirements",
"list"
] | def check_requirements(dist, attr, value):
"""Verify that install_requires is a valid requirements list"""
try:
list(pkg_resources.parse_requirements(value))
if isinstance(value, (dict, set)):
raise TypeError("Unordered types are not allowed")
except (TypeError, ValueError) as error:
tmpl = (
"{attr!r} must be a string or list of strings "
"containing valid project/version requirement specifiers; {error}"
)
raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) | [
"def",
"check_requirements",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"list",
"(",
"pkg_resources",
".",
"parse_requirements",
"(",
"value",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"(",
"dict",
",",
"set",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Unordered types are not allowed\"",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
"as",
"error",
":",
"tmpl",
"=",
"(",
"\"{attr!r} must be a string or list of strings \"",
"\"containing valid project/version requirement specifiers; {error}\"",
")",
"raise",
"DistutilsSetupError",
"(",
"tmpl",
".",
"format",
"(",
"attr",
"=",
"attr",
",",
"error",
"=",
"error",
")",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/dist.py#L268-L279 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/atom/__init__.py | python | Person.__init__ | (self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None) | Foundation from which author and contributor are derived.
The constructor is provided for illustrative purposes, you should not
need to instantiate a Person.
Args:
name: Name The person's name
email: Email The person's email address
uri: Uri The URI of the person's webpage
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>) | Foundation from which author and contributor are derived. | [
"Foundation",
"from",
"which",
"author",
"and",
"contributor",
"are",
"derived",
"."
] | def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Foundation from which author and contributor are derived.
The constructor is provided for illustrative purposes, you should not
need to instantiate a Person.
Args:
name: Name The person's name
email: Email The person's email address
uri: Uri The URI of the person's webpage
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>)
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text | [
"def",
"__init__",
"(",
"self",
",",
"name",
"=",
"None",
",",
"email",
"=",
"None",
",",
"uri",
"=",
"None",
",",
"extension_elements",
"=",
"None",
",",
"extension_attributes",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"email",
"=",
"email",
"self",
".",
"uri",
"=",
"uri",
"self",
".",
"extension_elements",
"=",
"extension_elements",
"or",
"[",
"]",
"self",
".",
"extension_attributes",
"=",
"extension_attributes",
"or",
"{",
"}",
"self",
".",
"text",
"=",
"text"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/atom/__init__.py#L474-L498 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/factorization/python/ops/gmm_ops.py | python | _covariance | (x, diag) | return cov | Defines the covariance operation of a matrix.
Args:
x: a matrix Tensor. Dimension 0 should contain the number of examples.
diag: if True, it computes the diagonal covariance.
Returns:
A Tensor representing the covariance of x. In the case of
diagonal matrix just the diagonal is returned. | Defines the covariance operation of a matrix. | [
"Defines",
"the",
"covariance",
"operation",
"of",
"a",
"matrix",
"."
] | def _covariance(x, diag):
"""Defines the covariance operation of a matrix.
Args:
x: a matrix Tensor. Dimension 0 should contain the number of examples.
diag: if True, it computes the diagonal covariance.
Returns:
A Tensor representing the covariance of x. In the case of
diagonal matrix just the diagonal is returned.
"""
num_points = math_ops.to_float(array_ops.shape(x)[0])
x -= math_ops.reduce_mean(x, 0, keep_dims=True)
if diag:
cov = math_ops.reduce_sum(
math_ops.square(x), 0, keep_dims=True) / (num_points - 1)
else:
cov = math_ops.matmul(x, x, transpose_a=True) / (num_points - 1)
return cov | [
"def",
"_covariance",
"(",
"x",
",",
"diag",
")",
":",
"num_points",
"=",
"math_ops",
".",
"to_float",
"(",
"array_ops",
".",
"shape",
"(",
"x",
")",
"[",
"0",
"]",
")",
"x",
"-=",
"math_ops",
".",
"reduce_mean",
"(",
"x",
",",
"0",
",",
"keep_dims",
"=",
"True",
")",
"if",
"diag",
":",
"cov",
"=",
"math_ops",
".",
"reduce_sum",
"(",
"math_ops",
".",
"square",
"(",
"x",
")",
",",
"0",
",",
"keep_dims",
"=",
"True",
")",
"/",
"(",
"num_points",
"-",
"1",
")",
"else",
":",
"cov",
"=",
"math_ops",
".",
"matmul",
"(",
"x",
",",
"x",
",",
"transpose_a",
"=",
"True",
")",
"/",
"(",
"num_points",
"-",
"1",
")",
"return",
"cov"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L47-L65 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/fuzzbunch.py | python | Fuzzbunch.setbanner | (self) | Set the Fuzzbunch banner (seen when starting fuzzbunch) | Set the Fuzzbunch banner (seen when starting fuzzbunch) | [
"Set",
"the",
"Fuzzbunch",
"banner",
"(",
"seen",
"when",
"starting",
"fuzzbunch",
")"
] | def setbanner(self):
"""Set the Fuzzbunch banner (seen when starting fuzzbunch)"""
self.banner, font = figlet.newbanner(self.fontdir, self.bannerstr) | [
"def",
"setbanner",
"(",
"self",
")",
":",
"self",
".",
"banner",
",",
"font",
"=",
"figlet",
".",
"newbanner",
"(",
"self",
".",
"fontdir",
",",
"self",
".",
"bannerstr",
")"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/fuzzbunch.py#L154-L156 | ||
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/37.sudoku-solver.py | python | Solution.solveSudoku | (self, board: List[List[str]]) | Do not return anything, modify board in-place instead. | Do not return anything, modify board in-place instead. | [
"Do",
"not",
"return",
"anything",
"modify",
"board",
"in",
"-",
"place",
"instead",
"."
] | def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
n = len(board)
row = [[False for j in range(n)] for i in range(n)]
col = [[False for j in range(n)] for i in range(n)]
zone = [[False for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
if board[i][j] == '.':
continue
z = i // 3 * 3 + j // 3
num = int(board[i][j]) - 1
row[i][num] = True
col[j][num] = True
zone[z][num] = True
self.helper(board, 0, row, col, zone, n) | [
"def",
"solveSudoku",
"(",
"self",
",",
"board",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"None",
":",
"n",
"=",
"len",
"(",
"board",
")",
"row",
"=",
"[",
"[",
"False",
"for",
"j",
"in",
"range",
"(",
"n",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"col",
"=",
"[",
"[",
"False",
"for",
"j",
"in",
"range",
"(",
"n",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"zone",
"=",
"[",
"[",
"False",
"for",
"j",
"in",
"range",
"(",
"n",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"for",
"j",
"in",
"range",
"(",
"n",
")",
":",
"if",
"board",
"[",
"i",
"]",
"[",
"j",
"]",
"==",
"'.'",
":",
"continue",
"z",
"=",
"i",
"//",
"3",
"*",
"3",
"+",
"j",
"//",
"3",
"num",
"=",
"int",
"(",
"board",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"-",
"1",
"row",
"[",
"i",
"]",
"[",
"num",
"]",
"=",
"True",
"col",
"[",
"j",
"]",
"[",
"num",
"]",
"=",
"True",
"zone",
"[",
"z",
"]",
"[",
"num",
"]",
"=",
"True",
"self",
".",
"helper",
"(",
"board",
",",
"0",
",",
"row",
",",
"col",
",",
"zone",
",",
"n",
")"
] | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/37.sudoku-solver.py#L44-L66 | ||
ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | LeetCode/python3/1.py | python | Solution.twoSum | (self, nums, target) | return [] | :type nums: List[int]
:type target: int
:rtype: List[int] | :type nums: List[int]
:type target: int
:rtype: List[int] | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"type",
"target",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i in range(len(nums)):
diff = target - nums[i]
if diff in d:
return [d[diff], i]
d[nums[i]] = i
return [] | [
"def",
"twoSum",
"(",
"self",
",",
"nums",
",",
"target",
")",
":",
"d",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"nums",
")",
")",
":",
"diff",
"=",
"target",
"-",
"nums",
"[",
"i",
"]",
"if",
"diff",
"in",
"d",
":",
"return",
"[",
"d",
"[",
"diff",
"]",
",",
"i",
"]",
"d",
"[",
"nums",
"[",
"i",
"]",
"]",
"=",
"i",
"return",
"[",
"]"
] | https://github.com/ZintrulCre/LeetCode_Archiver/blob/de23e16ead29336b5ee7aa1898a392a5d6463d27/LeetCode/python3/1.py#L2-L14 | |
xhzdeng/crpn | a5aef0f80dbe486103123f740c634fb01e6cc9a1 | caffe-fast-rcnn/python/caffe/io.py | python | Transformer.preprocess | (self, in_, data) | return caffe_in | Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net | Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature | [
"Format",
"input",
"for",
"Caffe",
":",
"-",
"convert",
"to",
"single",
"-",
"resize",
"to",
"input",
"dimensions",
"(",
"preserving",
"number",
"of",
"channels",
")",
"-",
"transpose",
"dimensions",
"to",
"K",
"x",
"H",
"x",
"W",
"-",
"reorder",
"channels",
"(",
"for",
"instance",
"color",
"to",
"BGR",
")",
"-",
"scale",
"raw",
"input",
"(",
"e",
".",
"g",
".",
"from",
"[",
"0",
"1",
"]",
"to",
"[",
"0",
"255",
"]",
"for",
"ImageNet",
"models",
")",
"-",
"subtract",
"mean",
"-",
"scale",
"feature"
] | def preprocess(self, in_, data):
"""
Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net
"""
self.__check_input(in_)
caffe_in = data.astype(np.float32, copy=False)
transpose = self.transpose.get(in_)
channel_swap = self.channel_swap.get(in_)
raw_scale = self.raw_scale.get(in_)
mean = self.mean.get(in_)
input_scale = self.input_scale.get(in_)
in_dims = self.inputs[in_][2:]
if caffe_in.shape[:2] != in_dims:
caffe_in = resize_image(caffe_in, in_dims)
if transpose is not None:
caffe_in = caffe_in.transpose(transpose)
if channel_swap is not None:
caffe_in = caffe_in[channel_swap, :, :]
if raw_scale is not None:
caffe_in *= raw_scale
if mean is not None:
caffe_in -= mean
if input_scale is not None:
caffe_in *= input_scale
return caffe_in | [
"def",
"preprocess",
"(",
"self",
",",
"in_",
",",
"data",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"caffe_in",
"=",
"data",
".",
"astype",
"(",
"np",
".",
"float32",
",",
"copy",
"=",
"False",
")",
"transpose",
"=",
"self",
".",
"transpose",
".",
"get",
"(",
"in_",
")",
"channel_swap",
"=",
"self",
".",
"channel_swap",
".",
"get",
"(",
"in_",
")",
"raw_scale",
"=",
"self",
".",
"raw_scale",
".",
"get",
"(",
"in_",
")",
"mean",
"=",
"self",
".",
"mean",
".",
"get",
"(",
"in_",
")",
"input_scale",
"=",
"self",
".",
"input_scale",
".",
"get",
"(",
"in_",
")",
"in_dims",
"=",
"self",
".",
"inputs",
"[",
"in_",
"]",
"[",
"2",
":",
"]",
"if",
"caffe_in",
".",
"shape",
"[",
":",
"2",
"]",
"!=",
"in_dims",
":",
"caffe_in",
"=",
"resize_image",
"(",
"caffe_in",
",",
"in_dims",
")",
"if",
"transpose",
"is",
"not",
"None",
":",
"caffe_in",
"=",
"caffe_in",
".",
"transpose",
"(",
"transpose",
")",
"if",
"channel_swap",
"is",
"not",
"None",
":",
"caffe_in",
"=",
"caffe_in",
"[",
"channel_swap",
",",
":",
",",
":",
"]",
"if",
"raw_scale",
"is",
"not",
"None",
":",
"caffe_in",
"*=",
"raw_scale",
"if",
"mean",
"is",
"not",
"None",
":",
"caffe_in",
"-=",
"mean",
"if",
"input_scale",
"is",
"not",
"None",
":",
"caffe_in",
"*=",
"input_scale",
"return",
"caffe_in"
] | https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/caffe-fast-rcnn/python/caffe/io.py#L122-L162 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | dom/bindings/Codegen.py | python | CallbackMember.__init__ | (self, sig, name, descriptorProvider, needThisHandling,
rethrowContentException=False, typedArraysAreStructs=False) | needThisHandling is True if we need to be able to accept a specified
thisObj, False otherwise. | needThisHandling is True if we need to be able to accept a specified
thisObj, False otherwise. | [
"needThisHandling",
"is",
"True",
"if",
"we",
"need",
"to",
"be",
"able",
"to",
"accept",
"a",
"specified",
"thisObj",
"False",
"otherwise",
"."
] | def __init__(self, sig, name, descriptorProvider, needThisHandling,
rethrowContentException=False, typedArraysAreStructs=False):
"""
needThisHandling is True if we need to be able to accept a specified
thisObj, False otherwise.
"""
assert not rethrowContentException or not needThisHandling
self.retvalType = sig[0]
self.originalSig = sig
args = sig[1]
self.argCount = len(args)
if self.argCount > 0:
# Check for variadic arguments
lastArg = args[self.argCount-1]
if lastArg.variadic:
self.argCountStr = ("(%d - 1) + %s.Length()" %
(self.argCount, lastArg.identifier.name))
else:
self.argCountStr = "%d" % self.argCount
self.needThisHandling = needThisHandling
# If needThisHandling, we generate ourselves as private and the caller
# will handle generating public versions that handle the "this" stuff.
visibility = "private" if needThisHandling else "public"
self.rethrowContentException = rethrowContentException
# We don't care, for callback codegen, whether our original member was
# a method or attribute or whatnot. Just always pass FakeMember()
# here.
CGNativeMember.__init__(self, descriptorProvider, FakeMember(),
name, (self.retvalType, args),
extendedAttrs={},
passJSBitsAsNeeded=False,
visibility=visibility,
typedArraysAreStructs=typedArraysAreStructs)
# We have to do all the generation of our body now, because
# the caller relies on us throwing if we can't manage it.
self.exceptionCode = ("aRv.Throw(NS_ERROR_UNEXPECTED);\n"
"return%s;\n" % self.getDefaultRetval())
self.body = self.getImpl() | [
"def",
"__init__",
"(",
"self",
",",
"sig",
",",
"name",
",",
"descriptorProvider",
",",
"needThisHandling",
",",
"rethrowContentException",
"=",
"False",
",",
"typedArraysAreStructs",
"=",
"False",
")",
":",
"assert",
"not",
"rethrowContentException",
"or",
"not",
"needThisHandling",
"self",
".",
"retvalType",
"=",
"sig",
"[",
"0",
"]",
"self",
".",
"originalSig",
"=",
"sig",
"args",
"=",
"sig",
"[",
"1",
"]",
"self",
".",
"argCount",
"=",
"len",
"(",
"args",
")",
"if",
"self",
".",
"argCount",
">",
"0",
":",
"# Check for variadic arguments",
"lastArg",
"=",
"args",
"[",
"self",
".",
"argCount",
"-",
"1",
"]",
"if",
"lastArg",
".",
"variadic",
":",
"self",
".",
"argCountStr",
"=",
"(",
"\"(%d - 1) + %s.Length()\"",
"%",
"(",
"self",
".",
"argCount",
",",
"lastArg",
".",
"identifier",
".",
"name",
")",
")",
"else",
":",
"self",
".",
"argCountStr",
"=",
"\"%d\"",
"%",
"self",
".",
"argCount",
"self",
".",
"needThisHandling",
"=",
"needThisHandling",
"# If needThisHandling, we generate ourselves as private and the caller",
"# will handle generating public versions that handle the \"this\" stuff.",
"visibility",
"=",
"\"private\"",
"if",
"needThisHandling",
"else",
"\"public\"",
"self",
".",
"rethrowContentException",
"=",
"rethrowContentException",
"# We don't care, for callback codegen, whether our original member was",
"# a method or attribute or whatnot. Just always pass FakeMember()",
"# here.",
"CGNativeMember",
".",
"__init__",
"(",
"self",
",",
"descriptorProvider",
",",
"FakeMember",
"(",
")",
",",
"name",
",",
"(",
"self",
".",
"retvalType",
",",
"args",
")",
",",
"extendedAttrs",
"=",
"{",
"}",
",",
"passJSBitsAsNeeded",
"=",
"False",
",",
"visibility",
"=",
"visibility",
",",
"typedArraysAreStructs",
"=",
"typedArraysAreStructs",
")",
"# We have to do all the generation of our body now, because",
"# the caller relies on us throwing if we can't manage it.",
"self",
".",
"exceptionCode",
"=",
"(",
"\"aRv.Throw(NS_ERROR_UNEXPECTED);\\n\"",
"\"return%s;\\n\"",
"%",
"self",
".",
"getDefaultRetval",
"(",
")",
")",
"self",
".",
"body",
"=",
"self",
".",
"getImpl",
"(",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/Codegen.py#L13504-L13542 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/pyserial/serial/sermsdos.py | python | Serial.setRTS | (self,level=1) | Set terminal status line | Set terminal status line | [
"Set",
"terminal",
"status",
"line"
] | def setRTS(self,level=1):
"""Set terminal status line"""
raise NotImplementedError | [
"def",
"setRTS",
"(",
"self",
",",
"level",
"=",
"1",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/sermsdos.py#L169-L171 | ||
ARM-software/armnn | 5e9965cae1cc6162649910f423ebd86001fc1931 | python/pyarmnn/swig_generate.py | python | check_swig_version | (expected_version: str) | Checks version of swig.
Args:
expected_version(str): String containing expected version.
Returns:
bool: True if version is correct, False otherwise | Checks version of swig. | [
"Checks",
"version",
"of",
"swig",
"."
] | def check_swig_version(expected_version: str):
"""Checks version of swig.
Args:
expected_version(str): String containing expected version.
Returns:
bool: True if version is correct, False otherwise
"""
cmd = subprocess.Popen([__swig_exec, "-version"], stdout=subprocess.PIPE)
out, _ = cmd.communicate()
pattern = re.compile(r"(?<=Version ).+(?=$)", re.MULTILINE)
match = pattern.search(out.decode('utf-8'))
if match:
version_string = match.group(0).strip()
if __verbose:
print(f"SWIG version: {version_string}")
return version_string.startswith(expected_version)
else:
return False | [
"def",
"check_swig_version",
"(",
"expected_version",
":",
"str",
")",
":",
"cmd",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"__swig_exec",
",",
"\"-version\"",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
",",
"_",
"=",
"cmd",
".",
"communicate",
"(",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"(?<=Version ).+(?=$)\"",
",",
"re",
".",
"MULTILINE",
")",
"match",
"=",
"pattern",
".",
"search",
"(",
"out",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"if",
"match",
":",
"version_string",
"=",
"match",
".",
"group",
"(",
"0",
")",
".",
"strip",
"(",
")",
"if",
"__verbose",
":",
"print",
"(",
"f\"SWIG version: {version_string}\"",
")",
"return",
"version_string",
".",
"startswith",
"(",
"expected_version",
")",
"else",
":",
"return",
"False"
] | https://github.com/ARM-software/armnn/blob/5e9965cae1cc6162649910f423ebd86001fc1931/python/pyarmnn/swig_generate.py#L45-L66 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Variable.set | (self, value) | return self._tk.globalsetvar(self._name, value) | Set the variable to VALUE. | Set the variable to VALUE. | [
"Set",
"the",
"variable",
"to",
"VALUE",
"."
] | def set(self, value):
"""Set the variable to VALUE."""
return self._tk.globalsetvar(self._name, value) | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"_tk",
".",
"globalsetvar",
"(",
"self",
".",
"_name",
",",
"value",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L234-L236 | |
facebookincubator/fizz | bd0ba1b80f72023cb7ede671a4caa85f6664d3f6 | build/fbcode_builder/fbcode_builder.py | python | FBCodeBuilder.diagnostics | (self) | return self.step(
"Diagnostics",
[
self.comment("Builder {0}".format(repr(self))),
self.run(ShellQuoted("hostname")),
self.run(ShellQuoted("cat /etc/issue || echo no /etc/issue")),
self.run(ShellQuoted("g++ --version || echo g++ not installed")),
self.run(ShellQuoted("cmake --version || echo cmake not installed")),
],
) | Log some system diagnostics before/after setup for ease of debugging | Log some system diagnostics before/after setup for ease of debugging | [
"Log",
"some",
"system",
"diagnostics",
"before",
"/",
"after",
"setup",
"for",
"ease",
"of",
"debugging"
] | def diagnostics(self):
"Log some system diagnostics before/after setup for ease of debugging"
# The builder's repr is not used in a command to avoid pointlessly
# invalidating Docker's build cache.
return self.step(
"Diagnostics",
[
self.comment("Builder {0}".format(repr(self))),
self.run(ShellQuoted("hostname")),
self.run(ShellQuoted("cat /etc/issue || echo no /etc/issue")),
self.run(ShellQuoted("g++ --version || echo g++ not installed")),
self.run(ShellQuoted("cmake --version || echo cmake not installed")),
],
) | [
"def",
"diagnostics",
"(",
"self",
")",
":",
"# The builder's repr is not used in a command to avoid pointlessly",
"# invalidating Docker's build cache.",
"return",
"self",
".",
"step",
"(",
"\"Diagnostics\"",
",",
"[",
"self",
".",
"comment",
"(",
"\"Builder {0}\"",
".",
"format",
"(",
"repr",
"(",
"self",
")",
")",
")",
",",
"self",
".",
"run",
"(",
"ShellQuoted",
"(",
"\"hostname\"",
")",
")",
",",
"self",
".",
"run",
"(",
"ShellQuoted",
"(",
"\"cat /etc/issue || echo no /etc/issue\"",
")",
")",
",",
"self",
".",
"run",
"(",
"ShellQuoted",
"(",
"\"g++ --version || echo g++ not installed\"",
")",
")",
",",
"self",
".",
"run",
"(",
"ShellQuoted",
"(",
"\"cmake --version || echo cmake not installed\"",
")",
")",
",",
"]",
",",
")"
] | https://github.com/facebookincubator/fizz/blob/bd0ba1b80f72023cb7ede671a4caa85f6664d3f6/build/fbcode_builder/fbcode_builder.py#L153-L166 | |
lawy623/SVS | b7c7ae367c82a4797ff4a896a2ff304f02e7f724 | caffe/scripts/cpp_lint.py | python | CheckAltTokens | (filename, clean_lines, linenum, error) | Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Check alternative keywords being used in boolean expressions. | [
"Check",
"alternative",
"keywords",
"being",
"used",
"in",
"boolean",
"expressions",
"."
] | def CheckAltTokens(filename, clean_lines, linenum, error):
"""Check alternative keywords being used in boolean expressions.
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]
# Avoid preprocessor lines
if Match(r'^\s*#', line):
return
# Last ditch effort to avoid multi-line comments. This will not help
# if the comment started before the current line or ended after the
# current line, but it catches most of the false positives. At least,
# it provides a way to workaround this warning for people who use
# multi-line comments in preprocessor macros.
#
# TODO(unknown): remove this once cpplint has better support for
# multi-line comments.
if line.find('/*') >= 0 or line.find('*/') >= 0:
return
for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
error(filename, linenum, 'readability/alt_tokens', 2,
'Use operator %s instead of %s' % (
_ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) | [
"def",
"CheckAltTokens",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Avoid preprocessor lines",
"if",
"Match",
"(",
"r'^\\s*#'",
",",
"line",
")",
":",
"return",
"# Last ditch effort to avoid multi-line comments. This will not help",
"# if the comment started before the current line or ended after the",
"# current line, but it catches most of the false positives. At least,",
"# it provides a way to workaround this warning for people who use",
"# multi-line comments in preprocessor macros.",
"#",
"# TODO(unknown): remove this once cpplint has better support for",
"# multi-line comments.",
"if",
"line",
".",
"find",
"(",
"'/*'",
")",
">=",
"0",
"or",
"line",
".",
"find",
"(",
"'*/'",
")",
">=",
"0",
":",
"return",
"for",
"match",
"in",
"_ALT_TOKEN_REPLACEMENT_PATTERN",
".",
"finditer",
"(",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/alt_tokens'",
",",
"2",
",",
"'Use operator %s instead of %s'",
"%",
"(",
"_ALT_TOKEN_REPLACEMENT",
"[",
"match",
".",
"group",
"(",
"1",
")",
"]",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")"
] | https://github.com/lawy623/SVS/blob/b7c7ae367c82a4797ff4a896a2ff304f02e7f724/caffe/scripts/cpp_lint.py#L3405-L3434 | ||
raspberrypi/tools | 13474ee775d0c5ec8a7da4fb0a9fa84187abfc87 | arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/share/gdb/python/gdb/prompt.py | python | _prompt_object_attr | (func, what, attr, nattr) | Internal worker for fetching GDB attributes. | Internal worker for fetching GDB attributes. | [
"Internal",
"worker",
"for",
"fetching",
"GDB",
"attributes",
"."
] | def _prompt_object_attr(func, what, attr, nattr):
"""Internal worker for fetching GDB attributes."""
if attr is None:
attr = nattr
try:
obj = func()
except gdb.error:
return '<no %s>' % what
if hasattr(obj, attr):
result = getattr(obj, attr)
if callable(result):
result = result()
return result
else:
return '<no attribute %s on current %s>' % (attr, what) | [
"def",
"_prompt_object_attr",
"(",
"func",
",",
"what",
",",
"attr",
",",
"nattr",
")",
":",
"if",
"attr",
"is",
"None",
":",
"attr",
"=",
"nattr",
"try",
":",
"obj",
"=",
"func",
"(",
")",
"except",
"gdb",
".",
"error",
":",
"return",
"'<no %s>'",
"%",
"what",
"if",
"hasattr",
"(",
"obj",
",",
"attr",
")",
":",
"result",
"=",
"getattr",
"(",
"obj",
",",
"attr",
")",
"if",
"callable",
"(",
"result",
")",
":",
"result",
"=",
"result",
"(",
")",
"return",
"result",
"else",
":",
"return",
"'<no attribute %s on current %s>'",
"%",
"(",
"attr",
",",
"what",
")"
] | https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/share/gdb/python/gdb/prompt.py#L26-L40 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/position.py | python | Position.prev_realised_pnl | (self, prev_realised_pnl) | Sets the prev_realised_pnl of this Position.
:param prev_realised_pnl: The prev_realised_pnl of this Position. # noqa: E501
:type: float | Sets the prev_realised_pnl of this Position. | [
"Sets",
"the",
"prev_realised_pnl",
"of",
"this",
"Position",
"."
] | def prev_realised_pnl(self, prev_realised_pnl):
"""Sets the prev_realised_pnl of this Position.
:param prev_realised_pnl: The prev_realised_pnl of this Position. # noqa: E501
:type: float
"""
self._prev_realised_pnl = prev_realised_pnl | [
"def",
"prev_realised_pnl",
"(",
"self",
",",
"prev_realised_pnl",
")",
":",
"self",
".",
"_prev_realised_pnl",
"=",
"prev_realised_pnl"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L787-L795 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Input/BlockInfo.py | python | BlockInfo.toolTip | (self) | return self.description | A suitable description that could be used in a tool tip.
Return:
str: A description of this block. | A suitable description that could be used in a tool tip.
Return:
str: A description of this block. | [
"A",
"suitable",
"description",
"that",
"could",
"be",
"used",
"in",
"a",
"tool",
"tip",
".",
"Return",
":",
"str",
":",
"A",
"description",
"of",
"this",
"block",
"."
] | def toolTip(self):
"""
A suitable description that could be used in a tool tip.
Return:
str: A description of this block.
"""
return self.description | [
"def",
"toolTip",
"(",
"self",
")",
":",
"return",
"self",
".",
"description"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/BlockInfo.py#L339-L345 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/reshape/tile.py | python | _preprocess_for_cut | (x) | return x_is_series, series_index, name, x | handles preprocessing for cut where we convert passed
input to array, strip the index information and store it
separately | handles preprocessing for cut where we convert passed
input to array, strip the index information and store it
separately | [
"handles",
"preprocessing",
"for",
"cut",
"where",
"we",
"convert",
"passed",
"input",
"to",
"array",
"strip",
"the",
"index",
"information",
"and",
"store",
"it",
"separately"
] | def _preprocess_for_cut(x):
"""
handles preprocessing for cut where we convert passed
input to array, strip the index information and store it
separately
"""
x_is_series = isinstance(x, Series)
series_index = None
name = None
if x_is_series:
series_index = x.index
name = x.name
# Check that the passed array is a Pandas or Numpy object
# We don't want to strip away a Pandas data-type here (e.g. datetimetz)
ndim = getattr(x, 'ndim', None)
if ndim is None:
x = np.asarray(x)
if x.ndim != 1:
raise ValueError("Input array must be 1 dimensional")
return x_is_series, series_index, name, x | [
"def",
"_preprocess_for_cut",
"(",
"x",
")",
":",
"x_is_series",
"=",
"isinstance",
"(",
"x",
",",
"Series",
")",
"series_index",
"=",
"None",
"name",
"=",
"None",
"if",
"x_is_series",
":",
"series_index",
"=",
"x",
".",
"index",
"name",
"=",
"x",
".",
"name",
"# Check that the passed array is a Pandas or Numpy object",
"# We don't want to strip away a Pandas data-type here (e.g. datetimetz)",
"ndim",
"=",
"getattr",
"(",
"x",
",",
"'ndim'",
",",
"None",
")",
"if",
"ndim",
"is",
"None",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"if",
"x",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Input array must be 1 dimensional\"",
")",
"return",
"x_is_series",
",",
"series_index",
",",
"name",
",",
"x"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/reshape/tile.py#L494-L516 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/IntegrateSingePtSubWindow.py | python | IntegrateSinglePtIntensityWindow.do_refresh_roi | (self) | return | refresh ROI list from parent
:return: | refresh ROI list from parent
:return: | [
"refresh",
"ROI",
"list",
"from",
"parent",
":",
"return",
":"
] | def do_refresh_roi(self):
"""
refresh ROI list from parent
:return:
"""
roi_list = self._controller.get_region_of_interest_list()
# add ROI
self._roiMutex = True
self.ui.comboBox_roiList.clear()
for roi_name in sorted(roi_list):
self.ui.comboBox_roiList.addItem(roi_name)
self._roiMutex = False
return | [
"def",
"do_refresh_roi",
"(",
"self",
")",
":",
"roi_list",
"=",
"self",
".",
"_controller",
".",
"get_region_of_interest_list",
"(",
")",
"# add ROI",
"self",
".",
"_roiMutex",
"=",
"True",
"self",
".",
"ui",
".",
"comboBox_roiList",
".",
"clear",
"(",
")",
"for",
"roi_name",
"in",
"sorted",
"(",
"roi_list",
")",
":",
"self",
".",
"ui",
".",
"comboBox_roiList",
".",
"addItem",
"(",
"roi_name",
")",
"self",
".",
"_roiMutex",
"=",
"False",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/IntegrateSingePtSubWindow.py#L416-L432 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/distributions/python/ops/onehot_categorical.py | python | OneHotCategorical.event_size | (self) | return self._event_size | Scalar `int32` tensor: the number of classes. | Scalar `int32` tensor: the number of classes. | [
"Scalar",
"int32",
"tensor",
":",
"the",
"number",
"of",
"classes",
"."
] | def event_size(self):
"""Scalar `int32` tensor: the number of classes."""
return self._event_size | [
"def",
"event_size",
"(",
"self",
")",
":",
"return",
"self",
".",
"_event_size"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/onehot_categorical.py#L148-L150 | |
freesurfer/freesurfer | 6dbe527d43ffa611acb2cd112e9469f9bfec8e36 | psacnn_brain_segmentation/psacnn_brain_segmentation/image_utils/image_utils/patch_utils.py | python | show_slices | (slices) | Function to display row of image slices | Function to display row of image slices | [
"Function",
"to",
"display",
"row",
"of",
"image",
"slices"
] | def show_slices(slices):
""" Function to display row of image slices """
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, len(slices))
for i, slice in enumerate(slices):
axes[i].imshow(slice.T, cmap="gray", origin="lower") | [
"def",
"show_slices",
"(",
"slices",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"fig",
",",
"axes",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"len",
"(",
"slices",
")",
")",
"for",
"i",
",",
"slice",
"in",
"enumerate",
"(",
"slices",
")",
":",
"axes",
"[",
"i",
"]",
".",
"imshow",
"(",
"slice",
".",
"T",
",",
"cmap",
"=",
"\"gray\"",
",",
"origin",
"=",
"\"lower\"",
")"
] | https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/psacnn_brain_segmentation/psacnn_brain_segmentation/image_utils/image_utils/patch_utils.py#L1-L6 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/arraypad.py | python | _prepend_min | (arr, pad_amt, num, axis=-1) | return np.concatenate((min_chunk.repeat(pad_amt, axis=axis), arr),
axis=axis) | Prepend `pad_amt` minimum values along `axis`.
Parameters
----------
arr : ndarray
Input array of arbitrary shape.
pad_amt : int
Amount of padding to prepend.
num : int
Depth into `arr` along `axis` to calculate minimum.
Range: [1, `arr.shape[axis]`] or None (entire axis)
axis : int
Axis along which to pad `arr`.
Returns
-------
padarr : ndarray
Output array, with `pad_amt` values prepended along `axis`. The
prepended region is the minimum of the first `num` values along
`axis`. | Prepend `pad_amt` minimum values along `axis`. | [
"Prepend",
"pad_amt",
"minimum",
"values",
"along",
"axis",
"."
] | def _prepend_min(arr, pad_amt, num, axis=-1):
"""
Prepend `pad_amt` minimum values along `axis`.
Parameters
----------
arr : ndarray
Input array of arbitrary shape.
pad_amt : int
Amount of padding to prepend.
num : int
Depth into `arr` along `axis` to calculate minimum.
Range: [1, `arr.shape[axis]`] or None (entire axis)
axis : int
Axis along which to pad `arr`.
Returns
-------
padarr : ndarray
Output array, with `pad_amt` values prepended along `axis`. The
prepended region is the minimum of the first `num` values along
`axis`.
"""
if pad_amt == 0:
return arr
# Equivalent to edge padding for single value, so do that instead
if num == 1:
return _prepend_edge(arr, pad_amt, axis)
# Use entire array if `num` is too large
if num is not None:
if num >= arr.shape[axis]:
num = None
# Slice a chunk from the edge to calculate stats on
min_slice = tuple(slice(None) if i != axis else slice(num)
for (i, x) in enumerate(arr.shape))
# Shape to restore singleton dimension after slicing
pad_singleton = tuple(x if i != axis else 1
for (i, x) in enumerate(arr.shape))
# Extract slice, calculate min, reshape to add singleton dimension back
min_chunk = arr[min_slice].min(axis=axis).reshape(pad_singleton)
# Concatenate `arr` with `min_chunk`, extended along `axis` by `pad_amt`
return np.concatenate((min_chunk.repeat(pad_amt, axis=axis), arr),
axis=axis) | [
"def",
"_prepend_min",
"(",
"arr",
",",
"pad_amt",
",",
"num",
",",
"axis",
"=",
"-",
"1",
")",
":",
"if",
"pad_amt",
"==",
"0",
":",
"return",
"arr",
"# Equivalent to edge padding for single value, so do that instead",
"if",
"num",
"==",
"1",
":",
"return",
"_prepend_edge",
"(",
"arr",
",",
"pad_amt",
",",
"axis",
")",
"# Use entire array if `num` is too large",
"if",
"num",
"is",
"not",
"None",
":",
"if",
"num",
">=",
"arr",
".",
"shape",
"[",
"axis",
"]",
":",
"num",
"=",
"None",
"# Slice a chunk from the edge to calculate stats on",
"min_slice",
"=",
"tuple",
"(",
"slice",
"(",
"None",
")",
"if",
"i",
"!=",
"axis",
"else",
"slice",
"(",
"num",
")",
"for",
"(",
"i",
",",
"x",
")",
"in",
"enumerate",
"(",
"arr",
".",
"shape",
")",
")",
"# Shape to restore singleton dimension after slicing",
"pad_singleton",
"=",
"tuple",
"(",
"x",
"if",
"i",
"!=",
"axis",
"else",
"1",
"for",
"(",
"i",
",",
"x",
")",
"in",
"enumerate",
"(",
"arr",
".",
"shape",
")",
")",
"# Extract slice, calculate min, reshape to add singleton dimension back",
"min_chunk",
"=",
"arr",
"[",
"min_slice",
"]",
".",
"min",
"(",
"axis",
"=",
"axis",
")",
".",
"reshape",
"(",
"pad_singleton",
")",
"# Concatenate `arr` with `min_chunk`, extended along `axis` by `pad_amt`",
"return",
"np",
".",
"concatenate",
"(",
"(",
"min_chunk",
".",
"repeat",
"(",
"pad_amt",
",",
"axis",
"=",
"axis",
")",
",",
"arr",
")",
",",
"axis",
"=",
"axis",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/arraypad.py#L649-L698 | |
lyxok1/Tiny-DSOD | 94d15450699bea0dd3720e75e2d273e476174fba | scripts/cpp_lint.py | python | _CppLintState.SetCountingStyle | (self, counting_style) | Sets the module's counting options. | Sets the module's counting options. | [
"Sets",
"the",
"module",
"s",
"counting",
"options",
"."
] | def SetCountingStyle(self, counting_style):
"""Sets the module's counting options."""
self.counting = counting_style | [
"def",
"SetCountingStyle",
"(",
"self",
",",
"counting_style",
")",
":",
"self",
".",
"counting",
"=",
"counting_style"
] | https://github.com/lyxok1/Tiny-DSOD/blob/94d15450699bea0dd3720e75e2d273e476174fba/scripts/cpp_lint.py#L713-L715 | ||
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | llvm/utils/lit/lit/LitConfig.py | python | LitConfig.getBashPath | (self) | return self.bashPath | getBashPath - Get the path to 'bash | getBashPath - Get the path to 'bash | [
"getBashPath",
"-",
"Get",
"the",
"path",
"to",
"bash"
] | def getBashPath(self):
"""getBashPath - Get the path to 'bash'"""
if self.bashPath is not None:
return self.bashPath
self.bashPath = lit.util.which('bash', os.pathsep.join(self.path))
if self.bashPath is None:
self.bashPath = lit.util.which('bash')
if self.bashPath is None:
self.bashPath = ''
# Check whether the found version of bash is able to cope with paths in
# the host path format. If not, don't return it as it can't be used to
# run scripts. For example, WSL's bash.exe requires '/mnt/c/foo' rather
# than 'C:\\foo' or 'C:/foo'.
if self.isWindows and self.bashPath:
command = [self.bashPath, '-c',
'[[ -f "%s" ]]' % self.bashPath.replace('\\', '\\\\')]
_, _, exitCode = lit.util.executeCommand(command)
if exitCode:
self.note('bash command failed: %s' % (
' '.join('"%s"' % c for c in command)))
self.bashPath = ''
if not self.bashPath:
self.warning('Unable to find a usable version of bash.')
return self.bashPath | [
"def",
"getBashPath",
"(",
"self",
")",
":",
"if",
"self",
".",
"bashPath",
"is",
"not",
"None",
":",
"return",
"self",
".",
"bashPath",
"self",
".",
"bashPath",
"=",
"lit",
".",
"util",
".",
"which",
"(",
"'bash'",
",",
"os",
".",
"pathsep",
".",
"join",
"(",
"self",
".",
"path",
")",
")",
"if",
"self",
".",
"bashPath",
"is",
"None",
":",
"self",
".",
"bashPath",
"=",
"lit",
".",
"util",
".",
"which",
"(",
"'bash'",
")",
"if",
"self",
".",
"bashPath",
"is",
"None",
":",
"self",
".",
"bashPath",
"=",
"''",
"# Check whether the found version of bash is able to cope with paths in",
"# the host path format. If not, don't return it as it can't be used to",
"# run scripts. For example, WSL's bash.exe requires '/mnt/c/foo' rather",
"# than 'C:\\\\foo' or 'C:/foo'.",
"if",
"self",
".",
"isWindows",
"and",
"self",
".",
"bashPath",
":",
"command",
"=",
"[",
"self",
".",
"bashPath",
",",
"'-c'",
",",
"'[[ -f \"%s\" ]]'",
"%",
"self",
".",
"bashPath",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
"]",
"_",
",",
"_",
",",
"exitCode",
"=",
"lit",
".",
"util",
".",
"executeCommand",
"(",
"command",
")",
"if",
"exitCode",
":",
"self",
".",
"note",
"(",
"'bash command failed: %s'",
"%",
"(",
"' '",
".",
"join",
"(",
"'\"%s\"'",
"%",
"c",
"for",
"c",
"in",
"command",
")",
")",
")",
"self",
".",
"bashPath",
"=",
"''",
"if",
"not",
"self",
".",
"bashPath",
":",
"self",
".",
"warning",
"(",
"'Unable to find a usable version of bash.'",
")",
"return",
"self",
".",
"bashPath"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/llvm/utils/lit/lit/LitConfig.py#L119-L147 | |
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/internal/decoder.py | python | _DecodeUnknownFieldSet | (buffer, pos, end_pos=None) | return (unknown_field_set, pos) | Decode UnknownFieldSet. Returns the UnknownFieldSet and new position. | Decode UnknownFieldSet. Returns the UnknownFieldSet and new position. | [
"Decode",
"UnknownFieldSet",
".",
"Returns",
"the",
"UnknownFieldSet",
"and",
"new",
"position",
"."
] | def _DecodeUnknownFieldSet(buffer, pos, end_pos=None):
"""Decode UnknownFieldSet. Returns the UnknownFieldSet and new position."""
unknown_field_set = containers.UnknownFieldSet()
while end_pos is None or pos < end_pos:
(tag_bytes, pos) = ReadTag(buffer, pos)
(tag, _) = _DecodeVarint(tag_bytes, 0)
field_number, wire_type = wire_format.UnpackTag(tag)
if wire_type == wire_format.WIRETYPE_END_GROUP:
break
(data, pos) = _DecodeUnknownField(buffer, pos, wire_type)
# pylint: disable=protected-access
unknown_field_set._add(field_number, wire_type, data)
return (unknown_field_set, pos) | [
"def",
"_DecodeUnknownFieldSet",
"(",
"buffer",
",",
"pos",
",",
"end_pos",
"=",
"None",
")",
":",
"unknown_field_set",
"=",
"containers",
".",
"UnknownFieldSet",
"(",
")",
"while",
"end_pos",
"is",
"None",
"or",
"pos",
"<",
"end_pos",
":",
"(",
"tag_bytes",
",",
"pos",
")",
"=",
"ReadTag",
"(",
"buffer",
",",
"pos",
")",
"(",
"tag",
",",
"_",
")",
"=",
"_DecodeVarint",
"(",
"tag_bytes",
",",
"0",
")",
"field_number",
",",
"wire_type",
"=",
"wire_format",
".",
"UnpackTag",
"(",
"tag",
")",
"if",
"wire_type",
"==",
"wire_format",
".",
"WIRETYPE_END_GROUP",
":",
"break",
"(",
"data",
",",
"pos",
")",
"=",
"_DecodeUnknownField",
"(",
"buffer",
",",
"pos",
",",
"wire_type",
")",
"# pylint: disable=protected-access",
"unknown_field_set",
".",
"_add",
"(",
"field_number",
",",
"wire_type",
",",
"data",
")",
"return",
"(",
"unknown_field_set",
",",
"pos",
")"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/internal/decoder.py#L930-L944 | |
junhyukoh/caffe-lstm | 598d45456fa2a1b127a644f4aa38daa8fb9fc722 | python/caffe/io.py | python | Transformer.deprocess | (self, in_, data) | return decaf_in | Invert Caffe formatting; see preprocess(). | Invert Caffe formatting; see preprocess(). | [
"Invert",
"Caffe",
"formatting",
";",
"see",
"preprocess",
"()",
"."
] | def deprocess(self, in_, data):
"""
Invert Caffe formatting; see preprocess().
"""
self.__check_input(in_)
decaf_in = data.copy().squeeze()
transpose = self.transpose.get(in_)
channel_swap = self.channel_swap.get(in_)
raw_scale = self.raw_scale.get(in_)
mean = self.mean.get(in_)
input_scale = self.input_scale.get(in_)
if input_scale is not None:
decaf_in /= input_scale
if mean is not None:
decaf_in += mean
if raw_scale is not None:
decaf_in /= raw_scale
if channel_swap is not None:
decaf_in = decaf_in[channel_swap, :, :]
if transpose is not None:
decaf_in = decaf_in.transpose([transpose[t] for t in transpose])
return decaf_in | [
"def",
"deprocess",
"(",
"self",
",",
"in_",
",",
"data",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"decaf_in",
"=",
"data",
".",
"copy",
"(",
")",
".",
"squeeze",
"(",
")",
"transpose",
"=",
"self",
".",
"transpose",
".",
"get",
"(",
"in_",
")",
"channel_swap",
"=",
"self",
".",
"channel_swap",
".",
"get",
"(",
"in_",
")",
"raw_scale",
"=",
"self",
".",
"raw_scale",
".",
"get",
"(",
"in_",
")",
"mean",
"=",
"self",
".",
"mean",
".",
"get",
"(",
"in_",
")",
"input_scale",
"=",
"self",
".",
"input_scale",
".",
"get",
"(",
"in_",
")",
"if",
"input_scale",
"is",
"not",
"None",
":",
"decaf_in",
"/=",
"input_scale",
"if",
"mean",
"is",
"not",
"None",
":",
"decaf_in",
"+=",
"mean",
"if",
"raw_scale",
"is",
"not",
"None",
":",
"decaf_in",
"/=",
"raw_scale",
"if",
"channel_swap",
"is",
"not",
"None",
":",
"decaf_in",
"=",
"decaf_in",
"[",
"channel_swap",
",",
":",
",",
":",
"]",
"if",
"transpose",
"is",
"not",
"None",
":",
"decaf_in",
"=",
"decaf_in",
".",
"transpose",
"(",
"[",
"transpose",
"[",
"t",
"]",
"for",
"t",
"in",
"transpose",
"]",
")",
"return",
"decaf_in"
] | https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/python/caffe/io.py#L160-L181 | |
ethz-asl/kalibr | 1c9d7e0e57cf7b0d2e0351a71b312adfd8996f05 | aslam_offline_calibration/kalibr/python/kalibr_rs_camera_calibration/RsCalibrator.py | python | RsCalibrator.__generateIntrinsicsInitialGuess | (self) | return self.__camera.initializeIntrinsics(self.__observations) | Get an initial guess for the camera geometry (intrinsics, distortion). Distortion is typically left as 0,0,0,0.
The parameters of the geometryModel are updated in place. | Get an initial guess for the camera geometry (intrinsics, distortion). Distortion is typically left as 0,0,0,0.
The parameters of the geometryModel are updated in place. | [
"Get",
"an",
"initial",
"guess",
"for",
"the",
"camera",
"geometry",
"(",
"intrinsics",
"distortion",
")",
".",
"Distortion",
"is",
"typically",
"left",
"as",
"0",
"0",
"0",
"0",
".",
"The",
"parameters",
"of",
"the",
"geometryModel",
"are",
"updated",
"in",
"place",
"."
] | def __generateIntrinsicsInitialGuess(self):
"""
Get an initial guess for the camera geometry (intrinsics, distortion). Distortion is typically left as 0,0,0,0.
The parameters of the geometryModel are updated in place.
"""
if (self.__isRollingShutter()):
sensorRows = self.__observations[0].imRows()
self.__camera.shutter().setParameters(np.array([1.0 / self.__config.framerate / float(sensorRows)]))
return self.__camera.initializeIntrinsics(self.__observations) | [
"def",
"__generateIntrinsicsInitialGuess",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"__isRollingShutter",
"(",
")",
")",
":",
"sensorRows",
"=",
"self",
".",
"__observations",
"[",
"0",
"]",
".",
"imRows",
"(",
")",
"self",
".",
"__camera",
".",
"shutter",
"(",
")",
".",
"setParameters",
"(",
"np",
".",
"array",
"(",
"[",
"1.0",
"/",
"self",
".",
"__config",
".",
"framerate",
"/",
"float",
"(",
"sensorRows",
")",
"]",
")",
")",
"return",
"self",
".",
"__camera",
".",
"initializeIntrinsics",
"(",
"self",
".",
"__observations",
")"
] | https://github.com/ethz-asl/kalibr/blob/1c9d7e0e57cf7b0d2e0351a71b312adfd8996f05/aslam_offline_calibration/kalibr/python/kalibr_rs_camera_calibration/RsCalibrator.py#L209-L218 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py | python | Context._ignore_all_flags | (self) | return self._ignore_flags(*_signals) | Ignore all flags, if they are raised | Ignore all flags, if they are raised | [
"Ignore",
"all",
"flags",
"if",
"they",
"are",
"raised"
] | def _ignore_all_flags(self):
"""Ignore all flags, if they are raised"""
return self._ignore_flags(*_signals) | [
"def",
"_ignore_all_flags",
"(",
"self",
")",
":",
"return",
"self",
".",
"_ignore_flags",
"(",
"*",
"_signals",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py#L3874-L3876 | |
cocos-creator/engine-native | 984c4c9f5838253313b44ccd429bd8fac4ec8a6a | tools/bindings-generator/clang/cindex.py | python | Cursor.is_mutable_field | (self) | return conf.lib.clang_CXXField_isMutable(self) | Returns True if the cursor refers to a C++ field that is declared
'mutable'. | Returns True if the cursor refers to a C++ field that is declared
'mutable'. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"C",
"++",
"field",
"that",
"is",
"declared",
"mutable",
"."
] | def is_mutable_field(self):
"""Returns True if the cursor refers to a C++ field that is declared
'mutable'.
"""
return conf.lib.clang_CXXField_isMutable(self) | [
"def",
"is_mutable_field",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CXXField_isMutable",
"(",
"self",
")"
] | https://github.com/cocos-creator/engine-native/blob/984c4c9f5838253313b44ccd429bd8fac4ec8a6a/tools/bindings-generator/clang/cindex.py#L1476-L1480 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/third_party/Python/module/pexpect-2.4/screen.py | python | screen.__init__ | (self, r=24, c=80) | This initializes a blank scree of the given dimentions. | This initializes a blank scree of the given dimentions. | [
"This",
"initializes",
"a",
"blank",
"scree",
"of",
"the",
"given",
"dimentions",
"."
] | def __init__(self, r=24, c=80):
"""This initializes a blank scree of the given dimentions."""
self.rows = r
self.cols = c
self.cur_r = 1
self.cur_c = 1
self.cur_saved_r = 1
self.cur_saved_c = 1
self.scroll_row_start = 1
self.scroll_row_end = self.rows
self.w = [[SPACE] * self.cols for c in range(self.rows)] | [
"def",
"__init__",
"(",
"self",
",",
"r",
"=",
"24",
",",
"c",
"=",
"80",
")",
":",
"self",
".",
"rows",
"=",
"r",
"self",
".",
"cols",
"=",
"c",
"self",
".",
"cur_r",
"=",
"1",
"self",
".",
"cur_c",
"=",
"1",
"self",
".",
"cur_saved_r",
"=",
"1",
"self",
".",
"cur_saved_c",
"=",
"1",
"self",
".",
"scroll_row_start",
"=",
"1",
"self",
".",
"scroll_row_end",
"=",
"self",
".",
"rows",
"self",
".",
"w",
"=",
"[",
"[",
"SPACE",
"]",
"*",
"self",
".",
"cols",
"for",
"c",
"in",
"range",
"(",
"self",
".",
"rows",
")",
"]"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/screen.py#L49-L60 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/mailbox.py | python | Mailbox.get_string | (self, key) | return email.message_from_bytes(self.get_bytes(key)).as_string() | Return a string representation or raise a KeyError.
Uses email.message.Message to create a 7bit clean string
representation of the message. | Return a string representation or raise a KeyError. | [
"Return",
"a",
"string",
"representation",
"or",
"raise",
"a",
"KeyError",
"."
] | def get_string(self, key):
"""Return a string representation or raise a KeyError.
Uses email.message.Message to create a 7bit clean string
representation of the message."""
return email.message_from_bytes(self.get_bytes(key)).as_string() | [
"def",
"get_string",
"(",
"self",
",",
"key",
")",
":",
"return",
"email",
".",
"message_from_bytes",
"(",
"self",
".",
"get_bytes",
"(",
"key",
")",
")",
".",
"as_string",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L83-L88 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | Target.PreActionInput | (self, flavor) | return self.FinalOutput() or self.preaction_stamp | Return the path, if any, that should be used as a dependency of
any dependent action step. | Return the path, if any, that should be used as a dependency of
any dependent action step. | [
"Return",
"the",
"path",
"if",
"any",
"that",
"should",
"be",
"used",
"as",
"a",
"dependency",
"of",
"any",
"dependent",
"action",
"step",
"."
] | def PreActionInput(self, flavor):
"""Return the path, if any, that should be used as a dependency of
any dependent action step."""
if self.UsesToc(flavor):
return self.FinalOutput() + '.TOC'
return self.FinalOutput() or self.preaction_stamp | [
"def",
"PreActionInput",
"(",
"self",
",",
"flavor",
")",
":",
"if",
"self",
".",
"UsesToc",
"(",
"flavor",
")",
":",
"return",
"self",
".",
"FinalOutput",
"(",
")",
"+",
"'.TOC'",
"return",
"self",
".",
"FinalOutput",
"(",
")",
"or",
"self",
".",
"preaction_stamp"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L166-L171 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | samples/ide/activegrid/tool/UICommon.py | python | AddWsdlAgToProjectFromWsdlRegistration | (wsdlRegistration) | Add wsdl ag for registry entry. | Add wsdl ag for registry entry. | [
"Add",
"wsdl",
"ag",
"for",
"registry",
"entry",
"."
] | def AddWsdlAgToProjectFromWsdlRegistration(wsdlRegistration):
"""Add wsdl ag for registry entry."""
wsdlPath = wsdlRegistration.path
rootPath = None
serviceRefName = wsdlRegistration.name
agwsDoc = _InitWsdlAg(wsdlPath, rootPath, serviceRefName)
if (agwsDoc == None):
return
serviceRef = agwsDoc.GetModel()
serviceRef.serviceType = wsdlRegistration.type
import activegrid.server.deployment as deployment
if (serviceRef.serviceType == deployment.SERVICE_LOCAL):
serviceRef.localService = deployment.LocalService(
wsdlRegistration.codeFile)
elif (serviceRef.serviceType == deployment.SERVICE_DATABASE):
serviceRef.databaseService = deployment.DatabaseService(
wsdlRegistration.datasourceName)
elif (serviceRef.serviceType == deployment.SERVICE_SOAP):
pass
elif (serviceRef.serviceType == deployment.SERVICE_RSS):
serviceRef.rssService = deployment.RssService(wsdlRegistration.feedUrl)
elif (serviceRef.serviceType == deployment.SERVICE_REST):
serviceRef.restService = deployment.RestService(
wsdlRegistration.baseUrl)
else:
raise AssertionError("Unknown service type")
_AddToProject(agwsDoc, addWsdl=True) | [
"def",
"AddWsdlAgToProjectFromWsdlRegistration",
"(",
"wsdlRegistration",
")",
":",
"wsdlPath",
"=",
"wsdlRegistration",
".",
"path",
"rootPath",
"=",
"None",
"serviceRefName",
"=",
"wsdlRegistration",
".",
"name",
"agwsDoc",
"=",
"_InitWsdlAg",
"(",
"wsdlPath",
",",
"rootPath",
",",
"serviceRefName",
")",
"if",
"(",
"agwsDoc",
"==",
"None",
")",
":",
"return",
"serviceRef",
"=",
"agwsDoc",
".",
"GetModel",
"(",
")",
"serviceRef",
".",
"serviceType",
"=",
"wsdlRegistration",
".",
"type",
"import",
"activegrid",
".",
"server",
".",
"deployment",
"as",
"deployment",
"if",
"(",
"serviceRef",
".",
"serviceType",
"==",
"deployment",
".",
"SERVICE_LOCAL",
")",
":",
"serviceRef",
".",
"localService",
"=",
"deployment",
".",
"LocalService",
"(",
"wsdlRegistration",
".",
"codeFile",
")",
"elif",
"(",
"serviceRef",
".",
"serviceType",
"==",
"deployment",
".",
"SERVICE_DATABASE",
")",
":",
"serviceRef",
".",
"databaseService",
"=",
"deployment",
".",
"DatabaseService",
"(",
"wsdlRegistration",
".",
"datasourceName",
")",
"elif",
"(",
"serviceRef",
".",
"serviceType",
"==",
"deployment",
".",
"SERVICE_SOAP",
")",
":",
"pass",
"elif",
"(",
"serviceRef",
".",
"serviceType",
"==",
"deployment",
".",
"SERVICE_RSS",
")",
":",
"serviceRef",
".",
"rssService",
"=",
"deployment",
".",
"RssService",
"(",
"wsdlRegistration",
".",
"feedUrl",
")",
"elif",
"(",
"serviceRef",
".",
"serviceType",
"==",
"deployment",
".",
"SERVICE_REST",
")",
":",
"serviceRef",
".",
"restService",
"=",
"deployment",
".",
"RestService",
"(",
"wsdlRegistration",
".",
"baseUrl",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"\"Unknown service type\"",
")",
"_AddToProject",
"(",
"agwsDoc",
",",
"addWsdl",
"=",
"True",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/ide/activegrid/tool/UICommon.py#L581-L619 | ||
crankyoldgit/IRremoteESP8266 | 6bc095af80e5aec47d66f8c6263f3a943ea3b4d5 | tools/auto_analyse_raw_data.py | python | RawIRMessage.add_data_code | (self, bin_str, name="", footer=True) | return code | Add the common "data" sequence of code to send the bulk of a message. | Add the common "data" sequence of code to send the bulk of a message. | [
"Add",
"the",
"common",
"data",
"sequence",
"of",
"code",
"to",
"send",
"the",
"bulk",
"of",
"a",
"message",
"."
] | def add_data_code(self, bin_str, name="", footer=True):
"""Add the common "data" sequence of code to send the bulk of a message."""
# pylint: disable=no-self-use
code = []
nbits = len(bin_str)
code.append(f" // Data Section #{self.section_count}")
code.append(f" // e.g. data = 0x{int(bin_str, 2):X}, nbits = {nbits}")
code.append(f" sendData(k{name}BitMark, k{name}OneSpace, k{name}BitMark,"
f" k{name}ZeroSpace, send_data, {nbits}, true);")
code.append(f" send_data >>= {nbits};")
if footer:
code.append(" // Footer")
code.append(f" mark(k{name}BitMark);")
return code | [
"def",
"add_data_code",
"(",
"self",
",",
"bin_str",
",",
"name",
"=",
"\"\"",
",",
"footer",
"=",
"True",
")",
":",
"# pylint: disable=no-self-use",
"code",
"=",
"[",
"]",
"nbits",
"=",
"len",
"(",
"bin_str",
")",
"code",
".",
"append",
"(",
"f\" // Data Section #{self.section_count}\"",
")",
"code",
".",
"append",
"(",
"f\" // e.g. data = 0x{int(bin_str, 2):X}, nbits = {nbits}\"",
")",
"code",
".",
"append",
"(",
"f\" sendData(k{name}BitMark, k{name}OneSpace, k{name}BitMark,\"",
"f\" k{name}ZeroSpace, send_data, {nbits}, true);\"",
")",
"code",
".",
"append",
"(",
"f\" send_data >>= {nbits};\"",
")",
"if",
"footer",
":",
"code",
".",
"append",
"(",
"\" // Footer\"",
")",
"code",
".",
"append",
"(",
"f\" mark(k{name}BitMark);\"",
")",
"return",
"code"
] | https://github.com/crankyoldgit/IRremoteESP8266/blob/6bc095af80e5aec47d66f8c6263f3a943ea3b4d5/tools/auto_analyse_raw_data.py#L101-L114 | |
google/omaha | 61e8c2833fd69c9a13978400108e5b9ebff24a09 | omaha/omaha_version_utils.py | python | ConvertVersionToString | (version) | return '%d.%d.%d.%d' % (version[0], version[1], version[2], version[3]) | Converts a four-element version list to a version string. | Converts a four-element version list to a version string. | [
"Converts",
"a",
"four",
"-",
"element",
"version",
"list",
"to",
"a",
"version",
"string",
"."
] | def ConvertVersionToString(version):
"""Converts a four-element version list to a version string."""
return '%d.%d.%d.%d' % (version[0], version[1], version[2], version[3]) | [
"def",
"ConvertVersionToString",
"(",
"version",
")",
":",
"return",
"'%d.%d.%d.%d'",
"%",
"(",
"version",
"[",
"0",
"]",
",",
"version",
"[",
"1",
"]",
",",
"version",
"[",
"2",
"]",
",",
"version",
"[",
"3",
"]",
")"
] | https://github.com/google/omaha/blob/61e8c2833fd69c9a13978400108e5b9ebff24a09/omaha/omaha_version_utils.py#L175-L177 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/PfemFluidDynamicsApplication/python_scripts/pfem_fluid_dynamics_analysis.py | python | PfemFluidDynamicsAnalysis.GraphicalOutputExecuteInitialize | (self) | This function performs the initialize of the graphical output | This function performs the initialize of the graphical output | [
"This",
"function",
"performs",
"the",
"initialize",
"of",
"the",
"graphical",
"output"
] | def GraphicalOutputExecuteInitialize(self):
"""This function performs the initialize of the graphical output
"""
self.graphical_output.ExecuteInitialize() | [
"def",
"GraphicalOutputExecuteInitialize",
"(",
"self",
")",
":",
"self",
".",
"graphical_output",
".",
"ExecuteInitialize",
"(",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/PfemFluidDynamicsApplication/python_scripts/pfem_fluid_dynamics_analysis.py#L257-L260 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pyparsing/py3/pyparsing/exceptions.py | python | ParseBaseException.line | (self) | return line(self.loc, self.pstr) | Return the line of text where the exception occurred. | Return the line of text where the exception occurred. | [
"Return",
"the",
"line",
"of",
"text",
"where",
"the",
"exception",
"occurred",
"."
] | def line(self) -> str:
"""
Return the line of text where the exception occurred.
"""
return line(self.loc, self.pstr) | [
"def",
"line",
"(",
"self",
")",
"->",
"str",
":",
"return",
"line",
"(",
"self",
".",
"loc",
",",
"self",
".",
"pstr",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py3/pyparsing/exceptions.py#L116-L120 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/configprovider.py | python | ConfigValueStore.set_config_provider | (self, logical_name, provider) | Set the provider for a config value.
This provides control over how a particular configuration value is
loaded. This replaces the provider for ``logical_name`` with the new
``provider``.
:type logical_name: str
:param logical_name: The name of the config value to change the config
provider for.
:type provider: :class:`botocore.configprovider.BaseProvider`
:param provider: The new provider that should be responsible for
providing a value for the config named ``logical_name``. | Set the provider for a config value. | [
"Set",
"the",
"provider",
"for",
"a",
"config",
"value",
"."
] | def set_config_provider(self, logical_name, provider):
"""Set the provider for a config value.
This provides control over how a particular configuration value is
loaded. This replaces the provider for ``logical_name`` with the new
``provider``.
:type logical_name: str
:param logical_name: The name of the config value to change the config
provider for.
:type provider: :class:`botocore.configprovider.BaseProvider`
:param provider: The new provider that should be responsible for
providing a value for the config named ``logical_name``.
"""
self._mapping[logical_name] = provider | [
"def",
"set_config_provider",
"(",
"self",
",",
"logical_name",
",",
"provider",
")",
":",
"self",
".",
"_mapping",
"[",
"logical_name",
"]",
"=",
"provider"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/configprovider.py#L330-L345 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | ItemContainer.SetString | (*args, **kwargs) | return _core_.ItemContainer_SetString(*args, **kwargs) | SetString(self, int n, String s)
Sets the label for the given item. | SetString(self, int n, String s) | [
"SetString",
"(",
"self",
"int",
"n",
"String",
"s",
")"
] | def SetString(*args, **kwargs):
"""
SetString(self, int n, String s)
Sets the label for the given item.
"""
return _core_.ItemContainer_SetString(*args, **kwargs) | [
"def",
"SetString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"ItemContainer_SetString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L12973-L12979 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/which/which.py | python | _getRegisteredExecutable | (exeName) | return registered | Windows allow application paths to be registered in the registry. | Windows allow application paths to be registered in the registry. | [
"Windows",
"allow",
"application",
"paths",
"to",
"be",
"registered",
"in",
"the",
"registry",
"."
] | def _getRegisteredExecutable(exeName):
"""Windows allow application paths to be registered in the registry."""
registered = None
if sys.platform.startswith('win'):
if os.path.splitext(exeName)[1].lower() != '.exe':
exeName += '.exe'
import _winreg
try:
key = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" +\
exeName
value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key)
registered = (value, "from HKLM\\"+key)
except _winreg.error:
pass
if registered and not os.path.exists(registered[0]):
registered = None
return registered | [
"def",
"_getRegisteredExecutable",
"(",
"exeName",
")",
":",
"registered",
"=",
"None",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"exeName",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"!=",
"'.exe'",
":",
"exeName",
"+=",
"'.exe'",
"import",
"_winreg",
"try",
":",
"key",
"=",
"\"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\App Paths\\\\\"",
"+",
"exeName",
"value",
"=",
"_winreg",
".",
"QueryValue",
"(",
"_winreg",
".",
"HKEY_LOCAL_MACHINE",
",",
"key",
")",
"registered",
"=",
"(",
"value",
",",
"\"from HKLM\\\\\"",
"+",
"key",
")",
"except",
"_winreg",
".",
"error",
":",
"pass",
"if",
"registered",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"registered",
"[",
"0",
"]",
")",
":",
"registered",
"=",
"None",
"return",
"registered"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/which/which.py#L87-L103 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/utils/git-svn/convert.py | python | do_convert | (file) | Skip all preceding mail message headers until 'From: ' is encountered.
Then for each line ('From: ' header included), replace the dos style CRLF
end-of-line with unix style LF end-of-line. | Skip all preceding mail message headers until 'From: ' is encountered.
Then for each line ('From: ' header included), replace the dos style CRLF
end-of-line with unix style LF end-of-line. | [
"Skip",
"all",
"preceding",
"mail",
"message",
"headers",
"until",
"From",
":",
"is",
"encountered",
".",
"Then",
"for",
"each",
"line",
"(",
"From",
":",
"header",
"included",
")",
"replace",
"the",
"dos",
"style",
"CRLF",
"end",
"-",
"of",
"-",
"line",
"with",
"unix",
"style",
"LF",
"end",
"-",
"of",
"-",
"line",
"."
] | def do_convert(file):
"""Skip all preceding mail message headers until 'From: ' is encountered.
Then for each line ('From: ' header included), replace the dos style CRLF
end-of-line with unix style LF end-of-line.
"""
print "converting %s ..." % file
with open(file, 'r') as f_in:
content = f_in.read()
# The new content to be written back to the same file.
new_content = StringIO.StringIO()
# Boolean flag controls whether to start printing lines.
from_header_seen = False
# By default, splitlines() don't include line breaks. CRLF should be gone.
for line in content.splitlines():
# Wait till we scan the 'From: ' header before start printing the
# lines.
if not from_header_seen:
if not line.startswith('From: '):
continue
else:
from_header_seen = True
print >> new_content, line
with open(file, 'w') as f_out:
f_out.write(new_content.getvalue())
print "done" | [
"def",
"do_convert",
"(",
"file",
")",
":",
"print",
"\"converting %s ...\"",
"%",
"file",
"with",
"open",
"(",
"file",
",",
"'r'",
")",
"as",
"f_in",
":",
"content",
"=",
"f_in",
".",
"read",
"(",
")",
"# The new content to be written back to the same file.",
"new_content",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"# Boolean flag controls whether to start printing lines.",
"from_header_seen",
"=",
"False",
"# By default, splitlines() don't include line breaks. CRLF should be gone.",
"for",
"line",
"in",
"content",
".",
"splitlines",
"(",
")",
":",
"# Wait till we scan the 'From: ' header before start printing the",
"# lines.",
"if",
"not",
"from_header_seen",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"'From: '",
")",
":",
"continue",
"else",
":",
"from_header_seen",
"=",
"True",
"print",
">>",
"new_content",
",",
"line",
"with",
"open",
"(",
"file",
",",
"'w'",
")",
"as",
"f_out",
":",
"f_out",
".",
"write",
"(",
"new_content",
".",
"getvalue",
"(",
")",
")",
"print",
"\"done\""
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/utils/git-svn/convert.py#L27-L58 | ||
crosslife/OpenBird | 9e0198a1a2295f03fa1e8676e216e22c9c7d380b | cocos2d/tools/project-creator/module/core.py | python | CocosProject.__processPlatformProjects | (self, platform) | Process each platform project.
Arg:
platform: "ios_mac", "android", "win32", "linux" | Process each platform project.
Arg:
platform: "ios_mac", "android", "win32", "linux" | [
"Process",
"each",
"platform",
"project",
".",
"Arg",
":",
"platform",
":",
"ios_mac",
"android",
"win32",
"linux"
] | def __processPlatformProjects(self, platform):
""" Process each platform project.
Arg:
platform: "ios_mac", "android", "win32", "linux"
"""
# determine proj_path
proj_path = os.path.join(self.context["dst_project_path"], "proj." + platform)
java_package_path = ""
# read json config file for the current platform
conf_path = os.path.join(self.context["script_dir"], "%s.json" % platform)
f = open(conf_path)
data = json.load(f)
# rename package path, like "org.cocos2dx.hello" to "com.company.game". This is a special process for android
if platform == "android":
src_pkg = self.context["src_package_name"].split('.')
dst_pkg = self.context["dst_package_name"].split('.')
java_package_path = os.path.join(*dst_pkg)
# rename files and folders
for item in data["rename"]:
tmp = item.replace("PACKAGE_PATH", java_package_path)
src = tmp.replace("PROJECT_NAME", self.context["src_project_name"])
dst = tmp.replace("PROJECT_NAME", self.context["dst_project_name"])
if os.path.exists(os.path.join(proj_path, src)):
os.rename(os.path.join(proj_path, src), os.path.join(proj_path, dst))
# remove useless files and folders
for item in data["remove"]:
dst = item.replace("PROJECT_NAME", self.context["dst_project_name"])
if os.path.exists(os.path.join(proj_path, dst)):
shutil.rmtree(os.path.join(proj_path, dst))
# rename package_name. This should be replaced at first. Don't change this sequence
for item in data["replace_package_name"]:
tmp = item.replace("PACKAGE_PATH", java_package_path)
dst = tmp.replace("PROJECT_NAME", self.context["dst_project_name"])
if os.path.exists(os.path.join(proj_path, dst)):
replaceString(os.path.join(proj_path, dst), self.context["src_package_name"], self.context["dst_package_name"])
# rename project_name
for item in data["replace_project_name"]:
tmp = item.replace("PACKAGE_PATH", java_package_path)
dst = tmp.replace("PROJECT_NAME", self.context["dst_project_name"])
if os.path.exists(os.path.join(proj_path, dst)):
replaceString(os.path.join(proj_path, dst), self.context["src_project_name"], self.context["dst_project_name"])
# done!
showMsg = "proj.%s\t\t: Done!" % platform
self.step += 1
if self.callbackfun:
self.callbackfun(self.step,self.totalStep,showMsg)
print (showMsg) | [
"def",
"__processPlatformProjects",
"(",
"self",
",",
"platform",
")",
":",
"# determine proj_path",
"proj_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"context",
"[",
"\"dst_project_path\"",
"]",
",",
"\"proj.\"",
"+",
"platform",
")",
"java_package_path",
"=",
"\"\"",
"# read json config file for the current platform",
"conf_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"context",
"[",
"\"script_dir\"",
"]",
",",
"\"%s.json\"",
"%",
"platform",
")",
"f",
"=",
"open",
"(",
"conf_path",
")",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"# rename package path, like \"org.cocos2dx.hello\" to \"com.company.game\". This is a special process for android",
"if",
"platform",
"==",
"\"android\"",
":",
"src_pkg",
"=",
"self",
".",
"context",
"[",
"\"src_package_name\"",
"]",
".",
"split",
"(",
"'.'",
")",
"dst_pkg",
"=",
"self",
".",
"context",
"[",
"\"dst_package_name\"",
"]",
".",
"split",
"(",
"'.'",
")",
"java_package_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"dst_pkg",
")",
"# rename files and folders",
"for",
"item",
"in",
"data",
"[",
"\"rename\"",
"]",
":",
"tmp",
"=",
"item",
".",
"replace",
"(",
"\"PACKAGE_PATH\"",
",",
"java_package_path",
")",
"src",
"=",
"tmp",
".",
"replace",
"(",
"\"PROJECT_NAME\"",
",",
"self",
".",
"context",
"[",
"\"src_project_name\"",
"]",
")",
"dst",
"=",
"tmp",
".",
"replace",
"(",
"\"PROJECT_NAME\"",
",",
"self",
".",
"context",
"[",
"\"dst_project_name\"",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"proj_path",
",",
"src",
")",
")",
":",
"os",
".",
"rename",
"(",
"os",
".",
"path",
".",
"join",
"(",
"proj_path",
",",
"src",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"proj_path",
",",
"dst",
")",
")",
"# remove useless files and folders",
"for",
"item",
"in",
"data",
"[",
"\"remove\"",
"]",
":",
"dst",
"=",
"item",
".",
"replace",
"(",
"\"PROJECT_NAME\"",
",",
"self",
".",
"context",
"[",
"\"dst_project_name\"",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"proj_path",
",",
"dst",
")",
")",
":",
"shutil",
".",
"rmtree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"proj_path",
",",
"dst",
")",
")",
"# rename package_name. This should be replaced at first. Don't change this sequence",
"for",
"item",
"in",
"data",
"[",
"\"replace_package_name\"",
"]",
":",
"tmp",
"=",
"item",
".",
"replace",
"(",
"\"PACKAGE_PATH\"",
",",
"java_package_path",
")",
"dst",
"=",
"tmp",
".",
"replace",
"(",
"\"PROJECT_NAME\"",
",",
"self",
".",
"context",
"[",
"\"dst_project_name\"",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"proj_path",
",",
"dst",
")",
")",
":",
"replaceString",
"(",
"os",
".",
"path",
".",
"join",
"(",
"proj_path",
",",
"dst",
")",
",",
"self",
".",
"context",
"[",
"\"src_package_name\"",
"]",
",",
"self",
".",
"context",
"[",
"\"dst_package_name\"",
"]",
")",
"# rename project_name",
"for",
"item",
"in",
"data",
"[",
"\"replace_project_name\"",
"]",
":",
"tmp",
"=",
"item",
".",
"replace",
"(",
"\"PACKAGE_PATH\"",
",",
"java_package_path",
")",
"dst",
"=",
"tmp",
".",
"replace",
"(",
"\"PROJECT_NAME\"",
",",
"self",
".",
"context",
"[",
"\"dst_project_name\"",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"proj_path",
",",
"dst",
")",
")",
":",
"replaceString",
"(",
"os",
".",
"path",
".",
"join",
"(",
"proj_path",
",",
"dst",
")",
",",
"self",
".",
"context",
"[",
"\"src_project_name\"",
"]",
",",
"self",
".",
"context",
"[",
"\"dst_project_name\"",
"]",
")",
"# done!",
"showMsg",
"=",
"\"proj.%s\\t\\t: Done!\"",
"%",
"platform",
"self",
".",
"step",
"+=",
"1",
"if",
"self",
".",
"callbackfun",
":",
"self",
".",
"callbackfun",
"(",
"self",
".",
"step",
",",
"self",
".",
"totalStep",
",",
"showMsg",
")",
"print",
"(",
"showMsg",
")"
] | https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/project-creator/module/core.py#L214-L269 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ribbon/buttonbar.py | python | RibbonButtonBarEvent.GetBar | (self) | return self._bar | Returns the bar which contains the button which the event relates to.
:returns: An instance of :class:`RibbonButtonBar`. | Returns the bar which contains the button which the event relates to. | [
"Returns",
"the",
"bar",
"which",
"contains",
"the",
"button",
"which",
"the",
"event",
"relates",
"to",
"."
] | def GetBar(self):
"""
Returns the bar which contains the button which the event relates to.
:returns: An instance of :class:`RibbonButtonBar`.
"""
return self._bar | [
"def",
"GetBar",
"(",
"self",
")",
":",
"return",
"self",
".",
"_bar"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ribbon/buttonbar.py#L170-L177 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/grid.py | python | GridEvent.__init__ | (self, *args, **kwargs) | __init__(self, int id, EventType type, Object obj, int row=-1, int col=-1,
int x=-1, int y=-1, bool sel=True, bool control=False,
bool shift=False, bool alt=False,
bool meta=False) -> GridEvent | __init__(self, int id, EventType type, Object obj, int row=-1, int col=-1,
int x=-1, int y=-1, bool sel=True, bool control=False,
bool shift=False, bool alt=False,
bool meta=False) -> GridEvent | [
"__init__",
"(",
"self",
"int",
"id",
"EventType",
"type",
"Object",
"obj",
"int",
"row",
"=",
"-",
"1",
"int",
"col",
"=",
"-",
"1",
"int",
"x",
"=",
"-",
"1",
"int",
"y",
"=",
"-",
"1",
"bool",
"sel",
"=",
"True",
"bool",
"control",
"=",
"False",
"bool",
"shift",
"=",
"False",
"bool",
"alt",
"=",
"False",
"bool",
"meta",
"=",
"False",
")",
"-",
">",
"GridEvent"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, int id, EventType type, Object obj, int row=-1, int col=-1,
int x=-1, int y=-1, bool sel=True, bool control=False,
bool shift=False, bool alt=False,
bool meta=False) -> GridEvent
"""
_grid.GridEvent_swiginit(self,_grid.new_GridEvent(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_grid",
".",
"GridEvent_swiginit",
"(",
"self",
",",
"_grid",
".",
"new_GridEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L2297-L2304 | ||
linyouhappy/kongkongxiyou | 7a69b2913eb29f4be77f9a62fb90cdd72c4160f1 | cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | Cursor.get_children_array | (self) | return children | Return an iterator for accessing the children of this cursor. | Return an iterator for accessing the children of this cursor. | [
"Return",
"an",
"iterator",
"for",
"accessing",
"the",
"children",
"of",
"this",
"cursor",
"."
] | def get_children_array(self):
"""Return an iterator for accessing the children of this cursor."""
# FIXME: Expose iteration from CIndex, PR6125.
def visitor(child, parent, children):
# FIXME: Document this assertion in API.
# FIXME: There should just be an isNull method.
assert child != conf.lib.clang_getNullCursor()
# Create reference to TU so it isn't GC'd before Cursor.
child._tu = self._tu
children.append(child)
return 1 # continue
children = []
conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
children)
return children | [
"def",
"get_children_array",
"(",
"self",
")",
":",
"# FIXME: Expose iteration from CIndex, PR6125.",
"def",
"visitor",
"(",
"child",
",",
"parent",
",",
"children",
")",
":",
"# FIXME: Document this assertion in API.",
"# FIXME: There should just be an isNull method.",
"assert",
"child",
"!=",
"conf",
".",
"lib",
".",
"clang_getNullCursor",
"(",
")",
"# Create reference to TU so it isn't GC'd before Cursor.",
"child",
".",
"_tu",
"=",
"self",
".",
"_tu",
"children",
".",
"append",
"(",
"child",
")",
"return",
"1",
"# continue",
"children",
"=",
"[",
"]",
"conf",
".",
"lib",
".",
"clang_visitChildren",
"(",
"self",
",",
"callbacks",
"[",
"'cursor_visit'",
"]",
"(",
"visitor",
")",
",",
"children",
")",
"return",
"children"
] | https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1461-L1477 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py | python | BufferingFormatter.formatFooter | (self, records) | return "" | Return the footer string for the specified records. | Return the footer string for the specified records. | [
"Return",
"the",
"footer",
"string",
"for",
"the",
"specified",
"records",
"."
] | def formatFooter(self, records):
"""
Return the footer string for the specified records.
"""
return "" | [
"def",
"formatFooter",
"(",
"self",
",",
"records",
")",
":",
"return",
"\"\""
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py#L514-L518 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/lib/debug_events_writer.py | python | DebugEventsWriter.Close | (self) | Close the writer. | Close the writer. | [
"Close",
"the",
"writer",
"."
] | def Close(self):
"""Close the writer."""
_pywrap_debug_events_writer.Close(self._dump_root) | [
"def",
"Close",
"(",
"self",
")",
":",
"_pywrap_debug_events_writer",
".",
"Close",
"(",
"self",
".",
"_dump_root",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/debug_events_writer.py#L148-L150 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/layers/python/layers/summaries.py | python | _add_histogram_summary | (tensor, tag=None) | return summary.histogram(tag, tensor) | Add a summary operation for the histogram of a tensor.
Args:
tensor: The tensor to summarize.
tag: The tag to use, if None then use tensor's op's name.
Returns:
The created histogram summary.
Raises:
ValueError: If the tag is already in use. | Add a summary operation for the histogram of a tensor. | [
"Add",
"a",
"summary",
"operation",
"for",
"the",
"histogram",
"of",
"a",
"tensor",
"."
] | def _add_histogram_summary(tensor, tag=None):
"""Add a summary operation for the histogram of a tensor.
Args:
tensor: The tensor to summarize.
tag: The tag to use, if None then use tensor's op's name.
Returns:
The created histogram summary.
Raises:
ValueError: If the tag is already in use.
"""
tag = tag or '%s_summary' % tensor.op.name
return summary.histogram(tag, tensor) | [
"def",
"_add_histogram_summary",
"(",
"tensor",
",",
"tag",
"=",
"None",
")",
":",
"tag",
"=",
"tag",
"or",
"'%s_summary'",
"%",
"tensor",
".",
"op",
".",
"name",
"return",
"summary",
".",
"histogram",
"(",
"tag",
",",
"tensor",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/layers/python/layers/summaries.py#L61-L75 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cgi.py | python | dolog | (fmt, *args) | Write a log message to the log file. See initlog() for docs. | Write a log message to the log file. See initlog() for docs. | [
"Write",
"a",
"log",
"message",
"to",
"the",
"log",
"file",
".",
"See",
"initlog",
"()",
"for",
"docs",
"."
] | def dolog(fmt, *args):
"""Write a log message to the log file. See initlog() for docs."""
logfp.write(fmt%args + "\n") | [
"def",
"dolog",
"(",
"fmt",
",",
"*",
"args",
")",
":",
"logfp",
".",
"write",
"(",
"fmt",
"%",
"args",
"+",
"\"\\n\"",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cgi.py#L106-L108 | ||
limbo018/DREAMPlace | 146c3b9fd003d1acd52c96d9fd02e3f0a05154e4 | dreamplace/PlaceObj.py | python | PlaceObj.build_precondition | (self, params, placedb, data_collections) | return PreconditionOp(placedb, data_collections) | @brief preconditioning to gradient
@param params parameters
@param placedb placement database
@param data_collections a collection of data and variables required for constructing ops | [] | def build_precondition(self, params, placedb, data_collections):
"""
@brief preconditioning to gradient
@param params parameters
@param placedb placement database
@param data_collections a collection of data and variables required for constructing ops
"""
return PreconditionOp(placedb, data_collections) | [
"def",
"build_precondition",
"(",
"self",
",",
"params",
",",
"placedb",
",",
"data_collections",
")",
":",
"return",
"PreconditionOp",
"(",
"placedb",
",",
"data_collections",
")"
] | https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/PlaceObj.py#L924-L932 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/io_ops.py | python | _ReadFileShape | (op) | return [op.inputs[0].get_shape().merge_with(tensor_shape.scalar())] | Shape function for the ReadFile op. | Shape function for the ReadFile op. | [
"Shape",
"function",
"for",
"the",
"ReadFile",
"op",
"."
] | def _ReadFileShape(op):
"""Shape function for the ReadFile op."""
return [op.inputs[0].get_shape().merge_with(tensor_shape.scalar())] | [
"def",
"_ReadFileShape",
"(",
"op",
")",
":",
"return",
"[",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"scalar",
"(",
")",
")",
"]"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/io_ops.py#L622-L624 | |
tinyobjloader/tinyobjloader | 8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93 | deps/cpplint.py | python | IsCppString | (line) | return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant. | Does line terminate so, that the next symbol is in string constant. | [
"Does",
"line",
"terminate",
"so",
"that",
"the",
"next",
"symbol",
"is",
"in",
"string",
"constant",
"."
] | def IsCppString(line):
"""Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant.
"""
line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | [
"def",
"IsCppString",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"r'\\\\'",
",",
"'XX'",
")",
"# after this, \\\\\" does not match to \\\"",
"return",
"(",
"(",
"line",
".",
"count",
"(",
"'\"'",
")",
"-",
"line",
".",
"count",
"(",
"r'\\\"'",
")",
"-",
"line",
".",
"count",
"(",
"\"'\\\"'\"",
")",
")",
"&",
"1",
")",
"==",
"1"
] | https://github.com/tinyobjloader/tinyobjloader/blob/8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93/deps/cpplint.py#L1147-L1161 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/optim/zero_redundancy_optimizer.py | python | ZeroRedundancyOptimizer._get_assigned_rank | (self, bucket_index: int) | return bucket_index % self.world_size | r"""
Returns the single rank assigned to a :class:`DistributedDataParallel`
gradient bucket.
Arguments:
bucket_index (int): index of the :class:`DistributedDataParallel`
bucket for which to get the assigned rank. | r"""
Returns the single rank assigned to a :class:`DistributedDataParallel`
gradient bucket. | [
"r",
"Returns",
"the",
"single",
"rank",
"assigned",
"to",
"a",
":",
"class",
":",
"DistributedDataParallel",
"gradient",
"bucket",
"."
] | def _get_assigned_rank(self, bucket_index: int) -> int:
r"""
Returns the single rank assigned to a :class:`DistributedDataParallel`
gradient bucket.
Arguments:
bucket_index (int): index of the :class:`DistributedDataParallel`
bucket for which to get the assigned rank.
"""
assert not self._overlap_info.shard_buckets, \
"The bucket assignment requires global bucket information and " \
"will be computed later; there should be no need to use this " \
"method"
return bucket_index % self.world_size | [
"def",
"_get_assigned_rank",
"(",
"self",
",",
"bucket_index",
":",
"int",
")",
"->",
"int",
":",
"assert",
"not",
"self",
".",
"_overlap_info",
".",
"shard_buckets",
",",
"\"The bucket assignment requires global bucket information and \"",
"\"will be computed later; there should be no need to use this \"",
"\"method\"",
"return",
"bucket_index",
"%",
"self",
".",
"world_size"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/optim/zero_redundancy_optimizer.py#L1428-L1441 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/graph_editor/util.py | python | is_iterable | (obj) | return True | Return true if the object is iterable. | Return true if the object is iterable. | [
"Return",
"true",
"if",
"the",
"object",
"is",
"iterable",
"."
] | def is_iterable(obj):
"""Return true if the object is iterable."""
try:
_ = iter(obj)
except Exception: # pylint: disable=broad-except
return False
return True | [
"def",
"is_iterable",
"(",
"obj",
")",
":",
"try",
":",
"_",
"=",
"iter",
"(",
"obj",
")",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"return",
"False",
"return",
"True"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/graph_editor/util.py#L63-L69 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | .github/github_org_control/check_pr.py | python | get_category_labels | (pull) | return labels | Gets list of category labels by all PR reviwer teams | Gets list of category labels by all PR reviwer teams | [
"Gets",
"list",
"of",
"category",
"labels",
"by",
"all",
"PR",
"reviwer",
"teams"
] | def get_category_labels(pull):
"""Gets list of category labels by all PR reviwer teams"""
labels = []
pr_lables = get_pr_labels(pull)
for reviewer_team in pull.get_review_requests()[1]:
reviewer_label = get_label_by_team_name_map(reviewer_team.name)
if reviewer_label and reviewer_label not in pr_lables:
labels.append(reviewer_label)
return labels | [
"def",
"get_category_labels",
"(",
"pull",
")",
":",
"labels",
"=",
"[",
"]",
"pr_lables",
"=",
"get_pr_labels",
"(",
"pull",
")",
"for",
"reviewer_team",
"in",
"pull",
".",
"get_review_requests",
"(",
")",
"[",
"1",
"]",
":",
"reviewer_label",
"=",
"get_label_by_team_name_map",
"(",
"reviewer_team",
".",
"name",
")",
"if",
"reviewer_label",
"and",
"reviewer_label",
"not",
"in",
"pr_lables",
":",
"labels",
".",
"append",
"(",
"reviewer_label",
")",
"return",
"labels"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/.github/github_org_control/check_pr.py#L86-L94 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/groupby/groupby.py | python | _GroupBy.get_group | (self, name, obj=None) | return obj._take(inds, axis=self.axis) | Constructs NDFrame from group with provided name.
Parameters
----------
name : object
the name of the group to get as a DataFrame
obj : NDFrame, default None
the NDFrame to take the DataFrame out of. If
it is None, the object groupby was called on will
be used
Returns
-------
group : same type as obj | Constructs NDFrame from group with provided name. | [
"Constructs",
"NDFrame",
"from",
"group",
"with",
"provided",
"name",
"."
] | def get_group(self, name, obj=None):
"""
Constructs NDFrame from group with provided name.
Parameters
----------
name : object
the name of the group to get as a DataFrame
obj : NDFrame, default None
the NDFrame to take the DataFrame out of. If
it is None, the object groupby was called on will
be used
Returns
-------
group : same type as obj
"""
if obj is None:
obj = self._selected_obj
inds = self._get_index(name)
if not len(inds):
raise KeyError(name)
return obj._take(inds, axis=self.axis) | [
"def",
"get_group",
"(",
"self",
",",
"name",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"None",
":",
"obj",
"=",
"self",
".",
"_selected_obj",
"inds",
"=",
"self",
".",
"_get_index",
"(",
"name",
")",
"if",
"not",
"len",
"(",
"inds",
")",
":",
"raise",
"KeyError",
"(",
"name",
")",
"return",
"obj",
".",
"_take",
"(",
"inds",
",",
"axis",
"=",
"self",
".",
"axis",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/groupby/groupby.py#L626-L650 | |
unicode-org/icu | 2f8749a026f3ddc8cf54d4622480b7c543bb7fc0 | icu4c/source/python/icutools/databuilder/filtration.py | python | UnionFilter.match | (self, file) | return False | Match iff any of the sub-filters match. | Match iff any of the sub-filters match. | [
"Match",
"iff",
"any",
"of",
"the",
"sub",
"-",
"filters",
"match",
"."
] | def match(self, file):
"""Match iff any of the sub-filters match."""
for filter in self.sub_filters:
if filter.match(file):
return True
return False | [
"def",
"match",
"(",
"self",
",",
"file",
")",
":",
"for",
"filter",
"in",
"self",
".",
"sub_filters",
":",
"if",
"filter",
".",
"match",
"(",
"file",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/unicode-org/icu/blob/2f8749a026f3ddc8cf54d4622480b7c543bb7fc0/icu4c/source/python/icutools/databuilder/filtration.py#L156-L161 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/MSVSToolFile.py | python | Writer.WriteIfChanged | (self) | Writes the tool file. | Writes the tool file. | [
"Writes",
"the",
"tool",
"file",
"."
] | def WriteIfChanged(self):
"""Writes the tool file."""
content = ['VisualStudioToolFile',
{'Version': '8.00',
'Name': self.name
},
self.rules_section
]
easy_xml.WriteXmlIfChanged(content, self.tool_file_path,
encoding="Windows-1252") | [
"def",
"WriteIfChanged",
"(",
"self",
")",
":",
"content",
"=",
"[",
"'VisualStudioToolFile'",
",",
"{",
"'Version'",
":",
"'8.00'",
",",
"'Name'",
":",
"self",
".",
"name",
"}",
",",
"self",
".",
"rules_section",
"]",
"easy_xml",
".",
"WriteXmlIfChanged",
"(",
"content",
",",
"self",
".",
"tool_file_path",
",",
"encoding",
"=",
"\"Windows-1252\"",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/MSVSToolFile.py#L49-L58 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/idl/idl/binder.py | python | _validate_field_of_type_enum | (ctxt, field) | Validate that for fields with a type of enum, no other properties are set. | Validate that for fields with a type of enum, no other properties are set. | [
"Validate",
"that",
"for",
"fields",
"with",
"a",
"type",
"of",
"enum",
"no",
"other",
"properties",
"are",
"set",
"."
] | def _validate_field_of_type_enum(ctxt, field):
# type: (errors.ParserContext, syntax.Field) -> None
"""Validate that for fields with a type of enum, no other properties are set."""
if field.default is not None:
ctxt.add_enum_field_must_be_empty_error(field, field.name, "default") | [
"def",
"_validate_field_of_type_enum",
"(",
"ctxt",
",",
"field",
")",
":",
"# type: (errors.ParserContext, syntax.Field) -> None",
"if",
"field",
".",
"default",
"is",
"not",
"None",
":",
"ctxt",
".",
"add_enum_field_must_be_empty_error",
"(",
"field",
",",
"field",
".",
"name",
",",
"\"default\"",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/binder.py#L353-L357 | ||
alibaba/MNN | c4d9566171d589c3ded23aa18ffb197016995a12 | pymnn/pip_package/MNN/expr/__init__.py | python | sin | (x) | return _F.sin(x) | sin(x)
Return the sin(x), element-wise.
Parameters
----------
x : var_like, input value.
Returns
-------
y : Var. The sin of `x`.
Example:
-------
>>> expr.sin([9., 4.5])
var([0.4121185, -0.9775301]) | sin(x)
Return the sin(x), element-wise. | [
"sin",
"(",
"x",
")",
"Return",
"the",
"sin",
"(",
"x",
")",
"element",
"-",
"wise",
"."
] | def sin(x):
'''
sin(x)
Return the sin(x), element-wise.
Parameters
----------
x : var_like, input value.
Returns
-------
y : Var. The sin of `x`.
Example:
-------
>>> expr.sin([9., 4.5])
var([0.4121185, -0.9775301])
'''
x = _to_var(x)
return _F.sin(x) | [
"def",
"sin",
"(",
"x",
")",
":",
"x",
"=",
"_to_var",
"(",
"x",
")",
"return",
"_F",
".",
"sin",
"(",
"x",
")"
] | https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/expr/__init__.py#L348-L367 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py | python | BufferingFormatter.formatHeader | (self, records) | return "" | Return the header string for the specified records. | Return the header string for the specified records. | [
"Return",
"the",
"header",
"string",
"for",
"the",
"specified",
"records",
"."
] | def formatHeader(self, records):
"""
Return the header string for the specified records.
"""
return "" | [
"def",
"formatHeader",
"(",
"self",
",",
"records",
")",
":",
"return",
"\"\""
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py#L508-L512 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/distributed/StagedObject.py | python | StagedObject.goOffStage | (self, *args, **kw) | If a stage switch is needed, the correct "handle" function
will be called. Otherwise, nothing happens. | If a stage switch is needed, the correct "handle" function
will be called. Otherwise, nothing happens. | [
"If",
"a",
"stage",
"switch",
"is",
"needed",
"the",
"correct",
"handle",
"function",
"will",
"be",
"called",
".",
"Otherwise",
"nothing",
"happens",
"."
] | def goOffStage(self, *args, **kw):
"""
If a stage switch is needed, the correct "handle" function
will be called. Otherwise, nothing happens.
"""
# This is the high level function that clients of
# your class should call to set the on/off stage state.
if not self.isOffStage():
self.handleOffStage(*args, **kw) | [
"def",
"goOffStage",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# This is the high level function that clients of",
"# your class should call to set the on/off stage state.",
"if",
"not",
"self",
".",
"isOffStage",
"(",
")",
":",
"self",
".",
"handleOffStage",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/distributed/StagedObject.py#L40-L49 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/alerts.py | python | _GetBisectStatusDict | (anomalies) | return {b.key.id(): b.latest_bisect_status for b in bugs if b} | Returns a dictionary of bug ID to bisect status string. | Returns a dictionary of bug ID to bisect status string. | [
"Returns",
"a",
"dictionary",
"of",
"bug",
"ID",
"to",
"bisect",
"status",
"string",
"."
] | def _GetBisectStatusDict(anomalies):
"""Returns a dictionary of bug ID to bisect status string."""
bug_id_list = {a.bug_id for a in anomalies if a.bug_id > 0}
bugs = ndb.get_multi(ndb.Key('Bug', b) for b in bug_id_list)
return {b.key.id(): b.latest_bisect_status for b in bugs if b} | [
"def",
"_GetBisectStatusDict",
"(",
"anomalies",
")",
":",
"bug_id_list",
"=",
"{",
"a",
".",
"bug_id",
"for",
"a",
"in",
"anomalies",
"if",
"a",
".",
"bug_id",
">",
"0",
"}",
"bugs",
"=",
"ndb",
".",
"get_multi",
"(",
"ndb",
".",
"Key",
"(",
"'Bug'",
",",
"b",
")",
"for",
"b",
"in",
"bug_id_list",
")",
"return",
"{",
"b",
".",
"key",
".",
"id",
"(",
")",
":",
"b",
".",
"latest_bisect_status",
"for",
"b",
"in",
"bugs",
"if",
"b",
"}"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/alerts.py#L203-L207 | |
su2code/SU2 | 72b2fa977b64b9683a388920f05298a40d39e5c5 | SU2_PY/SU2/run/interface.py | python | run_command | ( Command ) | return return_code | runs os command with subprocess
checks for errors from command | runs os command with subprocess
checks for errors from command | [
"runs",
"os",
"command",
"with",
"subprocess",
"checks",
"for",
"errors",
"from",
"command"
] | def run_command( Command ):
""" runs os command with subprocess
checks for errors from command
"""
sys.stdout.flush()
proc = subprocess.Popen( Command, shell=True ,
stdout=sys.stdout ,
stderr=subprocess.PIPE )
return_code = proc.wait()
message = proc.stderr.read().decode()
if return_code < 0:
message = "SU2 process was terminated by signal '%s'\n%s" % (-return_code,message)
raise SystemExit(message)
elif return_code > 0:
message = "Path = %s\nCommand = %s\nSU2 process returned error '%s'\n%s" % (os.path.abspath(','),Command,return_code,message)
if return_code in return_code_map.keys():
exception = return_code_map[return_code]
else:
exception = RuntimeError
raise exception(message)
else:
sys.stdout.write(message)
return return_code | [
"def",
"run_command",
"(",
"Command",
")",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"Command",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"sys",
".",
"stdout",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"return_code",
"=",
"proc",
".",
"wait",
"(",
")",
"message",
"=",
"proc",
".",
"stderr",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
"if",
"return_code",
"<",
"0",
":",
"message",
"=",
"\"SU2 process was terminated by signal '%s'\\n%s\"",
"%",
"(",
"-",
"return_code",
",",
"message",
")",
"raise",
"SystemExit",
"(",
"message",
")",
"elif",
"return_code",
">",
"0",
":",
"message",
"=",
"\"Path = %s\\nCommand = %s\\nSU2 process returned error '%s'\\n%s\"",
"%",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"','",
")",
",",
"Command",
",",
"return_code",
",",
"message",
")",
"if",
"return_code",
"in",
"return_code_map",
".",
"keys",
"(",
")",
":",
"exception",
"=",
"return_code_map",
"[",
"return_code",
"]",
"else",
":",
"exception",
"=",
"RuntimeError",
"raise",
"exception",
"(",
"message",
")",
"else",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"message",
")",
"return",
"return_code"
] | https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/SU2/run/interface.py#L248-L274 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/find-original-array-from-doubled-array.py | python | Solution.findOriginalArray | (self, changed) | return list(cnts.elements()) | :type changed: List[int]
:rtype: List[int] | :type changed: List[int]
:rtype: List[int] | [
":",
"type",
"changed",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def findOriginalArray(self, changed):
"""
:type changed: List[int]
:rtype: List[int]
"""
if len(changed)%2:
return []
cnts = collections.Counter(changed)
for x in sorted(cnts.iterkeys()):
if cnts[x] > cnts[2*x]:
return []
cnts[2*x] -= cnts[x] if x else cnts[x]//2
return list(cnts.elements()) | [
"def",
"findOriginalArray",
"(",
"self",
",",
"changed",
")",
":",
"if",
"len",
"(",
"changed",
")",
"%",
"2",
":",
"return",
"[",
"]",
"cnts",
"=",
"collections",
".",
"Counter",
"(",
"changed",
")",
"for",
"x",
"in",
"sorted",
"(",
"cnts",
".",
"iterkeys",
"(",
")",
")",
":",
"if",
"cnts",
"[",
"x",
"]",
">",
"cnts",
"[",
"2",
"*",
"x",
"]",
":",
"return",
"[",
"]",
"cnts",
"[",
"2",
"*",
"x",
"]",
"-=",
"cnts",
"[",
"x",
"]",
"if",
"x",
"else",
"cnts",
"[",
"x",
"]",
"//",
"2",
"return",
"list",
"(",
"cnts",
".",
"elements",
"(",
")",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/find-original-array-from-doubled-array.py#L5-L17 | |
Cisco-Talos/moflow | ed71dfb0540d9e0d7a4c72f0881b58958d573728 | BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/mox.py | python | IsA.__init__ | (self, class_name) | Initialize IsA
Args:
class_name: basic python type or a class | Initialize IsA | [
"Initialize",
"IsA"
] | def __init__(self, class_name):
"""Initialize IsA
Args:
class_name: basic python type or a class
"""
self._class_name = class_name | [
"def",
"__init__",
"(",
"self",
",",
"class_name",
")",
":",
"self",
".",
"_class_name",
"=",
"class_name"
] | https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/mox.py#L798-L805 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | driver/python/bson/code.py | python | Code.scope | (self) | return self.__scope | Scope dictionary for this instance. | Scope dictionary for this instance. | [
"Scope",
"dictionary",
"for",
"this",
"instance",
"."
] | def scope(self):
"""Scope dictionary for this instance.
"""
return self.__scope | [
"def",
"scope",
"(",
"self",
")",
":",
"return",
"self",
".",
"__scope"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/bson/code.py#L68-L71 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/util/structure.py | python | from_compatible_tensor_list | (element_spec, tensor_list) | return _from_tensor_list_helper(
lambda spec, value: spec._from_compatible_tensor_list(value),
element_spec, tensor_list) | Returns an element constructed from the given spec and tensor list.
Args:
element_spec: A nested structure of `tf.TypeSpec` objects representing to
element type specification.
tensor_list: A list of tensors to use for constructing the value.
Returns:
An element constructed from the given spec and tensor list.
Raises:
ValueError: If the number of tensors needed to construct an element for
the given spec does not match the given number of tensors. | Returns an element constructed from the given spec and tensor list. | [
"Returns",
"an",
"element",
"constructed",
"from",
"the",
"given",
"spec",
"and",
"tensor",
"list",
"."
] | def from_compatible_tensor_list(element_spec, tensor_list):
"""Returns an element constructed from the given spec and tensor list.
Args:
element_spec: A nested structure of `tf.TypeSpec` objects representing to
element type specification.
tensor_list: A list of tensors to use for constructing the value.
Returns:
An element constructed from the given spec and tensor list.
Raises:
ValueError: If the number of tensors needed to construct an element for
the given spec does not match the given number of tensors.
"""
# pylint: disable=protected-access
# pylint: disable=g-long-lambda
return _from_tensor_list_helper(
lambda spec, value: spec._from_compatible_tensor_list(value),
element_spec, tensor_list) | [
"def",
"from_compatible_tensor_list",
"(",
"element_spec",
",",
"tensor_list",
")",
":",
"# pylint: disable=protected-access",
"# pylint: disable=g-long-lambda",
"return",
"_from_tensor_list_helper",
"(",
"lambda",
"spec",
",",
"value",
":",
"spec",
".",
"_from_compatible_tensor_list",
"(",
"value",
")",
",",
"element_spec",
",",
"tensor_list",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/util/structure.py#L206-L226 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/command/build_py.py | python | build_py.find_data_files | (self, package, src_dir) | return files | Return filenames for package's data files in 'src_dir | Return filenames for package's data files in 'src_dir | [
"Return",
"filenames",
"for",
"package",
"s",
"data",
"files",
"in",
"src_dir"
] | def find_data_files(self, package, src_dir):
"""Return filenames for package's data files in 'src_dir'"""
globs = (self.package_data.get('', [])
+ self.package_data.get(package, []))
files = []
for pattern in globs:
# Each pattern has to be converted to a platform-specific path
filelist = glob(os.path.join(src_dir, convert_path(pattern)))
# Files that match more than one pattern are only added once
files.extend([fn for fn in filelist if fn not in files])
return files | [
"def",
"find_data_files",
"(",
"self",
",",
"package",
",",
"src_dir",
")",
":",
"globs",
"=",
"(",
"self",
".",
"package_data",
".",
"get",
"(",
"''",
",",
"[",
"]",
")",
"+",
"self",
".",
"package_data",
".",
"get",
"(",
"package",
",",
"[",
"]",
")",
")",
"files",
"=",
"[",
"]",
"for",
"pattern",
"in",
"globs",
":",
"# Each pattern has to be converted to a platform-specific path",
"filelist",
"=",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"src_dir",
",",
"convert_path",
"(",
"pattern",
")",
")",
")",
"# Files that match more than one pattern are only added once",
"files",
".",
"extend",
"(",
"[",
"fn",
"for",
"fn",
"in",
"filelist",
"if",
"fn",
"not",
"in",
"files",
"]",
")",
"return",
"files"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/command/build_py.py#L122-L132 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TNEANetAStrI.__init__ | (self, *args) | __init__(TNEANetAStrI self) -> TNEANetAStrI
__init__(TNEANetAStrI self, TStrVecIter const & HIter, TStr attribute, bool isEdgeIter, TNEANet GraphPt) -> TNEANetAStrI
Parameters:
HIter: TStrVecIter const &
attribute: TStr
isEdgeIter: bool
GraphPt: TNEANet const *
__init__(TNEANetAStrI self, TNEANet::TAStrI const & I) -> TNEANetAStrI
Parameters:
I: TNEANet::TAStrI const & | __init__(TNEANetAStrI self) -> TNEANetAStrI
__init__(TNEANetAStrI self, TStrVecIter const & HIter, TStr attribute, bool isEdgeIter, TNEANet GraphPt) -> TNEANetAStrI | [
"__init__",
"(",
"TNEANetAStrI",
"self",
")",
"-",
">",
"TNEANetAStrI",
"__init__",
"(",
"TNEANetAStrI",
"self",
"TStrVecIter",
"const",
"&",
"HIter",
"TStr",
"attribute",
"bool",
"isEdgeIter",
"TNEANet",
"GraphPt",
")",
"-",
">",
"TNEANetAStrI"
] | def __init__(self, *args):
"""
__init__(TNEANetAStrI self) -> TNEANetAStrI
__init__(TNEANetAStrI self, TStrVecIter const & HIter, TStr attribute, bool isEdgeIter, TNEANet GraphPt) -> TNEANetAStrI
Parameters:
HIter: TStrVecIter const &
attribute: TStr
isEdgeIter: bool
GraphPt: TNEANet const *
__init__(TNEANetAStrI self, TNEANet::TAStrI const & I) -> TNEANetAStrI
Parameters:
I: TNEANet::TAStrI const &
"""
_snap.TNEANetAStrI_swiginit(self,_snap.new_TNEANetAStrI(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_snap",
".",
"TNEANetAStrI_swiginit",
"(",
"self",
",",
"_snap",
".",
"new_TNEANetAStrI",
"(",
"*",
"args",
")",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L21044-L21061 | ||
xiaohaoChen/rrc_detection | 4f2b110cd122da7f55e8533275a9b4809a88785a | scripts/cpp_lint.py | python | CheckForMultilineCommentsAndStrings | (filename, clean_lines, linenum, error) | Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
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. | Logs an error if we see /* ... */ or "..." that extend past one line. | [
"Logs",
"an",
"error",
"if",
"we",
"see",
"/",
"*",
"...",
"*",
"/",
"or",
"...",
"that",
"extend",
"past",
"one",
"line",
"."
] | def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
"""Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
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]
# Remove all \\ (escaped backslashes) from the line. They are OK, and the
# second (escaped) slash may trigger later \" detection erroneously.
line = line.replace('\\\\', '')
if line.count('/*') > line.count('*/'):
error(filename, linenum, 'readability/multiline_comment', 5,
'Complex multi-line /*...*/-style comment found. '
'Lint may give bogus warnings. '
'Consider replacing these with //-style comments, '
'with #if 0...#endif, '
'or with more clearly structured multi-line comments.')
if (line.count('"') - line.count('\\"')) % 2:
error(filename, linenum, 'readability/multiline_string', 5,
'Multi-line string ("...") found. This lint script doesn\'t '
'do well with such strings, and may give bogus warnings. '
'Use C++11 raw strings or concatenation instead.') | [
"def",
"CheckForMultilineCommentsAndStrings",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the",
"# second (escaped) slash may trigger later \\\" detection erroneously.",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"''",
")",
"if",
"line",
".",
"count",
"(",
"'/*'",
")",
">",
"line",
".",
"count",
"(",
"'*/'",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/multiline_comment'",
",",
"5",
",",
"'Complex multi-line /*...*/-style comment found. '",
"'Lint may give bogus warnings. '",
"'Consider replacing these with //-style comments, '",
"'with #if 0...#endif, '",
"'or with more clearly structured multi-line comments.'",
")",
"if",
"(",
"line",
".",
"count",
"(",
"'\"'",
")",
"-",
"line",
".",
"count",
"(",
"'\\\\\"'",
")",
")",
"%",
"2",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/multiline_string'",
",",
"5",
",",
"'Multi-line string (\"...\") found. This lint script doesn\\'t '",
"'do well with such strings, and may give bogus warnings. '",
"'Use C++11 raw strings or concatenation instead.'",
")"
] | https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/scripts/cpp_lint.py#L1526-L1561 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py | python | PlatformDetail.get_configuration | (self, configuration_name) | Lookup a specific platform configuration detail based on a configuration name
:param configuration_name: The configuration name to lookup
:return: The configuration details for a particular configuration name for this platform
:exception Errors.WafError: | Lookup a specific platform configuration detail based on a configuration name
:param configuration_name: The configuration name to lookup
:return: The configuration details for a particular configuration name for this platform
:exception Errors.WafError: | [
"Lookup",
"a",
"specific",
"platform",
"configuration",
"detail",
"based",
"on",
"a",
"configuration",
"name",
":",
"param",
"configuration_name",
":",
"The",
"configuration",
"name",
"to",
"lookup",
":",
"return",
":",
"The",
"configuration",
"details",
"for",
"a",
"particular",
"configuration",
"name",
"for",
"this",
"platform",
":",
"exception",
"Errors",
".",
"WafError",
":"
] | def get_configuration(self, configuration_name):
"""
Lookup a specific platform configuration detail based on a configuration name
:param configuration_name: The configuration name to lookup
:return: The configuration details for a particular configuration name for this platform
:exception Errors.WafError:
"""
try:
return self.platform_configs[configuration_name]
except KeyError:
raise Errors.WafError("Invalid configuration '{}' for platform '{}'".format(configuration_name, self.platform)) | [
"def",
"get_configuration",
"(",
"self",
",",
"configuration_name",
")",
":",
"try",
":",
"return",
"self",
".",
"platform_configs",
"[",
"configuration_name",
"]",
"except",
"KeyError",
":",
"raise",
"Errors",
".",
"WafError",
"(",
"\"Invalid configuration '{}' for platform '{}'\"",
".",
"format",
"(",
"configuration_name",
",",
"self",
".",
"platform",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py#L265-L275 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/tasks.py | python | Task.current_task | (cls, loop=None) | return current_task(loop) | Return the currently running task in an event loop or None.
By default the current task for the current event loop is returned.
None is returned when called not in the context of a Task. | Return the currently running task in an event loop or None. | [
"Return",
"the",
"currently",
"running",
"task",
"in",
"an",
"event",
"loop",
"or",
"None",
"."
] | def current_task(cls, loop=None):
"""Return the currently running task in an event loop or None.
By default the current task for the current event loop is returned.
None is returned when called not in the context of a Task.
"""
warnings.warn("Task.current_task() is deprecated, "
"use asyncio.current_task() instead",
PendingDeprecationWarning,
stacklevel=2)
if loop is None:
loop = events.get_event_loop()
return current_task(loop) | [
"def",
"current_task",
"(",
"cls",
",",
"loop",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Task.current_task() is deprecated, \"",
"\"use asyncio.current_task() instead\"",
",",
"PendingDeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"loop",
"is",
"None",
":",
"loop",
"=",
"events",
".",
"get_event_loop",
"(",
")",
"return",
"current_task",
"(",
"loop",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/tasks.py#L100-L113 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/combinations.py | python | in_main_process | () | return not _running_in_worker | Whether it's in the main test process.
This is normally used to prepare the test environment which should only happen
in the main process.
Returns:
A boolean. | Whether it's in the main test process. | [
"Whether",
"it",
"s",
"in",
"the",
"main",
"test",
"process",
"."
] | def in_main_process():
"""Whether it's in the main test process.
This is normally used to prepare the test environment which should only happen
in the main process.
Returns:
A boolean.
"""
return not _running_in_worker | [
"def",
"in_main_process",
"(",
")",
":",
"return",
"not",
"_running_in_worker"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/combinations.py#L418-L427 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/utils.py | python | verify_flash_from_bin | (bin_filename, backend, offset=0, max_read_chunk=None) | return True | Verify the contents of flash against a bin-file
:param filename: Name/path of bin-file to verify
:param backend: Reference the Backend class of pymcuprog
:param offset: Memory offset to start verify from
:returns: Boolean value indicating success or failure of the operation | Verify the contents of flash against a bin-file | [
"Verify",
"the",
"contents",
"of",
"flash",
"against",
"a",
"bin",
"-",
"file"
] | def verify_flash_from_bin(bin_filename, backend, offset=0, max_read_chunk=None):
"""
Verify the contents of flash against a bin-file
:param filename: Name/path of bin-file to verify
:param backend: Reference the Backend class of pymcuprog
:param offset: Memory offset to start verify from
:returns: Boolean value indicating success or failure of the operation
"""
bin_file = open(bin_filename, 'rb')
bin_data = bytearray()
for line in bin_file.readlines():
bin_data.extend(line)
verify_status = backend.verify_memory(bin_data, 'flash', offset, max_read_chunk=max_read_chunk)
if verify_status is False:
return False
return True | [
"def",
"verify_flash_from_bin",
"(",
"bin_filename",
",",
"backend",
",",
"offset",
"=",
"0",
",",
"max_read_chunk",
"=",
"None",
")",
":",
"bin_file",
"=",
"open",
"(",
"bin_filename",
",",
"'rb'",
")",
"bin_data",
"=",
"bytearray",
"(",
")",
"for",
"line",
"in",
"bin_file",
".",
"readlines",
"(",
")",
":",
"bin_data",
".",
"extend",
"(",
"line",
")",
"verify_status",
"=",
"backend",
".",
"verify_memory",
"(",
"bin_data",
",",
"'flash'",
",",
"offset",
",",
"max_read_chunk",
"=",
"max_read_chunk",
")",
"if",
"verify_status",
"is",
"False",
":",
"return",
"False",
"return",
"True"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/utils.py#L258-L275 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/cookielib.py | python | request_host | (request) | return host.lower() | Return request-host, as defined by RFC 2965.
Variation from RFC: returned value is lowercased, for convenient
comparison. | Return request-host, as defined by RFC 2965. | [
"Return",
"request",
"-",
"host",
"as",
"defined",
"by",
"RFC",
"2965",
"."
] | def request_host(request):
"""Return request-host, as defined by RFC 2965.
Variation from RFC: returned value is lowercased, for convenient
comparison.
"""
url = request.get_full_url()
host = urlparse.urlparse(url)[1]
if host == "":
host = request.get_header("Host", "")
# remove port, if present
host = cut_port_re.sub("", host, 1)
return host.lower() | [
"def",
"request_host",
"(",
"request",
")",
":",
"url",
"=",
"request",
".",
"get_full_url",
"(",
")",
"host",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"[",
"1",
"]",
"if",
"host",
"==",
"\"\"",
":",
"host",
"=",
"request",
".",
"get_header",
"(",
"\"Host\"",
",",
"\"\"",
")",
"# remove port, if present",
"host",
"=",
"cut_port_re",
".",
"sub",
"(",
"\"\"",
",",
"host",
",",
"1",
")",
"return",
"host",
".",
"lower",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/cookielib.py#L598-L612 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | EvtHandler.DeletePendingEvents | (*args, **kwargs) | return _core_.EvtHandler_DeletePendingEvents(*args, **kwargs) | DeletePendingEvents(self) | DeletePendingEvents(self) | [
"DeletePendingEvents",
"(",
"self",
")"
] | def DeletePendingEvents(*args, **kwargs):
"""DeletePendingEvents(self)"""
return _core_.EvtHandler_DeletePendingEvents(*args, **kwargs) | [
"def",
"DeletePendingEvents",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"EvtHandler_DeletePendingEvents",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L4176-L4178 | |
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/jellyfish-2.2.0/swig/python/jellyfish.py | python | ReadMerFile.next | (self) | return _jellyfish.ReadMerFile_next(self) | Iterate through all the mers in the file, passing two values: a mer and its count | Iterate through all the mers in the file, passing two values: a mer and its count | [
"Iterate",
"through",
"all",
"the",
"mers",
"in",
"the",
"file",
"passing",
"two",
"values",
":",
"a",
"mer",
"and",
"its",
"count"
] | def next(self):
"""Iterate through all the mers in the file, passing two values: a mer and its count"""
return _jellyfish.ReadMerFile_next(self) | [
"def",
"next",
"(",
"self",
")",
":",
"return",
"_jellyfish",
".",
"ReadMerFile_next",
"(",
"self",
")"
] | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/jellyfish-2.2.0/swig/python/jellyfish.py#L254-L256 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/support.py | python | set_menu_items_special_chars | (dad) | Set Special Chars menu items | Set Special Chars menu items | [
"Set",
"Special",
"Chars",
"menu",
"items"
] | def set_menu_items_special_chars(dad):
"""Set Special Chars menu items"""
if not "special_menu_1" in dir(dad):
dad.special_menu_1 = gtk.Menu()
first_run = True
else:
children_1 = dad.special_menu_1.get_children()
for children in children_1:
children.destroy()
first_run = False
for special_char in dad.special_chars:
menu_item = gtk.MenuItem(special_char)
menu_item.connect("activate", insert_special_char, special_char, dad)
menu_item.show()
dad.special_menu_1.append(menu_item)
if first_run:
# main menu
special_menuitem = gtk.ImageMenuItem(_("Insert _Special Character"))
special_menuitem.set_image(gtk.image_new_from_stock("insert", gtk.ICON_SIZE_MENU))
special_menuitem.set_tooltip_text(_("Insert a Special Character"))
special_menuitem.set_submenu(dad.special_menu_1)
dad.ui.get_widget("/MenuBar/EditMenu").get_submenu().insert(special_menuitem, 14) | [
"def",
"set_menu_items_special_chars",
"(",
"dad",
")",
":",
"if",
"not",
"\"special_menu_1\"",
"in",
"dir",
"(",
"dad",
")",
":",
"dad",
".",
"special_menu_1",
"=",
"gtk",
".",
"Menu",
"(",
")",
"first_run",
"=",
"True",
"else",
":",
"children_1",
"=",
"dad",
".",
"special_menu_1",
".",
"get_children",
"(",
")",
"for",
"children",
"in",
"children_1",
":",
"children",
".",
"destroy",
"(",
")",
"first_run",
"=",
"False",
"for",
"special_char",
"in",
"dad",
".",
"special_chars",
":",
"menu_item",
"=",
"gtk",
".",
"MenuItem",
"(",
"special_char",
")",
"menu_item",
".",
"connect",
"(",
"\"activate\"",
",",
"insert_special_char",
",",
"special_char",
",",
"dad",
")",
"menu_item",
".",
"show",
"(",
")",
"dad",
".",
"special_menu_1",
".",
"append",
"(",
"menu_item",
")",
"if",
"first_run",
":",
"# main menu",
"special_menuitem",
"=",
"gtk",
".",
"ImageMenuItem",
"(",
"_",
"(",
"\"Insert _Special Character\"",
")",
")",
"special_menuitem",
".",
"set_image",
"(",
"gtk",
".",
"image_new_from_stock",
"(",
"\"insert\"",
",",
"gtk",
".",
"ICON_SIZE_MENU",
")",
")",
"special_menuitem",
".",
"set_tooltip_text",
"(",
"_",
"(",
"\"Insert a Special Character\"",
")",
")",
"special_menuitem",
".",
"set_submenu",
"(",
"dad",
".",
"special_menu_1",
")",
"dad",
".",
"ui",
".",
"get_widget",
"(",
"\"/MenuBar/EditMenu\"",
")",
".",
"get_submenu",
"(",
")",
".",
"insert",
"(",
"special_menuitem",
",",
"14",
")"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/support.py#L1870-L1891 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/affine/binary_operators.py | python | MulExpression.is_decr | (self, idx) | return self.args[1-idx].is_nonpos() | Is the composition non-increasing in argument idx? | Is the composition non-increasing in argument idx? | [
"Is",
"the",
"composition",
"non",
"-",
"increasing",
"in",
"argument",
"idx?"
] | def is_decr(self, idx) -> bool:
"""Is the composition non-increasing in argument idx?
"""
return self.args[1-idx].is_nonpos() | [
"def",
"is_decr",
"(",
"self",
",",
"idx",
")",
"->",
"bool",
":",
"return",
"self",
".",
"args",
"[",
"1",
"-",
"idx",
"]",
".",
"is_nonpos",
"(",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/affine/binary_operators.py#L165-L168 | |
facebookarchive/fb-caffe-exts | 5e95a5df428bf9a769d71a465fb38247846bcf84 | conversions/conversions.py | python | scanning | (conv_prototxt, output_scanning_prototxt) | Add a scanning layer on top of all softmax layers, so we max-pool
the class probabilities over spatial locations. | Add a scanning layer on top of all softmax layers, so we max-pool
the class probabilities over spatial locations. | [
"Add",
"a",
"scanning",
"layer",
"on",
"top",
"of",
"all",
"softmax",
"layers",
"so",
"we",
"max",
"-",
"pool",
"the",
"class",
"probabilities",
"over",
"spatial",
"locations",
"."
] | def scanning(conv_prototxt, output_scanning_prototxt):
"""
Add a scanning layer on top of all softmax layers, so we max-pool
the class probabilities over spatial locations.
"""
conv_params = load_prototxt(conv_prototxt)
def add_scanning(layer):
if layer.type != "Softmax":
return [layer]
scanning_layer = pb2.LayerParameter()
scanning_layer.name = "{}_scanning".format(layer.name)
scanning_layer.bottom.extend(layer.top)
scanning_layer.top.extend([scanning_layer.name])
scanning_layer.type = "Pooling"
scanning_layer.pooling_param.pool = pb2.PoolingParameter.MAX
scanning_layer.pooling_param.global_pooling = True
return [layer, scanning_layer]
scanning_layers = flatmap(add_scanning, conv_params.layer)
scanning_params = pb2.NetParameter()
scanning_params.CopyFrom(conv_params)
del scanning_params.layer[:]
scanning_params.layer.extend(scanning_layers)
scanning_prototxt = tempfile.NamedTemporaryFile(
dir=os.path.dirname(output_scanning_prototxt),
delete=False).name
with open(scanning_prototxt, "w") as f:
f.write(google.protobuf.text_format.MessageToString(scanning_params))
# Verify the net loads with the scanning change.
caffe.Net(str(scanning_prototxt), caffe.TEST)
log.info("Moving: %s to %s", scanning_prototxt, output_scanning_prototxt)
os.rename(scanning_prototxt, output_scanning_prototxt) | [
"def",
"scanning",
"(",
"conv_prototxt",
",",
"output_scanning_prototxt",
")",
":",
"conv_params",
"=",
"load_prototxt",
"(",
"conv_prototxt",
")",
"def",
"add_scanning",
"(",
"layer",
")",
":",
"if",
"layer",
".",
"type",
"!=",
"\"Softmax\"",
":",
"return",
"[",
"layer",
"]",
"scanning_layer",
"=",
"pb2",
".",
"LayerParameter",
"(",
")",
"scanning_layer",
".",
"name",
"=",
"\"{}_scanning\"",
".",
"format",
"(",
"layer",
".",
"name",
")",
"scanning_layer",
".",
"bottom",
".",
"extend",
"(",
"layer",
".",
"top",
")",
"scanning_layer",
".",
"top",
".",
"extend",
"(",
"[",
"scanning_layer",
".",
"name",
"]",
")",
"scanning_layer",
".",
"type",
"=",
"\"Pooling\"",
"scanning_layer",
".",
"pooling_param",
".",
"pool",
"=",
"pb2",
".",
"PoolingParameter",
".",
"MAX",
"scanning_layer",
".",
"pooling_param",
".",
"global_pooling",
"=",
"True",
"return",
"[",
"layer",
",",
"scanning_layer",
"]",
"scanning_layers",
"=",
"flatmap",
"(",
"add_scanning",
",",
"conv_params",
".",
"layer",
")",
"scanning_params",
"=",
"pb2",
".",
"NetParameter",
"(",
")",
"scanning_params",
".",
"CopyFrom",
"(",
"conv_params",
")",
"del",
"scanning_params",
".",
"layer",
"[",
":",
"]",
"scanning_params",
".",
"layer",
".",
"extend",
"(",
"scanning_layers",
")",
"scanning_prototxt",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output_scanning_prototxt",
")",
",",
"delete",
"=",
"False",
")",
".",
"name",
"with",
"open",
"(",
"scanning_prototxt",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"google",
".",
"protobuf",
".",
"text_format",
".",
"MessageToString",
"(",
"scanning_params",
")",
")",
"# Verify the net loads with the scanning change.",
"caffe",
".",
"Net",
"(",
"str",
"(",
"scanning_prototxt",
")",
",",
"caffe",
".",
"TEST",
")",
"log",
".",
"info",
"(",
"\"Moving: %s to %s\"",
",",
"scanning_prototxt",
",",
"output_scanning_prototxt",
")",
"os",
".",
"rename",
"(",
"scanning_prototxt",
",",
"output_scanning_prototxt",
")"
] | https://github.com/facebookarchive/fb-caffe-exts/blob/5e95a5df428bf9a769d71a465fb38247846bcf84/conversions/conversions.py#L188-L220 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/mixture/_gaussian_mixture.py | python | _estimate_gaussian_covariances_full | (resp, X, nk, means, reg_covar) | return covariances | Estimate the full covariance matrices.
Parameters
----------
resp : array-like, shape (n_samples, n_components)
X : array-like, shape (n_samples, n_features)
nk : array-like, shape (n_components,)
means : array-like, shape (n_components, n_features)
reg_covar : float
Returns
-------
covariances : array, shape (n_components, n_features, n_features)
The covariance matrix of the current components. | Estimate the full covariance matrices. | [
"Estimate",
"the",
"full",
"covariance",
"matrices",
"."
] | def _estimate_gaussian_covariances_full(resp, X, nk, means, reg_covar):
"""Estimate the full covariance matrices.
Parameters
----------
resp : array-like, shape (n_samples, n_components)
X : array-like, shape (n_samples, n_features)
nk : array-like, shape (n_components,)
means : array-like, shape (n_components, n_features)
reg_covar : float
Returns
-------
covariances : array, shape (n_components, n_features, n_features)
The covariance matrix of the current components.
"""
n_components, n_features = means.shape
covariances = np.empty((n_components, n_features, n_features))
for k in range(n_components):
diff = X - means[k]
covariances[k] = np.dot(resp[:, k] * diff.T, diff) / nk[k]
covariances[k].flat[::n_features + 1] += reg_covar
return covariances | [
"def",
"_estimate_gaussian_covariances_full",
"(",
"resp",
",",
"X",
",",
"nk",
",",
"means",
",",
"reg_covar",
")",
":",
"n_components",
",",
"n_features",
"=",
"means",
".",
"shape",
"covariances",
"=",
"np",
".",
"empty",
"(",
"(",
"n_components",
",",
"n_features",
",",
"n_features",
")",
")",
"for",
"k",
"in",
"range",
"(",
"n_components",
")",
":",
"diff",
"=",
"X",
"-",
"means",
"[",
"k",
"]",
"covariances",
"[",
"k",
"]",
"=",
"np",
".",
"dot",
"(",
"resp",
"[",
":",
",",
"k",
"]",
"*",
"diff",
".",
"T",
",",
"diff",
")",
"/",
"nk",
"[",
"k",
"]",
"covariances",
"[",
"k",
"]",
".",
"flat",
"[",
":",
":",
"n_features",
"+",
"1",
"]",
"+=",
"reg_covar",
"return",
"covariances"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/mixture/_gaussian_mixture.py#L142-L168 | |
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | utils/lui/lldbutil.py | python | get_line_numbers | (thread) | return [GetLineNumber(i) for i in range(thread.GetNumFrames())] | Returns a sequence of line numbers from the stack frames of this thread. | Returns a sequence of line numbers from the stack frames of this thread. | [
"Returns",
"a",
"sequence",
"of",
"line",
"numbers",
"from",
"the",
"stack",
"frames",
"of",
"this",
"thread",
"."
] | def get_line_numbers(thread):
"""
Returns a sequence of line numbers from the stack frames of this thread.
"""
def GetLineNumber(i):
return thread.GetFrameAtIndex(i).GetLineEntry().GetLine()
return [GetLineNumber(i) for i in range(thread.GetNumFrames())] | [
"def",
"get_line_numbers",
"(",
"thread",
")",
":",
"def",
"GetLineNumber",
"(",
"i",
")",
":",
"return",
"thread",
".",
"GetFrameAtIndex",
"(",
"i",
")",
".",
"GetLineEntry",
"(",
")",
".",
"GetLine",
"(",
")",
"return",
"[",
"GetLineNumber",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"thread",
".",
"GetNumFrames",
"(",
")",
")",
"]"
] | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/utils/lui/lldbutil.py#L745-L752 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.AddStyledText | (*args, **kwargs) | return _stc.StyledTextCtrl_AddStyledText(*args, **kwargs) | AddStyledText(self, wxMemoryBuffer data)
Add array of cells to document. | AddStyledText(self, wxMemoryBuffer data) | [
"AddStyledText",
"(",
"self",
"wxMemoryBuffer",
"data",
")"
] | def AddStyledText(*args, **kwargs):
"""
AddStyledText(self, wxMemoryBuffer data)
Add array of cells to document.
"""
return _stc.StyledTextCtrl_AddStyledText(*args, **kwargs) | [
"def",
"AddStyledText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_AddStyledText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L2043-L2049 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/compiler/tf2xla/python/xla.py | python | _broadcasting_binary_op | (fn) | return broadcasting_binary_op_wrapper | Wraps a binary Tensorflow operator and performs XLA-style broadcasting. | Wraps a binary Tensorflow operator and performs XLA-style broadcasting. | [
"Wraps",
"a",
"binary",
"Tensorflow",
"operator",
"and",
"performs",
"XLA",
"-",
"style",
"broadcasting",
"."
] | def _broadcasting_binary_op(fn):
"""Wraps a binary Tensorflow operator and performs XLA-style broadcasting."""
def broadcasting_binary_op_wrapper(x, y, broadcast_dims=None, name=None):
"""Inner wrapper function."""
broadcast_dims = broadcast_dims or []
broadcast_dims = ops.convert_to_tensor(broadcast_dims, dtypes.int64)
# Rather than relying on having static shape information in the TensorFlow
# graph, we use an XlaBroadcastHelper op that can compute the correct shapes
# at JIT compilation time.
x, y = gen_xla_ops.xla_broadcast_helper(x, y, broadcast_dims)
return fn(x, y, name=name)
return broadcasting_binary_op_wrapper | [
"def",
"_broadcasting_binary_op",
"(",
"fn",
")",
":",
"def",
"broadcasting_binary_op_wrapper",
"(",
"x",
",",
"y",
",",
"broadcast_dims",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"\"\"\"Inner wrapper function.\"\"\"",
"broadcast_dims",
"=",
"broadcast_dims",
"or",
"[",
"]",
"broadcast_dims",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"broadcast_dims",
",",
"dtypes",
".",
"int64",
")",
"# Rather than relying on having static shape information in the TensorFlow",
"# graph, we use an XlaBroadcastHelper op that can compute the correct shapes",
"# at JIT compilation time.",
"x",
",",
"y",
"=",
"gen_xla_ops",
".",
"xla_broadcast_helper",
"(",
"x",
",",
"y",
",",
"broadcast_dims",
")",
"return",
"fn",
"(",
"x",
",",
"y",
",",
"name",
"=",
"name",
")",
"return",
"broadcasting_binary_op_wrapper"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/compiler/tf2xla/python/xla.py#L111-L124 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/generic.py | python | NDFrame.filter | (self, items=None, like=None, regex=None, axis=None) | Subset rows or columns of dataframe according to labels in
the specified index.
Note that this routine does not filter a dataframe on its
contents. The filter is applied to the labels of the index.
Parameters
----------
items : list-like
List of axis to restrict to (must not all be present).
like : string
Keep axis where "arg in col == True".
regex : string (regular expression)
Keep axis with re.search(regex, col) == True.
axis : int or string axis name
The axis to filter on. By default this is the info axis,
'index' for Series, 'columns' for DataFrame.
Returns
-------
same type as input object
See Also
--------
DataFrame.loc
Notes
-----
The ``items``, ``like``, and ``regex`` parameters are
enforced to be mutually exclusive.
``axis`` defaults to the info axis that is used when indexing
with ``[]``.
Examples
--------
>>> df = pd.DataFrame(np.array(([1,2,3], [4,5,6])),
... index=['mouse', 'rabbit'],
... columns=['one', 'two', 'three'])
>>> # select columns by name
>>> df.filter(items=['one', 'three'])
one three
mouse 1 3
rabbit 4 6
>>> # select columns by regular expression
>>> df.filter(regex='e$', axis=1)
one three
mouse 1 3
rabbit 4 6
>>> # select rows containing 'bbi'
>>> df.filter(like='bbi', axis=0)
one two three
rabbit 4 5 6 | Subset rows or columns of dataframe according to labels in
the specified index. | [
"Subset",
"rows",
"or",
"columns",
"of",
"dataframe",
"according",
"to",
"labels",
"in",
"the",
"specified",
"index",
"."
] | def filter(self, items=None, like=None, regex=None, axis=None):
"""
Subset rows or columns of dataframe according to labels in
the specified index.
Note that this routine does not filter a dataframe on its
contents. The filter is applied to the labels of the index.
Parameters
----------
items : list-like
List of axis to restrict to (must not all be present).
like : string
Keep axis where "arg in col == True".
regex : string (regular expression)
Keep axis with re.search(regex, col) == True.
axis : int or string axis name
The axis to filter on. By default this is the info axis,
'index' for Series, 'columns' for DataFrame.
Returns
-------
same type as input object
See Also
--------
DataFrame.loc
Notes
-----
The ``items``, ``like``, and ``regex`` parameters are
enforced to be mutually exclusive.
``axis`` defaults to the info axis that is used when indexing
with ``[]``.
Examples
--------
>>> df = pd.DataFrame(np.array(([1,2,3], [4,5,6])),
... index=['mouse', 'rabbit'],
... columns=['one', 'two', 'three'])
>>> # select columns by name
>>> df.filter(items=['one', 'three'])
one three
mouse 1 3
rabbit 4 6
>>> # select columns by regular expression
>>> df.filter(regex='e$', axis=1)
one three
mouse 1 3
rabbit 4 6
>>> # select rows containing 'bbi'
>>> df.filter(like='bbi', axis=0)
one two three
rabbit 4 5 6
"""
import re
nkw = com.count_not_none(items, like, regex)
if nkw > 1:
raise TypeError('Keyword arguments `items`, `like`, or `regex` '
'are mutually exclusive')
if axis is None:
axis = self._info_axis_name
labels = self._get_axis(axis)
if items is not None:
name = self._get_axis_name(axis)
return self.reindex(
**{name: [r for r in items if r in labels]})
elif like:
def f(x):
return like in to_str(x)
values = labels.map(f)
return self.loc(axis=axis)[values]
elif regex:
def f(x):
return matcher.search(to_str(x)) is not None
matcher = re.compile(regex)
values = labels.map(f)
return self.loc(axis=axis)[values]
else:
raise TypeError('Must pass either `items`, `like`, or `regex`') | [
"def",
"filter",
"(",
"self",
",",
"items",
"=",
"None",
",",
"like",
"=",
"None",
",",
"regex",
"=",
"None",
",",
"axis",
"=",
"None",
")",
":",
"import",
"re",
"nkw",
"=",
"com",
".",
"count_not_none",
"(",
"items",
",",
"like",
",",
"regex",
")",
"if",
"nkw",
">",
"1",
":",
"raise",
"TypeError",
"(",
"'Keyword arguments `items`, `like`, or `regex` '",
"'are mutually exclusive'",
")",
"if",
"axis",
"is",
"None",
":",
"axis",
"=",
"self",
".",
"_info_axis_name",
"labels",
"=",
"self",
".",
"_get_axis",
"(",
"axis",
")",
"if",
"items",
"is",
"not",
"None",
":",
"name",
"=",
"self",
".",
"_get_axis_name",
"(",
"axis",
")",
"return",
"self",
".",
"reindex",
"(",
"*",
"*",
"{",
"name",
":",
"[",
"r",
"for",
"r",
"in",
"items",
"if",
"r",
"in",
"labels",
"]",
"}",
")",
"elif",
"like",
":",
"def",
"f",
"(",
"x",
")",
":",
"return",
"like",
"in",
"to_str",
"(",
"x",
")",
"values",
"=",
"labels",
".",
"map",
"(",
"f",
")",
"return",
"self",
".",
"loc",
"(",
"axis",
"=",
"axis",
")",
"[",
"values",
"]",
"elif",
"regex",
":",
"def",
"f",
"(",
"x",
")",
":",
"return",
"matcher",
".",
"search",
"(",
"to_str",
"(",
"x",
")",
")",
"is",
"not",
"None",
"matcher",
"=",
"re",
".",
"compile",
"(",
"regex",
")",
"values",
"=",
"labels",
".",
"map",
"(",
"f",
")",
"return",
"self",
".",
"loc",
"(",
"axis",
"=",
"axis",
")",
"[",
"values",
"]",
"else",
":",
"raise",
"TypeError",
"(",
"'Must pass either `items`, `like`, or `regex`'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/generic.py#L4497-L4583 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewItemAttr.HasColour | (*args, **kwargs) | return _dataview.DataViewItemAttr_HasColour(*args, **kwargs) | HasColour(self) -> bool | HasColour(self) -> bool | [
"HasColour",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasColour(*args, **kwargs):
"""HasColour(self) -> bool"""
return _dataview.DataViewItemAttr_HasColour(*args, **kwargs) | [
"def",
"HasColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewItemAttr_HasColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L345-L347 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/reduction_gui/reduction/sans/hfir_detector_script.py | python | Detector.from_setup_info | (self, xml_str) | Read in data from XML using the string representation of the setup algorithm used
to prepare the reduction properties.
@param xml_str: text to read the data from | Read in data from XML using the string representation of the setup algorithm used
to prepare the reduction properties. | [
"Read",
"in",
"data",
"from",
"XML",
"using",
"the",
"string",
"representation",
"of",
"the",
"setup",
"algorithm",
"used",
"to",
"prepare",
"the",
"reduction",
"properties",
"."
] | def from_setup_info(self, xml_str):
"""
Read in data from XML using the string representation of the setup algorithm used
to prepare the reduction properties.
@param xml_str: text to read the data from
"""
self.reset()
(alg, _) = BaseScriptElement.getAlgorithmFromXML(xml_str)
# Sensitivity correction
self.sensitivity_data = BaseScriptElement.getPropertyValue(alg, "SensitivityFile", default='')
self.sensitivity_corr = len(self.sensitivity_data)>0
self.sensitivity_dark = BaseScriptElement.getPropertyValue(alg, "SensitivityDarkCurrentFile", default='')
self.use_sample_dark = BaseScriptElement.getPropertyValue(alg, "UseDefaultDC",
default = Detector.use_sample_dark)
self.min_sensitivity = BaseScriptElement.getPropertyValue(alg, "MinEfficiency",
default=Detector.min_sensitivity)
self.max_sensitivity = BaseScriptElement.getPropertyValue(alg, "MaxEfficiency",
default=Detector.max_sensitivity)
sensitivity_center_method = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterMethod",
default='None')
self.flood_use_finder = sensitivity_center_method in ['DirectBeam', 'Scattering']
self.flood_use_direct_beam = sensitivity_center_method=='DirectBeam'
self.use_sample_beam_center = sensitivity_center_method=='None'
self.flood_x_position = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterX",
default=Detector.flood_x_position)
self.flood_y_position = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterY",
default=Detector.flood_y_position)
self.flood_beam_file = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterFile", default='')
self.flood_beam_radius = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterRadius",
default=Detector.flood_beam_radius)
# Beam center
center_method = BaseScriptElement.getPropertyValue(alg, "BeamCenterMethod", default='None')
self.use_finder = center_method in ['DirectBeam', 'Scattering']
self.use_direct_beam = center_method=='DirectBeam'
self.x_position = BaseScriptElement.getPropertyValue(alg, "BeamCenterX",
default=Detector.x_position)
self.y_position = BaseScriptElement.getPropertyValue(alg, "BeamCenterY",
default=Detector.y_position)
self.beam_file = BaseScriptElement.getPropertyValue(alg, "BeamCenterFile", default='')
self.beam_radius = BaseScriptElement.getPropertyValue(alg, "BeamRadius",
default=Detector.beam_radius) | [
"def",
"from_setup_info",
"(",
"self",
",",
"xml_str",
")",
":",
"self",
".",
"reset",
"(",
")",
"(",
"alg",
",",
"_",
")",
"=",
"BaseScriptElement",
".",
"getAlgorithmFromXML",
"(",
"xml_str",
")",
"# Sensitivity correction",
"self",
".",
"sensitivity_data",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"SensitivityFile\"",
",",
"default",
"=",
"''",
")",
"self",
".",
"sensitivity_corr",
"=",
"len",
"(",
"self",
".",
"sensitivity_data",
")",
">",
"0",
"self",
".",
"sensitivity_dark",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"SensitivityDarkCurrentFile\"",
",",
"default",
"=",
"''",
")",
"self",
".",
"use_sample_dark",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"UseDefaultDC\"",
",",
"default",
"=",
"Detector",
".",
"use_sample_dark",
")",
"self",
".",
"min_sensitivity",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"MinEfficiency\"",
",",
"default",
"=",
"Detector",
".",
"min_sensitivity",
")",
"self",
".",
"max_sensitivity",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"MaxEfficiency\"",
",",
"default",
"=",
"Detector",
".",
"max_sensitivity",
")",
"sensitivity_center_method",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"SensitivityBeamCenterMethod\"",
",",
"default",
"=",
"'None'",
")",
"self",
".",
"flood_use_finder",
"=",
"sensitivity_center_method",
"in",
"[",
"'DirectBeam'",
",",
"'Scattering'",
"]",
"self",
".",
"flood_use_direct_beam",
"=",
"sensitivity_center_method",
"==",
"'DirectBeam'",
"self",
".",
"use_sample_beam_center",
"=",
"sensitivity_center_method",
"==",
"'None'",
"self",
".",
"flood_x_position",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"SensitivityBeamCenterX\"",
",",
"default",
"=",
"Detector",
".",
"flood_x_position",
")",
"self",
".",
"flood_y_position",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"SensitivityBeamCenterY\"",
",",
"default",
"=",
"Detector",
".",
"flood_y_position",
")",
"self",
".",
"flood_beam_file",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"SensitivityBeamCenterFile\"",
",",
"default",
"=",
"''",
")",
"self",
".",
"flood_beam_radius",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"SensitivityBeamCenterRadius\"",
",",
"default",
"=",
"Detector",
".",
"flood_beam_radius",
")",
"# Beam center",
"center_method",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"BeamCenterMethod\"",
",",
"default",
"=",
"'None'",
")",
"self",
".",
"use_finder",
"=",
"center_method",
"in",
"[",
"'DirectBeam'",
",",
"'Scattering'",
"]",
"self",
".",
"use_direct_beam",
"=",
"center_method",
"==",
"'DirectBeam'",
"self",
".",
"x_position",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"BeamCenterX\"",
",",
"default",
"=",
"Detector",
".",
"x_position",
")",
"self",
".",
"y_position",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"BeamCenterY\"",
",",
"default",
"=",
"Detector",
".",
"y_position",
")",
"self",
".",
"beam_file",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"BeamCenterFile\"",
",",
"default",
"=",
"''",
")",
"self",
".",
"beam_radius",
"=",
"BaseScriptElement",
".",
"getPropertyValue",
"(",
"alg",
",",
"\"BeamRadius\"",
",",
"default",
"=",
"Detector",
".",
"beam_radius",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_gui/reduction/sans/hfir_detector_script.py#L230-L273 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/examples/how_tos/reading_data/fully_connected_preloaded_var.py | python | run_training | () | Train MNIST for a number of epochs. | Train MNIST for a number of epochs. | [
"Train",
"MNIST",
"for",
"a",
"number",
"of",
"epochs",
"."
] | def run_training():
"""Train MNIST for a number of epochs."""
# Get the sets of images and labels for training, validation, and
# test on MNIST.
data_sets = input_data.read_data_sets(FLAGS.train_dir, FLAGS.fake_data)
# Tell TensorFlow that the model will be built into the default Graph.
with tf.Graph().as_default():
with tf.name_scope('input'):
# Input data
images_initializer = tf.placeholder(
dtype=data_sets.train.images.dtype,
shape=data_sets.train.images.shape)
labels_initializer = tf.placeholder(
dtype=data_sets.train.labels.dtype,
shape=data_sets.train.labels.shape)
input_images = tf.Variable(
images_initializer, trainable=False, collections=[])
input_labels = tf.Variable(
labels_initializer, trainable=False, collections=[])
image, label = tf.train.slice_input_producer(
[input_images, input_labels], num_epochs=FLAGS.num_epochs)
label = tf.cast(label, tf.int32)
images, labels = tf.train.batch(
[image, label], batch_size=FLAGS.batch_size)
# Build a Graph that computes predictions from the inference model.
logits = mnist.inference(images, FLAGS.hidden1, FLAGS.hidden2)
# Add to the Graph the Ops for loss calculation.
loss = mnist.loss(logits, labels)
# Add to the Graph the Ops that calculate and apply gradients.
train_op = mnist.training(loss, FLAGS.learning_rate)
# Add the Op to compare the logits to the labels during evaluation.
eval_correct = mnist.evaluation(logits, labels)
# Build the summary operation based on the TF collection of Summaries.
summary_op = tf.merge_all_summaries()
# Create a saver for writing training checkpoints.
saver = tf.train.Saver()
# Create the op for initializing variables.
init_op = tf.initialize_all_variables()
# Create a session for running Ops on the Graph.
sess = tf.Session()
# Run the Op to initialize the variables.
sess.run(init_op)
sess.run(input_images.initializer,
feed_dict={images_initializer: data_sets.train.images})
sess.run(input_labels.initializer,
feed_dict={labels_initializer: data_sets.train.labels})
# Instantiate a SummaryWriter to output summaries and the Graph.
summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph)
# Start input enqueue threads.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
# And then after everything is built, start the training loop.
try:
step = 0
while not coord.should_stop():
start_time = time.time()
# Run one step of the model.
_, loss_value = sess.run([train_op, loss])
duration = time.time() - start_time
# Write the summaries and print an overview fairly often.
if step % 100 == 0:
# Print status to stdout.
print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value,
duration))
# Update the events file.
summary_str = sess.run(summary_op)
summary_writer.add_summary(summary_str, step)
step += 1
# Save a checkpoint periodically.
if (step + 1) % 1000 == 0:
print('Saving')
saver.save(sess, FLAGS.train_dir, global_step=step)
step += 1
except tf.errors.OutOfRangeError:
print('Saving')
saver.save(sess, FLAGS.train_dir, global_step=step)
print('Done training for %d epochs, %d steps.' % (FLAGS.num_epochs, step))
finally:
# When done, ask the threads to stop.
coord.request_stop()
# Wait for threads to finish.
coord.join(threads)
sess.close() | [
"def",
"run_training",
"(",
")",
":",
"# Get the sets of images and labels for training, validation, and",
"# test on MNIST.",
"data_sets",
"=",
"input_data",
".",
"read_data_sets",
"(",
"FLAGS",
".",
"train_dir",
",",
"FLAGS",
".",
"fake_data",
")",
"# Tell TensorFlow that the model will be built into the default Graph.",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'input'",
")",
":",
"# Input data",
"images_initializer",
"=",
"tf",
".",
"placeholder",
"(",
"dtype",
"=",
"data_sets",
".",
"train",
".",
"images",
".",
"dtype",
",",
"shape",
"=",
"data_sets",
".",
"train",
".",
"images",
".",
"shape",
")",
"labels_initializer",
"=",
"tf",
".",
"placeholder",
"(",
"dtype",
"=",
"data_sets",
".",
"train",
".",
"labels",
".",
"dtype",
",",
"shape",
"=",
"data_sets",
".",
"train",
".",
"labels",
".",
"shape",
")",
"input_images",
"=",
"tf",
".",
"Variable",
"(",
"images_initializer",
",",
"trainable",
"=",
"False",
",",
"collections",
"=",
"[",
"]",
")",
"input_labels",
"=",
"tf",
".",
"Variable",
"(",
"labels_initializer",
",",
"trainable",
"=",
"False",
",",
"collections",
"=",
"[",
"]",
")",
"image",
",",
"label",
"=",
"tf",
".",
"train",
".",
"slice_input_producer",
"(",
"[",
"input_images",
",",
"input_labels",
"]",
",",
"num_epochs",
"=",
"FLAGS",
".",
"num_epochs",
")",
"label",
"=",
"tf",
".",
"cast",
"(",
"label",
",",
"tf",
".",
"int32",
")",
"images",
",",
"labels",
"=",
"tf",
".",
"train",
".",
"batch",
"(",
"[",
"image",
",",
"label",
"]",
",",
"batch_size",
"=",
"FLAGS",
".",
"batch_size",
")",
"# Build a Graph that computes predictions from the inference model.",
"logits",
"=",
"mnist",
".",
"inference",
"(",
"images",
",",
"FLAGS",
".",
"hidden1",
",",
"FLAGS",
".",
"hidden2",
")",
"# Add to the Graph the Ops for loss calculation.",
"loss",
"=",
"mnist",
".",
"loss",
"(",
"logits",
",",
"labels",
")",
"# Add to the Graph the Ops that calculate and apply gradients.",
"train_op",
"=",
"mnist",
".",
"training",
"(",
"loss",
",",
"FLAGS",
".",
"learning_rate",
")",
"# Add the Op to compare the logits to the labels during evaluation.",
"eval_correct",
"=",
"mnist",
".",
"evaluation",
"(",
"logits",
",",
"labels",
")",
"# Build the summary operation based on the TF collection of Summaries.",
"summary_op",
"=",
"tf",
".",
"merge_all_summaries",
"(",
")",
"# Create a saver for writing training checkpoints.",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
"# Create the op for initializing variables.",
"init_op",
"=",
"tf",
".",
"initialize_all_variables",
"(",
")",
"# Create a session for running Ops on the Graph.",
"sess",
"=",
"tf",
".",
"Session",
"(",
")",
"# Run the Op to initialize the variables.",
"sess",
".",
"run",
"(",
"init_op",
")",
"sess",
".",
"run",
"(",
"input_images",
".",
"initializer",
",",
"feed_dict",
"=",
"{",
"images_initializer",
":",
"data_sets",
".",
"train",
".",
"images",
"}",
")",
"sess",
".",
"run",
"(",
"input_labels",
".",
"initializer",
",",
"feed_dict",
"=",
"{",
"labels_initializer",
":",
"data_sets",
".",
"train",
".",
"labels",
"}",
")",
"# Instantiate a SummaryWriter to output summaries and the Graph.",
"summary_writer",
"=",
"tf",
".",
"train",
".",
"SummaryWriter",
"(",
"FLAGS",
".",
"train_dir",
",",
"sess",
".",
"graph",
")",
"# Start input enqueue threads.",
"coord",
"=",
"tf",
".",
"train",
".",
"Coordinator",
"(",
")",
"threads",
"=",
"tf",
".",
"train",
".",
"start_queue_runners",
"(",
"sess",
"=",
"sess",
",",
"coord",
"=",
"coord",
")",
"# And then after everything is built, start the training loop.",
"try",
":",
"step",
"=",
"0",
"while",
"not",
"coord",
".",
"should_stop",
"(",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"# Run one step of the model.",
"_",
",",
"loss_value",
"=",
"sess",
".",
"run",
"(",
"[",
"train_op",
",",
"loss",
"]",
")",
"duration",
"=",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
"# Write the summaries and print an overview fairly often.",
"if",
"step",
"%",
"100",
"==",
"0",
":",
"# Print status to stdout.",
"print",
"(",
"'Step %d: loss = %.2f (%.3f sec)'",
"%",
"(",
"step",
",",
"loss_value",
",",
"duration",
")",
")",
"# Update the events file.",
"summary_str",
"=",
"sess",
".",
"run",
"(",
"summary_op",
")",
"summary_writer",
".",
"add_summary",
"(",
"summary_str",
",",
"step",
")",
"step",
"+=",
"1",
"# Save a checkpoint periodically.",
"if",
"(",
"step",
"+",
"1",
")",
"%",
"1000",
"==",
"0",
":",
"print",
"(",
"'Saving'",
")",
"saver",
".",
"save",
"(",
"sess",
",",
"FLAGS",
".",
"train_dir",
",",
"global_step",
"=",
"step",
")",
"step",
"+=",
"1",
"except",
"tf",
".",
"errors",
".",
"OutOfRangeError",
":",
"print",
"(",
"'Saving'",
")",
"saver",
".",
"save",
"(",
"sess",
",",
"FLAGS",
".",
"train_dir",
",",
"global_step",
"=",
"step",
")",
"print",
"(",
"'Done training for %d epochs, %d steps.'",
"%",
"(",
"FLAGS",
".",
"num_epochs",
",",
"step",
")",
")",
"finally",
":",
"# When done, ask the threads to stop.",
"coord",
".",
"request_stop",
"(",
")",
"# Wait for threads to finish.",
"coord",
".",
"join",
"(",
"threads",
")",
"sess",
".",
"close",
"(",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/examples/how_tos/reading_data/fully_connected_preloaded_var.py#L54-L156 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject.Name | (self) | Return the name corresponding to an object.
Not all objects necessarily need to be nameable, and not all that do have
a "name" property. Override as needed. | Return the name corresponding to an object. | [
"Return",
"the",
"name",
"corresponding",
"to",
"an",
"object",
"."
] | def Name(self):
"""Return the name corresponding to an object.
Not all objects necessarily need to be nameable, and not all that do have
a "name" property. Override as needed.
"""
# If the schema indicates that "name" is required, try to access the
# property even if it doesn't exist. This will result in a KeyError
# being raised for the property that should be present, which seems more
# appropriate than NotImplementedError in this case.
if 'name' in self._properties or \
('name' in self._schema and self._schema['name'][3]):
return self._properties['name']
raise NotImplementedError(self.__class__.__name__ + ' must implement Name') | [
"def",
"Name",
"(",
"self",
")",
":",
"# If the schema indicates that \"name\" is required, try to access the",
"# property even if it doesn't exist. This will result in a KeyError",
"# being raised for the property that should be present, which seems more",
"# appropriate than NotImplementedError in this case.",
"if",
"'name'",
"in",
"self",
".",
"_properties",
"or",
"(",
"'name'",
"in",
"self",
".",
"_schema",
"and",
"self",
".",
"_schema",
"[",
"'name'",
"]",
"[",
"3",
"]",
")",
":",
"return",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"raise",
"NotImplementedError",
"(",
"self",
".",
"__class__",
".",
"__name__",
"+",
"' must implement Name'",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L350-L365 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/urllib.py | python | unquote | (s) | return ''.join(res) | unquote('abc%20def') -> 'abc def'. | unquote('abc%20def') -> 'abc def'. | [
"unquote",
"(",
"abc%20def",
")",
"-",
">",
"abc",
"def",
"."
] | def unquote(s):
"""unquote('abc%20def') -> 'abc def'."""
if _is_unicode(s):
if '%' not in s:
return s
bits = _asciire.split(s)
res = [bits[0]]
append = res.append
for i in range(1, len(bits), 2):
append(unquote(str(bits[i])).decode('latin1'))
append(bits[i + 1])
return ''.join(res)
bits = s.split('%')
# fastpath
if len(bits) == 1:
return s
res = [bits[0]]
append = res.append
for item in bits[1:]:
try:
append(_hextochr[item[:2]])
append(item[2:])
except KeyError:
append('%')
append(item)
return ''.join(res) | [
"def",
"unquote",
"(",
"s",
")",
":",
"if",
"_is_unicode",
"(",
"s",
")",
":",
"if",
"'%'",
"not",
"in",
"s",
":",
"return",
"s",
"bits",
"=",
"_asciire",
".",
"split",
"(",
"s",
")",
"res",
"=",
"[",
"bits",
"[",
"0",
"]",
"]",
"append",
"=",
"res",
".",
"append",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"bits",
")",
",",
"2",
")",
":",
"append",
"(",
"unquote",
"(",
"str",
"(",
"bits",
"[",
"i",
"]",
")",
")",
".",
"decode",
"(",
"'latin1'",
")",
")",
"append",
"(",
"bits",
"[",
"i",
"+",
"1",
"]",
")",
"return",
"''",
".",
"join",
"(",
"res",
")",
"bits",
"=",
"s",
".",
"split",
"(",
"'%'",
")",
"# fastpath",
"if",
"len",
"(",
"bits",
")",
"==",
"1",
":",
"return",
"s",
"res",
"=",
"[",
"bits",
"[",
"0",
"]",
"]",
"append",
"=",
"res",
".",
"append",
"for",
"item",
"in",
"bits",
"[",
"1",
":",
"]",
":",
"try",
":",
"append",
"(",
"_hextochr",
"[",
"item",
"[",
":",
"2",
"]",
"]",
")",
"append",
"(",
"item",
"[",
"2",
":",
"]",
")",
"except",
"KeyError",
":",
"append",
"(",
"'%'",
")",
"append",
"(",
"item",
")",
"return",
"''",
".",
"join",
"(",
"res",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/urllib.py#L1204-L1230 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/module/bucketing_module.py | python | BucketingModule.output_names | (self) | A list of names for the outputs of this module. | A list of names for the outputs of this module. | [
"A",
"list",
"of",
"names",
"for",
"the",
"outputs",
"of",
"this",
"module",
"."
] | def output_names(self):
"""A list of names for the outputs of this module."""
if self.binded:
return self._curr_module.output_names
else:
symbol, _, _ = self._call_sym_gen(self._default_bucket_key)
return symbol.list_outputs() | [
"def",
"output_names",
"(",
"self",
")",
":",
"if",
"self",
".",
"binded",
":",
"return",
"self",
".",
"_curr_module",
".",
"output_names",
"else",
":",
"symbol",
",",
"_",
",",
"_",
"=",
"self",
".",
"_call_sym_gen",
"(",
"self",
".",
"_default_bucket_key",
")",
"return",
"symbol",
".",
"list_outputs",
"(",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/module/bucketing_module.py#L121-L127 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Position.__ne__ | (*args, **kwargs) | return _core_.Position___ne__(*args, **kwargs) | __ne__(self, PyObject other) -> bool
Test for inequality of wx.Position objects. | __ne__(self, PyObject other) -> bool | [
"__ne__",
"(",
"self",
"PyObject",
"other",
")",
"-",
">",
"bool"
] | def __ne__(*args, **kwargs):
"""
__ne__(self, PyObject other) -> bool
Test for inequality of wx.Position objects.
"""
return _core_.Position___ne__(*args, **kwargs) | [
"def",
"__ne__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Position___ne__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L2118-L2124 | |
rsocket/rsocket-cpp | 45ed594ebd6701f40795c31ec922d784ec7fc921 | build/fbcode_builder/getdeps/load.py | python | ManifestLoader._compute_project_hash | (self, manifest) | return h | This recursive function computes a hash for a given manifest.
The hash takes into account some environmental factors on the
host machine and includes the hashes of its dependencies.
No caching of the computation is performed, which is theoretically
wasteful but the computation is fast enough that it is not required
to cache across multiple invocations. | This recursive function computes a hash for a given manifest.
The hash takes into account some environmental factors on the
host machine and includes the hashes of its dependencies.
No caching of the computation is performed, which is theoretically
wasteful but the computation is fast enough that it is not required
to cache across multiple invocations. | [
"This",
"recursive",
"function",
"computes",
"a",
"hash",
"for",
"a",
"given",
"manifest",
".",
"The",
"hash",
"takes",
"into",
"account",
"some",
"environmental",
"factors",
"on",
"the",
"host",
"machine",
"and",
"includes",
"the",
"hashes",
"of",
"its",
"dependencies",
".",
"No",
"caching",
"of",
"the",
"computation",
"is",
"performed",
"which",
"is",
"theoretically",
"wasteful",
"but",
"the",
"computation",
"is",
"fast",
"enough",
"that",
"it",
"is",
"not",
"required",
"to",
"cache",
"across",
"multiple",
"invocations",
"."
] | def _compute_project_hash(self, manifest):
"""This recursive function computes a hash for a given manifest.
The hash takes into account some environmental factors on the
host machine and includes the hashes of its dependencies.
No caching of the computation is performed, which is theoretically
wasteful but the computation is fast enough that it is not required
to cache across multiple invocations."""
ctx = self.ctx_gen.get_context(manifest.name)
hasher = hashlib.sha256()
# Some environmental and configuration things matter
env = {}
env["install_dir"] = self.build_opts.install_dir
env["scratch_dir"] = self.build_opts.scratch_dir
env["vcvars_path"] = self.build_opts.vcvars_path
env["os"] = self.build_opts.host_type.ostype
env["distro"] = self.build_opts.host_type.distro
env["distro_vers"] = self.build_opts.host_type.distrovers
for name in [
"CXXFLAGS",
"CPPFLAGS",
"LDFLAGS",
"CXX",
"CC",
"GETDEPS_CMAKE_DEFINES",
]:
env[name] = os.environ.get(name)
for tool in ["cc", "c++", "gcc", "g++", "clang", "clang++"]:
env["tool-%s" % tool] = path_search(os.environ, tool)
for name in manifest.get_section_as_args("depends.environment", ctx):
env[name] = os.environ.get(name)
fetcher = self.create_fetcher(manifest)
env["fetcher.hash"] = fetcher.hash()
for name in sorted(env.keys()):
hasher.update(name.encode("utf-8"))
value = env.get(name)
if value is not None:
try:
hasher.update(value.encode("utf-8"))
except AttributeError as exc:
raise AttributeError("name=%r, value=%r: %s" % (name, value, exc))
manifest.update_hash(hasher, ctx)
dep_list = sorted(manifest.get_section_as_dict("dependencies", ctx).keys())
for dep in dep_list:
dep_manifest = self.load_manifest(dep)
dep_hash = self.get_project_hash(dep_manifest)
hasher.update(dep_hash.encode("utf-8"))
# Use base64 to represent the hash, rather than the simple hex digest,
# so that the string is shorter. Use the URL-safe encoding so that
# the hash can also be safely used as a filename component.
h = base64.urlsafe_b64encode(hasher.digest()).decode("ascii")
# ... and because cmd.exe is troublesome with `=` signs, nerf those.
# They tend to be padding characters at the end anyway, so we can
# safely discard them.
h = h.replace("=", "")
return h | [
"def",
"_compute_project_hash",
"(",
"self",
",",
"manifest",
")",
":",
"ctx",
"=",
"self",
".",
"ctx_gen",
".",
"get_context",
"(",
"manifest",
".",
"name",
")",
"hasher",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"# Some environmental and configuration things matter",
"env",
"=",
"{",
"}",
"env",
"[",
"\"install_dir\"",
"]",
"=",
"self",
".",
"build_opts",
".",
"install_dir",
"env",
"[",
"\"scratch_dir\"",
"]",
"=",
"self",
".",
"build_opts",
".",
"scratch_dir",
"env",
"[",
"\"vcvars_path\"",
"]",
"=",
"self",
".",
"build_opts",
".",
"vcvars_path",
"env",
"[",
"\"os\"",
"]",
"=",
"self",
".",
"build_opts",
".",
"host_type",
".",
"ostype",
"env",
"[",
"\"distro\"",
"]",
"=",
"self",
".",
"build_opts",
".",
"host_type",
".",
"distro",
"env",
"[",
"\"distro_vers\"",
"]",
"=",
"self",
".",
"build_opts",
".",
"host_type",
".",
"distrovers",
"for",
"name",
"in",
"[",
"\"CXXFLAGS\"",
",",
"\"CPPFLAGS\"",
",",
"\"LDFLAGS\"",
",",
"\"CXX\"",
",",
"\"CC\"",
",",
"\"GETDEPS_CMAKE_DEFINES\"",
",",
"]",
":",
"env",
"[",
"name",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
")",
"for",
"tool",
"in",
"[",
"\"cc\"",
",",
"\"c++\"",
",",
"\"gcc\"",
",",
"\"g++\"",
",",
"\"clang\"",
",",
"\"clang++\"",
"]",
":",
"env",
"[",
"\"tool-%s\"",
"%",
"tool",
"]",
"=",
"path_search",
"(",
"os",
".",
"environ",
",",
"tool",
")",
"for",
"name",
"in",
"manifest",
".",
"get_section_as_args",
"(",
"\"depends.environment\"",
",",
"ctx",
")",
":",
"env",
"[",
"name",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
")",
"fetcher",
"=",
"self",
".",
"create_fetcher",
"(",
"manifest",
")",
"env",
"[",
"\"fetcher.hash\"",
"]",
"=",
"fetcher",
".",
"hash",
"(",
")",
"for",
"name",
"in",
"sorted",
"(",
"env",
".",
"keys",
"(",
")",
")",
":",
"hasher",
".",
"update",
"(",
"name",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"value",
"=",
"env",
".",
"get",
"(",
"name",
")",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"hasher",
".",
"update",
"(",
"value",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"except",
"AttributeError",
"as",
"exc",
":",
"raise",
"AttributeError",
"(",
"\"name=%r, value=%r: %s\"",
"%",
"(",
"name",
",",
"value",
",",
"exc",
")",
")",
"manifest",
".",
"update_hash",
"(",
"hasher",
",",
"ctx",
")",
"dep_list",
"=",
"sorted",
"(",
"manifest",
".",
"get_section_as_dict",
"(",
"\"dependencies\"",
",",
"ctx",
")",
".",
"keys",
"(",
")",
")",
"for",
"dep",
"in",
"dep_list",
":",
"dep_manifest",
"=",
"self",
".",
"load_manifest",
"(",
"dep",
")",
"dep_hash",
"=",
"self",
".",
"get_project_hash",
"(",
"dep_manifest",
")",
"hasher",
".",
"update",
"(",
"dep_hash",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"# Use base64 to represent the hash, rather than the simple hex digest,",
"# so that the string is shorter. Use the URL-safe encoding so that",
"# the hash can also be safely used as a filename component.",
"h",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"hasher",
".",
"digest",
"(",
")",
")",
".",
"decode",
"(",
"\"ascii\"",
")",
"# ... and because cmd.exe is troublesome with `=` signs, nerf those.",
"# They tend to be padding characters at the end anyway, so we can",
"# safely discard them.",
"h",
"=",
"h",
".",
"replace",
"(",
"\"=\"",
",",
"\"\"",
")",
"return",
"h"
] | https://github.com/rsocket/rsocket-cpp/blob/45ed594ebd6701f40795c31ec922d784ec7fc921/build/fbcode_builder/getdeps/load.py#L260-L321 | |
NeoGeographyToolkit/StereoPipeline | eedf54a919fb5cce1ab0e280bb0df4050763aa11 | src/asp/IceBridge/icebridge_common.py | python | stopTaskPool | (pool) | Stop remaining tasks and kill the pool. | Stop remaining tasks and kill the pool. | [
"Stop",
"remaining",
"tasks",
"and",
"kill",
"the",
"pool",
"."
] | def stopTaskPool(pool):
'''Stop remaining tasks and kill the pool.'''
PROCESS_POOL_KILL_TIMEOUT = 3
pool.close()
time.sleep(PROCESS_POOL_KILL_TIMEOUT)
pool.terminate()
pool.join() | [
"def",
"stopTaskPool",
"(",
"pool",
")",
":",
"PROCESS_POOL_KILL_TIMEOUT",
"=",
"3",
"pool",
".",
"close",
"(",
")",
"time",
".",
"sleep",
"(",
"PROCESS_POOL_KILL_TIMEOUT",
")",
"pool",
".",
"terminate",
"(",
")",
"pool",
".",
"join",
"(",
")"
] | https://github.com/NeoGeographyToolkit/StereoPipeline/blob/eedf54a919fb5cce1ab0e280bb0df4050763aa11/src/asp/IceBridge/icebridge_common.py#L1439-L1446 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | example/ssd/tools/caffe_converter/compare_layers.py | python | _ch_dev | (arg_params, aux_params, ctx) | return new_args, new_auxs | Changes device of given mxnet arguments
:param arg_params: arguments
:param aux_params: auxiliary parameters
:param ctx: new device context
:return: arguments and auxiliary parameters on new device | Changes device of given mxnet arguments
:param arg_params: arguments
:param aux_params: auxiliary parameters
:param ctx: new device context
:return: arguments and auxiliary parameters on new device | [
"Changes",
"device",
"of",
"given",
"mxnet",
"arguments",
":",
"param",
"arg_params",
":",
"arguments",
":",
"param",
"aux_params",
":",
"auxiliary",
"parameters",
":",
"param",
"ctx",
":",
"new",
"device",
"context",
":",
"return",
":",
"arguments",
"and",
"auxiliary",
"parameters",
"on",
"new",
"device"
] | def _ch_dev(arg_params, aux_params, ctx):
"""
Changes device of given mxnet arguments
:param arg_params: arguments
:param aux_params: auxiliary parameters
:param ctx: new device context
:return: arguments and auxiliary parameters on new device
"""
new_args = dict()
new_auxs = dict()
for k, v in arg_params.items():
new_args[k] = v.as_in_context(ctx)
for k, v in aux_params.items():
new_auxs[k] = v.as_in_context(ctx)
return new_args, new_auxs | [
"def",
"_ch_dev",
"(",
"arg_params",
",",
"aux_params",
",",
"ctx",
")",
":",
"new_args",
"=",
"dict",
"(",
")",
"new_auxs",
"=",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"arg_params",
".",
"items",
"(",
")",
":",
"new_args",
"[",
"k",
"]",
"=",
"v",
".",
"as_in_context",
"(",
"ctx",
")",
"for",
"k",
",",
"v",
"in",
"aux_params",
".",
"items",
"(",
")",
":",
"new_auxs",
"[",
"k",
"]",
"=",
"v",
".",
"as_in_context",
"(",
"ctx",
")",
"return",
"new_args",
",",
"new_auxs"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/ssd/tools/caffe_converter/compare_layers.py#L64-L78 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/installer.py | python | strip_marker | (req) | return req | Return a new requirement without the environment marker to avoid
calling pip with something like `babel; extra == "i18n"`, which
would always be ignored. | Return a new requirement without the environment marker to avoid
calling pip with something like `babel; extra == "i18n"`, which
would always be ignored. | [
"Return",
"a",
"new",
"requirement",
"without",
"the",
"environment",
"marker",
"to",
"avoid",
"calling",
"pip",
"with",
"something",
"like",
"babel",
";",
"extra",
"==",
"i18n",
"which",
"would",
"always",
"be",
"ignored",
"."
] | def strip_marker(req):
"""
Return a new requirement without the environment marker to avoid
calling pip with something like `babel; extra == "i18n"`, which
would always be ignored.
"""
# create a copy to avoid mutating the input
req = pkg_resources.Requirement.parse(str(req))
req.marker = None
return req | [
"def",
"strip_marker",
"(",
"req",
")",
":",
"# create a copy to avoid mutating the input",
"req",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"str",
"(",
"req",
")",
")",
"req",
".",
"marker",
"=",
"None",
"return",
"req"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/installer.py#L141-L150 | |
alibaba/weex_js_engine | 2bdf4b6f020c1fc99c63f649718f6faf7e27fdde | jni/v8core/v8/build/gyp/pylib/gyp/input.py | python | DependencyGraphNode._AddImportedDependencies | (self, targets, dependencies=None) | return dependencies | Given a list of direct dependencies, adds indirect dependencies that
other dependencies have declared to export their settings.
This method does not operate on self. Rather, it operates on the list
of dependencies in the |dependencies| argument. For each dependency in
that list, if any declares that it exports the settings of one of its
own dependencies, those dependencies whose settings are "passed through"
are added to the list. As new items are added to the list, they too will
be processed, so it is possible to import settings through multiple levels
of dependencies.
This method is not terribly useful on its own, it depends on being
"primed" with a list of direct dependencies such as one provided by
DirectDependencies. DirectAndImportedDependencies is intended to be the
public entry point. | Given a list of direct dependencies, adds indirect dependencies that
other dependencies have declared to export their settings. | [
"Given",
"a",
"list",
"of",
"direct",
"dependencies",
"adds",
"indirect",
"dependencies",
"that",
"other",
"dependencies",
"have",
"declared",
"to",
"export",
"their",
"settings",
"."
] | def _AddImportedDependencies(self, targets, dependencies=None):
"""Given a list of direct dependencies, adds indirect dependencies that
other dependencies have declared to export their settings.
This method does not operate on self. Rather, it operates on the list
of dependencies in the |dependencies| argument. For each dependency in
that list, if any declares that it exports the settings of one of its
own dependencies, those dependencies whose settings are "passed through"
are added to the list. As new items are added to the list, they too will
be processed, so it is possible to import settings through multiple levels
of dependencies.
This method is not terribly useful on its own, it depends on being
"primed" with a list of direct dependencies such as one provided by
DirectDependencies. DirectAndImportedDependencies is intended to be the
public entry point.
"""
if dependencies == None:
dependencies = []
index = 0
while index < len(dependencies):
dependency = dependencies[index]
dependency_dict = targets[dependency]
# Add any dependencies whose settings should be imported to the list
# if not already present. Newly-added items will be checked for
# their own imports when the list iteration reaches them.
# Rather than simply appending new items, insert them after the
# dependency that exported them. This is done to more closely match
# the depth-first method used by DeepDependencies.
add_index = 1
for imported_dependency in \
dependency_dict.get('export_dependent_settings', []):
if imported_dependency not in dependencies:
dependencies.insert(index + add_index, imported_dependency)
add_index = add_index + 1
index = index + 1
return dependencies | [
"def",
"_AddImportedDependencies",
"(",
"self",
",",
"targets",
",",
"dependencies",
"=",
"None",
")",
":",
"if",
"dependencies",
"==",
"None",
":",
"dependencies",
"=",
"[",
"]",
"index",
"=",
"0",
"while",
"index",
"<",
"len",
"(",
"dependencies",
")",
":",
"dependency",
"=",
"dependencies",
"[",
"index",
"]",
"dependency_dict",
"=",
"targets",
"[",
"dependency",
"]",
"# Add any dependencies whose settings should be imported to the list",
"# if not already present. Newly-added items will be checked for",
"# their own imports when the list iteration reaches them.",
"# Rather than simply appending new items, insert them after the",
"# dependency that exported them. This is done to more closely match",
"# the depth-first method used by DeepDependencies.",
"add_index",
"=",
"1",
"for",
"imported_dependency",
"in",
"dependency_dict",
".",
"get",
"(",
"'export_dependent_settings'",
",",
"[",
"]",
")",
":",
"if",
"imported_dependency",
"not",
"in",
"dependencies",
":",
"dependencies",
".",
"insert",
"(",
"index",
"+",
"add_index",
",",
"imported_dependency",
")",
"add_index",
"=",
"add_index",
"+",
"1",
"index",
"=",
"index",
"+",
"1",
"return",
"dependencies"
] | https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/input.py#L1315-L1354 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py | python | _singlefileMailbox.__len__ | (self) | return len(self._toc) | Return a count of messages in the mailbox. | Return a count of messages in the mailbox. | [
"Return",
"a",
"count",
"of",
"messages",
"in",
"the",
"mailbox",
"."
] | def __len__(self):
"""Return a count of messages in the mailbox."""
self._lookup()
return len(self._toc) | [
"def",
"__len__",
"(",
"self",
")",
":",
"self",
".",
"_lookup",
"(",
")",
"return",
"len",
"(",
"self",
".",
"_toc",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py#L617-L620 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/seq2seq/python/ops/decoder.py | python | dynamic_decode | (decoder,
output_time_major=False,
impute_finished=False,
maximum_iterations=None,
parallel_iterations=32,
swap_memory=False,
scope=None) | return final_outputs, final_state, final_sequence_lengths | Perform dynamic decoding with `decoder`.
Calls initialize() once and step() repeatedly on the Decoder object.
Args:
decoder: A `Decoder` instance.
output_time_major: Python boolean. Default: `False` (batch major). If
`True`, outputs are returned as time major tensors (this mode is faster).
Otherwise, outputs are returned as batch major tensors (this adds extra
time to the computation).
impute_finished: Python boolean. If `True`, then states for batch
entries which are marked as finished get copied through and the
corresponding outputs get zeroed out. This causes some slowdown at
each time step, but ensures that the final state and outputs have
the correct values and that backprop ignores time steps that were
marked as finished.
maximum_iterations: `int32` scalar, maximum allowed number of decoding
steps. Default is `None` (decode until the decoder is fully done).
parallel_iterations: Argument passed to `tf.while_loop`.
swap_memory: Argument passed to `tf.while_loop`.
scope: Optional variable scope to use.
Returns:
`(final_outputs, final_state, final_sequence_lengths)`.
Raises:
TypeError: if `decoder` is not an instance of `Decoder`.
ValueError: if `maximum_iterations` is provided but is not a scalar. | Perform dynamic decoding with `decoder`. | [
"Perform",
"dynamic",
"decoding",
"with",
"decoder",
"."
] | def dynamic_decode(decoder,
output_time_major=False,
impute_finished=False,
maximum_iterations=None,
parallel_iterations=32,
swap_memory=False,
scope=None):
"""Perform dynamic decoding with `decoder`.
Calls initialize() once and step() repeatedly on the Decoder object.
Args:
decoder: A `Decoder` instance.
output_time_major: Python boolean. Default: `False` (batch major). If
`True`, outputs are returned as time major tensors (this mode is faster).
Otherwise, outputs are returned as batch major tensors (this adds extra
time to the computation).
impute_finished: Python boolean. If `True`, then states for batch
entries which are marked as finished get copied through and the
corresponding outputs get zeroed out. This causes some slowdown at
each time step, but ensures that the final state and outputs have
the correct values and that backprop ignores time steps that were
marked as finished.
maximum_iterations: `int32` scalar, maximum allowed number of decoding
steps. Default is `None` (decode until the decoder is fully done).
parallel_iterations: Argument passed to `tf.while_loop`.
swap_memory: Argument passed to `tf.while_loop`.
scope: Optional variable scope to use.
Returns:
`(final_outputs, final_state, final_sequence_lengths)`.
Raises:
TypeError: if `decoder` is not an instance of `Decoder`.
ValueError: if `maximum_iterations` is provided but is not a scalar.
"""
if not isinstance(decoder, Decoder):
raise TypeError("Expected decoder to be type Decoder, but saw: %s" %
type(decoder))
with variable_scope.variable_scope(scope, "decoder") as varscope:
# Properly cache variable values inside the while_loop
if varscope.caching_device is None:
varscope.set_caching_device(lambda op: op.device)
if maximum_iterations is not None:
maximum_iterations = ops.convert_to_tensor(
maximum_iterations, dtype=dtypes.int32, name="maximum_iterations")
if maximum_iterations.get_shape().ndims != 0:
raise ValueError("maximum_iterations must be a scalar")
initial_finished, initial_inputs, initial_state = decoder.initialize()
zero_outputs = _create_zero_outputs(decoder.output_size,
decoder.output_dtype,
decoder.batch_size)
if maximum_iterations is not None:
initial_finished = math_ops.logical_or(
initial_finished, 0 >= maximum_iterations)
initial_sequence_lengths = array_ops.zeros_like(
initial_finished, dtype=dtypes.int32)
initial_time = constant_op.constant(0, dtype=dtypes.int32)
def _shape(batch_size, from_shape):
if not isinstance(from_shape, tensor_shape.TensorShape):
return tensor_shape.TensorShape(None)
else:
batch_size = tensor_util.constant_value(
ops.convert_to_tensor(
batch_size, name="batch_size"))
return tensor_shape.TensorShape([batch_size]).concatenate(from_shape)
def _create_ta(s, d):
return tensor_array_ops.TensorArray(
dtype=d,
size=0,
dynamic_size=True,
element_shape=_shape(decoder.batch_size, s))
initial_outputs_ta = nest.map_structure(_create_ta, decoder.output_size,
decoder.output_dtype)
def condition(unused_time, unused_outputs_ta, unused_state, unused_inputs,
finished, unused_sequence_lengths):
return math_ops.logical_not(math_ops.reduce_all(finished))
def body(time, outputs_ta, state, inputs, finished, sequence_lengths):
"""Internal while_loop body.
Args:
time: scalar int32 tensor.
outputs_ta: structure of TensorArray.
state: (structure of) state tensors and TensorArrays.
inputs: (structure of) input tensors.
finished: bool tensor (keeping track of what's finished).
sequence_lengths: int32 tensor (keeping track of time of finish).
Returns:
`(time + 1, outputs_ta, next_state, next_inputs, next_finished,
next_sequence_lengths)`.
```
"""
(next_outputs, decoder_state, next_inputs,
decoder_finished) = decoder.step(time, inputs, state)
if decoder.tracks_own_finished:
next_finished = decoder_finished
else:
next_finished = math_ops.logical_or(decoder_finished, finished)
if maximum_iterations is not None:
next_finished = math_ops.logical_or(
next_finished, time + 1 >= maximum_iterations)
next_sequence_lengths = array_ops.where(
math_ops.logical_and(math_ops.logical_not(finished), next_finished),
array_ops.fill(array_ops.shape(sequence_lengths), time + 1),
sequence_lengths)
nest.assert_same_structure(state, decoder_state)
nest.assert_same_structure(outputs_ta, next_outputs)
nest.assert_same_structure(inputs, next_inputs)
# Zero out output values past finish
if impute_finished:
emit = nest.map_structure(
lambda out, zero: array_ops.where(finished, zero, out),
next_outputs,
zero_outputs)
else:
emit = next_outputs
# Copy through states past finish
def _maybe_copy_state(new, cur):
# TensorArrays and scalar states get passed through.
if isinstance(cur, tensor_array_ops.TensorArray):
pass_through = True
else:
new.set_shape(cur.shape)
pass_through = (new.shape.ndims == 0)
return new if pass_through else array_ops.where(finished, cur, new)
if impute_finished:
next_state = nest.map_structure(
_maybe_copy_state, decoder_state, state)
else:
next_state = decoder_state
outputs_ta = nest.map_structure(lambda ta, out: ta.write(time, out),
outputs_ta, emit)
return (time + 1, outputs_ta, next_state, next_inputs, next_finished,
next_sequence_lengths)
res = control_flow_ops.while_loop(
condition,
body,
loop_vars=[
initial_time, initial_outputs_ta, initial_state, initial_inputs,
initial_finished, initial_sequence_lengths,
],
parallel_iterations=parallel_iterations,
swap_memory=swap_memory)
final_outputs_ta = res[1]
final_state = res[2]
final_sequence_lengths = res[5]
final_outputs = nest.map_structure(lambda ta: ta.stack(), final_outputs_ta)
try:
final_outputs, final_state = decoder.finalize(
final_outputs, final_state, final_sequence_lengths)
except NotImplementedError:
pass
if not output_time_major:
final_outputs = nest.map_structure(_transpose_batch_time, final_outputs)
return final_outputs, final_state, final_sequence_lengths | [
"def",
"dynamic_decode",
"(",
"decoder",
",",
"output_time_major",
"=",
"False",
",",
"impute_finished",
"=",
"False",
",",
"maximum_iterations",
"=",
"None",
",",
"parallel_iterations",
"=",
"32",
",",
"swap_memory",
"=",
"False",
",",
"scope",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"decoder",
",",
"Decoder",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected decoder to be type Decoder, but saw: %s\"",
"%",
"type",
"(",
"decoder",
")",
")",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"scope",
",",
"\"decoder\"",
")",
"as",
"varscope",
":",
"# Properly cache variable values inside the while_loop",
"if",
"varscope",
".",
"caching_device",
"is",
"None",
":",
"varscope",
".",
"set_caching_device",
"(",
"lambda",
"op",
":",
"op",
".",
"device",
")",
"if",
"maximum_iterations",
"is",
"not",
"None",
":",
"maximum_iterations",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"maximum_iterations",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
",",
"name",
"=",
"\"maximum_iterations\"",
")",
"if",
"maximum_iterations",
".",
"get_shape",
"(",
")",
".",
"ndims",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"maximum_iterations must be a scalar\"",
")",
"initial_finished",
",",
"initial_inputs",
",",
"initial_state",
"=",
"decoder",
".",
"initialize",
"(",
")",
"zero_outputs",
"=",
"_create_zero_outputs",
"(",
"decoder",
".",
"output_size",
",",
"decoder",
".",
"output_dtype",
",",
"decoder",
".",
"batch_size",
")",
"if",
"maximum_iterations",
"is",
"not",
"None",
":",
"initial_finished",
"=",
"math_ops",
".",
"logical_or",
"(",
"initial_finished",
",",
"0",
">=",
"maximum_iterations",
")",
"initial_sequence_lengths",
"=",
"array_ops",
".",
"zeros_like",
"(",
"initial_finished",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
"initial_time",
"=",
"constant_op",
".",
"constant",
"(",
"0",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
"def",
"_shape",
"(",
"batch_size",
",",
"from_shape",
")",
":",
"if",
"not",
"isinstance",
"(",
"from_shape",
",",
"tensor_shape",
".",
"TensorShape",
")",
":",
"return",
"tensor_shape",
".",
"TensorShape",
"(",
"None",
")",
"else",
":",
"batch_size",
"=",
"tensor_util",
".",
"constant_value",
"(",
"ops",
".",
"convert_to_tensor",
"(",
"batch_size",
",",
"name",
"=",
"\"batch_size\"",
")",
")",
"return",
"tensor_shape",
".",
"TensorShape",
"(",
"[",
"batch_size",
"]",
")",
".",
"concatenate",
"(",
"from_shape",
")",
"def",
"_create_ta",
"(",
"s",
",",
"d",
")",
":",
"return",
"tensor_array_ops",
".",
"TensorArray",
"(",
"dtype",
"=",
"d",
",",
"size",
"=",
"0",
",",
"dynamic_size",
"=",
"True",
",",
"element_shape",
"=",
"_shape",
"(",
"decoder",
".",
"batch_size",
",",
"s",
")",
")",
"initial_outputs_ta",
"=",
"nest",
".",
"map_structure",
"(",
"_create_ta",
",",
"decoder",
".",
"output_size",
",",
"decoder",
".",
"output_dtype",
")",
"def",
"condition",
"(",
"unused_time",
",",
"unused_outputs_ta",
",",
"unused_state",
",",
"unused_inputs",
",",
"finished",
",",
"unused_sequence_lengths",
")",
":",
"return",
"math_ops",
".",
"logical_not",
"(",
"math_ops",
".",
"reduce_all",
"(",
"finished",
")",
")",
"def",
"body",
"(",
"time",
",",
"outputs_ta",
",",
"state",
",",
"inputs",
",",
"finished",
",",
"sequence_lengths",
")",
":",
"\"\"\"Internal while_loop body.\n\n Args:\n time: scalar int32 tensor.\n outputs_ta: structure of TensorArray.\n state: (structure of) state tensors and TensorArrays.\n inputs: (structure of) input tensors.\n finished: bool tensor (keeping track of what's finished).\n sequence_lengths: int32 tensor (keeping track of time of finish).\n\n Returns:\n `(time + 1, outputs_ta, next_state, next_inputs, next_finished,\n next_sequence_lengths)`.\n ```\n \"\"\"",
"(",
"next_outputs",
",",
"decoder_state",
",",
"next_inputs",
",",
"decoder_finished",
")",
"=",
"decoder",
".",
"step",
"(",
"time",
",",
"inputs",
",",
"state",
")",
"if",
"decoder",
".",
"tracks_own_finished",
":",
"next_finished",
"=",
"decoder_finished",
"else",
":",
"next_finished",
"=",
"math_ops",
".",
"logical_or",
"(",
"decoder_finished",
",",
"finished",
")",
"if",
"maximum_iterations",
"is",
"not",
"None",
":",
"next_finished",
"=",
"math_ops",
".",
"logical_or",
"(",
"next_finished",
",",
"time",
"+",
"1",
">=",
"maximum_iterations",
")",
"next_sequence_lengths",
"=",
"array_ops",
".",
"where",
"(",
"math_ops",
".",
"logical_and",
"(",
"math_ops",
".",
"logical_not",
"(",
"finished",
")",
",",
"next_finished",
")",
",",
"array_ops",
".",
"fill",
"(",
"array_ops",
".",
"shape",
"(",
"sequence_lengths",
")",
",",
"time",
"+",
"1",
")",
",",
"sequence_lengths",
")",
"nest",
".",
"assert_same_structure",
"(",
"state",
",",
"decoder_state",
")",
"nest",
".",
"assert_same_structure",
"(",
"outputs_ta",
",",
"next_outputs",
")",
"nest",
".",
"assert_same_structure",
"(",
"inputs",
",",
"next_inputs",
")",
"# Zero out output values past finish",
"if",
"impute_finished",
":",
"emit",
"=",
"nest",
".",
"map_structure",
"(",
"lambda",
"out",
",",
"zero",
":",
"array_ops",
".",
"where",
"(",
"finished",
",",
"zero",
",",
"out",
")",
",",
"next_outputs",
",",
"zero_outputs",
")",
"else",
":",
"emit",
"=",
"next_outputs",
"# Copy through states past finish",
"def",
"_maybe_copy_state",
"(",
"new",
",",
"cur",
")",
":",
"# TensorArrays and scalar states get passed through.",
"if",
"isinstance",
"(",
"cur",
",",
"tensor_array_ops",
".",
"TensorArray",
")",
":",
"pass_through",
"=",
"True",
"else",
":",
"new",
".",
"set_shape",
"(",
"cur",
".",
"shape",
")",
"pass_through",
"=",
"(",
"new",
".",
"shape",
".",
"ndims",
"==",
"0",
")",
"return",
"new",
"if",
"pass_through",
"else",
"array_ops",
".",
"where",
"(",
"finished",
",",
"cur",
",",
"new",
")",
"if",
"impute_finished",
":",
"next_state",
"=",
"nest",
".",
"map_structure",
"(",
"_maybe_copy_state",
",",
"decoder_state",
",",
"state",
")",
"else",
":",
"next_state",
"=",
"decoder_state",
"outputs_ta",
"=",
"nest",
".",
"map_structure",
"(",
"lambda",
"ta",
",",
"out",
":",
"ta",
".",
"write",
"(",
"time",
",",
"out",
")",
",",
"outputs_ta",
",",
"emit",
")",
"return",
"(",
"time",
"+",
"1",
",",
"outputs_ta",
",",
"next_state",
",",
"next_inputs",
",",
"next_finished",
",",
"next_sequence_lengths",
")",
"res",
"=",
"control_flow_ops",
".",
"while_loop",
"(",
"condition",
",",
"body",
",",
"loop_vars",
"=",
"[",
"initial_time",
",",
"initial_outputs_ta",
",",
"initial_state",
",",
"initial_inputs",
",",
"initial_finished",
",",
"initial_sequence_lengths",
",",
"]",
",",
"parallel_iterations",
"=",
"parallel_iterations",
",",
"swap_memory",
"=",
"swap_memory",
")",
"final_outputs_ta",
"=",
"res",
"[",
"1",
"]",
"final_state",
"=",
"res",
"[",
"2",
"]",
"final_sequence_lengths",
"=",
"res",
"[",
"5",
"]",
"final_outputs",
"=",
"nest",
".",
"map_structure",
"(",
"lambda",
"ta",
":",
"ta",
".",
"stack",
"(",
")",
",",
"final_outputs_ta",
")",
"try",
":",
"final_outputs",
",",
"final_state",
"=",
"decoder",
".",
"finalize",
"(",
"final_outputs",
",",
"final_state",
",",
"final_sequence_lengths",
")",
"except",
"NotImplementedError",
":",
"pass",
"if",
"not",
"output_time_major",
":",
"final_outputs",
"=",
"nest",
".",
"map_structure",
"(",
"_transpose_batch_time",
",",
"final_outputs",
")",
"return",
"final_outputs",
",",
"final_state",
",",
"final_sequence_lengths"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/seq2seq/python/ops/decoder.py#L150-L326 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.