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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apache/parquet-cpp
|
642da055adf009652689b20e68a198cffb857651
|
build-support/cpplint.py
|
python
|
_VerboseLevel
|
()
|
return _cpplint_state.verbose_level
|
Returns the module's verbosity setting.
|
Returns the module's verbosity setting.
|
[
"Returns",
"the",
"module",
"s",
"verbosity",
"setting",
"."
] |
def _VerboseLevel():
"""Returns the module's verbosity setting."""
return _cpplint_state.verbose_level
|
[
"def",
"_VerboseLevel",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"verbose_level"
] |
https://github.com/apache/parquet-cpp/blob/642da055adf009652689b20e68a198cffb857651/build-support/cpplint.py#L861-L863
|
|
ros-perception/image_pipeline
|
cd4aa7ab38726d88e8e0144aa0d45ad2f236535a
|
camera_calibration/src/camera_calibration/calibrator.py
|
python
|
MonoCalibrator.cal
|
(self, images)
|
Calibrate camera from given images
|
Calibrate camera from given images
|
[
"Calibrate",
"camera",
"from",
"given",
"images"
] |
def cal(self, images):
"""
Calibrate camera from given images
"""
goodcorners = self.collect_corners(images)
self.cal_fromcorners(goodcorners)
self.calibrated = True
|
[
"def",
"cal",
"(",
"self",
",",
"images",
")",
":",
"goodcorners",
"=",
"self",
".",
"collect_corners",
"(",
"images",
")",
"self",
".",
"cal_fromcorners",
"(",
"goodcorners",
")",
"self",
".",
"calibrated",
"=",
"True"
] |
https://github.com/ros-perception/image_pipeline/blob/cd4aa7ab38726d88e8e0144aa0d45ad2f236535a/camera_calibration/src/camera_calibration/calibrator.py#L727-L733
|
||
idaholab/moose
|
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
|
python/peacock/ExodusViewer/plugins/ColorbarPlugin.py
|
python
|
ColorbarPlugin.updateColorbarOptions
|
(self)
|
Add/remove the colorbar object.
|
Add/remove the colorbar object.
|
[
"Add",
"/",
"remove",
"the",
"colorbar",
"object",
"."
] |
def updateColorbarOptions(self):
"""
Add/remove the colorbar object.
"""
if (self._window is None) or (self._result is None):
return
visible = self.ColorBarToggle.isChecked()
if visible:
if self._colorbar is None:
self._colorbar = chigger.exodus.ExodusColorBar(self._result, layer=3)
self._colorbar.setOptions('primary', font_size=16)
if self._colorbar not in self._window:
self._window.append(self._colorbar)
elif (self._colorbar in self._window) and (self._colorbar is not None):
self._window.remove(self._colorbar)
self._colorbar = None
|
[
"def",
"updateColorbarOptions",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_window",
"is",
"None",
")",
"or",
"(",
"self",
".",
"_result",
"is",
"None",
")",
":",
"return",
"visible",
"=",
"self",
".",
"ColorBarToggle",
".",
"isChecked",
"(",
")",
"if",
"visible",
":",
"if",
"self",
".",
"_colorbar",
"is",
"None",
":",
"self",
".",
"_colorbar",
"=",
"chigger",
".",
"exodus",
".",
"ExodusColorBar",
"(",
"self",
".",
"_result",
",",
"layer",
"=",
"3",
")",
"self",
".",
"_colorbar",
".",
"setOptions",
"(",
"'primary'",
",",
"font_size",
"=",
"16",
")",
"if",
"self",
".",
"_colorbar",
"not",
"in",
"self",
".",
"_window",
":",
"self",
".",
"_window",
".",
"append",
"(",
"self",
".",
"_colorbar",
")",
"elif",
"(",
"self",
".",
"_colorbar",
"in",
"self",
".",
"_window",
")",
"and",
"(",
"self",
".",
"_colorbar",
"is",
"not",
"None",
")",
":",
"self",
".",
"_window",
".",
"remove",
"(",
"self",
".",
"_colorbar",
")",
"self",
".",
"_colorbar",
"=",
"None"
] |
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/ColorbarPlugin.py#L206-L224
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/_controls.py
|
python
|
ListCtrl.DeleteAllItems
|
(*args, **kwargs)
|
return _controls_.ListCtrl_DeleteAllItems(*args, **kwargs)
|
DeleteAllItems(self) -> bool
|
DeleteAllItems(self) -> bool
|
[
"DeleteAllItems",
"(",
"self",
")",
"-",
">",
"bool"
] |
def DeleteAllItems(*args, **kwargs):
"""DeleteAllItems(self) -> bool"""
return _controls_.ListCtrl_DeleteAllItems(*args, **kwargs)
|
[
"def",
"DeleteAllItems",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_DeleteAllItems",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4645-L4647
|
|
oracle/graaljs
|
36a56e8e993d45fc40939a3a4d9c0c24990720f1
|
graal-nodejs/deps/v8/third_party/jinja2/runtime.py
|
python
|
Context.super
|
(self, name, current)
|
return BlockReference(name, self, blocks, index)
|
Render a parent block.
|
Render a parent block.
|
[
"Render",
"a",
"parent",
"block",
"."
] |
def super(self, name, current):
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined('there is no parent block '
'called %r.' % name,
name='super')
return BlockReference(name, self, blocks, index)
|
[
"def",
"super",
"(",
"self",
",",
"name",
",",
"current",
")",
":",
"try",
":",
"blocks",
"=",
"self",
".",
"blocks",
"[",
"name",
"]",
"index",
"=",
"blocks",
".",
"index",
"(",
"current",
")",
"+",
"1",
"blocks",
"[",
"index",
"]",
"except",
"LookupError",
":",
"return",
"self",
".",
"environment",
".",
"undefined",
"(",
"'there is no parent block '",
"'called %r.'",
"%",
"name",
",",
"name",
"=",
"'super'",
")",
"return",
"BlockReference",
"(",
"name",
",",
"self",
",",
"blocks",
",",
"index",
")"
] |
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/runtime.py#L175-L185
|
|
baidu-research/tensorflow-allreduce
|
66d5b855e90b0949e9fa5cca5599fd729a70e874
|
tensorflow/contrib/keras/python/keras/backend.py
|
python
|
pow
|
(x, a)
|
return math_ops.pow(x, a)
|
Element-wise exponentiation.
Arguments:
x: Tensor or variable.
a: Python integer.
Returns:
A tensor.
|
Element-wise exponentiation.
|
[
"Element",
"-",
"wise",
"exponentiation",
"."
] |
def pow(x, a):
"""Element-wise exponentiation.
Arguments:
x: Tensor or variable.
a: Python integer.
Returns:
A tensor.
"""
return math_ops.pow(x, a)
|
[
"def",
"pow",
"(",
"x",
",",
"a",
")",
":",
"return",
"math_ops",
".",
"pow",
"(",
"x",
",",
"a",
")"
] |
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/backend.py#L1632-L1642
|
|
kamyu104/LeetCode-Solutions
|
77605708a927ea3b85aee5a479db733938c7c211
|
Python/sum-of-digits-in-base-k.py
|
python
|
Solution.sumBase
|
(self, n, k)
|
return result
|
:type n: int
:type k: int
:rtype: int
|
:type n: int
:type k: int
:rtype: int
|
[
":",
"type",
"n",
":",
"int",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"int"
] |
def sumBase(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
result = 0
while n:
n, r = divmod(n, k)
result += r
return result
|
[
"def",
"sumBase",
"(",
"self",
",",
"n",
",",
"k",
")",
":",
"result",
"=",
"0",
"while",
"n",
":",
"n",
",",
"r",
"=",
"divmod",
"(",
"n",
",",
"k",
")",
"result",
"+=",
"r",
"return",
"result"
] |
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/sum-of-digits-in-base-k.py#L5-L15
|
|
KratosMultiphysics/Kratos
|
0000833054ed0503424eb28205d6508d9ca6cbbc
|
applications/ShallowWaterApplication/python_scripts/postprocess/line_graph_output_process.py
|
python
|
LineGraphOutputProcess.IsOutputStep
|
(self)
|
return self.interval.IsInInterval(time) and self.output_control.IsOutputStep()
|
Return if the current step is an output step.
|
Return if the current step is an output step.
|
[
"Return",
"if",
"the",
"current",
"step",
"is",
"an",
"output",
"step",
"."
] |
def IsOutputStep(self):
"""Return if the current step is an output step."""
time = self.model_part.ProcessInfo[KM.TIME]
return self.interval.IsInInterval(time) and self.output_control.IsOutputStep()
|
[
"def",
"IsOutputStep",
"(",
"self",
")",
":",
"time",
"=",
"self",
".",
"model_part",
".",
"ProcessInfo",
"[",
"KM",
".",
"TIME",
"]",
"return",
"self",
".",
"interval",
".",
"IsInInterval",
"(",
"time",
")",
"and",
"self",
".",
"output_control",
".",
"IsOutputStep",
"(",
")"
] |
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ShallowWaterApplication/python_scripts/postprocess/line_graph_output_process.py#L122-L126
|
|
niwinz/phantompy
|
ae25ddb6791e13cb7c35126971c410030ee5dfda
|
phantompy/context.py
|
python
|
Context.set_headers
|
(self, headers)
|
Set a list of headers.
|
Set a list of headers.
|
[
"Set",
"a",
"list",
"of",
"headers",
"."
] |
def set_headers(self, headers):
"""
Set a list of headers.
"""
lib.ph_context_set_headers(util.force_bytes(json.dumps(headers)))
|
[
"def",
"set_headers",
"(",
"self",
",",
"headers",
")",
":",
"lib",
".",
"ph_context_set_headers",
"(",
"util",
".",
"force_bytes",
"(",
"json",
".",
"dumps",
"(",
"headers",
")",
")",
")"
] |
https://github.com/niwinz/phantompy/blob/ae25ddb6791e13cb7c35126971c410030ee5dfda/phantompy/context.py#L92-L96
|
||
papyrussolution/OpenPapyrus
|
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
|
Src/OSF/xapian/xapian-maintainer-tools/buildbot/scripts/get_tarballs.py
|
python
|
get_archive_links
|
(url, archives)
|
return links
|
Get the links to the archive files.
|
Get the links to the archive files.
|
[
"Get",
"the",
"links",
"to",
"the",
"archive",
"files",
"."
] |
def get_archive_links(url, archives):
"""Get the links to the archive files.
"""
print("Getting links from '%s'" % url)
fd = u.urlopen(url)
html = fd.read()
fd.close()
max_revision, links = parsehtml(html, archives)
return links
|
[
"def",
"get_archive_links",
"(",
"url",
",",
"archives",
")",
":",
"print",
"(",
"\"Getting links from '%s'\"",
"%",
"url",
")",
"fd",
"=",
"u",
".",
"urlopen",
"(",
"url",
")",
"html",
"=",
"fd",
".",
"read",
"(",
")",
"fd",
".",
"close",
"(",
")",
"max_revision",
",",
"links",
"=",
"parsehtml",
"(",
"html",
",",
"archives",
")",
"return",
"links"
] |
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/xapian/xapian-maintainer-tools/buildbot/scripts/get_tarballs.py#L63-L72
|
|
kamyu104/LeetCode-Solutions
|
77605708a927ea3b85aee5a479db733938c7c211
|
Python/find-duplicate-subtrees.py
|
python
|
Solution.findDuplicateSubtrees
|
(self, root)
|
return [roots[0] for roots in trees.itervalues() if len(roots) > 1]
|
:type root: TreeNode
:rtype: List[TreeNode]
|
:type root: TreeNode
:rtype: List[TreeNode]
|
[
":",
"type",
"root",
":",
"TreeNode",
":",
"rtype",
":",
"List",
"[",
"TreeNode",
"]"
] |
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
def getid(root, lookup, trees):
if not root:
return -1
node_id = lookup[root.val,
getid(root.left, lookup, trees),
getid(root.right, lookup, trees)]
trees[node_id].append(root)
return node_id
trees = collections.defaultdict(list)
lookup = collections.defaultdict()
lookup.default_factory = lookup.__len__
getid(root, lookup, trees)
return [roots[0] for roots in trees.itervalues() if len(roots) > 1]
|
[
"def",
"findDuplicateSubtrees",
"(",
"self",
",",
"root",
")",
":",
"def",
"getid",
"(",
"root",
",",
"lookup",
",",
"trees",
")",
":",
"if",
"not",
"root",
":",
"return",
"-",
"1",
"node_id",
"=",
"lookup",
"[",
"root",
".",
"val",
",",
"getid",
"(",
"root",
".",
"left",
",",
"lookup",
",",
"trees",
")",
",",
"getid",
"(",
"root",
".",
"right",
",",
"lookup",
",",
"trees",
")",
"]",
"trees",
"[",
"node_id",
"]",
".",
"append",
"(",
"root",
")",
"return",
"node_id",
"trees",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"lookup",
"=",
"collections",
".",
"defaultdict",
"(",
")",
"lookup",
".",
"default_factory",
"=",
"lookup",
".",
"__len__",
"getid",
"(",
"root",
",",
"lookup",
",",
"trees",
")",
"return",
"[",
"roots",
"[",
"0",
"]",
"for",
"roots",
"in",
"trees",
".",
"itervalues",
"(",
")",
"if",
"len",
"(",
"roots",
")",
">",
"1",
"]"
] |
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/find-duplicate-subtrees.py#L8-L26
|
|
mantidproject/mantid
|
03deeb89254ec4289edb8771e0188c2090a02f32
|
qt/applications/workbench/workbench/config/user.py
|
python
|
UserConfig.set
|
(self, option, value, extra=None)
|
Set a value for an option in a given section. Can either supply
the fully qualified option or add the section as an additional
first argument. ``config.set('main', 'high_dpi_scaling',
True)`` is equivalent to ``config.set('main/high_dpi_scaling',
True)``
|
Set a value for an option in a given section. Can either supply
the fully qualified option or add the section as an additional
first argument. ``config.set('main', 'high_dpi_scaling',
True)`` is equivalent to ``config.set('main/high_dpi_scaling',
True)``
|
[
"Set",
"a",
"value",
"for",
"an",
"option",
"in",
"a",
"given",
"section",
".",
"Can",
"either",
"supply",
"the",
"fully",
"qualified",
"option",
"or",
"add",
"the",
"section",
"as",
"an",
"additional",
"first",
"argument",
".",
"config",
".",
"set",
"(",
"main",
"high_dpi_scaling",
"True",
")",
"is",
"equivalent",
"to",
"config",
".",
"set",
"(",
"main",
"/",
"high_dpi_scaling",
"True",
")"
] |
def set(self, option, value, extra=None):
"""Set a value for an option in a given section. Can either supply
the fully qualified option or add the section as an additional
first argument. ``config.set('main', 'high_dpi_scaling',
True)`` is equivalent to ``config.set('main/high_dpi_scaling',
True)``
"""
if extra is None:
option = self._check_section_option_is_valid(option, extra)
# value is in the right place
else:
option = self._check_section_option_is_valid(option, value)
value = extra
self.qsettings.setValue(option, value)
|
[
"def",
"set",
"(",
"self",
",",
"option",
",",
"value",
",",
"extra",
"=",
"None",
")",
":",
"if",
"extra",
"is",
"None",
":",
"option",
"=",
"self",
".",
"_check_section_option_is_valid",
"(",
"option",
",",
"extra",
")",
"# value is in the right place",
"else",
":",
"option",
"=",
"self",
".",
"_check_section_option_is_valid",
"(",
"option",
",",
"value",
")",
"value",
"=",
"extra",
"self",
".",
"qsettings",
".",
"setValue",
"(",
"option",
",",
"value",
")"
] |
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/config/user.py#L113-L126
|
||
benoitsteiner/tensorflow-opencl
|
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
|
tensorflow/contrib/distributions/python/ops/wishart.py
|
python
|
_WishartLinearOperator._multi_lgamma
|
(self, a, p, name="multi_lgamma")
|
Computes the log multivariate gamma function; log(Gamma_p(a)).
|
Computes the log multivariate gamma function; log(Gamma_p(a)).
|
[
"Computes",
"the",
"log",
"multivariate",
"gamma",
"function",
";",
"log",
"(",
"Gamma_p",
"(",
"a",
"))",
"."
] |
def _multi_lgamma(self, a, p, name="multi_lgamma"):
"""Computes the log multivariate gamma function; log(Gamma_p(a))."""
with self._name_scope(name, values=[a, p]):
seq = self._multi_gamma_sequence(a, p)
return (0.25 * p * (p - 1.) * math.log(math.pi) +
math_ops.reduce_sum(math_ops.lgamma(seq),
axis=[-1]))
|
[
"def",
"_multi_lgamma",
"(",
"self",
",",
"a",
",",
"p",
",",
"name",
"=",
"\"multi_lgamma\"",
")",
":",
"with",
"self",
".",
"_name_scope",
"(",
"name",
",",
"values",
"=",
"[",
"a",
",",
"p",
"]",
")",
":",
"seq",
"=",
"self",
".",
"_multi_gamma_sequence",
"(",
"a",
",",
"p",
")",
"return",
"(",
"0.25",
"*",
"p",
"*",
"(",
"p",
"-",
"1.",
")",
"*",
"math",
".",
"log",
"(",
"math",
".",
"pi",
")",
"+",
"math_ops",
".",
"reduce_sum",
"(",
"math_ops",
".",
"lgamma",
"(",
"seq",
")",
",",
"axis",
"=",
"[",
"-",
"1",
"]",
")",
")"
] |
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/wishart.py#L423-L429
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/Jinja2/py2/jinja2/environment.py
|
python
|
get_spontaneous_environment
|
(cls, *args)
|
Return a new spontaneous environment. A spontaneous environment
is used for templates created directly rather than through an
existing environment.
:param cls: Environment class to create.
:param args: Positional arguments passed to environment.
|
Return a new spontaneous environment. A spontaneous environment
is used for templates created directly rather than through an
existing environment.
|
[
"Return",
"a",
"new",
"spontaneous",
"environment",
".",
"A",
"spontaneous",
"environment",
"is",
"used",
"for",
"templates",
"created",
"directly",
"rather",
"than",
"through",
"an",
"existing",
"environment",
"."
] |
def get_spontaneous_environment(cls, *args):
"""Return a new spontaneous environment. A spontaneous environment
is used for templates created directly rather than through an
existing environment.
:param cls: Environment class to create.
:param args: Positional arguments passed to environment.
"""
key = (cls, args)
try:
return _spontaneous_environments[key]
except KeyError:
_spontaneous_environments[key] = env = cls(*args)
env.shared = True
return env
|
[
"def",
"get_spontaneous_environment",
"(",
"cls",
",",
"*",
"args",
")",
":",
"key",
"=",
"(",
"cls",
",",
"args",
")",
"try",
":",
"return",
"_spontaneous_environments",
"[",
"key",
"]",
"except",
"KeyError",
":",
"_spontaneous_environments",
"[",
"key",
"]",
"=",
"env",
"=",
"cls",
"(",
"*",
"args",
")",
"env",
".",
"shared",
"=",
"True",
"return",
"env"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/environment.py#L65-L80
|
||
ChromiumWebApps/chromium
|
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
|
third_party/jinja2/environment.py
|
python
|
Environment._generate
|
(self, source, name, filename, defer_init=False)
|
return generate(source, self, name, filename, defer_init=defer_init)
|
Internal hook that can be overridden to hook a different generate
method in.
.. versionadded:: 2.5
|
Internal hook that can be overridden to hook a different generate
method in.
|
[
"Internal",
"hook",
"that",
"can",
"be",
"overridden",
"to",
"hook",
"a",
"different",
"generate",
"method",
"in",
"."
] |
def _generate(self, source, name, filename, defer_init=False):
"""Internal hook that can be overridden to hook a different generate
method in.
.. versionadded:: 2.5
"""
return generate(source, self, name, filename, defer_init=defer_init)
|
[
"def",
"_generate",
"(",
"self",
",",
"source",
",",
"name",
",",
"filename",
",",
"defer_init",
"=",
"False",
")",
":",
"return",
"generate",
"(",
"source",
",",
"self",
",",
"name",
",",
"filename",
",",
"defer_init",
"=",
"defer_init",
")"
] |
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/environment.py#L498-L504
|
|
kushview/Element
|
1cc16380caa2ab79461246ba758b9de1f46db2a5
|
waflib/Build.py
|
python
|
BuildContext.add_post_fun
|
(self, meth)
|
Binds a callback method to execute immediately after the build is successful::
def call_ldconfig(bld):
bld.exec_command('/sbin/ldconfig')
def build(bld):
if bld.cmd == 'install':
bld.add_pre_fun(call_ldconfig)
|
Binds a callback method to execute immediately after the build is successful::
|
[
"Binds",
"a",
"callback",
"method",
"to",
"execute",
"immediately",
"after",
"the",
"build",
"is",
"successful",
"::"
] |
def add_post_fun(self, meth):
"""
Binds a callback method to execute immediately after the build is successful::
def call_ldconfig(bld):
bld.exec_command('/sbin/ldconfig')
def build(bld):
if bld.cmd == 'install':
bld.add_pre_fun(call_ldconfig)
"""
try:
self.post_funs.append(meth)
except AttributeError:
self.post_funs = [meth]
|
[
"def",
"add_post_fun",
"(",
"self",
",",
"meth",
")",
":",
"try",
":",
"self",
".",
"post_funs",
".",
"append",
"(",
"meth",
")",
"except",
"AttributeError",
":",
"self",
".",
"post_funs",
"=",
"[",
"meth",
"]"
] |
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Build.py#L564-L578
|
||
hfinkel/llvm-project-cxxjit
|
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
|
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
|
python
|
GetHeaderGuardCPPVariable
|
(filename)
|
return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
|
Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file.
|
Returns the CPP variable that should be used as a header guard.
|
[
"Returns",
"the",
"CPP",
"variable",
"that",
"should",
"be",
"used",
"as",
"a",
"header",
"guard",
"."
] |
def GetHeaderGuardCPPVariable(filename):
"""Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file.
"""
# Restores original filename in case that cpplint is invoked from Emacs's
# flymake.
filename = re.sub(r'_flymake\.h$', '.h', filename)
filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
fileinfo = FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
if _root:
file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
|
[
"def",
"GetHeaderGuardCPPVariable",
"(",
"filename",
")",
":",
"# Restores original filename in case that cpplint is invoked from Emacs's",
"# flymake.",
"filename",
"=",
"re",
".",
"sub",
"(",
"r'_flymake\\.h$'",
",",
"'.h'",
",",
"filename",
")",
"filename",
"=",
"re",
".",
"sub",
"(",
"r'/\\.flymake/([^/]*)$'",
",",
"r'/\\1'",
",",
"filename",
")",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"file_path_from_root",
"=",
"fileinfo",
".",
"RepositoryName",
"(",
")",
"if",
"_root",
":",
"file_path_from_root",
"=",
"re",
".",
"sub",
"(",
"'^'",
"+",
"_root",
"+",
"os",
".",
"sep",
",",
"''",
",",
"file_path_from_root",
")",
"return",
"re",
".",
"sub",
"(",
"r'[-./\\s]'",
",",
"'_'",
",",
"file_path_from_root",
")",
".",
"upper",
"(",
")",
"+",
"'_'"
] |
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1111-L1132
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python3/src/Lib/functools.py
|
python
|
_ge_from_lt
|
(self, other, NotImplemented=NotImplemented)
|
return not op_result
|
Return a >= b. Computed by @total_ordering from (not a < b).
|
Return a >= b. Computed by
|
[
"Return",
"a",
">",
"=",
"b",
".",
"Computed",
"by"
] |
def _ge_from_lt(self, other, NotImplemented=NotImplemented):
'Return a >= b. Computed by @total_ordering from (not a < b).'
op_result = type(self).__lt__(self, other)
if op_result is NotImplemented:
return op_result
return not op_result
|
[
"def",
"_ge_from_lt",
"(",
"self",
",",
"other",
",",
"NotImplemented",
"=",
"NotImplemented",
")",
":",
"op_result",
"=",
"type",
"(",
"self",
")",
".",
"__lt__",
"(",
"self",
",",
"other",
")",
"if",
"op_result",
"is",
"NotImplemented",
":",
"return",
"op_result",
"return",
"not",
"op_result"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/functools.py#L103-L108
|
|
idaholab/moose
|
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
|
python/moosesqa/get_documents.py
|
python
|
get_documents
|
(required_docs=INL_DOCUMENTS, **kwargs)
|
return [Document(name=name, title=name.replace('_', ' ').title(), filename=kwargs.get(name, None)) for name in required_docs]
|
Build SQA document dictionary from the provided directories.
|
Build SQA document dictionary from the provided directories.
|
[
"Build",
"SQA",
"document",
"dictionary",
"from",
"the",
"provided",
"directories",
"."
] |
def get_documents(required_docs=INL_DOCUMENTS, **kwargs):
"""
Build SQA document dictionary from the provided directories.
"""
return [Document(name=name, title=name.replace('_', ' ').title(), filename=kwargs.get(name, None)) for name in required_docs]
|
[
"def",
"get_documents",
"(",
"required_docs",
"=",
"INL_DOCUMENTS",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"Document",
"(",
"name",
"=",
"name",
",",
"title",
"=",
"name",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
".",
"title",
"(",
")",
",",
"filename",
"=",
"kwargs",
".",
"get",
"(",
"name",
",",
"None",
")",
")",
"for",
"name",
"in",
"required_docs",
"]"
] |
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/moosesqa/get_documents.py#L39-L43
|
|
eclipse/sumo
|
7132a9b8b6eea734bdec38479026b4d8c4336d03
|
tools/traci/_trafficlight.py
|
python
|
TrafficLightDomain.getPhaseName
|
(self, tlsID)
|
return self._getUniversal(tc.VAR_NAME, tlsID)
|
getPhase(string) -> string
Returns the name of the current phase.
|
getPhase(string) -> string
Returns the name of the current phase.
|
[
"getPhase",
"(",
"string",
")",
"-",
">",
"string",
"Returns",
"the",
"name",
"of",
"the",
"current",
"phase",
"."
] |
def getPhaseName(self, tlsID):
"""getPhase(string) -> string
Returns the name of the current phase.
"""
return self._getUniversal(tc.VAR_NAME, tlsID)
|
[
"def",
"getPhaseName",
"(",
"self",
",",
"tlsID",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_NAME",
",",
"tlsID",
")"
] |
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_trafficlight.py#L215-L219
|
|
baidu-research/tensorflow-allreduce
|
66d5b855e90b0949e9fa5cca5599fd729a70e874
|
tensorflow/contrib/data/python/ops/dataset_ops.py
|
python
|
Dataset.filter
|
(self, predicate)
|
return FilterDataset(self, predicate)
|
Filters this dataset according to `predicate`.
Args:
predicate: A function mapping a nested structure of tensors (having shapes
and types defined by `self.output_shapes` and `self.output_types`) to a
scalar `tf.bool` tensor.
Returns:
A `Dataset`.
|
Filters this dataset according to `predicate`.
|
[
"Filters",
"this",
"dataset",
"according",
"to",
"predicate",
"."
] |
def filter(self, predicate):
"""Filters this dataset according to `predicate`.
Args:
predicate: A function mapping a nested structure of tensors (having shapes
and types defined by `self.output_shapes` and `self.output_types`) to a
scalar `tf.bool` tensor.
Returns:
A `Dataset`.
"""
return FilterDataset(self, predicate)
|
[
"def",
"filter",
"(",
"self",
",",
"predicate",
")",
":",
"return",
"FilterDataset",
"(",
"self",
",",
"predicate",
")"
] |
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/data/python/ops/dataset_ops.py#L1061-L1072
|
|
quantOS-org/DataCore
|
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
|
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/descriptor_database.py
|
python
|
_ExtractSymbols
|
(desc_proto, package)
|
Pulls out all the symbols from a descriptor proto.
Args:
desc_proto: The proto to extract symbols from.
package: The package containing the descriptor type.
Yields:
The fully qualified name found in the descriptor.
|
Pulls out all the symbols from a descriptor proto.
|
[
"Pulls",
"out",
"all",
"the",
"symbols",
"from",
"a",
"descriptor",
"proto",
"."
] |
def _ExtractSymbols(desc_proto, package):
"""Pulls out all the symbols from a descriptor proto.
Args:
desc_proto: The proto to extract symbols from.
package: The package containing the descriptor type.
Yields:
The fully qualified name found in the descriptor.
"""
message_name = '.'.join((package, desc_proto.name))
yield message_name
for nested_type in desc_proto.nested_type:
for symbol in _ExtractSymbols(nested_type, message_name):
yield symbol
for enum_type in desc_proto.enum_type:
yield '.'.join((message_name, enum_type.name))
|
[
"def",
"_ExtractSymbols",
"(",
"desc_proto",
",",
"package",
")",
":",
"message_name",
"=",
"'.'",
".",
"join",
"(",
"(",
"package",
",",
"desc_proto",
".",
"name",
")",
")",
"yield",
"message_name",
"for",
"nested_type",
"in",
"desc_proto",
".",
"nested_type",
":",
"for",
"symbol",
"in",
"_ExtractSymbols",
"(",
"nested_type",
",",
"message_name",
")",
":",
"yield",
"symbol",
"for",
"enum_type",
"in",
"desc_proto",
".",
"enum_type",
":",
"yield",
"'.'",
".",
"join",
"(",
"(",
"message_name",
",",
"enum_type",
".",
"name",
")",
")"
] |
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/descriptor_database.py#L103-L120
|
||
mongodb/mongo
|
d8ff665343ad29cf286ee2cf4a1960d29371937b
|
buildscripts/resmokelib/powercycle/powercycle.py
|
python
|
wait_for_mongod_shutdown
|
(mongod_control, timeout=2 * ONE_HOUR_SECS)
|
return 0
|
Wait for for mongod to shutdown; return 0 if shutdown occurs within 'timeout', else 1.
|
Wait for for mongod to shutdown; return 0 if shutdown occurs within 'timeout', else 1.
|
[
"Wait",
"for",
"for",
"mongod",
"to",
"shutdown",
";",
"return",
"0",
"if",
"shutdown",
"occurs",
"within",
"timeout",
"else",
"1",
"."
] |
def wait_for_mongod_shutdown(mongod_control, timeout=2 * ONE_HOUR_SECS):
"""Wait for for mongod to shutdown; return 0 if shutdown occurs within 'timeout', else 1."""
start = time.time()
status = mongod_control.status()
while status != "stopped":
if time.time() - start >= timeout:
LOGGER.error("The mongod process has not stopped, current status is %s", status)
return 1
LOGGER.info("Waiting for mongod process to stop, current status is %s ", status)
time.sleep(3)
status = mongod_control.status()
LOGGER.info("The mongod process has stopped")
# We wait a bit, since files could still be flushed to disk, which was causing
# rsync "file has vanished" errors.
time.sleep(60)
return 0
|
[
"def",
"wait_for_mongod_shutdown",
"(",
"mongod_control",
",",
"timeout",
"=",
"2",
"*",
"ONE_HOUR_SECS",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"status",
"=",
"mongod_control",
".",
"status",
"(",
")",
"while",
"status",
"!=",
"\"stopped\"",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"start",
">=",
"timeout",
":",
"LOGGER",
".",
"error",
"(",
"\"The mongod process has not stopped, current status is %s\"",
",",
"status",
")",
"return",
"1",
"LOGGER",
".",
"info",
"(",
"\"Waiting for mongod process to stop, current status is %s \"",
",",
"status",
")",
"time",
".",
"sleep",
"(",
"3",
")",
"status",
"=",
"mongod_control",
".",
"status",
"(",
")",
"LOGGER",
".",
"info",
"(",
"\"The mongod process has stopped\"",
")",
"# We wait a bit, since files could still be flushed to disk, which was causing",
"# rsync \"file has vanished\" errors.",
"time",
".",
"sleep",
"(",
"60",
")",
"return",
"0"
] |
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/powercycle/powercycle.py#L1087-L1104
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
|
python
|
Menu.yposition
|
(self, index)
|
return self.tk.getint(self.tk.call(
self._w, 'yposition', index))
|
Return the y-position of the topmost pixel of the menu item at INDEX.
|
Return the y-position of the topmost pixel of the menu item at INDEX.
|
[
"Return",
"the",
"y",
"-",
"position",
"of",
"the",
"topmost",
"pixel",
"of",
"the",
"menu",
"item",
"at",
"INDEX",
"."
] |
def yposition(self, index):
"""Return the y-position of the topmost pixel of the menu item at INDEX."""
return self.tk.getint(self.tk.call(
self._w, 'yposition', index))
|
[
"def",
"yposition",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"tk",
".",
"getint",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'yposition'",
",",
"index",
")",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L2957-L2960
|
|
arangodb/arangodb
|
0d658689c7d1b721b314fa3ca27d38303e1570c8
|
3rdParty/V8/v7.9.317/third_party/jinja2/parser.py
|
python
|
Parser.parse_tuple
|
(self, simplified=False, with_condexpr=True,
extra_end_rules=None, explicit_parentheses=False)
|
return nodes.Tuple(args, 'load', lineno=lineno)
|
Works like `parse_expression` but if multiple expressions are
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
This method could also return a regular expression instead of a tuple
if no commas where found.
The default parsing mode is a full tuple. If `simplified` is `True`
only names and literals are parsed. The `no_condexpr` parameter is
forwarded to :meth:`parse_expression`.
Because tuples do not require delimiters and may end in a bogus comma
an extra hint is needed that marks the end of a tuple. For example
for loops support tuples between `for` and `in`. In that case the
`extra_end_rules` is set to ``['name:in']``.
`explicit_parentheses` is true if the parsing was triggered by an
expression in parentheses. This is used to figure out if an empty
tuple is a valid expression or not.
|
Works like `parse_expression` but if multiple expressions are
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
This method could also return a regular expression instead of a tuple
if no commas where found.
|
[
"Works",
"like",
"parse_expression",
"but",
"if",
"multiple",
"expressions",
"are",
"delimited",
"by",
"a",
"comma",
"a",
":",
"class",
":",
"~jinja2",
".",
"nodes",
".",
"Tuple",
"node",
"is",
"created",
".",
"This",
"method",
"could",
"also",
"return",
"a",
"regular",
"expression",
"instead",
"of",
"a",
"tuple",
"if",
"no",
"commas",
"where",
"found",
"."
] |
def parse_tuple(self, simplified=False, with_condexpr=True,
extra_end_rules=None, explicit_parentheses=False):
"""Works like `parse_expression` but if multiple expressions are
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
This method could also return a regular expression instead of a tuple
if no commas where found.
The default parsing mode is a full tuple. If `simplified` is `True`
only names and literals are parsed. The `no_condexpr` parameter is
forwarded to :meth:`parse_expression`.
Because tuples do not require delimiters and may end in a bogus comma
an extra hint is needed that marks the end of a tuple. For example
for loops support tuples between `for` and `in`. In that case the
`extra_end_rules` is set to ``['name:in']``.
`explicit_parentheses` is true if the parsing was triggered by an
expression in parentheses. This is used to figure out if an empty
tuple is a valid expression or not.
"""
lineno = self.stream.current.lineno
if simplified:
parse = self.parse_primary
elif with_condexpr:
parse = self.parse_expression
else:
parse = lambda: self.parse_expression(with_condexpr=False)
args = []
is_tuple = False
while 1:
if args:
self.stream.expect('comma')
if self.is_tuple_end(extra_end_rules):
break
args.append(parse())
if self.stream.current.type == 'comma':
is_tuple = True
else:
break
lineno = self.stream.current.lineno
if not is_tuple:
if args:
return args[0]
# if we don't have explicit parentheses, an empty tuple is
# not a valid expression. This would mean nothing (literally
# nothing) in the spot of an expression would be an empty
# tuple.
if not explicit_parentheses:
self.fail('Expected an expression, got \'%s\'' %
describe_token(self.stream.current))
return nodes.Tuple(args, 'load', lineno=lineno)
|
[
"def",
"parse_tuple",
"(",
"self",
",",
"simplified",
"=",
"False",
",",
"with_condexpr",
"=",
"True",
",",
"extra_end_rules",
"=",
"None",
",",
"explicit_parentheses",
"=",
"False",
")",
":",
"lineno",
"=",
"self",
".",
"stream",
".",
"current",
".",
"lineno",
"if",
"simplified",
":",
"parse",
"=",
"self",
".",
"parse_primary",
"elif",
"with_condexpr",
":",
"parse",
"=",
"self",
".",
"parse_expression",
"else",
":",
"parse",
"=",
"lambda",
":",
"self",
".",
"parse_expression",
"(",
"with_condexpr",
"=",
"False",
")",
"args",
"=",
"[",
"]",
"is_tuple",
"=",
"False",
"while",
"1",
":",
"if",
"args",
":",
"self",
".",
"stream",
".",
"expect",
"(",
"'comma'",
")",
"if",
"self",
".",
"is_tuple_end",
"(",
"extra_end_rules",
")",
":",
"break",
"args",
".",
"append",
"(",
"parse",
"(",
")",
")",
"if",
"self",
".",
"stream",
".",
"current",
".",
"type",
"==",
"'comma'",
":",
"is_tuple",
"=",
"True",
"else",
":",
"break",
"lineno",
"=",
"self",
".",
"stream",
".",
"current",
".",
"lineno",
"if",
"not",
"is_tuple",
":",
"if",
"args",
":",
"return",
"args",
"[",
"0",
"]",
"# if we don't have explicit parentheses, an empty tuple is",
"# not a valid expression. This would mean nothing (literally",
"# nothing) in the spot of an expression would be an empty",
"# tuple.",
"if",
"not",
"explicit_parentheses",
":",
"self",
".",
"fail",
"(",
"'Expected an expression, got \\'%s\\''",
"%",
"describe_token",
"(",
"self",
".",
"stream",
".",
"current",
")",
")",
"return",
"nodes",
".",
"Tuple",
"(",
"args",
",",
"'load'",
",",
"lineno",
"=",
"lineno",
")"
] |
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/parser.py#L586-L639
|
|
mantidproject/mantid
|
03deeb89254ec4289edb8771e0188c2090a02f32
|
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/fitting_context.py
|
python
|
FittingContext.active_fit_history
|
(self)
|
Returns the fit history for the currently active fitting mode. Override in a child class.
|
Returns the fit history for the currently active fitting mode. Override in a child class.
|
[
"Returns",
"the",
"fit",
"history",
"for",
"the",
"currently",
"active",
"fitting",
"mode",
".",
"Override",
"in",
"a",
"child",
"class",
"."
] |
def active_fit_history(self) -> None:
"""Returns the fit history for the currently active fitting mode. Override in a child class."""
raise NotImplementedError("This needs to be overridden by a child class.")
|
[
"def",
"active_fit_history",
"(",
"self",
")",
"->",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"This needs to be overridden by a child class.\"",
")"
] |
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/fitting_context.py#L354-L356
|
||
snap-stanford/snap-python
|
d53c51b0a26aa7e3e7400b014cdf728948fde80a
|
setup/snap.py
|
python
|
TIntV.AddUnique
|
(self, *args)
|
return _snap.TIntV_AddUnique(self, *args)
|
AddUnique(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
|
AddUnique(TIntV self, TInt Val) -> int
|
[
"AddUnique",
"(",
"TIntV",
"self",
"TInt",
"Val",
")",
"-",
">",
"int"
] |
def AddUnique(self, *args):
"""
AddUnique(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_AddUnique(self, *args)
|
[
"def",
"AddUnique",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TIntV_AddUnique",
"(",
"self",
",",
"*",
"args",
")"
] |
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L15737-L15745
|
|
RamadhanAmizudin/malware
|
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
|
GMBot/gmbot/apps/smsg_r/smsapp/remote_api.py
|
python
|
cb_forward_disabled
|
(rec)
|
Call forwarding ended for the phone
@param rec: Phone data record
@type rec: models.PhoneData
@rtype: None
|
Call forwarding ended for the phone
|
[
"Call",
"forwarding",
"ended",
"for",
"the",
"phone"
] |
def cb_forward_disabled(rec):
"""
Call forwarding ended for the phone
@param rec: Phone data record
@type rec: models.PhoneData
@rtype: None
"""
rec.forwarding_calls = None
rec.save()
|
[
"def",
"cb_forward_disabled",
"(",
"rec",
")",
":",
"rec",
".",
"forwarding_calls",
"=",
"None",
"rec",
".",
"save",
"(",
")"
] |
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/GMBot/gmbot/apps/smsg_r/smsapp/remote_api.py#L451-L459
|
||
apache/arrow
|
af33dd1157eb8d7d9bfac25ebf61445b793b7943
|
cpp/gdb_arrow.py
|
python
|
format_date32
|
(val)
|
Format a date32 value.
|
Format a date32 value.
|
[
"Format",
"a",
"date32",
"value",
"."
] |
def format_date32(val):
"""
Format a date32 value.
"""
val = int(val)
try:
decoded = datetime.date.fromordinal(val + _date_base)
except ValueError: # "ordinal must be >= 1"
return f"{val}d [year <= 0]"
else:
return f"{val}d [{decoded}]"
|
[
"def",
"format_date32",
"(",
"val",
")",
":",
"val",
"=",
"int",
"(",
"val",
")",
"try",
":",
"decoded",
"=",
"datetime",
".",
"date",
".",
"fromordinal",
"(",
"val",
"+",
"_date_base",
")",
"except",
"ValueError",
":",
"# \"ordinal must be >= 1\"",
"return",
"f\"{val}d [year <= 0]\"",
"else",
":",
"return",
"f\"{val}d [{decoded}]\""
] |
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/cpp/gdb_arrow.py#L259-L269
|
||
ChromiumWebApps/chromium
|
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
|
third_party/closure_linter/closure_linter/common/tokens.py
|
python
|
Token.IsType
|
(self, token_type)
|
return self.type == token_type
|
Tests if this token is of the given type.
Args:
token_type: The type to test for.
Returns:
True if the type of this token matches the type passed in.
|
Tests if this token is of the given type.
|
[
"Tests",
"if",
"this",
"token",
"is",
"of",
"the",
"given",
"type",
"."
] |
def IsType(self, token_type):
"""Tests if this token is of the given type.
Args:
token_type: The type to test for.
Returns:
True if the type of this token matches the type passed in.
"""
return self.type == token_type
|
[
"def",
"IsType",
"(",
"self",
",",
"token_type",
")",
":",
"return",
"self",
".",
"type",
"==",
"token_type"
] |
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/common/tokens.py#L97-L106
|
|
mindspore-ai/mindspore
|
fb8fd3338605bb34fa5cea054e535a8b1d753fab
|
mindspore/python/mindspore/numpy/utils_const.py
|
python
|
_check_element_int
|
(lst)
|
return True
|
Check whether each element in `lst` is an integer.
|
Check whether each element in `lst` is an integer.
|
[
"Check",
"whether",
"each",
"element",
"in",
"lst",
"is",
"an",
"integer",
"."
] |
def _check_element_int(lst):
"""
Check whether each element in `lst` is an integer.
"""
for item in lst:
if not isinstance(item, int):
raise TypeError(f"Each element in {lst} should be integer, but got {type(item)}.")
return True
|
[
"def",
"_check_element_int",
"(",
"lst",
")",
":",
"for",
"item",
"in",
"lst",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"f\"Each element in {lst} should be integer, but got {type(item)}.\"",
")",
"return",
"True"
] |
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/utils_const.py#L382-L389
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Cipher/_mode_ofb.py
|
python
|
OfbMode.__init__
|
(self, block_cipher, iv)
|
Create a new block cipher, configured in OFB mode.
:Parameters:
block_cipher : C pointer
A smart pointer to the low-level block cipher instance.
iv : bytes/bytearray/memoryview
The initialization vector to use for encryption or decryption.
It is as long as the cipher block.
**The IV must be a nonce, to to be reused for any other
message**. It shall be a nonce or a random value.
Reusing the *IV* for encryptions performed with the same key
compromises confidentiality.
|
Create a new block cipher, configured in OFB mode.
|
[
"Create",
"a",
"new",
"block",
"cipher",
"configured",
"in",
"OFB",
"mode",
"."
] |
def __init__(self, block_cipher, iv):
"""Create a new block cipher, configured in OFB mode.
:Parameters:
block_cipher : C pointer
A smart pointer to the low-level block cipher instance.
iv : bytes/bytearray/memoryview
The initialization vector to use for encryption or decryption.
It is as long as the cipher block.
**The IV must be a nonce, to to be reused for any other
message**. It shall be a nonce or a random value.
Reusing the *IV* for encryptions performed with the same key
compromises confidentiality.
"""
self._state = VoidPointer()
result = raw_ofb_lib.OFB_start_operation(block_cipher.get(),
c_uint8_ptr(iv),
c_size_t(len(iv)),
self._state.address_of())
if result:
raise ValueError("Error %d while instantiating the OFB mode"
% result)
# Ensure that object disposal of this Python object will (eventually)
# free the memory allocated by the raw library for the cipher mode
self._state = SmartPointer(self._state.get(),
raw_ofb_lib.OFB_stop_operation)
# Memory allocated for the underlying block cipher is now owed
# by the cipher mode
block_cipher.release()
self.block_size = len(iv)
"""The block size of the underlying cipher, in bytes."""
self.iv = _copy_bytes(None, None, iv)
"""The Initialization Vector originally used to create the object.
The value does not change."""
self.IV = self.iv
"""Alias for `iv`"""
self._next = [ self.encrypt, self.decrypt ]
|
[
"def",
"__init__",
"(",
"self",
",",
"block_cipher",
",",
"iv",
")",
":",
"self",
".",
"_state",
"=",
"VoidPointer",
"(",
")",
"result",
"=",
"raw_ofb_lib",
".",
"OFB_start_operation",
"(",
"block_cipher",
".",
"get",
"(",
")",
",",
"c_uint8_ptr",
"(",
"iv",
")",
",",
"c_size_t",
"(",
"len",
"(",
"iv",
")",
")",
",",
"self",
".",
"_state",
".",
"address_of",
"(",
")",
")",
"if",
"result",
":",
"raise",
"ValueError",
"(",
"\"Error %d while instantiating the OFB mode\"",
"%",
"result",
")",
"# Ensure that object disposal of this Python object will (eventually)",
"# free the memory allocated by the raw library for the cipher mode",
"self",
".",
"_state",
"=",
"SmartPointer",
"(",
"self",
".",
"_state",
".",
"get",
"(",
")",
",",
"raw_ofb_lib",
".",
"OFB_stop_operation",
")",
"# Memory allocated for the underlying block cipher is now owed",
"# by the cipher mode",
"block_cipher",
".",
"release",
"(",
")",
"self",
".",
"block_size",
"=",
"len",
"(",
"iv",
")",
"\"\"\"The block size of the underlying cipher, in bytes.\"\"\"",
"self",
".",
"iv",
"=",
"_copy_bytes",
"(",
"None",
",",
"None",
",",
"iv",
")",
"\"\"\"The Initialization Vector originally used to create the object.\n The value does not change.\"\"\"",
"self",
".",
"IV",
"=",
"self",
".",
"iv",
"\"\"\"Alias for `iv`\"\"\"",
"self",
".",
"_next",
"=",
"[",
"self",
".",
"encrypt",
",",
"self",
".",
"decrypt",
"]"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Cipher/_mode_ofb.py#L73-L119
|
||
natanielruiz/android-yolo
|
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
|
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bijector.py
|
python
|
_Bijector.inverse_and_inverse_log_det_jacobian
|
(
self, x, name='inverse_and_inverse_log_det_jacobian')
|
Returns both the inverse evaluation and inverse_log_det_jacobian.
Enables possibly more efficient calculation when both inverse and
corresponding Jacobian are needed.
See `inverse()`, `inverse_log_det_jacobian()` for more details.
Args:
x: `Tensor`. The input to the "inverse" Jacobian evaluation.
name: The name to give this op.
Returns:
`Tensor`.
|
Returns both the inverse evaluation and inverse_log_det_jacobian.
|
[
"Returns",
"both",
"the",
"inverse",
"evaluation",
"and",
"inverse_log_det_jacobian",
"."
] |
def inverse_and_inverse_log_det_jacobian(
self, x, name='inverse_and_inverse_log_det_jacobian'):
"""Returns both the inverse evaluation and inverse_log_det_jacobian.
Enables possibly more efficient calculation when both inverse and
corresponding Jacobian are needed.
See `inverse()`, `inverse_log_det_jacobian()` for more details.
Args:
x: `Tensor`. The input to the "inverse" Jacobian evaluation.
name: The name to give this op.
Returns:
`Tensor`.
"""
with ops.name_scope(self.name):
with ops.op_scope([x], name):
x = ops.convert_to_tensor(x)
try:
return self._inverse_and_inverse_log_det_jacobian(x)
except NotImplementedError:
return self._inverse(x), self._inverse_log_det_jacobian(x)
|
[
"def",
"inverse_and_inverse_log_det_jacobian",
"(",
"self",
",",
"x",
",",
"name",
"=",
"'inverse_and_inverse_log_det_jacobian'",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"name",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"x",
"]",
",",
"name",
")",
":",
"x",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"x",
")",
"try",
":",
"return",
"self",
".",
"_inverse_and_inverse_log_det_jacobian",
"(",
"x",
")",
"except",
"NotImplementedError",
":",
"return",
"self",
".",
"_inverse",
"(",
"x",
")",
",",
"self",
".",
"_inverse_log_det_jacobian",
"(",
"x",
")"
] |
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bijector.py#L204-L226
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/msw/xrc.py
|
python
|
XmlDocument.GetFileEncoding
|
(*args, **kwargs)
|
return _xrc.XmlDocument_GetFileEncoding(*args, **kwargs)
|
GetFileEncoding(self) -> String
|
GetFileEncoding(self) -> String
|
[
"GetFileEncoding",
"(",
"self",
")",
"-",
">",
"String"
] |
def GetFileEncoding(*args, **kwargs):
"""GetFileEncoding(self) -> String"""
return _xrc.XmlDocument_GetFileEncoding(*args, **kwargs)
|
[
"def",
"GetFileEncoding",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlDocument_GetFileEncoding",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/xrc.py#L543-L545
|
|
mantidproject/mantid
|
03deeb89254ec4289edb8771e0188c2090a02f32
|
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_model.py
|
python
|
BasicFittingModel.current_exclude_end_x
|
(self, value: float)
|
Sets the value of the currently selected exclude end X.
|
Sets the value of the currently selected exclude end X.
|
[
"Sets",
"the",
"value",
"of",
"the",
"currently",
"selected",
"exclude",
"end",
"X",
"."
] |
def current_exclude_end_x(self, value: float) -> None:
"""Sets the value of the currently selected exclude end X."""
if value > self.current_exclude_start_x:
self.fitting_context.exclude_end_xs[self.fitting_context.current_dataset_index] = value
|
[
"def",
"current_exclude_end_x",
"(",
"self",
",",
"value",
":",
"float",
")",
"->",
"None",
":",
"if",
"value",
">",
"self",
".",
"current_exclude_start_x",
":",
"self",
".",
"fitting_context",
".",
"exclude_end_xs",
"[",
"self",
".",
"fitting_context",
".",
"current_dataset_index",
"]",
"=",
"value"
] |
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_model.py#L230-L233
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/_misc.py
|
python
|
Log.EnableLogging
|
(*args, **kwargs)
|
return _misc_.Log_EnableLogging(*args, **kwargs)
|
EnableLogging(bool enable=True) -> bool
|
EnableLogging(bool enable=True) -> bool
|
[
"EnableLogging",
"(",
"bool",
"enable",
"=",
"True",
")",
"-",
">",
"bool"
] |
def EnableLogging(*args, **kwargs):
"""EnableLogging(bool enable=True) -> bool"""
return _misc_.Log_EnableLogging(*args, **kwargs)
|
[
"def",
"EnableLogging",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Log_EnableLogging",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1466-L1468
|
|
PaddlePaddle/Paddle
|
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
|
python/paddle/fluid/layers/rnn.py
|
python
|
Decoder.initialize
|
(self, inits)
|
r"""
Called once before the decoding iterations.
Parameters:
inits: Argument provided by the caller.
Returns:
tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \
`initial_inputs` and `initial_states` both are a (possibly nested \
structure of) tensor variable[s], and `finished` is a tensor with \
bool data type.
|
r"""
Called once before the decoding iterations.
|
[
"r",
"Called",
"once",
"before",
"the",
"decoding",
"iterations",
"."
] |
def initialize(self, inits):
r"""
Called once before the decoding iterations.
Parameters:
inits: Argument provided by the caller.
Returns:
tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \
`initial_inputs` and `initial_states` both are a (possibly nested \
structure of) tensor variable[s], and `finished` is a tensor with \
bool data type.
"""
raise NotImplementedError
|
[
"def",
"initialize",
"(",
"self",
",",
"inits",
")",
":",
"raise",
"NotImplementedError"
] |
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/rnn.py#L786-L799
|
||
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py
|
python
|
Text.edit_redo
|
(self)
|
return self.edit("redo")
|
Redo the last undone edit
When the undo option is true, reapplies the last
undone edits provided no other edits were done since
then. Generates an error when the redo stack is empty.
Does nothing when the undo option is false.
|
Redo the last undone edit
|
[
"Redo",
"the",
"last",
"undone",
"edit"
] |
def edit_redo(self):
"""Redo the last undone edit
When the undo option is true, reapplies the last
undone edits provided no other edits were done since
then. Generates an error when the redo stack is empty.
Does nothing when the undo option is false.
"""
return self.edit("redo")
|
[
"def",
"edit_redo",
"(",
"self",
")",
":",
"return",
"self",
".",
"edit",
"(",
"\"redo\"",
")"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2987-L2995
|
|
milvus-io/milvus
|
3b1030de2b6c39e3512833e97f6044d63eb24237
|
internal/core/build-support/cpplint.py
|
python
|
GetPreviousNonBlankLine
|
(clean_lines, linenum)
|
return ('', -1)
|
Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line.
|
Return the most recent non-blank line and its line number.
|
[
"Return",
"the",
"most",
"recent",
"non",
"-",
"blank",
"line",
"and",
"its",
"line",
"number",
"."
] |
def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line.
"""
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline): # if not a blank line...
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1)
|
[
"def",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"prevlinenum",
"=",
"linenum",
"-",
"1",
"while",
"prevlinenum",
">=",
"0",
":",
"prevline",
"=",
"clean_lines",
".",
"elided",
"[",
"prevlinenum",
"]",
"if",
"not",
"IsBlankLine",
"(",
"prevline",
")",
":",
"# if not a blank line...",
"return",
"(",
"prevline",
",",
"prevlinenum",
")",
"prevlinenum",
"-=",
"1",
"return",
"(",
"''",
",",
"-",
"1",
")"
] |
https://github.com/milvus-io/milvus/blob/3b1030de2b6c39e3512833e97f6044d63eb24237/internal/core/build-support/cpplint.py#L4209-L4229
|
|
hughperkins/tf-coriander
|
970d3df6c11400ad68405f22b0c42a52374e94ca
|
tensorflow/contrib/graph_editor/transform.py
|
python
|
copy_with_input_replacements
|
(sgv, replacement_ts,
dst_graph=None, dst_scope="", src_scope="",
reuse_dst_scope=False)
|
return copier(
sgv, dst_graph, dst_scope, src_scope, reuse_dst_scope=reuse_dst_scope)
|
Copy a subgraph, replacing some of its inputs.
Note a replacement only happens if the tensor to be replaced
is an input of the given subgraph. The inputs of a subgraph can
be queried using sgv.inputs.
Args:
sgv: the source subgraph-view. This argument is converted to a subgraph
using the same rules as the function subgraph.make_view.
replacement_ts: dictionary mapping from original tensors to the
replaced one.
dst_graph: the destination graph.
dst_scope: the destination scope.
src_scope: the source scope.
reuse_dst_scope: if True the dst_scope is re-used if it already exists.
Otherwise, the scope is given a unique name based on the one given
by appending an underscore followed by a digit (default).
Returns:
A tuple `(sgv, info)` where:
`sgv` is the transformed subgraph view;
`info` is an instance of Transformer.ResultInfo containing
information about the transform, including mapping between
original and transformed tensors and operations.
Raises:
TypeError: if dst_graph is not a tf.Graph.
StandardError: if sgv cannot be converted to a SubGraphView using
the same rules as the function subgraph.make_view.
|
Copy a subgraph, replacing some of its inputs.
|
[
"Copy",
"a",
"subgraph",
"replacing",
"some",
"of",
"its",
"inputs",
"."
] |
def copy_with_input_replacements(sgv, replacement_ts,
dst_graph=None, dst_scope="", src_scope="",
reuse_dst_scope=False):
"""Copy a subgraph, replacing some of its inputs.
Note a replacement only happens if the tensor to be replaced
is an input of the given subgraph. The inputs of a subgraph can
be queried using sgv.inputs.
Args:
sgv: the source subgraph-view. This argument is converted to a subgraph
using the same rules as the function subgraph.make_view.
replacement_ts: dictionary mapping from original tensors to the
replaced one.
dst_graph: the destination graph.
dst_scope: the destination scope.
src_scope: the source scope.
reuse_dst_scope: if True the dst_scope is re-used if it already exists.
Otherwise, the scope is given a unique name based on the one given
by appending an underscore followed by a digit (default).
Returns:
A tuple `(sgv, info)` where:
`sgv` is the transformed subgraph view;
`info` is an instance of Transformer.ResultInfo containing
information about the transform, including mapping between
original and transformed tensors and operations.
Raises:
TypeError: if dst_graph is not a tf.Graph.
StandardError: if sgv cannot be converted to a SubGraphView using
the same rules as the function subgraph.make_view.
"""
sgv = subgraph.make_view(sgv)
if dst_graph is None:
dst_graph = sgv.graph
if not isinstance(dst_graph, tf_ops.Graph):
raise TypeError("Expected a tf.Graph, got: {}".format(type(dst_graph)))
copier = Transformer()
# Replace tensor if possible.
def replace_t_with_replacement_handler(info, t):
if t in replacement_ts:
return replacement_ts[t]
else:
return keep_t_if_possible_handler(info, t)
copier.transform_external_input_handler = replace_t_with_replacement_handler
return copier(
sgv, dst_graph, dst_scope, src_scope, reuse_dst_scope=reuse_dst_scope)
|
[
"def",
"copy_with_input_replacements",
"(",
"sgv",
",",
"replacement_ts",
",",
"dst_graph",
"=",
"None",
",",
"dst_scope",
"=",
"\"\"",
",",
"src_scope",
"=",
"\"\"",
",",
"reuse_dst_scope",
"=",
"False",
")",
":",
"sgv",
"=",
"subgraph",
".",
"make_view",
"(",
"sgv",
")",
"if",
"dst_graph",
"is",
"None",
":",
"dst_graph",
"=",
"sgv",
".",
"graph",
"if",
"not",
"isinstance",
"(",
"dst_graph",
",",
"tf_ops",
".",
"Graph",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a tf.Graph, got: {}\"",
".",
"format",
"(",
"type",
"(",
"dst_graph",
")",
")",
")",
"copier",
"=",
"Transformer",
"(",
")",
"# Replace tensor if possible.",
"def",
"replace_t_with_replacement_handler",
"(",
"info",
",",
"t",
")",
":",
"if",
"t",
"in",
"replacement_ts",
":",
"return",
"replacement_ts",
"[",
"t",
"]",
"else",
":",
"return",
"keep_t_if_possible_handler",
"(",
"info",
",",
"t",
")",
"copier",
".",
"transform_external_input_handler",
"=",
"replace_t_with_replacement_handler",
"return",
"copier",
"(",
"sgv",
",",
"dst_graph",
",",
"dst_scope",
",",
"src_scope",
",",
"reuse_dst_scope",
"=",
"reuse_dst_scope",
")"
] |
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/graph_editor/transform.py#L623-L669
|
|
devsisters/libquic
|
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
|
src/third_party/protobuf/python/google/protobuf/internal/well_known_types.py
|
python
|
_IsValidPath
|
(message_descriptor, path)
|
return last in message_descriptor.fields_by_name
|
Checks whether the path is valid for Message Descriptor.
|
Checks whether the path is valid for Message Descriptor.
|
[
"Checks",
"whether",
"the",
"path",
"is",
"valid",
"for",
"Message",
"Descriptor",
"."
] |
def _IsValidPath(message_descriptor, path):
"""Checks whether the path is valid for Message Descriptor."""
parts = path.split('.')
last = parts.pop()
for name in parts:
field = message_descriptor.fields_by_name[name]
if (field is None or
field.label == FieldDescriptor.LABEL_REPEATED or
field.type != FieldDescriptor.TYPE_MESSAGE):
return False
message_descriptor = field.message_type
return last in message_descriptor.fields_by_name
|
[
"def",
"_IsValidPath",
"(",
"message_descriptor",
",",
"path",
")",
":",
"parts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"last",
"=",
"parts",
".",
"pop",
"(",
")",
"for",
"name",
"in",
"parts",
":",
"field",
"=",
"message_descriptor",
".",
"fields_by_name",
"[",
"name",
"]",
"if",
"(",
"field",
"is",
"None",
"or",
"field",
".",
"label",
"==",
"FieldDescriptor",
".",
"LABEL_REPEATED",
"or",
"field",
".",
"type",
"!=",
"FieldDescriptor",
".",
"TYPE_MESSAGE",
")",
":",
"return",
"False",
"message_descriptor",
"=",
"field",
".",
"message_type",
"return",
"last",
"in",
"message_descriptor",
".",
"fields_by_name"
] |
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L452-L463
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/scikit-learn/py2/sklearn/decomposition/dict_learning.py
|
python
|
MiniBatchDictionaryLearning.partial_fit
|
(self, X, y=None, iter_offset=None)
|
return self
|
Updates the model using the data in X as a mini-batch.
Parameters
----------
X: array-like, shape (n_samples, n_features)
Training vector, where n_samples in the number of samples
and n_features is the number of features.
iter_offset: integer, optional
The number of iteration on data batches that has been
performed before this call to partial_fit. This is optional:
if no number is passed, the memory of the object is
used.
Returns
-------
self : object
Returns the instance itself.
|
Updates the model using the data in X as a mini-batch.
|
[
"Updates",
"the",
"model",
"using",
"the",
"data",
"in",
"X",
"as",
"a",
"mini",
"-",
"batch",
"."
] |
def partial_fit(self, X, y=None, iter_offset=None):
"""Updates the model using the data in X as a mini-batch.
Parameters
----------
X: array-like, shape (n_samples, n_features)
Training vector, where n_samples in the number of samples
and n_features is the number of features.
iter_offset: integer, optional
The number of iteration on data batches that has been
performed before this call to partial_fit. This is optional:
if no number is passed, the memory of the object is
used.
Returns
-------
self : object
Returns the instance itself.
"""
if not hasattr(self, 'random_state_'):
self.random_state_ = check_random_state(self.random_state)
X = check_array(X)
if hasattr(self, 'components_'):
dict_init = self.components_
else:
dict_init = self.dict_init
inner_stats = getattr(self, 'inner_stats_', None)
if iter_offset is None:
iter_offset = getattr(self, 'iter_offset_', 0)
U, (A, B) = dict_learning_online(
X, self.n_components, self.alpha,
n_iter=self.n_iter, method=self.fit_algorithm,
n_jobs=self.n_jobs, dict_init=dict_init,
batch_size=len(X), shuffle=False,
verbose=self.verbose, return_code=False,
iter_offset=iter_offset, random_state=self.random_state_,
return_inner_stats=True, inner_stats=inner_stats)
self.components_ = U
# Keep track of the state of the algorithm to be able to do
# some online fitting (partial_fit)
self.inner_stats_ = (A, B)
self.iter_offset_ = iter_offset + self.n_iter
return self
|
[
"def",
"partial_fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"iter_offset",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'random_state_'",
")",
":",
"self",
".",
"random_state_",
"=",
"check_random_state",
"(",
"self",
".",
"random_state",
")",
"X",
"=",
"check_array",
"(",
"X",
")",
"if",
"hasattr",
"(",
"self",
",",
"'components_'",
")",
":",
"dict_init",
"=",
"self",
".",
"components_",
"else",
":",
"dict_init",
"=",
"self",
".",
"dict_init",
"inner_stats",
"=",
"getattr",
"(",
"self",
",",
"'inner_stats_'",
",",
"None",
")",
"if",
"iter_offset",
"is",
"None",
":",
"iter_offset",
"=",
"getattr",
"(",
"self",
",",
"'iter_offset_'",
",",
"0",
")",
"U",
",",
"(",
"A",
",",
"B",
")",
"=",
"dict_learning_online",
"(",
"X",
",",
"self",
".",
"n_components",
",",
"self",
".",
"alpha",
",",
"n_iter",
"=",
"self",
".",
"n_iter",
",",
"method",
"=",
"self",
".",
"fit_algorithm",
",",
"n_jobs",
"=",
"self",
".",
"n_jobs",
",",
"dict_init",
"=",
"dict_init",
",",
"batch_size",
"=",
"len",
"(",
"X",
")",
",",
"shuffle",
"=",
"False",
",",
"verbose",
"=",
"self",
".",
"verbose",
",",
"return_code",
"=",
"False",
",",
"iter_offset",
"=",
"iter_offset",
",",
"random_state",
"=",
"self",
".",
"random_state_",
",",
"return_inner_stats",
"=",
"True",
",",
"inner_stats",
"=",
"inner_stats",
")",
"self",
".",
"components_",
"=",
"U",
"# Keep track of the state of the algorithm to be able to do",
"# some online fitting (partial_fit)",
"self",
".",
"inner_stats_",
"=",
"(",
"A",
",",
"B",
")",
"self",
".",
"iter_offset_",
"=",
"iter_offset",
"+",
"self",
".",
"n_iter",
"return",
"self"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/decomposition/dict_learning.py#L1246-L1290
|
|
genn-team/genn
|
75e1eb218cafa228bf36ae4613d1ce26e877b12c
|
generate_swig_interfaces.py
|
python
|
SwigAsIsScope.__init__
|
( self, ofs )
|
Adds %{ %} block. The code within %{ %} block is added to the wrapper C++ file as is without being processed by SWIG
|
Adds %{ %} block. The code within %{ %} block is added to the wrapper C++ file as is without being processed by SWIG
|
[
"Adds",
"%",
"{",
"%",
"}",
"block",
".",
"The",
"code",
"within",
"%",
"{",
"%",
"}",
"block",
"is",
"added",
"to",
"the",
"wrapper",
"C",
"++",
"file",
"as",
"is",
"without",
"being",
"processed",
"by",
"SWIG"
] |
def __init__( self, ofs ):
'''Adds %{ %} block. The code within %{ %} block is added to the wrapper C++ file as is without being processed by SWIG'''
self.os = ofs
|
[
"def",
"__init__",
"(",
"self",
",",
"ofs",
")",
":",
"self",
".",
"os",
"=",
"ofs"
] |
https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/generate_swig_interfaces.py#L84-L86
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/npytypes.py
|
python
|
Record.members
|
(self)
|
return [(k, v.type) for k, v in ordered]
|
An ordered list of (name, type) for the fields.
|
An ordered list of (name, type) for the fields.
|
[
"An",
"ordered",
"list",
"of",
"(",
"name",
"type",
")",
"for",
"the",
"fields",
"."
] |
def members(self):
"""An ordered list of (name, type) for the fields.
"""
ordered = sorted(self.fields.items(), key=lambda x: x[1].offset)
return [(k, v.type) for k, v in ordered]
|
[
"def",
"members",
"(",
"self",
")",
":",
"ordered",
"=",
"sorted",
"(",
"self",
".",
"fields",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
".",
"offset",
")",
"return",
"[",
"(",
"k",
",",
"v",
".",
"type",
")",
"for",
"k",
",",
"v",
"in",
"ordered",
"]"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/npytypes.py#L196-L200
|
|
ricardoquesada/Spidermonkey
|
4a75ea2543408bd1b2c515aa95901523eeef7858
|
addon-sdk/source/python-lib/cuddlefish/runner.py
|
python
|
XulrunnerAppRunner.command
|
(self)
|
Returns the command list to run.
|
Returns the command list to run.
|
[
"Returns",
"the",
"command",
"list",
"to",
"run",
"."
] |
def command(self):
"""Returns the command list to run."""
if self.__is_xulrunner_sdk:
return [self.binary, self.__app_ini, '-profile',
self.profile.profile]
else:
return [self.binary, '-app', self.__app_ini, '-profile',
self.profile.profile]
|
[
"def",
"command",
"(",
"self",
")",
":",
"if",
"self",
".",
"__is_xulrunner_sdk",
":",
"return",
"[",
"self",
".",
"binary",
",",
"self",
".",
"__app_ini",
",",
"'-profile'",
",",
"self",
".",
"profile",
".",
"profile",
"]",
"else",
":",
"return",
"[",
"self",
".",
"binary",
",",
"'-app'",
",",
"self",
".",
"__app_ini",
",",
"'-profile'",
",",
"self",
".",
"profile",
".",
"profile",
"]"
] |
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/addon-sdk/source/python-lib/cuddlefish/runner.py#L353-L361
|
||
OGRECave/ogre-next
|
287307980e6de8910f04f3cc0994451b075071fd
|
Tools/Wings3DExporter/io3d_ogre.py
|
python
|
ogre_writer.add_geometry
|
(self, geometry_elem, vertices)
|
add given vertices to an XML element
|
add given vertices to an XML element
|
[
"add",
"given",
"vertices",
"to",
"an",
"XML",
"element"
] |
def add_geometry(self, geometry_elem, vertices):
"add given vertices to an XML element"
geometry_elem.setProp("vertexcount", str(len(vertices)))
want_uvs = vertices[0].uv != None
vb_elem = geometry_elem.newChild(None, "vertexbuffer", None)
vb_elem.setProp("positions", "true")
vb_elem.setProp("normals", "true")
vb_elem.setProp("colours_diffuse", "false")
if want_uvs:
vb_elem.setProp("texture_coords", "1")
vb_elem.setProp("texture_coord_dimensions_0", "2")
else:
vb_elem.setProp("texture_coords", "0")
try:
for vert in vertices:
vertex_elem = vb_elem.newChild(None, "vertex", None)
position_elem = vertex_elem.newChild(None, "position", None)
vector_to_xml(position_elem, vert.pos, ["x", "y", "z"])
normal_elem = vertex_elem.newChild(None, "normal", None)
vector_to_xml(normal_elem, vert.normal, ["x", "y", "z"])
if want_uvs:
texcoord_elem = vertex_elem.newChild(None, "texcoord", None)
vector_to_xml(texcoord_elem, vert.uv, ["u", "v"])
except:
pp = pprint.PrettyPrinter(indent=4,width=78)
pp.pprint(vertices)
raise
|
[
"def",
"add_geometry",
"(",
"self",
",",
"geometry_elem",
",",
"vertices",
")",
":",
"geometry_elem",
".",
"setProp",
"(",
"\"vertexcount\"",
",",
"str",
"(",
"len",
"(",
"vertices",
")",
")",
")",
"want_uvs",
"=",
"vertices",
"[",
"0",
"]",
".",
"uv",
"!=",
"None",
"vb_elem",
"=",
"geometry_elem",
".",
"newChild",
"(",
"None",
",",
"\"vertexbuffer\"",
",",
"None",
")",
"vb_elem",
".",
"setProp",
"(",
"\"positions\"",
",",
"\"true\"",
")",
"vb_elem",
".",
"setProp",
"(",
"\"normals\"",
",",
"\"true\"",
")",
"vb_elem",
".",
"setProp",
"(",
"\"colours_diffuse\"",
",",
"\"false\"",
")",
"if",
"want_uvs",
":",
"vb_elem",
".",
"setProp",
"(",
"\"texture_coords\"",
",",
"\"1\"",
")",
"vb_elem",
".",
"setProp",
"(",
"\"texture_coord_dimensions_0\"",
",",
"\"2\"",
")",
"else",
":",
"vb_elem",
".",
"setProp",
"(",
"\"texture_coords\"",
",",
"\"0\"",
")",
"try",
":",
"for",
"vert",
"in",
"vertices",
":",
"vertex_elem",
"=",
"vb_elem",
".",
"newChild",
"(",
"None",
",",
"\"vertex\"",
",",
"None",
")",
"position_elem",
"=",
"vertex_elem",
".",
"newChild",
"(",
"None",
",",
"\"position\"",
",",
"None",
")",
"vector_to_xml",
"(",
"position_elem",
",",
"vert",
".",
"pos",
",",
"[",
"\"x\"",
",",
"\"y\"",
",",
"\"z\"",
"]",
")",
"normal_elem",
"=",
"vertex_elem",
".",
"newChild",
"(",
"None",
",",
"\"normal\"",
",",
"None",
")",
"vector_to_xml",
"(",
"normal_elem",
",",
"vert",
".",
"normal",
",",
"[",
"\"x\"",
",",
"\"y\"",
",",
"\"z\"",
"]",
")",
"if",
"want_uvs",
":",
"texcoord_elem",
"=",
"vertex_elem",
".",
"newChild",
"(",
"None",
",",
"\"texcoord\"",
",",
"None",
")",
"vector_to_xml",
"(",
"texcoord_elem",
",",
"vert",
".",
"uv",
",",
"[",
"\"u\"",
",",
"\"v\"",
"]",
")",
"except",
":",
"pp",
"=",
"pprint",
".",
"PrettyPrinter",
"(",
"indent",
"=",
"4",
",",
"width",
"=",
"78",
")",
"pp",
".",
"pprint",
"(",
"vertices",
")",
"raise"
] |
https://github.com/OGRECave/ogre-next/blob/287307980e6de8910f04f3cc0994451b075071fd/Tools/Wings3DExporter/io3d_ogre.py#L65-L98
|
||
PlatformLab/Arachne
|
e67391471007174dd4002dc2c160628e19c284e8
|
scripts/cpplint.py
|
python
|
CheckBracesSpacing
|
(filename, clean_lines, linenum, nesting_state, error)
|
Checks for horizontal spacing near commas.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
|
Checks for horizontal spacing near commas.
|
[
"Checks",
"for",
"horizontal",
"spacing",
"near",
"commas",
"."
] |
def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for horizontal spacing near commas.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
# braces when they are delimiting blocks, classes, namespaces etc.
# And since you should never have braces at the beginning of a line,
# this is an easy test. Except that braces used for initialization don't
# follow the same rule; we often don't want spaces before those.
match = Match(r'^(.*[^ ({>]){', line)
if match:
# Try a bit harder to check for brace initialization. This
# happens in one of the following forms:
# Constructor() : initializer_list_{} { ... }
# Constructor{}.MemberFunction()
# Type variable{};
# FunctionCall(type{}, ...);
# LastArgument(..., type{});
# LOG(INFO) << type{} << " ...";
# map_of_type[{...}] = ...;
# ternary = expr ? new type{} : nullptr;
# OuterTemplate<InnerTemplateConstructor<Type>{}>
#
# We check for the character following the closing brace, and
# silence the warning if it's one of those listed above, i.e.
# "{.;,)<>]:".
#
# To account for nested initializer list, we allow any number of
# closing braces up to "{;,)<". We can't simply silence the
# warning on first sight of closing brace, because that would
# cause false negatives for things that are not initializer lists.
# Silence this: But not this:
# Outer{ if (...) {
# Inner{...} if (...){ // Missing space before {
# }; }
#
# There is a false negative with this approach if people inserted
# spurious semicolons, e.g. "if (cond){};", but we will catch the
# spurious semicolon with a separate check.
leading_text = match.group(1)
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
trailing_text = ''
if endpos > -1:
trailing_text = endline[endpos:]
for offset in xrange(endlinenum + 1,
min(endlinenum + 3, clean_lines.NumLines() - 1)):
trailing_text += clean_lines.elided[offset]
# We also suppress warnings for `uint64_t{expression}` etc., as the style
# guide recommends brace initialization for integral types to avoid
# overflow/truncation.
if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
and not _IsType(clean_lines, nesting_state, leading_text)):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before {')
# Make sure '} else {' has spaces.
if Search(r'}else', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before else')
# You shouldn't have a space before a semicolon at the end of the line.
# There's a special case for "for" since the style guide allows space before
# the semicolon there.
if Search(r':\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Semicolon defining empty statement. Use {} instead.')
elif Search(r'^\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Line contains only semicolon. If this should be an empty statement, '
'use {} instead.')
elif (Search(r'\s+;\s*$', line) and
not Search(r'\bfor\b', line)):
error(filename, linenum, 'whitespace/semicolon', 5,
'Extra space before last semicolon. If this should be an empty '
'statement, use {} instead.')
|
[
"def",
"CheckBracesSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Except after an opening paren, or after another opening brace (in case of",
"# an initializer list, for instance), you should have spaces before your",
"# braces when they are delimiting blocks, classes, namespaces etc.",
"# And since you should never have braces at the beginning of a line,",
"# this is an easy test. Except that braces used for initialization don't",
"# follow the same rule; we often don't want spaces before those.",
"match",
"=",
"Match",
"(",
"r'^(.*[^ ({>]){'",
",",
"line",
")",
"if",
"match",
":",
"# Try a bit harder to check for brace initialization. This",
"# happens in one of the following forms:",
"# Constructor() : initializer_list_{} { ... }",
"# Constructor{}.MemberFunction()",
"# Type variable{};",
"# FunctionCall(type{}, ...);",
"# LastArgument(..., type{});",
"# LOG(INFO) << type{} << \" ...\";",
"# map_of_type[{...}] = ...;",
"# ternary = expr ? new type{} : nullptr;",
"# OuterTemplate<InnerTemplateConstructor<Type>{}>",
"#",
"# We check for the character following the closing brace, and",
"# silence the warning if it's one of those listed above, i.e.",
"# \"{.;,)<>]:\".",
"#",
"# To account for nested initializer list, we allow any number of",
"# closing braces up to \"{;,)<\". We can't simply silence the",
"# warning on first sight of closing brace, because that would",
"# cause false negatives for things that are not initializer lists.",
"# Silence this: But not this:",
"# Outer{ if (...) {",
"# Inner{...} if (...){ // Missing space before {",
"# }; }",
"#",
"# There is a false negative with this approach if people inserted",
"# spurious semicolons, e.g. \"if (cond){};\", but we will catch the",
"# spurious semicolon with a separate check.",
"leading_text",
"=",
"match",
".",
"group",
"(",
"1",
")",
"(",
"endline",
",",
"endlinenum",
",",
"endpos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"len",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"trailing_text",
"=",
"''",
"if",
"endpos",
">",
"-",
"1",
":",
"trailing_text",
"=",
"endline",
"[",
"endpos",
":",
"]",
"for",
"offset",
"in",
"xrange",
"(",
"endlinenum",
"+",
"1",
",",
"min",
"(",
"endlinenum",
"+",
"3",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
"-",
"1",
")",
")",
":",
"trailing_text",
"+=",
"clean_lines",
".",
"elided",
"[",
"offset",
"]",
"# We also suppress warnings for `uint64_t{expression}` etc., as the style",
"# guide recommends brace initialization for integral types to avoid",
"# overflow/truncation.",
"if",
"(",
"not",
"Match",
"(",
"r'^[\\s}]*[{.;,)<>\\]:]'",
",",
"trailing_text",
")",
"and",
"not",
"_IsType",
"(",
"clean_lines",
",",
"nesting_state",
",",
"leading_text",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/braces'",
",",
"5",
",",
"'Missing space before {'",
")",
"# Make sure '} else {' has spaces.",
"if",
"Search",
"(",
"r'}else'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/braces'",
",",
"5",
",",
"'Missing space before else'",
")",
"# You shouldn't have a space before a semicolon at the end of the line.",
"# There's a special case for \"for\" since the style guide allows space before",
"# the semicolon there.",
"if",
"Search",
"(",
"r':\\s*;\\s*$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/semicolon'",
",",
"5",
",",
"'Semicolon defining empty statement. Use {} instead.'",
")",
"elif",
"Search",
"(",
"r'^\\s*;\\s*$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/semicolon'",
",",
"5",
",",
"'Line contains only semicolon. If this should be an empty statement, '",
"'use {} instead.'",
")",
"elif",
"(",
"Search",
"(",
"r'\\s+;\\s*$'",
",",
"line",
")",
"and",
"not",
"Search",
"(",
"r'\\bfor\\b'",
",",
"line",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/semicolon'",
",",
"5",
",",
"'Extra space before last semicolon. If this should be an empty '",
"'statement, use {} instead.'",
")"
] |
https://github.com/PlatformLab/Arachne/blob/e67391471007174dd4002dc2c160628e19c284e8/scripts/cpplint.py#L3439-L3525
|
||
krishauser/Klampt
|
972cc83ea5befac3f653c1ba20f80155768ad519
|
Python/python2_version/klampt/model/trajectory.py
|
python
|
HermiteTrajectory.length
|
(self)
|
return Trajectory.length(self,distance)
|
Returns an upper bound on length given by the Bezier property.
Faster than calculating the true length. To retrieve an approximation
of true length, use self.discretize(dt).length().
|
Returns an upper bound on length given by the Bezier property.
Faster than calculating the true length. To retrieve an approximation
of true length, use self.discretize(dt).length().
|
[
"Returns",
"an",
"upper",
"bound",
"on",
"length",
"given",
"by",
"the",
"Bezier",
"property",
".",
"Faster",
"than",
"calculating",
"the",
"true",
"length",
".",
"To",
"retrieve",
"an",
"approximation",
"of",
"true",
"length",
"use",
"self",
".",
"discretize",
"(",
"dt",
")",
".",
"length",
"()",
"."
] |
def length(self):
"""Returns an upper bound on length given by the Bezier property.
Faster than calculating the true length. To retrieve an approximation
of true length, use self.discretize(dt).length().
"""
n = len(self.milestones[0])//2
third = 1.0/3.0
def distance(x,y):
cp0 = x[:n]
cp1 = vectorops.madd(cp0,x[n:],third)
cp3 = y[:n]
cp2 = vectorops.madd(cp3,y[n:],-third)
return third*vectorops.norm(x[n:]) + vectorops.distance(cp1,cp2) + third*vectorops.norm(y[n:])
return Trajectory.length(self,distance)
|
[
"def",
"length",
"(",
"self",
")",
":",
"n",
"=",
"len",
"(",
"self",
".",
"milestones",
"[",
"0",
"]",
")",
"//",
"2",
"third",
"=",
"1.0",
"/",
"3.0",
"def",
"distance",
"(",
"x",
",",
"y",
")",
":",
"cp0",
"=",
"x",
"[",
":",
"n",
"]",
"cp1",
"=",
"vectorops",
".",
"madd",
"(",
"cp0",
",",
"x",
"[",
"n",
":",
"]",
",",
"third",
")",
"cp3",
"=",
"y",
"[",
":",
"n",
"]",
"cp2",
"=",
"vectorops",
".",
"madd",
"(",
"cp3",
",",
"y",
"[",
"n",
":",
"]",
",",
"-",
"third",
")",
"return",
"third",
"*",
"vectorops",
".",
"norm",
"(",
"x",
"[",
"n",
":",
"]",
")",
"+",
"vectorops",
".",
"distance",
"(",
"cp1",
",",
"cp2",
")",
"+",
"third",
"*",
"vectorops",
".",
"norm",
"(",
"y",
"[",
"n",
":",
"]",
")",
"return",
"Trajectory",
".",
"length",
"(",
"self",
",",
"distance",
")"
] |
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/trajectory.py#L996-L1009
|
|
FreeCAD/FreeCAD
|
ba42231b9c6889b89e064d6d563448ed81e376ec
|
src/Mod/Draft/draftguitools/gui_lines.py
|
python
|
Wire.GetResources
|
(self)
|
return {'Pixmap': 'Draft_Wire',
'Accel': "P, L",
'MenuText': QT_TRANSLATE_NOOP("Draft_Wire", "Polyline"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Wire", "Creates a multiple-points line (polyline). CTRL to snap, SHIFT to constrain.")}
|
Set icon, menu and tooltip.
|
Set icon, menu and tooltip.
|
[
"Set",
"icon",
"menu",
"and",
"tooltip",
"."
] |
def GetResources(self):
"""Set icon, menu and tooltip."""
return {'Pixmap': 'Draft_Wire',
'Accel': "P, L",
'MenuText': QT_TRANSLATE_NOOP("Draft_Wire", "Polyline"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Wire", "Creates a multiple-points line (polyline). CTRL to snap, SHIFT to constrain.")}
|
[
"def",
"GetResources",
"(",
"self",
")",
":",
"return",
"{",
"'Pixmap'",
":",
"'Draft_Wire'",
",",
"'Accel'",
":",
"\"P, L\"",
",",
"'MenuText'",
":",
"QT_TRANSLATE_NOOP",
"(",
"\"Draft_Wire\"",
",",
"\"Polyline\"",
")",
",",
"'ToolTip'",
":",
"QT_TRANSLATE_NOOP",
"(",
"\"Draft_Wire\"",
",",
"\"Creates a multiple-points line (polyline). CTRL to snap, SHIFT to constrain.\"",
")",
"}"
] |
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_lines.py#L305-L311
|
|
bareos/bareos
|
56a10bb368b0a81e977bb51304033fe49d59efb0
|
core/src/plugins/filed/python/libcloud/BareosFdPluginLibcloud.py
|
python
|
BareosFdPluginLibcloud._check_config
|
(self, config_filename)
|
return True
|
Check the configuration and set or override options if necessary,
considering mandatory: username and password in the [credentials] section
|
Check the configuration and set or override options if necessary,
considering mandatory: username and password in the [credentials] section
|
[
"Check",
"the",
"configuration",
"and",
"set",
"or",
"override",
"options",
"if",
"necessary",
"considering",
"mandatory",
":",
"username",
"and",
"password",
"in",
"the",
"[",
"credentials",
"]",
"section"
] |
def _check_config(self, config_filename):
"""
Check the configuration and set or override options if necessary,
considering mandatory: username and password in the [credentials] section
"""
mandatory_sections = ["credentials", "host", "misc"]
mandatory_options = {}
mandatory_options["credentials"] = ["username", "password"]
mandatory_options["host"] = ["hostname", "port", "provider", "tls"]
mandatory_options["misc"] = [
"nb_worker",
"queue_size",
"prefetch_size",
"temporary_download_directory",
]
optional_options = {}
optional_options["misc"] = [
"fail_on_download_error",
"job_message_after_each_number_of_objects",
]
# this maps config file options to libcloud options
option_map = {
"hostname": "host",
"port": "port",
"provider": "provider",
"username": "key",
"password": "secret",
}
for section in mandatory_sections:
if not self.config.has_section(section):
debugmessage(
100,
"BareosFdPluginLibcloud: Section [%s] missing in config file %s\n"
% (section, config_filename),
)
return False
for option in mandatory_options[section]:
if not self.config.has_option(section, option):
debugmessage(
100,
"BareosFdPluginLibcloud: Option [%s] missing in Section %s\n"
% (option, section),
)
return False
value = self.config.get(section, option)
try:
if option == "tls":
self.options["secure"] = strtobool(value)
elif option == "nb_worker":
self.options["nb_worker"] = int(value)
elif option == "queue_size":
self.options["queue_size"] = int(value)
elif option == "prefetch_size":
self.options["prefetch_size"] = eval(value)
elif option == "temporary_download_directory":
self.options["temporary_download_directory"] = value
else:
self.options[option_map[option]] = value
except:
debugmessage(
100,
"Could not evaluate: %s in config file %s"
% (value, config_filename),
)
return False
for option in optional_options["misc"]:
if self.config.has_option(section, option):
try:
value = self.config.get(section, option)
if option == "fail_on_download_error":
self.options["fail_on_download_error"] = strtobool(value)
elif option == "job_message_after_each_number_of_objects":
self.options["job_message_after_each_number_of_objects"] = int(
value
)
except:
debugmessage(
100,
"Could not evaluate: %s in config file %s"
% (value, config_filename),
)
return False
return True
|
[
"def",
"_check_config",
"(",
"self",
",",
"config_filename",
")",
":",
"mandatory_sections",
"=",
"[",
"\"credentials\"",
",",
"\"host\"",
",",
"\"misc\"",
"]",
"mandatory_options",
"=",
"{",
"}",
"mandatory_options",
"[",
"\"credentials\"",
"]",
"=",
"[",
"\"username\"",
",",
"\"password\"",
"]",
"mandatory_options",
"[",
"\"host\"",
"]",
"=",
"[",
"\"hostname\"",
",",
"\"port\"",
",",
"\"provider\"",
",",
"\"tls\"",
"]",
"mandatory_options",
"[",
"\"misc\"",
"]",
"=",
"[",
"\"nb_worker\"",
",",
"\"queue_size\"",
",",
"\"prefetch_size\"",
",",
"\"temporary_download_directory\"",
",",
"]",
"optional_options",
"=",
"{",
"}",
"optional_options",
"[",
"\"misc\"",
"]",
"=",
"[",
"\"fail_on_download_error\"",
",",
"\"job_message_after_each_number_of_objects\"",
",",
"]",
"# this maps config file options to libcloud options",
"option_map",
"=",
"{",
"\"hostname\"",
":",
"\"host\"",
",",
"\"port\"",
":",
"\"port\"",
",",
"\"provider\"",
":",
"\"provider\"",
",",
"\"username\"",
":",
"\"key\"",
",",
"\"password\"",
":",
"\"secret\"",
",",
"}",
"for",
"section",
"in",
"mandatory_sections",
":",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"debugmessage",
"(",
"100",
",",
"\"BareosFdPluginLibcloud: Section [%s] missing in config file %s\\n\"",
"%",
"(",
"section",
",",
"config_filename",
")",
",",
")",
"return",
"False",
"for",
"option",
"in",
"mandatory_options",
"[",
"section",
"]",
":",
"if",
"not",
"self",
".",
"config",
".",
"has_option",
"(",
"section",
",",
"option",
")",
":",
"debugmessage",
"(",
"100",
",",
"\"BareosFdPluginLibcloud: Option [%s] missing in Section %s\\n\"",
"%",
"(",
"option",
",",
"section",
")",
",",
")",
"return",
"False",
"value",
"=",
"self",
".",
"config",
".",
"get",
"(",
"section",
",",
"option",
")",
"try",
":",
"if",
"option",
"==",
"\"tls\"",
":",
"self",
".",
"options",
"[",
"\"secure\"",
"]",
"=",
"strtobool",
"(",
"value",
")",
"elif",
"option",
"==",
"\"nb_worker\"",
":",
"self",
".",
"options",
"[",
"\"nb_worker\"",
"]",
"=",
"int",
"(",
"value",
")",
"elif",
"option",
"==",
"\"queue_size\"",
":",
"self",
".",
"options",
"[",
"\"queue_size\"",
"]",
"=",
"int",
"(",
"value",
")",
"elif",
"option",
"==",
"\"prefetch_size\"",
":",
"self",
".",
"options",
"[",
"\"prefetch_size\"",
"]",
"=",
"eval",
"(",
"value",
")",
"elif",
"option",
"==",
"\"temporary_download_directory\"",
":",
"self",
".",
"options",
"[",
"\"temporary_download_directory\"",
"]",
"=",
"value",
"else",
":",
"self",
".",
"options",
"[",
"option_map",
"[",
"option",
"]",
"]",
"=",
"value",
"except",
":",
"debugmessage",
"(",
"100",
",",
"\"Could not evaluate: %s in config file %s\"",
"%",
"(",
"value",
",",
"config_filename",
")",
",",
")",
"return",
"False",
"for",
"option",
"in",
"optional_options",
"[",
"\"misc\"",
"]",
":",
"if",
"self",
".",
"config",
".",
"has_option",
"(",
"section",
",",
"option",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"config",
".",
"get",
"(",
"section",
",",
"option",
")",
"if",
"option",
"==",
"\"fail_on_download_error\"",
":",
"self",
".",
"options",
"[",
"\"fail_on_download_error\"",
"]",
"=",
"strtobool",
"(",
"value",
")",
"elif",
"option",
"==",
"\"job_message_after_each_number_of_objects\"",
":",
"self",
".",
"options",
"[",
"\"job_message_after_each_number_of_objects\"",
"]",
"=",
"int",
"(",
"value",
")",
"except",
":",
"debugmessage",
"(",
"100",
",",
"\"Could not evaluate: %s in config file %s\"",
"%",
"(",
"value",
",",
"config_filename",
")",
",",
")",
"return",
"False",
"return",
"True"
] |
https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/core/src/plugins/filed/python/libcloud/BareosFdPluginLibcloud.py#L166-L255
|
|
google/llvm-propeller
|
45c226984fe8377ebfb2ad7713c680d652ba678d
|
lldb/third_party/Python/module/pexpect-4.6/pexpect/fdpexpect.py
|
python
|
fdspawn.send
|
(self, s)
|
return os.write(self.child_fd, b)
|
Write to fd, return number of bytes written
|
Write to fd, return number of bytes written
|
[
"Write",
"to",
"fd",
"return",
"number",
"of",
"bytes",
"written"
] |
def send(self, s):
"Write to fd, return number of bytes written"
s = self._coerce_send_string(s)
self._log(s, 'send')
b = self._encoder.encode(s, final=False)
return os.write(self.child_fd, b)
|
[
"def",
"send",
"(",
"self",
",",
"s",
")",
":",
"s",
"=",
"self",
".",
"_coerce_send_string",
"(",
"s",
")",
"self",
".",
"_log",
"(",
"s",
",",
"'send'",
")",
"b",
"=",
"self",
".",
"_encoder",
".",
"encode",
"(",
"s",
",",
"final",
"=",
"False",
")",
"return",
"os",
".",
"write",
"(",
"self",
".",
"child_fd",
",",
"b",
")"
] |
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/pexpect-4.6/pexpect/fdpexpect.py#L96-L102
|
|
DanielSWolf/rhubarb-lip-sync
|
5cface0af3b6e4e58c0b829c51561d784fb9f52f
|
rhubarb/lib/sphinxbase-rev13216/doc/doxy2swig.py
|
python
|
Doxy2SWIG.__init__
|
(self, src, include_function_definition=True, quiet=False)
|
Initialize the instance given a source object. `src` can
be a file or filename. If you do not want to include function
definitions from doxygen then set
`include_function_definition` to `False`. This is handy since
this allows you to use the swig generated function definition
using %feature("autodoc", [0,1]).
|
Initialize the instance given a source object. `src` can
be a file or filename. If you do not want to include function
definitions from doxygen then set
`include_function_definition` to `False`. This is handy since
this allows you to use the swig generated function definition
using %feature("autodoc", [0,1]).
|
[
"Initialize",
"the",
"instance",
"given",
"a",
"source",
"object",
".",
"src",
"can",
"be",
"a",
"file",
"or",
"filename",
".",
"If",
"you",
"do",
"not",
"want",
"to",
"include",
"function",
"definitions",
"from",
"doxygen",
"then",
"set",
"include_function_definition",
"to",
"False",
".",
"This",
"is",
"handy",
"since",
"this",
"allows",
"you",
"to",
"use",
"the",
"swig",
"generated",
"function",
"definition",
"using",
"%feature",
"(",
"autodoc",
"[",
"0",
"1",
"]",
")",
"."
] |
def __init__(self, src, include_function_definition=True, quiet=False):
"""Initialize the instance given a source object. `src` can
be a file or filename. If you do not want to include function
definitions from doxygen then set
`include_function_definition` to `False`. This is handy since
this allows you to use the swig generated function definition
using %feature("autodoc", [0,1]).
"""
f = my_open_read(src)
self.my_dir = os.path.dirname(f.name)
self.xmldoc = minidom.parse(f).documentElement
f.close()
self.pieces = []
self.pieces.append('\n// File: %s\n'%\
os.path.basename(f.name))
self.space_re = re.compile(r'\s+')
self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)')
self.multi = 0
self.ignores = ['inheritancegraph', 'param', 'listofallmembers',
'innerclass', 'name', 'declname', 'incdepgraph',
'invincdepgraph', 'programlisting', 'type',
'references', 'referencedby', 'location',
'collaborationgraph', 'reimplements',
'reimplementedby', 'derivedcompoundref',
'basecompoundref']
#self.generics = []
self.include_function_definition = include_function_definition
if not include_function_definition:
self.ignores.append('argsstring')
self.quiet = quiet
|
[
"def",
"__init__",
"(",
"self",
",",
"src",
",",
"include_function_definition",
"=",
"True",
",",
"quiet",
"=",
"False",
")",
":",
"f",
"=",
"my_open_read",
"(",
"src",
")",
"self",
".",
"my_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"f",
".",
"name",
")",
"self",
".",
"xmldoc",
"=",
"minidom",
".",
"parse",
"(",
"f",
")",
".",
"documentElement",
"f",
".",
"close",
"(",
")",
"self",
".",
"pieces",
"=",
"[",
"]",
"self",
".",
"pieces",
".",
"append",
"(",
"'\\n// File: %s\\n'",
"%",
"os",
".",
"path",
".",
"basename",
"(",
"f",
".",
"name",
")",
")",
"self",
".",
"space_re",
"=",
"re",
".",
"compile",
"(",
"r'\\s+'",
")",
"self",
".",
"lead_spc",
"=",
"re",
".",
"compile",
"(",
"r'^(%feature\\S+\\s+\\S+\\s*?)\"\\s+(\\S)'",
")",
"self",
".",
"multi",
"=",
"0",
"self",
".",
"ignores",
"=",
"[",
"'inheritancegraph'",
",",
"'param'",
",",
"'listofallmembers'",
",",
"'innerclass'",
",",
"'name'",
",",
"'declname'",
",",
"'incdepgraph'",
",",
"'invincdepgraph'",
",",
"'programlisting'",
",",
"'type'",
",",
"'references'",
",",
"'referencedby'",
",",
"'location'",
",",
"'collaborationgraph'",
",",
"'reimplements'",
",",
"'reimplementedby'",
",",
"'derivedcompoundref'",
",",
"'basecompoundref'",
"]",
"#self.generics = []",
"self",
".",
"include_function_definition",
"=",
"include_function_definition",
"if",
"not",
"include_function_definition",
":",
"self",
".",
"ignores",
".",
"append",
"(",
"'argsstring'",
")",
"self",
".",
"quiet",
"=",
"quiet"
] |
https://github.com/DanielSWolf/rhubarb-lip-sync/blob/5cface0af3b6e4e58c0b829c51561d784fb9f52f/rhubarb/lib/sphinxbase-rev13216/doc/doxy2swig.py#L82-L115
|
||
pytorch/pytorch
|
7176c92687d3cc847cc046bf002269c6949a21c2
|
torch/package/package_exporter.py
|
python
|
PackageExporter.denied_modules
|
(self)
|
return self._nodes_with_action_type(_ModuleProviderAction.DENY)
|
Return all modules that are currently denied.
Returns:
A list containing the names of modules which will be
denied in this package.
|
Return all modules that are currently denied.
|
[
"Return",
"all",
"modules",
"that",
"are",
"currently",
"denied",
"."
] |
def denied_modules(self) -> List[str]:
"""Return all modules that are currently denied.
Returns:
A list containing the names of modules which will be
denied in this package.
"""
return self._nodes_with_action_type(_ModuleProviderAction.DENY)
|
[
"def",
"denied_modules",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"self",
".",
"_nodes_with_action_type",
"(",
"_ModuleProviderAction",
".",
"DENY",
")"
] |
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/package/package_exporter.py#L1084-L1091
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python/src/Lib/lib-tk/ttk.py
|
python
|
Treeview.move
|
(self, item, parent, index)
|
Moves item to position index in parent's list of children.
It is illegal to move an item under one of its descendants. If
index is less than or equal to zero, item is moved to the
beginning, if greater than or equal to the number of children,
it is moved to the end. If item was detached it is reattached.
|
Moves item to position index in parent's list of children.
|
[
"Moves",
"item",
"to",
"position",
"index",
"in",
"parent",
"s",
"list",
"of",
"children",
"."
] |
def move(self, item, parent, index):
"""Moves item to position index in parent's list of children.
It is illegal to move an item under one of its descendants. If
index is less than or equal to zero, item is moved to the
beginning, if greater than or equal to the number of children,
it is moved to the end. If item was detached it is reattached."""
self.tk.call(self._w, "move", item, parent, index)
|
[
"def",
"move",
"(",
"self",
",",
"item",
",",
"parent",
",",
"index",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"\"move\"",
",",
"item",
",",
"parent",
",",
"index",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/ttk.py#L1356-L1363
|
||
omnisci/omniscidb
|
b9c95f1bd602b4ffc8b0edf18bfad61031e08d86
|
python/omnisci/cursor.py
|
python
|
Cursor.description
|
(self)
|
return self._description
|
Read-only sequence describing columns of the result set.
Each column is an instance of `Description` describing
- name
- type_code
- display_size
- internal_size
- precision
- scale
- null_ok
We only use name, type_code, and null_ok; The rest are always ``None``
|
Read-only sequence describing columns of the result set.
Each column is an instance of `Description` describing
|
[
"Read",
"-",
"only",
"sequence",
"describing",
"columns",
"of",
"the",
"result",
"set",
".",
"Each",
"column",
"is",
"an",
"instance",
"of",
"Description",
"describing"
] |
def description(self):
"""
Read-only sequence describing columns of the result set.
Each column is an instance of `Description` describing
- name
- type_code
- display_size
- internal_size
- precision
- scale
- null_ok
We only use name, type_code, and null_ok; The rest are always ``None``
"""
return self._description
|
[
"def",
"description",
"(",
"self",
")",
":",
"return",
"self",
".",
"_description"
] |
https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/python/omnisci/cursor.py#L32-L47
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
wx/tools/Editra/src/extern/pkg_resources.py
|
python
|
IResourceProvider.get_resource_string
|
(manager, resource_name)
|
Return a string containing the contents of `resource_name`
`manager` must be an ``IResourceManager``
|
Return a string containing the contents of `resource_name`
|
[
"Return",
"a",
"string",
"containing",
"the",
"contents",
"of",
"resource_name"
] |
def get_resource_string(manager, resource_name):
"""Return a string containing the contents of `resource_name`
`manager` must be an ``IResourceManager``"""
|
[
"def",
"get_resource_string",
"(",
"manager",
",",
"resource_name",
")",
":"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/pkg_resources.py#L307-L310
|
||
eProsima/Fast-DDS
|
6639a84b7855e8fda66a4afb541326ef22f8c727
|
tools/fastdds/fastdds.py
|
python
|
FastDDSParser.__check_python_version
|
(self)
|
Assert python version is valid.
|
Assert python version is valid.
|
[
"Assert",
"python",
"version",
"is",
"valid",
"."
] |
def __check_python_version(self):
"""Assert python version is valid."""
req_v = self.__required_python_version
v = sys.version_info
if not (
((v[0] == req_v[0]) and (v[1] >= req_v[1])) or
(v[0] > req_v[0])
):
print('fastdds: Invalid Python version. {}.{}.x or greater'
' is required'.format(req_v[0], req_v[1]))
sys.exit(1)
|
[
"def",
"__check_python_version",
"(",
"self",
")",
":",
"req_v",
"=",
"self",
".",
"__required_python_version",
"v",
"=",
"sys",
".",
"version_info",
"if",
"not",
"(",
"(",
"(",
"v",
"[",
"0",
"]",
"==",
"req_v",
"[",
"0",
"]",
")",
"and",
"(",
"v",
"[",
"1",
"]",
">=",
"req_v",
"[",
"1",
"]",
")",
")",
"or",
"(",
"v",
"[",
"0",
"]",
">",
"req_v",
"[",
"0",
"]",
")",
")",
":",
"print",
"(",
"'fastdds: Invalid Python version. {}.{}.x or greater'",
"' is required'",
".",
"format",
"(",
"req_v",
"[",
"0",
"]",
",",
"req_v",
"[",
"1",
"]",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] |
https://github.com/eProsima/Fast-DDS/blob/6639a84b7855e8fda66a4afb541326ef22f8c727/tools/fastdds/fastdds.py#L89-L99
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python/src/Lib/logging/__init__.py
|
python
|
LoggerAdapter.critical
|
(self, msg, *args, **kwargs)
|
Delegate a critical call to the underlying logger, after adding
contextual information from this adapter instance.
|
Delegate a critical call to the underlying logger, after adding
contextual information from this adapter instance.
|
[
"Delegate",
"a",
"critical",
"call",
"to",
"the",
"underlying",
"logger",
"after",
"adding",
"contextual",
"information",
"from",
"this",
"adapter",
"instance",
"."
] |
def critical(self, msg, *args, **kwargs):
"""
Delegate a critical call to the underlying logger, after adding
contextual information from this adapter instance.
"""
msg, kwargs = self.process(msg, kwargs)
self.logger.critical(msg, *args, **kwargs)
|
[
"def",
"critical",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
",",
"kwargs",
"=",
"self",
".",
"process",
"(",
"msg",
",",
"kwargs",
")",
"self",
".",
"logger",
".",
"critical",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/logging/__init__.py#L1482-L1488
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/models/direct_url.py
|
python
|
DirectUrl.redacted_url
|
(self)
|
return surl
|
url with user:password part removed unless it is formed with
environment variables as specified in PEP 610, or it is ``git``
in the case of a git URL.
|
url with user:password part removed unless it is formed with
|
[
"url",
"with",
"user",
":",
"password",
"part",
"removed",
"unless",
"it",
"is",
"formed",
"with"
] |
def redacted_url(self):
# type: () -> str
"""url with user:password part removed unless it is formed with
environment variables as specified in PEP 610, or it is ``git``
in the case of a git URL.
"""
purl = urllib.parse.urlsplit(self.url)
netloc = self._remove_auth_from_netloc(purl.netloc)
surl = urllib.parse.urlunsplit(
(purl.scheme, netloc, purl.path, purl.query, purl.fragment)
)
return surl
|
[
"def",
"redacted_url",
"(",
"self",
")",
":",
"# type: () -> str",
"purl",
"=",
"urllib",
".",
"parse",
".",
"urlsplit",
"(",
"self",
".",
"url",
")",
"netloc",
"=",
"self",
".",
"_remove_auth_from_netloc",
"(",
"purl",
".",
"netloc",
")",
"surl",
"=",
"urllib",
".",
"parse",
".",
"urlunsplit",
"(",
"(",
"purl",
".",
"scheme",
",",
"netloc",
",",
"purl",
".",
"path",
",",
"purl",
".",
"query",
",",
"purl",
".",
"fragment",
")",
")",
"return",
"surl"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/models/direct_url.py#L381-L403
|
|
TGAC/KAT
|
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
|
deps/boost/tools/build/src/build/project.py
|
python
|
ProjectRegistry.current
|
(self)
|
return self.current_project
|
Returns the project which is currently being loaded.
|
Returns the project which is currently being loaded.
|
[
"Returns",
"the",
"project",
"which",
"is",
"currently",
"being",
"loaded",
"."
] |
def current(self):
"""Returns the project which is currently being loaded."""
if not self.current_project:
get_manager().errors()(
'Reference to the project currently being loaded requested '
'when there was no project module being loaded.'
)
return self.current_project
|
[
"def",
"current",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"current_project",
":",
"get_manager",
"(",
")",
".",
"errors",
"(",
")",
"(",
"'Reference to the project currently being loaded requested '",
"'when there was no project module being loaded.'",
")",
"return",
"self",
".",
"current_project"
] |
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/project.py#L557-L564
|
|
baidu/bigflow
|
449245016c0df7d1252e85581e588bfc60cefad3
|
bigflow_python/python/bigflow/serde.py
|
python
|
SameTypeListSerde.deserialize
|
(self, buf)
|
return result
|
deserialize
|
deserialize
|
[
"deserialize"
] |
def deserialize(self, buf):
""" deserialize """
buf_len = len(buf)
result = []
buf_offset = 0
while buf_offset < buf_len:
element_size = struct.unpack("<I", buf[buf_offset:buf_offset + 4])[0]
val = self._value.deserialize(buf[buf_offset + 4:buf_offset + 4 + element_size])
result.append(val)
buf_offset += 4 + element_size
return result
|
[
"def",
"deserialize",
"(",
"self",
",",
"buf",
")",
":",
"buf_len",
"=",
"len",
"(",
"buf",
")",
"result",
"=",
"[",
"]",
"buf_offset",
"=",
"0",
"while",
"buf_offset",
"<",
"buf_len",
":",
"element_size",
"=",
"struct",
".",
"unpack",
"(",
"\"<I\"",
",",
"buf",
"[",
"buf_offset",
":",
"buf_offset",
"+",
"4",
"]",
")",
"[",
"0",
"]",
"val",
"=",
"self",
".",
"_value",
".",
"deserialize",
"(",
"buf",
"[",
"buf_offset",
"+",
"4",
":",
"buf_offset",
"+",
"4",
"+",
"element_size",
"]",
")",
"result",
".",
"append",
"(",
"val",
")",
"buf_offset",
"+=",
"4",
"+",
"element_size",
"return",
"result"
] |
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/serde.py#L260-L270
|
|
BitMEX/api-connectors
|
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
|
auto-generated/python/swagger_client/models/execution.py
|
python
|
Execution.ex_destination
|
(self, ex_destination)
|
Sets the ex_destination of this Execution.
:param ex_destination: The ex_destination of this Execution. # noqa: E501
:type: str
|
Sets the ex_destination of this Execution.
|
[
"Sets",
"the",
"ex_destination",
"of",
"this",
"Execution",
"."
] |
def ex_destination(self, ex_destination):
"""Sets the ex_destination of this Execution.
:param ex_destination: The ex_destination of this Execution. # noqa: E501
:type: str
"""
self._ex_destination = ex_destination
|
[
"def",
"ex_destination",
"(",
"self",
",",
"ex_destination",
")",
":",
"self",
".",
"_ex_destination",
"=",
"ex_destination"
] |
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/execution.py#L838-L846
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/dateutil/dateutil/parser/_parser.py
|
python
|
_timelex.isspace
|
(cls, nextchar)
|
return nextchar.isspace()
|
Whether the next character is whitespace
|
Whether the next character is whitespace
|
[
"Whether",
"the",
"next",
"character",
"is",
"whitespace"
] |
def isspace(cls, nextchar):
""" Whether the next character is whitespace """
return nextchar.isspace()
|
[
"def",
"isspace",
"(",
"cls",
",",
"nextchar",
")",
":",
"return",
"nextchar",
".",
"isspace",
"(",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/dateutil/dateutil/parser/_parser.py#L214-L216
|
|
freesurfer/freesurfer
|
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
|
cnn_sphere_register/ext/pynd-lib/pynd/ndutils.py
|
python
|
volsize2ndgrid
|
(volsize)
|
return ndgrid(*ranges)
|
return the dense nd-grid for the volume with size volsize
essentially return the ndgrid fpr
|
return the dense nd-grid for the volume with size volsize
essentially return the ndgrid fpr
|
[
"return",
"the",
"dense",
"nd",
"-",
"grid",
"for",
"the",
"volume",
"with",
"size",
"volsize",
"essentially",
"return",
"the",
"ndgrid",
"fpr"
] |
def volsize2ndgrid(volsize):
"""
return the dense nd-grid for the volume with size volsize
essentially return the ndgrid fpr
"""
ranges = [np.arange(e) for e in volsize]
return ndgrid(*ranges)
|
[
"def",
"volsize2ndgrid",
"(",
"volsize",
")",
":",
"ranges",
"=",
"[",
"np",
".",
"arange",
"(",
"e",
")",
"for",
"e",
"in",
"volsize",
"]",
"return",
"ndgrid",
"(",
"*",
"ranges",
")"
] |
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/cnn_sphere_register/ext/pynd-lib/pynd/ndutils.py#L163-L169
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py
|
python
|
CompoundKernel.theta
|
(self, theta)
|
Sets the (flattened, log-transformed) non-fixed hyperparameters.
Parameters
----------
theta : array, shape (n_dims,)
The non-fixed, log-transformed hyperparameters of the kernel
|
Sets the (flattened, log-transformed) non-fixed hyperparameters.
|
[
"Sets",
"the",
"(",
"flattened",
"log",
"-",
"transformed",
")",
"non",
"-",
"fixed",
"hyperparameters",
"."
] |
def theta(self, theta):
"""Sets the (flattened, log-transformed) non-fixed hyperparameters.
Parameters
----------
theta : array, shape (n_dims,)
The non-fixed, log-transformed hyperparameters of the kernel
"""
k_dims = self.k1.n_dims
for i, kernel in enumerate(self.kernels):
kernel.theta = theta[i * k_dims:(i + 1) * k_dims]
|
[
"def",
"theta",
"(",
"self",
",",
"theta",
")",
":",
"k_dims",
"=",
"self",
".",
"k1",
".",
"n_dims",
"for",
"i",
",",
"kernel",
"in",
"enumerate",
"(",
"self",
".",
"kernels",
")",
":",
"kernel",
".",
"theta",
"=",
"theta",
"[",
"i",
"*",
"k_dims",
":",
"(",
"i",
"+",
"1",
")",
"*",
"k_dims",
"]"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py#L436-L446
|
||
Z3Prover/z3
|
d745d03afdfdf638d66093e2bfbacaf87187f35b
|
src/api/python/z3/z3.py
|
python
|
SortRef.name
|
(self)
|
return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
|
Return the name (string) of sort `self`.
>>> BoolSort().name()
'Bool'
>>> ArraySort(IntSort(), IntSort()).name()
'Array'
|
Return the name (string) of sort `self`.
|
[
"Return",
"the",
"name",
"(",
"string",
")",
"of",
"sort",
"self",
"."
] |
def name(self):
"""Return the name (string) of sort `self`.
>>> BoolSort().name()
'Bool'
>>> ArraySort(IntSort(), IntSort()).name()
'Array'
"""
return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
|
[
"def",
"name",
"(",
"self",
")",
":",
"return",
"_symbol2py",
"(",
"self",
".",
"ctx",
",",
"Z3_get_sort_name",
"(",
"self",
".",
"ctx_ref",
"(",
")",
",",
"self",
".",
"ast",
")",
")"
] |
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L607-L615
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python3/src/Lib/logging/__init__.py
|
python
|
LoggerAdapter.log
|
(self, level, msg, *args, **kwargs)
|
Delegate a log call to the underlying logger, after adding
contextual information from this adapter instance.
|
Delegate a log call to the underlying logger, after adding
contextual information from this adapter instance.
|
[
"Delegate",
"a",
"log",
"call",
"to",
"the",
"underlying",
"logger",
"after",
"adding",
"contextual",
"information",
"from",
"this",
"adapter",
"instance",
"."
] |
def log(self, level, msg, *args, **kwargs):
"""
Delegate a log call to the underlying logger, after adding
contextual information from this adapter instance.
"""
if self.isEnabledFor(level):
msg, kwargs = self.process(msg, kwargs)
self.logger.log(level, msg, *args, **kwargs)
|
[
"def",
"log",
"(",
"self",
",",
"level",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"isEnabledFor",
"(",
"level",
")",
":",
"msg",
",",
"kwargs",
"=",
"self",
".",
"process",
"(",
"msg",
",",
"kwargs",
")",
"self",
".",
"logger",
".",
"log",
"(",
"level",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/__init__.py#L1837-L1844
|
||
mhammond/pywin32
|
44afd86ba8485194df93234639243252deeb40d5
|
adodbapi/remote.py
|
python
|
Connection._rollback
|
(self)
|
In case a database does provide transactions this method causes the the database to roll back to
the start of any pending transaction. Closing a connection without committing the changes first will
cause an implicit rollback to be performed.
|
In case a database does provide transactions this method causes the the database to roll back to
the start of any pending transaction. Closing a connection without committing the changes first will
cause an implicit rollback to be performed.
|
[
"In",
"case",
"a",
"database",
"does",
"provide",
"transactions",
"this",
"method",
"causes",
"the",
"the",
"database",
"to",
"roll",
"back",
"to",
"the",
"start",
"of",
"any",
"pending",
"transaction",
".",
"Closing",
"a",
"connection",
"without",
"committing",
"the",
"changes",
"first",
"will",
"cause",
"an",
"implicit",
"rollback",
"to",
"be",
"performed",
"."
] |
def _rollback(self):
"""In case a database does provide transactions this method causes the the database to roll back to
the start of any pending transaction. Closing a connection without committing the changes first will
cause an implicit rollback to be performed.
"""
result = self.proxy.rollback()
if result:
self._raiseConnectionError(
api.OperationalError, "Error during rollback: %s" % result
)
|
[
"def",
"_rollback",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"proxy",
".",
"rollback",
"(",
")",
"if",
"result",
":",
"self",
".",
"_raiseConnectionError",
"(",
"api",
".",
"OperationalError",
",",
"\"Error during rollback: %s\"",
"%",
"result",
")"
] |
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/adodbapi/remote.py#L289-L298
|
||
hpi-xnor/BMXNet-v2
|
af2b1859eafc5c721b1397cef02f946aaf2ce20d
|
example/kaggle-ndsb2/Train.py
|
python
|
encode_label
|
(label_data)
|
return systole_encode, diastole_encode
|
Run encoding to encode the label into the CDF target.
|
Run encoding to encode the label into the CDF target.
|
[
"Run",
"encoding",
"to",
"encode",
"the",
"label",
"into",
"the",
"CDF",
"target",
"."
] |
def encode_label(label_data):
"""Run encoding to encode the label into the CDF target.
"""
systole = label_data[:, 1]
diastole = label_data[:, 2]
systole_encode = np.array([
(x < np.arange(600)) for x in systole
], dtype=np.uint8)
diastole_encode = np.array([
(x < np.arange(600)) for x in diastole
], dtype=np.uint8)
return systole_encode, diastole_encode
|
[
"def",
"encode_label",
"(",
"label_data",
")",
":",
"systole",
"=",
"label_data",
"[",
":",
",",
"1",
"]",
"diastole",
"=",
"label_data",
"[",
":",
",",
"2",
"]",
"systole_encode",
"=",
"np",
".",
"array",
"(",
"[",
"(",
"x",
"<",
"np",
".",
"arange",
"(",
"600",
")",
")",
"for",
"x",
"in",
"systole",
"]",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"diastole_encode",
"=",
"np",
".",
"array",
"(",
"[",
"(",
"x",
"<",
"np",
".",
"arange",
"(",
"600",
")",
")",
"for",
"x",
"in",
"diastole",
"]",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"return",
"systole_encode",
",",
"diastole_encode"
] |
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/kaggle-ndsb2/Train.py#L69-L80
|
|
windystrife/UnrealEngine_NVIDIAGameWorks
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32comext/axdebug/gateways.py
|
python
|
DebugStackFrame.GetLanguageString
|
(self)
|
Returns a short or long textual description of the language.
fLong -- A flag indicating if the long name is requested.
|
Returns a short or long textual description of the language.
|
[
"Returns",
"a",
"short",
"or",
"long",
"textual",
"description",
"of",
"the",
"language",
"."
] |
def GetLanguageString(self):
"""Returns a short or long textual description of the language.
fLong -- A flag indicating if the long name is requested.
"""
RaiseNotImpl("GetLanguageString")
|
[
"def",
"GetLanguageString",
"(",
"self",
")",
":",
"RaiseNotImpl",
"(",
"\"GetLanguageString\"",
")"
] |
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32comext/axdebug/gateways.py#L279-L284
|
||
CGRU/cgru
|
1881a4128530e3d31ac6c25314c18314fc50c2c7
|
afanasy/python/parsers/parser.py
|
python
|
parser.toHTMLline
|
(self, i_line)
|
return self.tagHTML(i_line)
|
Convert line to HTML.
Designed for GUIs for escape sequences, errors highlighting.
:param i_line: input line
:return: converted line
|
Convert line to HTML.
Designed for GUIs for escape sequences, errors highlighting.
:param i_line: input line
:return: converted line
|
[
"Convert",
"line",
"to",
"HTML",
".",
"Designed",
"for",
"GUIs",
"for",
"escape",
"sequences",
"errors",
"highlighting",
".",
":",
"param",
"i_line",
":",
"input",
"line",
":",
"return",
":",
"converted",
"line"
] |
def toHTMLline(self, i_line):
""" Convert line to HTML.
Designed for GUIs for escape sequences, errors highlighting.
:param i_line: input line
:return: converted line
"""
self.parse({'data':i_line})
if self.error:
i_line = '<span style="background-color:#FF0000"><b>' + i_line + '</b></span>'
if self.badresult:
i_line = '<span style="background-color:#FF00FF"><b>' + i_line + '</b></span>'
if self.warning:
i_line = '<span style="background-color:#FFA500"><b>' + i_line + '</b></span>'
if self.finishedsuccess:
i_line = '<span style="color:#008800"><b>' + i_line + '</b></span>'
if len(self.activity):
i_line = '<span style="background-color:#00FF00"><b>' + i_line + '</b></span>'
if len(self.report):
i_line = '<i><b>' + i_line + '</b></i>'
return self.tagHTML(i_line)
|
[
"def",
"toHTMLline",
"(",
"self",
",",
"i_line",
")",
":",
"self",
".",
"parse",
"(",
"{",
"'data'",
":",
"i_line",
"}",
")",
"if",
"self",
".",
"error",
":",
"i_line",
"=",
"'<span style=\"background-color:#FF0000\"><b>'",
"+",
"i_line",
"+",
"'</b></span>'",
"if",
"self",
".",
"badresult",
":",
"i_line",
"=",
"'<span style=\"background-color:#FF00FF\"><b>'",
"+",
"i_line",
"+",
"'</b></span>'",
"if",
"self",
".",
"warning",
":",
"i_line",
"=",
"'<span style=\"background-color:#FFA500\"><b>'",
"+",
"i_line",
"+",
"'</b></span>'",
"if",
"self",
".",
"finishedsuccess",
":",
"i_line",
"=",
"'<span style=\"color:#008800\"><b>'",
"+",
"i_line",
"+",
"'</b></span>'",
"if",
"len",
"(",
"self",
".",
"activity",
")",
":",
"i_line",
"=",
"'<span style=\"background-color:#00FF00\"><b>'",
"+",
"i_line",
"+",
"'</b></span>'",
"if",
"len",
"(",
"self",
".",
"report",
")",
":",
"i_line",
"=",
"'<i><b>'",
"+",
"i_line",
"+",
"'</b></i>'",
"return",
"self",
".",
"tagHTML",
"(",
"i_line",
")"
] |
https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/parsers/parser.py#L255-L277
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
wx/tools/Editra/src/prefdlg.py
|
python
|
KeyBindingPanel.OnListBox
|
(self, evt)
|
Handle listbox selections and update binding display
@param evt: wx.CommandEvent
|
Handle listbox selections and update binding display
@param evt: wx.CommandEvent
|
[
"Handle",
"listbox",
"selections",
"and",
"update",
"binding",
"display",
"@param",
"evt",
":",
"wx",
".",
"CommandEvent"
] |
def OnListBox(self, evt):
"""Handle listbox selections and update binding display
@param evt: wx.CommandEvent
"""
if evt.GetId() == ID_MENU_ITEMS:
sel_idx = evt.GetSelection()
cmenu = self.FindWindowById(ID_MENUS).GetStringSelection()
menu_id = self.menumap.get(cmenu)[sel_idx][0]
keys = self.binder.GetRawBinding(menu_id)
self._UpdateKeyDisplay(keys)
else:
evt.Skip()
|
[
"def",
"OnListBox",
"(",
"self",
",",
"evt",
")",
":",
"if",
"evt",
".",
"GetId",
"(",
")",
"==",
"ID_MENU_ITEMS",
":",
"sel_idx",
"=",
"evt",
".",
"GetSelection",
"(",
")",
"cmenu",
"=",
"self",
".",
"FindWindowById",
"(",
"ID_MENUS",
")",
".",
"GetStringSelection",
"(",
")",
"menu_id",
"=",
"self",
".",
"menumap",
".",
"get",
"(",
"cmenu",
")",
"[",
"sel_idx",
"]",
"[",
"0",
"]",
"keys",
"=",
"self",
".",
"binder",
".",
"GetRawBinding",
"(",
"menu_id",
")",
"self",
".",
"_UpdateKeyDisplay",
"(",
"keys",
")",
"else",
":",
"evt",
".",
"Skip",
"(",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/prefdlg.py#L2059-L2071
|
||
PlatformLab/RAMCloud
|
b1866af19124325a6dfd8cbc267e2e3ef1f965d1
|
cpplint.py
|
python
|
CheckForCopyright
|
(filename, lines, error)
|
Logs an error if no Copyright message appears at the top of the file.
|
Logs an error if no Copyright message appears at the top of the file.
|
[
"Logs",
"an",
"error",
"if",
"no",
"Copyright",
"message",
"appears",
"at",
"the",
"top",
"of",
"the",
"file",
"."
] |
def CheckForCopyright(filename, lines, error):
"""Logs an error if no Copyright message appears at the top of the file."""
# We'll say it should occur by line 10. Don't forget there's a
# dummy line at the front.
for line in xrange(1, min(len(lines), 11)):
if re.search(r'Copyright', lines[line], re.I): break
else: # means no copyright line was found
error(filename, 0, 'legal/copyright', 5,
'No copyright message found. '
'You should have a line: "Copyright [year] <Copyright Owner>"')
|
[
"def",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"# We'll say it should occur by line 10. Don't forget there's a",
"# dummy line at the front.",
"for",
"line",
"in",
"xrange",
"(",
"1",
",",
"min",
"(",
"len",
"(",
"lines",
")",
",",
"11",
")",
")",
":",
"if",
"re",
".",
"search",
"(",
"r'Copyright'",
",",
"lines",
"[",
"line",
"]",
",",
"re",
".",
"I",
")",
":",
"break",
"else",
":",
"# means no copyright line was found",
"error",
"(",
"filename",
",",
"0",
",",
"'legal/copyright'",
",",
"5",
",",
"'No copyright message found. '",
"'You should have a line: \"Copyright [year] <Copyright Owner>\"'",
")"
] |
https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/cpplint.py#L952-L962
|
||
Xilinx/Vitis-AI
|
fc74d404563d9951b57245443c73bef389f3657f
|
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py
|
python
|
_CudnnRNN.call
|
(self,
inputs,
initial_state=None,
sequence_lengths=None,
time_major=True,
training=True)
|
Runs the forward step for the RNN model.
Args:
inputs: `3-D` tensor. If `time_major` is True (default), the Tensor shape
is [time_len, batch_size, input_size]. If `time_major` is False, the
shape is [batch_size, time_len, input_size].
initial_state: a tuple of tensor(s) of shape `[num_layers * num_dirs,
batch_size, num_units]` if `time_major` is True (default) or
`[batch_size, num_layers * num_dirs, num_units]` if `time_major` is
False. If not provided, use zero initial states. The tuple size is 2 for
LSTM and 1 for other RNNs.
sequence_lengths: an int32 array representing the variable sequence
lengths in a batch. The size of the array has to equal the batch_size.
If not provided, the same sequence length will be assumed.
time_major: The shape format of the `inputs` and `outputs` Tensors. If
true, these Tensors must be shaped ['max_time', 'batch_size', 'depth'].
If false, these Tensors must be shaped ['batch_size', 'max_time',
'depth']. By default this function accepts input and emits output in
time-major form. This param is only effective when 'sequence_lengths' is
used.
training: whether this operation will be used in training or inference.
Returns:
output: a tensor of shape `[time_len, batch_size, num_dirs * num_units]`
if `time_major` is True (default) or `[batch_size, time_len,
num_dirs * num_units]` if `time_major` is False.
It is a `concat([fwd_output, bak_output], axis=2)`.
output_states: a tuple of tensor(s) of the same shape and structure as
`initial_state`.
Raises:
TypeError: initial_state is not a tuple.
|
Runs the forward step for the RNN model.
|
[
"Runs",
"the",
"forward",
"step",
"for",
"the",
"RNN",
"model",
"."
] |
def call(self,
inputs,
initial_state=None,
sequence_lengths=None,
time_major=True,
training=True):
"""Runs the forward step for the RNN model.
Args:
inputs: `3-D` tensor. If `time_major` is True (default), the Tensor shape
is [time_len, batch_size, input_size]. If `time_major` is False, the
shape is [batch_size, time_len, input_size].
initial_state: a tuple of tensor(s) of shape `[num_layers * num_dirs,
batch_size, num_units]` if `time_major` is True (default) or
`[batch_size, num_layers * num_dirs, num_units]` if `time_major` is
False. If not provided, use zero initial states. The tuple size is 2 for
LSTM and 1 for other RNNs.
sequence_lengths: an int32 array representing the variable sequence
lengths in a batch. The size of the array has to equal the batch_size.
If not provided, the same sequence length will be assumed.
time_major: The shape format of the `inputs` and `outputs` Tensors. If
true, these Tensors must be shaped ['max_time', 'batch_size', 'depth'].
If false, these Tensors must be shaped ['batch_size', 'max_time',
'depth']. By default this function accepts input and emits output in
time-major form. This param is only effective when 'sequence_lengths' is
used.
training: whether this operation will be used in training or inference.
Returns:
output: a tensor of shape `[time_len, batch_size, num_dirs * num_units]`
if `time_major` is True (default) or `[batch_size, time_len,
num_dirs * num_units]` if `time_major` is False.
It is a `concat([fwd_output, bak_output], axis=2)`.
output_states: a tuple of tensor(s) of the same shape and structure as
`initial_state`.
Raises:
TypeError: initial_state is not a tuple.
"""
if initial_state is not None and not isinstance(initial_state, tuple):
raise TypeError("Invalid initial_state type: %s, expecting tuple." %
initial_state)
dtype = self.dtype
inputs = ops.convert_to_tensor(inputs, dtype=dtype)
batch_size = array_ops.shape(inputs)[1]
if initial_state is None:
initial_state = self._zero_state(batch_size)
if self._rnn_mode == CUDNN_LSTM:
h, c = initial_state # pylint:disable=unbalanced-tuple-unpacking,unpacking-non-sequence
else:
h, = initial_state # pylint:disable=unbalanced-tuple-unpacking,unpacking-non-sequence
h = ops.convert_to_tensor(h, dtype=dtype)
if self._rnn_mode == CUDNN_LSTM:
c = ops.convert_to_tensor(c, dtype=dtype)
else:
# For model that doesn't take input_c, replace with a dummy tensor.
c = array_ops.constant([], dtype=dtype)
outputs, (output_h, output_c) = self._forward(inputs, h, c, self.kernel,
sequence_lengths, time_major,
training)
if self._rnn_mode == CUDNN_LSTM:
return outputs, (output_h, output_c)
else:
return outputs, (output_h,)
|
[
"def",
"call",
"(",
"self",
",",
"inputs",
",",
"initial_state",
"=",
"None",
",",
"sequence_lengths",
"=",
"None",
",",
"time_major",
"=",
"True",
",",
"training",
"=",
"True",
")",
":",
"if",
"initial_state",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"initial_state",
",",
"tuple",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid initial_state type: %s, expecting tuple.\"",
"%",
"initial_state",
")",
"dtype",
"=",
"self",
".",
"dtype",
"inputs",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"inputs",
",",
"dtype",
"=",
"dtype",
")",
"batch_size",
"=",
"array_ops",
".",
"shape",
"(",
"inputs",
")",
"[",
"1",
"]",
"if",
"initial_state",
"is",
"None",
":",
"initial_state",
"=",
"self",
".",
"_zero_state",
"(",
"batch_size",
")",
"if",
"self",
".",
"_rnn_mode",
"==",
"CUDNN_LSTM",
":",
"h",
",",
"c",
"=",
"initial_state",
"# pylint:disable=unbalanced-tuple-unpacking,unpacking-non-sequence",
"else",
":",
"h",
",",
"=",
"initial_state",
"# pylint:disable=unbalanced-tuple-unpacking,unpacking-non-sequence",
"h",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"h",
",",
"dtype",
"=",
"dtype",
")",
"if",
"self",
".",
"_rnn_mode",
"==",
"CUDNN_LSTM",
":",
"c",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"c",
",",
"dtype",
"=",
"dtype",
")",
"else",
":",
"# For model that doesn't take input_c, replace with a dummy tensor.",
"c",
"=",
"array_ops",
".",
"constant",
"(",
"[",
"]",
",",
"dtype",
"=",
"dtype",
")",
"outputs",
",",
"(",
"output_h",
",",
"output_c",
")",
"=",
"self",
".",
"_forward",
"(",
"inputs",
",",
"h",
",",
"c",
",",
"self",
".",
"kernel",
",",
"sequence_lengths",
",",
"time_major",
",",
"training",
")",
"if",
"self",
".",
"_rnn_mode",
"==",
"CUDNN_LSTM",
":",
"return",
"outputs",
",",
"(",
"output_h",
",",
"output_c",
")",
"else",
":",
"return",
"outputs",
",",
"(",
"output_h",
",",
")"
] |
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py#L381-L444
|
||
esphome/esphome
|
40e06c9819f17409615d4f4eec5cfe4dc9a3776d
|
esphome/config_validation.py
|
python
|
hex_int_range
|
(min=None, max=None, min_included=True, max_included=True)
|
return All(
hex_int,
Range(min=min, max=max, min_included=min_included, max_included=max_included),
)
|
Validate that the config option is an integer in the given range.
|
Validate that the config option is an integer in the given range.
|
[
"Validate",
"that",
"the",
"config",
"option",
"is",
"an",
"integer",
"in",
"the",
"given",
"range",
"."
] |
def hex_int_range(min=None, max=None, min_included=True, max_included=True):
"""Validate that the config option is an integer in the given range."""
return All(
hex_int,
Range(min=min, max=max, min_included=min_included, max_included=max_included),
)
|
[
"def",
"hex_int_range",
"(",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"min_included",
"=",
"True",
",",
"max_included",
"=",
"True",
")",
":",
"return",
"All",
"(",
"hex_int",
",",
"Range",
"(",
"min",
"=",
"min",
",",
"max",
"=",
"max",
",",
"min_included",
"=",
"min_included",
",",
"max_included",
"=",
"max_included",
")",
",",
")"
] |
https://github.com/esphome/esphome/blob/40e06c9819f17409615d4f4eec5cfe4dc9a3776d/esphome/config_validation.py#L397-L402
|
|
NetSys/bess
|
ae52fc5804290fc3116daf2aef52226fafcedf5d
|
bin/dpdk-devbind.py
|
python
|
get_device_details
|
(devices_type)
|
This function populates the "devices" dictionary. The keys used are
the pci addresses (domain:bus:slot.func). The values are themselves
dictionaries - one for each NIC.
|
This function populates the "devices" dictionary. The keys used are
the pci addresses (domain:bus:slot.func). The values are themselves
dictionaries - one for each NIC.
|
[
"This",
"function",
"populates",
"the",
"devices",
"dictionary",
".",
"The",
"keys",
"used",
"are",
"the",
"pci",
"addresses",
"(",
"domain",
":",
"bus",
":",
"slot",
".",
"func",
")",
".",
"The",
"values",
"are",
"themselves",
"dictionaries",
"-",
"one",
"for",
"each",
"NIC",
"."
] |
def get_device_details(devices_type):
'''This function populates the "devices" dictionary. The keys used are
the pci addresses (domain:bus:slot.func). The values are themselves
dictionaries - one for each NIC.'''
global devices
global dpdk_drivers
# first loop through and read details for all devices
# request machine readable format, with numeric IDs and String
dev = {}
dev_lines = check_output(["lspci", "-Dvmmnnk"]).splitlines()
for dev_line in dev_lines:
if len(dev_line) == 0:
if device_type_match(dev, devices_type):
# Replace "Driver" with "Driver_str" to have consistency of
# of dictionary key names
if "Driver" in dev.keys():
dev["Driver_str"] = dev.pop("Driver")
# use dict to make copy of dev
devices[dev["Slot"]] = dict(dev)
# Clear previous device's data
dev = {}
else:
name, value = dev_line.decode().split("\t", 1)
value_list = value.rsplit(' ', 1)
if len(value_list) > 1:
# String stored in <name>_str
dev[name.rstrip(":") + '_str'] = value_list[0]
# Numeric IDs
dev[name.rstrip(":")] = value_list[len(value_list) - 1] \
.rstrip("]").lstrip("[")
if devices_type == network_devices:
# check what is the interface if any for an ssh connection if
# any to this host, so we can mark it later.
ssh_if = []
route = check_output(["ip", "-o", "route"])
# filter out all lines for 169.254 routes
route = "\n".join(filter(lambda ln: not ln.startswith("169.254"),
route.decode().splitlines()))
rt_info = route.split()
for i in range(len(rt_info) - 1):
if rt_info[i] == "dev":
ssh_if.append(rt_info[i+1])
# based on the basic info, get extended text details
for d in devices.keys():
if not device_type_match(devices[d], devices_type):
continue
# get additional info and add it to existing data
devices[d] = devices[d].copy()
# No need to probe lspci
devices[d].update(get_pci_device_details(d, False).items())
if devices_type == network_devices:
for _if in ssh_if:
if _if in devices[d]["Interface"].split(","):
devices[d]["Ssh_if"] = True
devices[d]["Active"] = "*Active*"
break
# add igb_uio to list of supporting modules if needed
if "Module_str" in devices[d]:
for driver in dpdk_drivers:
if driver not in devices[d]["Module_str"]:
devices[d]["Module_str"] = \
devices[d]["Module_str"] + ",%s" % driver
else:
devices[d]["Module_str"] = ",".join(dpdk_drivers)
# make sure the driver and module strings do not have any duplicates
if has_driver(d):
modules = devices[d]["Module_str"].split(",")
if devices[d]["Driver_str"] in modules:
modules.remove(devices[d]["Driver_str"])
devices[d]["Module_str"] = ",".join(modules)
|
[
"def",
"get_device_details",
"(",
"devices_type",
")",
":",
"global",
"devices",
"global",
"dpdk_drivers",
"# first loop through and read details for all devices",
"# request machine readable format, with numeric IDs and String",
"dev",
"=",
"{",
"}",
"dev_lines",
"=",
"check_output",
"(",
"[",
"\"lspci\"",
",",
"\"-Dvmmnnk\"",
"]",
")",
".",
"splitlines",
"(",
")",
"for",
"dev_line",
"in",
"dev_lines",
":",
"if",
"len",
"(",
"dev_line",
")",
"==",
"0",
":",
"if",
"device_type_match",
"(",
"dev",
",",
"devices_type",
")",
":",
"# Replace \"Driver\" with \"Driver_str\" to have consistency of",
"# of dictionary key names",
"if",
"\"Driver\"",
"in",
"dev",
".",
"keys",
"(",
")",
":",
"dev",
"[",
"\"Driver_str\"",
"]",
"=",
"dev",
".",
"pop",
"(",
"\"Driver\"",
")",
"# use dict to make copy of dev",
"devices",
"[",
"dev",
"[",
"\"Slot\"",
"]",
"]",
"=",
"dict",
"(",
"dev",
")",
"# Clear previous device's data",
"dev",
"=",
"{",
"}",
"else",
":",
"name",
",",
"value",
"=",
"dev_line",
".",
"decode",
"(",
")",
".",
"split",
"(",
"\"\\t\"",
",",
"1",
")",
"value_list",
"=",
"value",
".",
"rsplit",
"(",
"' '",
",",
"1",
")",
"if",
"len",
"(",
"value_list",
")",
">",
"1",
":",
"# String stored in <name>_str",
"dev",
"[",
"name",
".",
"rstrip",
"(",
"\":\"",
")",
"+",
"'_str'",
"]",
"=",
"value_list",
"[",
"0",
"]",
"# Numeric IDs",
"dev",
"[",
"name",
".",
"rstrip",
"(",
"\":\"",
")",
"]",
"=",
"value_list",
"[",
"len",
"(",
"value_list",
")",
"-",
"1",
"]",
".",
"rstrip",
"(",
"\"]\"",
")",
".",
"lstrip",
"(",
"\"[\"",
")",
"if",
"devices_type",
"==",
"network_devices",
":",
"# check what is the interface if any for an ssh connection if",
"# any to this host, so we can mark it later.",
"ssh_if",
"=",
"[",
"]",
"route",
"=",
"check_output",
"(",
"[",
"\"ip\"",
",",
"\"-o\"",
",",
"\"route\"",
"]",
")",
"# filter out all lines for 169.254 routes",
"route",
"=",
"\"\\n\"",
".",
"join",
"(",
"filter",
"(",
"lambda",
"ln",
":",
"not",
"ln",
".",
"startswith",
"(",
"\"169.254\"",
")",
",",
"route",
".",
"decode",
"(",
")",
".",
"splitlines",
"(",
")",
")",
")",
"rt_info",
"=",
"route",
".",
"split",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"rt_info",
")",
"-",
"1",
")",
":",
"if",
"rt_info",
"[",
"i",
"]",
"==",
"\"dev\"",
":",
"ssh_if",
".",
"append",
"(",
"rt_info",
"[",
"i",
"+",
"1",
"]",
")",
"# based on the basic info, get extended text details",
"for",
"d",
"in",
"devices",
".",
"keys",
"(",
")",
":",
"if",
"not",
"device_type_match",
"(",
"devices",
"[",
"d",
"]",
",",
"devices_type",
")",
":",
"continue",
"# get additional info and add it to existing data",
"devices",
"[",
"d",
"]",
"=",
"devices",
"[",
"d",
"]",
".",
"copy",
"(",
")",
"# No need to probe lspci",
"devices",
"[",
"d",
"]",
".",
"update",
"(",
"get_pci_device_details",
"(",
"d",
",",
"False",
")",
".",
"items",
"(",
")",
")",
"if",
"devices_type",
"==",
"network_devices",
":",
"for",
"_if",
"in",
"ssh_if",
":",
"if",
"_if",
"in",
"devices",
"[",
"d",
"]",
"[",
"\"Interface\"",
"]",
".",
"split",
"(",
"\",\"",
")",
":",
"devices",
"[",
"d",
"]",
"[",
"\"Ssh_if\"",
"]",
"=",
"True",
"devices",
"[",
"d",
"]",
"[",
"\"Active\"",
"]",
"=",
"\"*Active*\"",
"break",
"# add igb_uio to list of supporting modules if needed",
"if",
"\"Module_str\"",
"in",
"devices",
"[",
"d",
"]",
":",
"for",
"driver",
"in",
"dpdk_drivers",
":",
"if",
"driver",
"not",
"in",
"devices",
"[",
"d",
"]",
"[",
"\"Module_str\"",
"]",
":",
"devices",
"[",
"d",
"]",
"[",
"\"Module_str\"",
"]",
"=",
"devices",
"[",
"d",
"]",
"[",
"\"Module_str\"",
"]",
"+",
"\",%s\"",
"%",
"driver",
"else",
":",
"devices",
"[",
"d",
"]",
"[",
"\"Module_str\"",
"]",
"=",
"\",\"",
".",
"join",
"(",
"dpdk_drivers",
")",
"# make sure the driver and module strings do not have any duplicates",
"if",
"has_driver",
"(",
"d",
")",
":",
"modules",
"=",
"devices",
"[",
"d",
"]",
"[",
"\"Module_str\"",
"]",
".",
"split",
"(",
"\",\"",
")",
"if",
"devices",
"[",
"d",
"]",
"[",
"\"Driver_str\"",
"]",
"in",
"modules",
":",
"modules",
".",
"remove",
"(",
"devices",
"[",
"d",
"]",
"[",
"\"Driver_str\"",
"]",
")",
"devices",
"[",
"d",
"]",
"[",
"\"Module_str\"",
"]",
"=",
"\",\"",
".",
"join",
"(",
"modules",
")"
] |
https://github.com/NetSys/bess/blob/ae52fc5804290fc3116daf2aef52226fafcedf5d/bin/dpdk-devbind.py#L263-L339
|
||
hpi-xnor/BMXNet
|
ed0b201da6667887222b8e4b5f997c4f6b61943d
|
python/mxnet/registry.py
|
python
|
get_create_func
|
(base_class, nickname)
|
return create
|
Get creator function
Parameters
----------
base_class : type
base class for classes that will be reigstered
nickname : str
nickname of base_class for logging
Returns
-------
a creator function
|
Get creator function
|
[
"Get",
"creator",
"function"
] |
def get_create_func(base_class, nickname):
"""Get creator function
Parameters
----------
base_class : type
base class for classes that will be reigstered
nickname : str
nickname of base_class for logging
Returns
-------
a creator function
"""
if base_class not in _REGISTRY:
_REGISTRY[base_class] = {}
registry = _REGISTRY[base_class]
def create(*args, **kwargs):
"""Create instance from config"""
if len(args):
name = args[0]
args = args[1:]
else:
name = kwargs.pop(nickname)
if isinstance(name, base_class):
assert len(args) == 0 and len(kwargs) == 0, \
"%s is already an instance. Additional arguments are invalid"%(nickname)
return name
if isinstance(name, dict):
return create(**name)
assert isinstance(name, string_types), "%s must be of string type"%nickname
if name.startswith('['):
assert not args and not kwargs
name, kwargs = json.loads(name)
return create(name, **kwargs)
elif name.startswith('{'):
assert not args and not kwargs
kwargs = json.loads(name)
return create(**kwargs)
name = name.lower()
assert name in registry, \
"%s is not registered. Please register with %s.register first"%(
str(name), nickname)
return registry[name](*args, **kwargs)
create.__doc__ = """Create a %s instance from config.
Parameters
----------
%s : str or %s instance
class name of desired instance. If is a instance,
it will be returned directly.
**kwargs : dict
arguments to be passed to constructor"""%(nickname, nickname, base_class.__name__)
return create
|
[
"def",
"get_create_func",
"(",
"base_class",
",",
"nickname",
")",
":",
"if",
"base_class",
"not",
"in",
"_REGISTRY",
":",
"_REGISTRY",
"[",
"base_class",
"]",
"=",
"{",
"}",
"registry",
"=",
"_REGISTRY",
"[",
"base_class",
"]",
"def",
"create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Create instance from config\"\"\"",
"if",
"len",
"(",
"args",
")",
":",
"name",
"=",
"args",
"[",
"0",
"]",
"args",
"=",
"args",
"[",
"1",
":",
"]",
"else",
":",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"nickname",
")",
"if",
"isinstance",
"(",
"name",
",",
"base_class",
")",
":",
"assert",
"len",
"(",
"args",
")",
"==",
"0",
"and",
"len",
"(",
"kwargs",
")",
"==",
"0",
",",
"\"%s is already an instance. Additional arguments are invalid\"",
"%",
"(",
"nickname",
")",
"return",
"name",
"if",
"isinstance",
"(",
"name",
",",
"dict",
")",
":",
"return",
"create",
"(",
"*",
"*",
"name",
")",
"assert",
"isinstance",
"(",
"name",
",",
"string_types",
")",
",",
"\"%s must be of string type\"",
"%",
"nickname",
"if",
"name",
".",
"startswith",
"(",
"'['",
")",
":",
"assert",
"not",
"args",
"and",
"not",
"kwargs",
"name",
",",
"kwargs",
"=",
"json",
".",
"loads",
"(",
"name",
")",
"return",
"create",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"elif",
"name",
".",
"startswith",
"(",
"'{'",
")",
":",
"assert",
"not",
"args",
"and",
"not",
"kwargs",
"kwargs",
"=",
"json",
".",
"loads",
"(",
"name",
")",
"return",
"create",
"(",
"*",
"*",
"kwargs",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"assert",
"name",
"in",
"registry",
",",
"\"%s is not registered. Please register with %s.register first\"",
"%",
"(",
"str",
"(",
"name",
")",
",",
"nickname",
")",
"return",
"registry",
"[",
"name",
"]",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"create",
".",
"__doc__",
"=",
"\"\"\"Create a %s instance from config.\n\nParameters\n----------\n%s : str or %s instance\n class name of desired instance. If is a instance,\n it will be returned directly.\n**kwargs : dict\n arguments to be passed to constructor\"\"\"",
"%",
"(",
"nickname",
",",
"nickname",
",",
"base_class",
".",
"__name__",
")",
"return",
"create"
] |
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/registry.py#L97-L158
|
|
networkit/networkit
|
695b7a786a894a303fa8587597d5ef916e797729
|
networkit/GEXFIO.py
|
python
|
GEXFWriter.write
|
(self, graph, fname, eventStream = [], mapping = [])
|
Writes a NetworKit::Graph to the specified file fname.
Parameters:
-----------
graph: a NetworKit::Graph python object
fname: the desired file path and name to be written to
eventStream: stream of events
mapping: random node mapping
|
Writes a NetworKit::Graph to the specified file fname.
Parameters:
-----------
graph: a NetworKit::Graph python object
fname: the desired file path and name to be written to
eventStream: stream of events
mapping: random node mapping
|
[
"Writes",
"a",
"NetworKit",
"::",
"Graph",
"to",
"the",
"specified",
"file",
"fname",
".",
"Parameters",
":",
"-----------",
"graph",
":",
"a",
"NetworKit",
"::",
"Graph",
"python",
"object",
"fname",
":",
"the",
"desired",
"file",
"path",
"and",
"name",
"to",
"be",
"written",
"to",
"eventStream",
":",
"stream",
"of",
"events",
"mapping",
":",
"random",
"node",
"mapping"
] |
def write(self, graph, fname, eventStream = [], mapping = []):
"""
Writes a NetworKit::Graph to the specified file fname.
Parameters:
-----------
graph: a NetworKit::Graph python object
fname: the desired file path and name to be written to
eventStream: stream of events
mapping: random node mapping
"""
#0. Reset internal vars
self.__init__()
#1. Start with the root element and the right header information
root = ET.Element('gexf')
root.set("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance")
root.set("xsi:schemaLocation","http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd")
root.set('version', '1.2')
#2. Create graph element with appropriate information
graphElement = ET.SubElement(root,"graph")
if graph.isDirected():
graphElement.set('defaultedgetype', 'directed')
else:
graphElement.set('defaultedgetype', 'undirected')
if len(eventStream) > 0:
graphElement.set('mode', 'dynamic')
graphElement.set('timeformat', 'double')
for event in eventStream:
if event.type == GraphEvent.EDGE_WEIGHT_UPDATE:
dynamicAtt = ET.SubElement(graphElement, "attributes")
dynamicAtt.set('class', 'edge')
dynamicAtt.set('mode', 'dynamic')
dynamicWeight = ET.SubElement(dynamicAtt, "attribute")
dynamicWeight.set('id', 'weight')
dynamicWeight.set('title', 'Weight')
dynamicWeight.set('type', 'float')
self.hasDynamicWeight = True
break
else:
graphElement.set('mode', 'static')
#3. Add nodes
nodesElement = ET.SubElement(graphElement, "nodes")
nNodes, idArray = 0, []
#3.1 Count the # of nodes (inital + dynamic nodes)
for event in eventStream:
if event.type == GraphEvent.NODE_ADDITION:
nNodes +=1
nNodes += graph.numberOfNodes()
for i in range(0, nNodes):
idArray.append(i)
# Optional:Map nodes to a random mapping if user provided one
if (len(mapping) > 0):
if(nNodes != len(mapping)):
raise Exception('Size of nodes and mapping must match')
else:
for i in range(0, nNodes):
idArray[i] = mapping[i]
#3.2 Write nodes to the gexf file
for n in range(nNodes):
nodeElement = ET.SubElement(nodesElement,'node')
nodeElement.set('id', str(idArray[n]))
self.writeEvent(nodeElement, eventStream, n)
#4. Add edges
edgesElement = ET.SubElement(graphElement, "edges")
#4.1 Put all edges into a queue(inital + dynamic edges)
for u, v in graph.iterEdges():
self.q.put((u, v, graph.weight(u, v)))
for event in eventStream:
if event.type == GraphEvent.EDGE_ADDITION:
self.q.put((event.u, event.v, event.w))
#4.2 Write edges to the gexf file
while not self.q.empty():
edgeElement = ET.SubElement(edgesElement,'edge')
e = self.q.get()
edgeElement.set('source', str(idArray[e[0]]))
edgeElement.set('target', str(idArray[e[1]]))
edgeElement.set('id', "{0}".format(self.edgeIdctr))
self.edgeIdctr += 1
if graph.isWeighted():
edgeElement.set('weight', str(e[2]))
self.writeEvent(edgeElement, eventStream, e)
#5. Write the generated tree to the file
tree = ET.ElementTree(root)
tree.write(fname,"utf-8",True)
|
[
"def",
"write",
"(",
"self",
",",
"graph",
",",
"fname",
",",
"eventStream",
"=",
"[",
"]",
",",
"mapping",
"=",
"[",
"]",
")",
":",
"#0. Reset internal vars",
"self",
".",
"__init__",
"(",
")",
"#1. Start with the root element and the right header information",
"root",
"=",
"ET",
".",
"Element",
"(",
"'gexf'",
")",
"root",
".",
"set",
"(",
"\"xmlns:xsi\"",
",",
"\"http://www.w3.org/2001/XMLSchema-instance\"",
")",
"root",
".",
"set",
"(",
"\"xsi:schemaLocation\"",
",",
"\"http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd\"",
")",
"root",
".",
"set",
"(",
"'version'",
",",
"'1.2'",
")",
"#2. Create graph element with appropriate information",
"graphElement",
"=",
"ET",
".",
"SubElement",
"(",
"root",
",",
"\"graph\"",
")",
"if",
"graph",
".",
"isDirected",
"(",
")",
":",
"graphElement",
".",
"set",
"(",
"'defaultedgetype'",
",",
"'directed'",
")",
"else",
":",
"graphElement",
".",
"set",
"(",
"'defaultedgetype'",
",",
"'undirected'",
")",
"if",
"len",
"(",
"eventStream",
")",
">",
"0",
":",
"graphElement",
".",
"set",
"(",
"'mode'",
",",
"'dynamic'",
")",
"graphElement",
".",
"set",
"(",
"'timeformat'",
",",
"'double'",
")",
"for",
"event",
"in",
"eventStream",
":",
"if",
"event",
".",
"type",
"==",
"GraphEvent",
".",
"EDGE_WEIGHT_UPDATE",
":",
"dynamicAtt",
"=",
"ET",
".",
"SubElement",
"(",
"graphElement",
",",
"\"attributes\"",
")",
"dynamicAtt",
".",
"set",
"(",
"'class'",
",",
"'edge'",
")",
"dynamicAtt",
".",
"set",
"(",
"'mode'",
",",
"'dynamic'",
")",
"dynamicWeight",
"=",
"ET",
".",
"SubElement",
"(",
"dynamicAtt",
",",
"\"attribute\"",
")",
"dynamicWeight",
".",
"set",
"(",
"'id'",
",",
"'weight'",
")",
"dynamicWeight",
".",
"set",
"(",
"'title'",
",",
"'Weight'",
")",
"dynamicWeight",
".",
"set",
"(",
"'type'",
",",
"'float'",
")",
"self",
".",
"hasDynamicWeight",
"=",
"True",
"break",
"else",
":",
"graphElement",
".",
"set",
"(",
"'mode'",
",",
"'static'",
")",
"#3. Add nodes",
"nodesElement",
"=",
"ET",
".",
"SubElement",
"(",
"graphElement",
",",
"\"nodes\"",
")",
"nNodes",
",",
"idArray",
"=",
"0",
",",
"[",
"]",
"#3.1 Count the # of nodes (inital + dynamic nodes)",
"for",
"event",
"in",
"eventStream",
":",
"if",
"event",
".",
"type",
"==",
"GraphEvent",
".",
"NODE_ADDITION",
":",
"nNodes",
"+=",
"1",
"nNodes",
"+=",
"graph",
".",
"numberOfNodes",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"nNodes",
")",
":",
"idArray",
".",
"append",
"(",
"i",
")",
"# Optional:Map nodes to a random mapping if user provided one",
"if",
"(",
"len",
"(",
"mapping",
")",
">",
"0",
")",
":",
"if",
"(",
"nNodes",
"!=",
"len",
"(",
"mapping",
")",
")",
":",
"raise",
"Exception",
"(",
"'Size of nodes and mapping must match'",
")",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"nNodes",
")",
":",
"idArray",
"[",
"i",
"]",
"=",
"mapping",
"[",
"i",
"]",
"#3.2 Write nodes to the gexf file",
"for",
"n",
"in",
"range",
"(",
"nNodes",
")",
":",
"nodeElement",
"=",
"ET",
".",
"SubElement",
"(",
"nodesElement",
",",
"'node'",
")",
"nodeElement",
".",
"set",
"(",
"'id'",
",",
"str",
"(",
"idArray",
"[",
"n",
"]",
")",
")",
"self",
".",
"writeEvent",
"(",
"nodeElement",
",",
"eventStream",
",",
"n",
")",
"#4. Add edges",
"edgesElement",
"=",
"ET",
".",
"SubElement",
"(",
"graphElement",
",",
"\"edges\"",
")",
"#4.1 Put all edges into a queue(inital + dynamic edges)",
"for",
"u",
",",
"v",
"in",
"graph",
".",
"iterEdges",
"(",
")",
":",
"self",
".",
"q",
".",
"put",
"(",
"(",
"u",
",",
"v",
",",
"graph",
".",
"weight",
"(",
"u",
",",
"v",
")",
")",
")",
"for",
"event",
"in",
"eventStream",
":",
"if",
"event",
".",
"type",
"==",
"GraphEvent",
".",
"EDGE_ADDITION",
":",
"self",
".",
"q",
".",
"put",
"(",
"(",
"event",
".",
"u",
",",
"event",
".",
"v",
",",
"event",
".",
"w",
")",
")",
"#4.2 Write edges to the gexf file",
"while",
"not",
"self",
".",
"q",
".",
"empty",
"(",
")",
":",
"edgeElement",
"=",
"ET",
".",
"SubElement",
"(",
"edgesElement",
",",
"'edge'",
")",
"e",
"=",
"self",
".",
"q",
".",
"get",
"(",
")",
"edgeElement",
".",
"set",
"(",
"'source'",
",",
"str",
"(",
"idArray",
"[",
"e",
"[",
"0",
"]",
"]",
")",
")",
"edgeElement",
".",
"set",
"(",
"'target'",
",",
"str",
"(",
"idArray",
"[",
"e",
"[",
"1",
"]",
"]",
")",
")",
"edgeElement",
".",
"set",
"(",
"'id'",
",",
"\"{0}\"",
".",
"format",
"(",
"self",
".",
"edgeIdctr",
")",
")",
"self",
".",
"edgeIdctr",
"+=",
"1",
"if",
"graph",
".",
"isWeighted",
"(",
")",
":",
"edgeElement",
".",
"set",
"(",
"'weight'",
",",
"str",
"(",
"e",
"[",
"2",
"]",
")",
")",
"self",
".",
"writeEvent",
"(",
"edgeElement",
",",
"eventStream",
",",
"e",
")",
"#5. Write the generated tree to the file",
"tree",
"=",
"ET",
".",
"ElementTree",
"(",
"root",
")",
"tree",
".",
"write",
"(",
"fname",
",",
"\"utf-8\"",
",",
"True",
")"
] |
https://github.com/networkit/networkit/blob/695b7a786a894a303fa8587597d5ef916e797729/networkit/GEXFIO.py#L269-L358
|
||
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
|
python
|
Canvas.coords
|
(self, *args)
|
return map(getdouble,
self.tk.splitlist(
self.tk.call((self._w, 'coords') + args)))
|
Return a list of coordinates for the item given in ARGS.
|
Return a list of coordinates for the item given in ARGS.
|
[
"Return",
"a",
"list",
"of",
"coordinates",
"for",
"the",
"item",
"given",
"in",
"ARGS",
"."
] |
def coords(self, *args):
"""Return a list of coordinates for the item given in ARGS."""
# XXX Should use _flatten on args
return map(getdouble,
self.tk.splitlist(
self.tk.call((self._w, 'coords') + args)))
|
[
"def",
"coords",
"(",
"self",
",",
"*",
"args",
")",
":",
"# XXX Should use _flatten on args",
"return",
"map",
"(",
"getdouble",
",",
"self",
".",
"tk",
".",
"splitlist",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'coords'",
")",
"+",
"args",
")",
")",
")"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2235-L2240
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py
|
python
|
Decimal._compare_check_nans
|
(self, other, context)
|
return 0
|
Version of _check_nans used for the signaling comparisons
compare_signal, __le__, __lt__, __ge__, __gt__.
Signal InvalidOperation if either self or other is a (quiet
or signaling) NaN. Signaling NaNs take precedence over quiet
NaNs.
Return 0 if neither operand is a NaN.
|
Version of _check_nans used for the signaling comparisons
compare_signal, __le__, __lt__, __ge__, __gt__.
|
[
"Version",
"of",
"_check_nans",
"used",
"for",
"the",
"signaling",
"comparisons",
"compare_signal",
"__le__",
"__lt__",
"__ge__",
"__gt__",
"."
] |
def _compare_check_nans(self, other, context):
"""Version of _check_nans used for the signaling comparisons
compare_signal, __le__, __lt__, __ge__, __gt__.
Signal InvalidOperation if either self or other is a (quiet
or signaling) NaN. Signaling NaNs take precedence over quiet
NaNs.
Return 0 if neither operand is a NaN.
"""
if context is None:
context = getcontext()
if self._is_special or other._is_special:
if self.is_snan():
return context._raise_error(InvalidOperation,
'comparison involving sNaN',
self)
elif other.is_snan():
return context._raise_error(InvalidOperation,
'comparison involving sNaN',
other)
elif self.is_qnan():
return context._raise_error(InvalidOperation,
'comparison involving NaN',
self)
elif other.is_qnan():
return context._raise_error(InvalidOperation,
'comparison involving NaN',
other)
return 0
|
[
"def",
"_compare_check_nans",
"(",
"self",
",",
"other",
",",
"context",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"getcontext",
"(",
")",
"if",
"self",
".",
"_is_special",
"or",
"other",
".",
"_is_special",
":",
"if",
"self",
".",
"is_snan",
"(",
")",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
",",
"'comparison involving sNaN'",
",",
"self",
")",
"elif",
"other",
".",
"is_snan",
"(",
")",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
",",
"'comparison involving sNaN'",
",",
"other",
")",
"elif",
"self",
".",
"is_qnan",
"(",
")",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
",",
"'comparison involving NaN'",
",",
"self",
")",
"elif",
"other",
".",
"is_qnan",
"(",
")",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
",",
"'comparison involving NaN'",
",",
"other",
")",
"return",
"0"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py#L777-L808
|
|
Xilinx/Vitis-AI
|
fc74d404563d9951b57245443c73bef389f3657f
|
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py
|
python
|
_BucketizedColumn.length
|
(self)
|
return len(self.boundaries) + 1
|
Returns total number of buckets.
|
Returns total number of buckets.
|
[
"Returns",
"total",
"number",
"of",
"buckets",
"."
] |
def length(self):
"""Returns total number of buckets."""
return len(self.boundaries) + 1
|
[
"def",
"length",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"boundaries",
")",
"+",
"1"
] |
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py#L2100-L2102
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/pandas/py2/pandas/core/arrays/categorical.py
|
python
|
Categorical.as_ordered
|
(self, inplace=False)
|
return self.set_ordered(True, inplace=inplace)
|
Set the Categorical to be ordered.
Parameters
----------
inplace : boolean (default: False)
Whether or not to set the ordered attribute inplace or return a copy
of this categorical with ordered set to True
|
Set the Categorical to be ordered.
|
[
"Set",
"the",
"Categorical",
"to",
"be",
"ordered",
"."
] |
def as_ordered(self, inplace=False):
"""
Set the Categorical to be ordered.
Parameters
----------
inplace : boolean (default: False)
Whether or not to set the ordered attribute inplace or return a copy
of this categorical with ordered set to True
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
return self.set_ordered(True, inplace=inplace)
|
[
"def",
"as_ordered",
"(",
"self",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"return",
"self",
".",
"set_ordered",
"(",
"True",
",",
"inplace",
"=",
"inplace",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/categorical.py#L759-L770
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/_windows.py
|
python
|
PageSetupDialogData.SetDefaultMinMargins
|
(*args, **kwargs)
|
return _windows_.PageSetupDialogData_SetDefaultMinMargins(*args, **kwargs)
|
SetDefaultMinMargins(self, bool flag)
|
SetDefaultMinMargins(self, bool flag)
|
[
"SetDefaultMinMargins",
"(",
"self",
"bool",
"flag",
")"
] |
def SetDefaultMinMargins(*args, **kwargs):
"""SetDefaultMinMargins(self, bool flag)"""
return _windows_.PageSetupDialogData_SetDefaultMinMargins(*args, **kwargs)
|
[
"def",
"SetDefaultMinMargins",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PageSetupDialogData_SetDefaultMinMargins",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L4951-L4953
|
|
llvm-mirror/libcxx
|
78d6a7767ed57b50122a161b91f59f19c9bd0d19
|
utils/google-benchmark/mingw.py
|
python
|
root
|
(location = None, arch = None, version = None, threading = None,
exceptions = None, revision = None, log = EmptyLogger())
|
return root_dir
|
Returns the root folder of a specific version of the mingw-builds variant
of gcc. Will download the compiler if needed
|
Returns the root folder of a specific version of the mingw-builds variant
of gcc. Will download the compiler if needed
|
[
"Returns",
"the",
"root",
"folder",
"of",
"a",
"specific",
"version",
"of",
"the",
"mingw",
"-",
"builds",
"variant",
"of",
"gcc",
".",
"Will",
"download",
"the",
"compiler",
"if",
"needed"
] |
def root(location = None, arch = None, version = None, threading = None,
exceptions = None, revision = None, log = EmptyLogger()):
'''
Returns the root folder of a specific version of the mingw-builds variant
of gcc. Will download the compiler if needed
'''
# Get the repository if we don't have all the information
if not (arch and version and threading and exceptions and revision):
versions = repository(log = log)
# Determine some defaults
version = version or max(versions.keys())
if not arch:
arch = platform.machine().lower()
if arch == 'x86':
arch = 'i686'
elif arch == 'amd64':
arch = 'x86_64'
if not threading:
keys = versions[version][arch].keys()
if 'posix' in keys:
threading = 'posix'
elif 'win32' in keys:
threading = 'win32'
else:
threading = keys[0]
if not exceptions:
keys = versions[version][arch][threading].keys()
if 'seh' in keys:
exceptions = 'seh'
elif 'sjlj' in keys:
exceptions = 'sjlj'
else:
exceptions = keys[0]
if revision == None:
revision = max(versions[version][arch][threading][exceptions].keys())
if not location:
location = os.path.join(tempfile.gettempdir(), 'mingw-builds')
# Get the download url
url = versions[version][arch][threading][exceptions][revision]
# Tell the user whatzzup
log.info('finding MinGW %s', '.'.join(str(v) for v in version))
log.debug(' - arch: %s', arch)
log.debug(' - threading: %s', threading)
log.debug(' - exceptions: %s', exceptions)
log.debug(' - revision: %s', revision)
log.debug(' - url: %s', url)
# Store each specific revision differently
slug = '{version}-{arch}-{threading}-{exceptions}-rev{revision}'
slug = slug.format(
version = '.'.join(str(v) for v in version),
arch = arch,
threading = threading,
exceptions = exceptions,
revision = revision
)
if arch == 'x86_64':
root_dir = os.path.join(location, slug, 'mingw64')
elif arch == 'i686':
root_dir = os.path.join(location, slug, 'mingw32')
else:
raise ValueError('Unknown MinGW arch: ' + arch)
# Download if needed
if not os.path.exists(root_dir):
downloaded = download(url, os.path.join(location, slug), log = log)
if downloaded != root_dir:
raise ValueError('The location of mingw did not match\n%s\n%s'
% (downloaded, root_dir))
return root_dir
|
[
"def",
"root",
"(",
"location",
"=",
"None",
",",
"arch",
"=",
"None",
",",
"version",
"=",
"None",
",",
"threading",
"=",
"None",
",",
"exceptions",
"=",
"None",
",",
"revision",
"=",
"None",
",",
"log",
"=",
"EmptyLogger",
"(",
")",
")",
":",
"# Get the repository if we don't have all the information",
"if",
"not",
"(",
"arch",
"and",
"version",
"and",
"threading",
"and",
"exceptions",
"and",
"revision",
")",
":",
"versions",
"=",
"repository",
"(",
"log",
"=",
"log",
")",
"# Determine some defaults",
"version",
"=",
"version",
"or",
"max",
"(",
"versions",
".",
"keys",
"(",
")",
")",
"if",
"not",
"arch",
":",
"arch",
"=",
"platform",
".",
"machine",
"(",
")",
".",
"lower",
"(",
")",
"if",
"arch",
"==",
"'x86'",
":",
"arch",
"=",
"'i686'",
"elif",
"arch",
"==",
"'amd64'",
":",
"arch",
"=",
"'x86_64'",
"if",
"not",
"threading",
":",
"keys",
"=",
"versions",
"[",
"version",
"]",
"[",
"arch",
"]",
".",
"keys",
"(",
")",
"if",
"'posix'",
"in",
"keys",
":",
"threading",
"=",
"'posix'",
"elif",
"'win32'",
"in",
"keys",
":",
"threading",
"=",
"'win32'",
"else",
":",
"threading",
"=",
"keys",
"[",
"0",
"]",
"if",
"not",
"exceptions",
":",
"keys",
"=",
"versions",
"[",
"version",
"]",
"[",
"arch",
"]",
"[",
"threading",
"]",
".",
"keys",
"(",
")",
"if",
"'seh'",
"in",
"keys",
":",
"exceptions",
"=",
"'seh'",
"elif",
"'sjlj'",
"in",
"keys",
":",
"exceptions",
"=",
"'sjlj'",
"else",
":",
"exceptions",
"=",
"keys",
"[",
"0",
"]",
"if",
"revision",
"==",
"None",
":",
"revision",
"=",
"max",
"(",
"versions",
"[",
"version",
"]",
"[",
"arch",
"]",
"[",
"threading",
"]",
"[",
"exceptions",
"]",
".",
"keys",
"(",
")",
")",
"if",
"not",
"location",
":",
"location",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"'mingw-builds'",
")",
"# Get the download url",
"url",
"=",
"versions",
"[",
"version",
"]",
"[",
"arch",
"]",
"[",
"threading",
"]",
"[",
"exceptions",
"]",
"[",
"revision",
"]",
"# Tell the user whatzzup",
"log",
".",
"info",
"(",
"'finding MinGW %s'",
",",
"'.'",
".",
"join",
"(",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"version",
")",
")",
"log",
".",
"debug",
"(",
"' - arch: %s'",
",",
"arch",
")",
"log",
".",
"debug",
"(",
"' - threading: %s'",
",",
"threading",
")",
"log",
".",
"debug",
"(",
"' - exceptions: %s'",
",",
"exceptions",
")",
"log",
".",
"debug",
"(",
"' - revision: %s'",
",",
"revision",
")",
"log",
".",
"debug",
"(",
"' - url: %s'",
",",
"url",
")",
"# Store each specific revision differently",
"slug",
"=",
"'{version}-{arch}-{threading}-{exceptions}-rev{revision}'",
"slug",
"=",
"slug",
".",
"format",
"(",
"version",
"=",
"'.'",
".",
"join",
"(",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"version",
")",
",",
"arch",
"=",
"arch",
",",
"threading",
"=",
"threading",
",",
"exceptions",
"=",
"exceptions",
",",
"revision",
"=",
"revision",
")",
"if",
"arch",
"==",
"'x86_64'",
":",
"root_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"location",
",",
"slug",
",",
"'mingw64'",
")",
"elif",
"arch",
"==",
"'i686'",
":",
"root_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"location",
",",
"slug",
",",
"'mingw32'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown MinGW arch: '",
"+",
"arch",
")",
"# Download if needed",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"root_dir",
")",
":",
"downloaded",
"=",
"download",
"(",
"url",
",",
"os",
".",
"path",
".",
"join",
"(",
"location",
",",
"slug",
")",
",",
"log",
"=",
"log",
")",
"if",
"downloaded",
"!=",
"root_dir",
":",
"raise",
"ValueError",
"(",
"'The location of mingw did not match\\n%s\\n%s'",
"%",
"(",
"downloaded",
",",
"root_dir",
")",
")",
"return",
"root_dir"
] |
https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/utils/google-benchmark/mingw.py#L172-L246
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/scikit-learn/py3/sklearn/impute/_base.py
|
python
|
MissingIndicator.fit_transform
|
(self, X, y=None)
|
return imputer_mask
|
Generate missing values indicator for X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The input data to complete.
Returns
-------
Xt : {ndarray or sparse matrix}, shape (n_samples, n_features) \
or (n_samples, n_features_with_missing)
The missing indicator for input data. The data type of ``Xt``
will be boolean.
|
Generate missing values indicator for X.
|
[
"Generate",
"missing",
"values",
"indicator",
"for",
"X",
"."
] |
def fit_transform(self, X, y=None):
"""Generate missing values indicator for X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The input data to complete.
Returns
-------
Xt : {ndarray or sparse matrix}, shape (n_samples, n_features) \
or (n_samples, n_features_with_missing)
The missing indicator for input data. The data type of ``Xt``
will be boolean.
"""
imputer_mask = self._fit(X, y)
if self.features_.size < self._n_features:
imputer_mask = imputer_mask[:, self.features_]
return imputer_mask
|
[
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"imputer_mask",
"=",
"self",
".",
"_fit",
"(",
"X",
",",
"y",
")",
"if",
"self",
".",
"features_",
".",
"size",
"<",
"self",
".",
"_n_features",
":",
"imputer_mask",
"=",
"imputer_mask",
"[",
":",
",",
"self",
".",
"features_",
"]",
"return",
"imputer_mask"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/impute/_base.py#L697-L718
|
|
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py
|
python
|
__methods
|
(cls)
|
return _dict.keys()
|
helper function for Scrolled Canvas
|
helper function for Scrolled Canvas
|
[
"helper",
"function",
"for",
"Scrolled",
"Canvas"
] |
def __methods(cls):
"""helper function for Scrolled Canvas"""
_dict = {}
__methodDict(cls, _dict)
return _dict.keys()
|
[
"def",
"__methods",
"(",
"cls",
")",
":",
"_dict",
"=",
"{",
"}",
"__methodDict",
"(",
"cls",
",",
"_dict",
")",
"return",
"_dict",
".",
"keys",
"(",
")"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py#L318-L322
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/tornado/tornado-6/tornado/httputil.py
|
python
|
HTTPServerConnectionDelegate.start_request
|
(
self, server_conn: object, request_conn: "HTTPConnection"
)
|
This method is called by the server when a new request has started.
:arg server_conn: is an opaque object representing the long-lived
(e.g. tcp-level) connection.
:arg request_conn: is a `.HTTPConnection` object for a single
request/response exchange.
This method should return a `.HTTPMessageDelegate`.
|
This method is called by the server when a new request has started.
|
[
"This",
"method",
"is",
"called",
"by",
"the",
"server",
"when",
"a",
"new",
"request",
"has",
"started",
"."
] |
def start_request(
self, server_conn: object, request_conn: "HTTPConnection"
) -> "HTTPMessageDelegate":
"""This method is called by the server when a new request has started.
:arg server_conn: is an opaque object representing the long-lived
(e.g. tcp-level) connection.
:arg request_conn: is a `.HTTPConnection` object for a single
request/response exchange.
This method should return a `.HTTPMessageDelegate`.
"""
raise NotImplementedError()
|
[
"def",
"start_request",
"(",
"self",
",",
"server_conn",
":",
"object",
",",
"request_conn",
":",
"\"HTTPConnection\"",
")",
"->",
"\"HTTPMessageDelegate\"",
":",
"raise",
"NotImplementedError",
"(",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/httputil.py#L494-L506
|
||
0vercl0k/rp
|
5fe693c26d76b514efaedb4084f6e37d820db023
|
src/third_party/fmt/support/docopt.py
|
python
|
parse_long
|
(tokens, options)
|
return [o]
|
long ::= '--' chars [ ( ' ' | '=' ) chars ] ;
|
long ::= '--' chars [ ( ' ' | '=' ) chars ] ;
|
[
"long",
"::",
"=",
"--",
"chars",
"[",
"(",
"|",
"=",
")",
"chars",
"]",
";"
] |
def parse_long(tokens, options):
"""long ::= '--' chars [ ( ' ' | '=' ) chars ] ;"""
long, eq, value = tokens.move().partition('=')
assert long.startswith('--')
value = None if eq == value == '' else value
similar = [o for o in options if o.long == long]
if tokens.error is DocoptExit and similar == []: # if no exact match
similar = [o for o in options if o.long and o.long.startswith(long)]
if len(similar) > 1: # might be simply specified ambiguously 2+ times?
raise tokens.error('%s is not a unique prefix: %s?' %
(long, ', '.join(o.long for o in similar)))
elif len(similar) < 1:
argcount = 1 if eq == '=' else 0
o = Option(None, long, argcount)
options.append(o)
if tokens.error is DocoptExit:
o = Option(None, long, argcount, value if argcount else True)
else:
o = Option(similar[0].short, similar[0].long,
similar[0].argcount, similar[0].value)
if o.argcount == 0:
if value is not None:
raise tokens.error('%s must not have an argument' % o.long)
else:
if value is None:
if tokens.current() in [None, '--']:
raise tokens.error('%s requires argument' % o.long)
value = tokens.move()
if tokens.error is DocoptExit:
o.value = value if value is not None else True
return [o]
|
[
"def",
"parse_long",
"(",
"tokens",
",",
"options",
")",
":",
"long",
",",
"eq",
",",
"value",
"=",
"tokens",
".",
"move",
"(",
")",
".",
"partition",
"(",
"'='",
")",
"assert",
"long",
".",
"startswith",
"(",
"'--'",
")",
"value",
"=",
"None",
"if",
"eq",
"==",
"value",
"==",
"''",
"else",
"value",
"similar",
"=",
"[",
"o",
"for",
"o",
"in",
"options",
"if",
"o",
".",
"long",
"==",
"long",
"]",
"if",
"tokens",
".",
"error",
"is",
"DocoptExit",
"and",
"similar",
"==",
"[",
"]",
":",
"# if no exact match",
"similar",
"=",
"[",
"o",
"for",
"o",
"in",
"options",
"if",
"o",
".",
"long",
"and",
"o",
".",
"long",
".",
"startswith",
"(",
"long",
")",
"]",
"if",
"len",
"(",
"similar",
")",
">",
"1",
":",
"# might be simply specified ambiguously 2+ times?",
"raise",
"tokens",
".",
"error",
"(",
"'%s is not a unique prefix: %s?'",
"%",
"(",
"long",
",",
"', '",
".",
"join",
"(",
"o",
".",
"long",
"for",
"o",
"in",
"similar",
")",
")",
")",
"elif",
"len",
"(",
"similar",
")",
"<",
"1",
":",
"argcount",
"=",
"1",
"if",
"eq",
"==",
"'='",
"else",
"0",
"o",
"=",
"Option",
"(",
"None",
",",
"long",
",",
"argcount",
")",
"options",
".",
"append",
"(",
"o",
")",
"if",
"tokens",
".",
"error",
"is",
"DocoptExit",
":",
"o",
"=",
"Option",
"(",
"None",
",",
"long",
",",
"argcount",
",",
"value",
"if",
"argcount",
"else",
"True",
")",
"else",
":",
"o",
"=",
"Option",
"(",
"similar",
"[",
"0",
"]",
".",
"short",
",",
"similar",
"[",
"0",
"]",
".",
"long",
",",
"similar",
"[",
"0",
"]",
".",
"argcount",
",",
"similar",
"[",
"0",
"]",
".",
"value",
")",
"if",
"o",
".",
"argcount",
"==",
"0",
":",
"if",
"value",
"is",
"not",
"None",
":",
"raise",
"tokens",
".",
"error",
"(",
"'%s must not have an argument'",
"%",
"o",
".",
"long",
")",
"else",
":",
"if",
"value",
"is",
"None",
":",
"if",
"tokens",
".",
"current",
"(",
")",
"in",
"[",
"None",
",",
"'--'",
"]",
":",
"raise",
"tokens",
".",
"error",
"(",
"'%s requires argument'",
"%",
"o",
".",
"long",
")",
"value",
"=",
"tokens",
".",
"move",
"(",
")",
"if",
"tokens",
".",
"error",
"is",
"DocoptExit",
":",
"o",
".",
"value",
"=",
"value",
"if",
"value",
"is",
"not",
"None",
"else",
"True",
"return",
"[",
"o",
"]"
] |
https://github.com/0vercl0k/rp/blob/5fe693c26d76b514efaedb4084f6e37d820db023/src/third_party/fmt/support/docopt.py#L301-L331
|
|
PaddlePaddle/Paddle
|
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
|
python/paddle/fluid/dygraph/checkpoint.py
|
python
|
save_dygraph
|
(state_dict, model_path)
|
:api_attr: imperative
Save Layer's state_dict to disk. This will generate a file with suffix ".pdparams"
The state_dict is get from Layers.state_dict function
Args:
state_dict(dict) : The state dict to be saved.
model_path(str) : the file prefix to save the state_dict. The format is "dirname/file_prefix". If file_prefix is empty str. A exception will be raised
Returns:
None
Examples:
.. code-block:: python
import paddle.fluid as fluid
with fluid.dygraph.guard():
emb = fluid.dygraph.Embedding([10, 10])
state_dict = emb.state_dict()
fluid.save_dygraph( state_dict, "paddle_dy")
adam = fluid.optimizer.Adam( learning_rate = fluid.layers.noam_decay( 100, 10000),
parameter_list = emb.parameters() )
state_dict = adam.state_dict()
fluid.save_dygraph( state_dict, "paddle_dy")
|
:api_attr: imperative
|
[
":",
"api_attr",
":",
"imperative"
] |
def save_dygraph(state_dict, model_path):
'''
:api_attr: imperative
Save Layer's state_dict to disk. This will generate a file with suffix ".pdparams"
The state_dict is get from Layers.state_dict function
Args:
state_dict(dict) : The state dict to be saved.
model_path(str) : the file prefix to save the state_dict. The format is "dirname/file_prefix". If file_prefix is empty str. A exception will be raised
Returns:
None
Examples:
.. code-block:: python
import paddle.fluid as fluid
with fluid.dygraph.guard():
emb = fluid.dygraph.Embedding([10, 10])
state_dict = emb.state_dict()
fluid.save_dygraph( state_dict, "paddle_dy")
adam = fluid.optimizer.Adam( learning_rate = fluid.layers.noam_decay( 100, 10000),
parameter_list = emb.parameters() )
state_dict = adam.state_dict()
fluid.save_dygraph( state_dict, "paddle_dy")
'''
base_name = os.path.basename(model_path)
assert base_name != "", "The input model_path MUST be format of dirname/filename [dirname\\filename in Windows system], but received filename is empty string."
suffix = ".pdparams"
assert len(state_dict) > 0, "state_dict is empty, no need to save"
param_num = 0
for k, v in state_dict.items():
if isinstance(v, ParamBase):
param_num += 1
if param_num == 0:
suffix = ".pdopt"
model_dict = {}
name_table = {}
for k, v in state_dict.items():
if isinstance(v, (Variable, core.VarBase)):
model_dict[k] = v.numpy()
name_table[k] = v.name
else:
model_dict[k] = v
model_dict["StructuredToParameterName@@"] = name_table
file_name = model_path + suffix
dir_name = os.path.dirname(file_name)
if dir_name and not os.path.exists(dir_name):
os.makedirs(dir_name)
with open(file_name, 'wb') as f:
pickle.dump(model_dict, f, protocol=2)
|
[
"def",
"save_dygraph",
"(",
"state_dict",
",",
"model_path",
")",
":",
"base_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"model_path",
")",
"assert",
"base_name",
"!=",
"\"\"",
",",
"\"The input model_path MUST be format of dirname/filename [dirname\\\\filename in Windows system], but received filename is empty string.\"",
"suffix",
"=",
"\".pdparams\"",
"assert",
"len",
"(",
"state_dict",
")",
">",
"0",
",",
"\"state_dict is empty, no need to save\"",
"param_num",
"=",
"0",
"for",
"k",
",",
"v",
"in",
"state_dict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"ParamBase",
")",
":",
"param_num",
"+=",
"1",
"if",
"param_num",
"==",
"0",
":",
"suffix",
"=",
"\".pdopt\"",
"model_dict",
"=",
"{",
"}",
"name_table",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"state_dict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"(",
"Variable",
",",
"core",
".",
"VarBase",
")",
")",
":",
"model_dict",
"[",
"k",
"]",
"=",
"v",
".",
"numpy",
"(",
")",
"name_table",
"[",
"k",
"]",
"=",
"v",
".",
"name",
"else",
":",
"model_dict",
"[",
"k",
"]",
"=",
"v",
"model_dict",
"[",
"\"StructuredToParameterName@@\"",
"]",
"=",
"name_table",
"file_name",
"=",
"model_path",
"+",
"suffix",
"dir_name",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"file_name",
")",
"if",
"dir_name",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir_name",
")",
":",
"os",
".",
"makedirs",
"(",
"dir_name",
")",
"with",
"open",
"(",
"file_name",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"model_dict",
",",
"f",
",",
"protocol",
"=",
"2",
")"
] |
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/checkpoint.py#L55-L119
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/states.py
|
python
|
Text.text
|
(self, match, context, next_state)
|
return [], next_state, []
|
Paragraph.
|
Paragraph.
|
[
"Paragraph",
"."
] |
def text(self, match, context, next_state):
"""Paragraph."""
startline = self.state_machine.abs_line_number() - 1
msg = None
try:
block = self.state_machine.get_text_block(flush_left=True)
except statemachine.UnexpectedIndentationError, err:
block, src, srcline = err.args
msg = self.reporter.error('Unexpected indentation.',
source=src, line=srcline)
lines = context + list(block)
paragraph, literalnext = self.paragraph(lines, startline)
self.parent += paragraph
self.parent += msg
if literalnext:
try:
self.state_machine.next_line()
except EOFError:
pass
self.parent += self.literal_block()
return [], next_state, []
|
[
"def",
"text",
"(",
"self",
",",
"match",
",",
"context",
",",
"next_state",
")",
":",
"startline",
"=",
"self",
".",
"state_machine",
".",
"abs_line_number",
"(",
")",
"-",
"1",
"msg",
"=",
"None",
"try",
":",
"block",
"=",
"self",
".",
"state_machine",
".",
"get_text_block",
"(",
"flush_left",
"=",
"True",
")",
"except",
"statemachine",
".",
"UnexpectedIndentationError",
",",
"err",
":",
"block",
",",
"src",
",",
"srcline",
"=",
"err",
".",
"args",
"msg",
"=",
"self",
".",
"reporter",
".",
"error",
"(",
"'Unexpected indentation.'",
",",
"source",
"=",
"src",
",",
"line",
"=",
"srcline",
")",
"lines",
"=",
"context",
"+",
"list",
"(",
"block",
")",
"paragraph",
",",
"literalnext",
"=",
"self",
".",
"paragraph",
"(",
"lines",
",",
"startline",
")",
"self",
".",
"parent",
"+=",
"paragraph",
"self",
".",
"parent",
"+=",
"msg",
"if",
"literalnext",
":",
"try",
":",
"self",
".",
"state_machine",
".",
"next_line",
"(",
")",
"except",
"EOFError",
":",
"pass",
"self",
".",
"parent",
"+=",
"self",
".",
"literal_block",
"(",
")",
"return",
"[",
"]",
",",
"next_state",
",",
"[",
"]"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/states.py#L2756-L2776
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/runtime/context.py
|
python
|
NRTContext.eh_check
|
(self, builder)
|
return has_raised
|
Check if an exception is raised
|
Check if an exception is raised
|
[
"Check",
"if",
"an",
"exception",
"is",
"raised"
] |
def eh_check(self, builder):
"""Check if an exception is raised
"""
ctx = self._context
cc = ctx.call_conv
# Inspect the excinfo argument on the function
trystatus = cc.check_try_status(builder)
excinfo = trystatus.excinfo
has_raised = builder.not_(cgutils.is_null(builder, excinfo))
with builder.if_then(has_raised):
self.eh_end_try(builder)
return has_raised
|
[
"def",
"eh_check",
"(",
"self",
",",
"builder",
")",
":",
"ctx",
"=",
"self",
".",
"_context",
"cc",
"=",
"ctx",
".",
"call_conv",
"# Inspect the excinfo argument on the function",
"trystatus",
"=",
"cc",
".",
"check_try_status",
"(",
"builder",
")",
"excinfo",
"=",
"trystatus",
".",
"excinfo",
"has_raised",
"=",
"builder",
".",
"not_",
"(",
"cgutils",
".",
"is_null",
"(",
"builder",
",",
"excinfo",
")",
")",
"with",
"builder",
".",
"if_then",
"(",
"has_raised",
")",
":",
"self",
".",
"eh_end_try",
"(",
"builder",
")",
"return",
"has_raised"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/runtime/context.py#L238-L249
|
|
protocolbuffers/protobuf
|
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
|
python/mox.py
|
python
|
MockAnything._Reset
|
(self)
|
Reset the state of this mock to record mode with an empty queue.
|
Reset the state of this mock to record mode with an empty queue.
|
[
"Reset",
"the",
"state",
"of",
"this",
"mock",
"to",
"record",
"mode",
"with",
"an",
"empty",
"queue",
"."
] |
def _Reset(self):
"""Reset the state of this mock to record mode with an empty queue."""
# Maintain a list of method calls we are expecting
self._expected_calls_queue = deque()
# Make sure we are in setup mode, not replay mode
self._replay_mode = False
|
[
"def",
"_Reset",
"(",
"self",
")",
":",
"# Maintain a list of method calls we are expecting",
"self",
".",
"_expected_calls_queue",
"=",
"deque",
"(",
")",
"# Make sure we are in setup mode, not replay mode",
"self",
".",
"_replay_mode",
"=",
"False"
] |
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/mox.py#L349-L356
|
||
happynear/caffe-windows
|
967eedf25009e334b7f6f933bb5e17aaaff5bef6
|
scripts/cpp_lint.py
|
python
|
FindNextMatchingAngleBracket
|
(clean_lines, linenum, init_suffix)
|
return True
|
Find the corresponding > to close a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_suffix: Remainder of the current line after the initial <.
Returns:
True if a matching bracket exists.
|
Find the corresponding > to close a template.
|
[
"Find",
"the",
"corresponding",
">",
"to",
"close",
"a",
"template",
"."
] |
def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix):
"""Find the corresponding > to close a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_suffix: Remainder of the current line after the initial <.
Returns:
True if a matching bracket exists.
"""
line = init_suffix
nesting_stack = ['<']
while True:
# Find the next operator that can tell us whether < is used as an
# opening bracket or as a less-than operator. We only want to
# warn on the latter case.
#
# We could also check all other operators and terminate the search
# early, e.g. if we got something like this "a<b+c", the "<" is
# most likely a less-than operator, but then we will get false
# positives for default arguments and other template expressions.
match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line)
if match:
# Found an operator, update nesting stack
operator = match.group(1)
line = match.group(2)
if nesting_stack[-1] == '<':
# Expecting closing angle bracket
if operator in ('<', '(', '['):
nesting_stack.append(operator)
elif operator == '>':
nesting_stack.pop()
if not nesting_stack:
# Found matching angle bracket
return True
elif operator == ',':
# Got a comma after a bracket, this is most likely a template
# argument. We have not seen a closing angle bracket yet, but
# it's probably a few lines later if we look for it, so just
# return early here.
return True
else:
# Got some other operator.
return False
else:
# Expecting closing parenthesis or closing bracket
if operator in ('<', '(', '['):
nesting_stack.append(operator)
elif operator in (')', ']'):
# We don't bother checking for matching () or []. If we got
# something like (] or [), it would have been a syntax error.
nesting_stack.pop()
else:
# Scan the next line
linenum += 1
if linenum >= len(clean_lines.elided):
break
line = clean_lines.elided[linenum]
# Exhausted all remaining lines and still no matching angle bracket.
# Most likely the input was incomplete, otherwise we should have
# seen a semicolon and returned early.
return True
|
[
"def",
"FindNextMatchingAngleBracket",
"(",
"clean_lines",
",",
"linenum",
",",
"init_suffix",
")",
":",
"line",
"=",
"init_suffix",
"nesting_stack",
"=",
"[",
"'<'",
"]",
"while",
"True",
":",
"# Find the next operator that can tell us whether < is used as an",
"# opening bracket or as a less-than operator. We only want to",
"# warn on the latter case.",
"#",
"# We could also check all other operators and terminate the search",
"# early, e.g. if we got something like this \"a<b+c\", the \"<\" is",
"# most likely a less-than operator, but then we will get false",
"# positives for default arguments and other template expressions.",
"match",
"=",
"Search",
"(",
"r'^[^<>(),;\\[\\]]*([<>(),;\\[\\]])(.*)$'",
",",
"line",
")",
"if",
"match",
":",
"# Found an operator, update nesting stack",
"operator",
"=",
"match",
".",
"group",
"(",
"1",
")",
"line",
"=",
"match",
".",
"group",
"(",
"2",
")",
"if",
"nesting_stack",
"[",
"-",
"1",
"]",
"==",
"'<'",
":",
"# Expecting closing angle bracket",
"if",
"operator",
"in",
"(",
"'<'",
",",
"'('",
",",
"'['",
")",
":",
"nesting_stack",
".",
"append",
"(",
"operator",
")",
"elif",
"operator",
"==",
"'>'",
":",
"nesting_stack",
".",
"pop",
"(",
")",
"if",
"not",
"nesting_stack",
":",
"# Found matching angle bracket",
"return",
"True",
"elif",
"operator",
"==",
"','",
":",
"# Got a comma after a bracket, this is most likely a template",
"# argument. We have not seen a closing angle bracket yet, but",
"# it's probably a few lines later if we look for it, so just",
"# return early here.",
"return",
"True",
"else",
":",
"# Got some other operator.",
"return",
"False",
"else",
":",
"# Expecting closing parenthesis or closing bracket",
"if",
"operator",
"in",
"(",
"'<'",
",",
"'('",
",",
"'['",
")",
":",
"nesting_stack",
".",
"append",
"(",
"operator",
")",
"elif",
"operator",
"in",
"(",
"')'",
",",
"']'",
")",
":",
"# We don't bother checking for matching () or []. If we got",
"# something like (] or [), it would have been a syntax error.",
"nesting_stack",
".",
"pop",
"(",
")",
"else",
":",
"# Scan the next line",
"linenum",
"+=",
"1",
"if",
"linenum",
">=",
"len",
"(",
"clean_lines",
".",
"elided",
")",
":",
"break",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Exhausted all remaining lines and still no matching angle bracket.",
"# Most likely the input was incomplete, otherwise we should have",
"# seen a semicolon and returned early.",
"return",
"True"
] |
https://github.com/happynear/caffe-windows/blob/967eedf25009e334b7f6f933bb5e17aaaff5bef6/scripts/cpp_lint.py#L2521-L2587
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/intrinsic_wrapper.py
|
python
|
all_sync
|
(mask, predicate)
|
return numba.cuda.vote_sync_intrinsic(mask, 0, predicate)[1]
|
If for all threads in the masked warp the predicate is true, then
a non-zero value is returned, otherwise 0 is returned.
|
If for all threads in the masked warp the predicate is true, then
a non-zero value is returned, otherwise 0 is returned.
|
[
"If",
"for",
"all",
"threads",
"in",
"the",
"masked",
"warp",
"the",
"predicate",
"is",
"true",
"then",
"a",
"non",
"-",
"zero",
"value",
"is",
"returned",
"otherwise",
"0",
"is",
"returned",
"."
] |
def all_sync(mask, predicate):
"""
If for all threads in the masked warp the predicate is true, then
a non-zero value is returned, otherwise 0 is returned.
"""
return numba.cuda.vote_sync_intrinsic(mask, 0, predicate)[1]
|
[
"def",
"all_sync",
"(",
"mask",
",",
"predicate",
")",
":",
"return",
"numba",
".",
"cuda",
".",
"vote_sync_intrinsic",
"(",
"mask",
",",
"0",
",",
"predicate",
")",
"[",
"1",
"]"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/intrinsic_wrapper.py#L7-L12
|
|
mindspore-ai/mindspore
|
fb8fd3338605bb34fa5cea054e535a8b1d753fab
|
mindspore/python/mindspore/mindrecord/tools/mnist_to_mr.py
|
python
|
MnistToMR.run
|
(self)
|
return SUCCESS
|
Execute transformation from Mnist to MindRecord.
Returns:
MSRStatus, whether successfully written into MindRecord.
|
Execute transformation from Mnist to MindRecord.
|
[
"Execute",
"transformation",
"from",
"Mnist",
"to",
"MindRecord",
"."
] |
def run(self):
"""
Execute transformation from Mnist to MindRecord.
Returns:
MSRStatus, whether successfully written into MindRecord.
"""
if not cv2:
raise ModuleNotFoundError("opencv-python module not found, please use pip install it.")
if self._transform_train() == FAILED:
return FAILED
if self._transform_test() == FAILED:
return FAILED
return SUCCESS
|
[
"def",
"run",
"(",
"self",
")",
":",
"if",
"not",
"cv2",
":",
"raise",
"ModuleNotFoundError",
"(",
"\"opencv-python module not found, please use pip install it.\"",
")",
"if",
"self",
".",
"_transform_train",
"(",
")",
"==",
"FAILED",
":",
"return",
"FAILED",
"if",
"self",
".",
"_transform_test",
"(",
")",
"==",
"FAILED",
":",
"return",
"FAILED",
"return",
"SUCCESS"
] |
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/mindrecord/tools/mnist_to_mr.py#L223-L238
|
|
eric612/MobileNet-YOLO
|
69b4441cb3ec8d553fbdef788ad033e246f901bd
|
scripts/cpp_lint.py
|
python
|
CleanseComments
|
(line)
|
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
|
Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
|
Removes //-comments and single-line C-style /* */ comments.
|
[
"Removes",
"//",
"-",
"comments",
"and",
"single",
"-",
"line",
"C",
"-",
"style",
"/",
"*",
"*",
"/",
"comments",
"."
] |
def CleanseComments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
|
[
"def",
"CleanseComments",
"(",
"line",
")",
":",
"commentpos",
"=",
"line",
".",
"find",
"(",
"'//'",
")",
"if",
"commentpos",
"!=",
"-",
"1",
"and",
"not",
"IsCppString",
"(",
"line",
"[",
":",
"commentpos",
"]",
")",
":",
"line",
"=",
"line",
"[",
":",
"commentpos",
"]",
".",
"rstrip",
"(",
")",
"# get rid of /* ... */",
"return",
"_RE_PATTERN_CLEANSE_LINE_C_COMMENTS",
".",
"sub",
"(",
"''",
",",
"line",
")"
] |
https://github.com/eric612/MobileNet-YOLO/blob/69b4441cb3ec8d553fbdef788ad033e246f901bd/scripts/cpp_lint.py#L1171-L1184
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/windows/Lib/collections/__init__.py
|
python
|
Counter.__isub__
|
(self, other)
|
return self._keep_positive()
|
Inplace subtract counter, but keep only results with positive counts.
>>> c = Counter('abbbc')
>>> c -= Counter('bccd')
>>> c
Counter({'b': 2, 'a': 1})
|
Inplace subtract counter, but keep only results with positive counts.
|
[
"Inplace",
"subtract",
"counter",
"but",
"keep",
"only",
"results",
"with",
"positive",
"counts",
"."
] |
def __isub__(self, other):
'''Inplace subtract counter, but keep only results with positive counts.
>>> c = Counter('abbbc')
>>> c -= Counter('bccd')
>>> c
Counter({'b': 2, 'a': 1})
'''
for elem, count in other.items():
self[elem] -= count
return self._keep_positive()
|
[
"def",
"__isub__",
"(",
"self",
",",
"other",
")",
":",
"for",
"elem",
",",
"count",
"in",
"other",
".",
"items",
"(",
")",
":",
"self",
"[",
"elem",
"]",
"-=",
"count",
"return",
"self",
".",
"_keep_positive",
"(",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/collections/__init__.py#L838-L849
|
|
blue-yonder/turbodbc
|
3cccd0af637944cf566c6c295c92f23ba90deffa
|
python/turbodbc/cursor.py
|
python
|
Cursor.execute
|
(self, sql, parameters=None)
|
return self._execute()
|
Execute an SQL command or query
:param sql: A (unicode) string that contains the SQL command or query. If you would like to
use parameters, please use a question mark ``?`` at the location where the
parameter shall be inserted.
:param parameters: An iterable of parameter values. The number of values must match
the number of parameters in the SQL string.
:return: The ``Cursor`` object to allow chaining of operations.
|
Execute an SQL command or query
|
[
"Execute",
"an",
"SQL",
"command",
"or",
"query"
] |
def execute(self, sql, parameters=None):
"""
Execute an SQL command or query
:param sql: A (unicode) string that contains the SQL command or query. If you would like to
use parameters, please use a question mark ``?`` at the location where the
parameter shall be inserted.
:param parameters: An iterable of parameter values. The number of values must match
the number of parameters in the SQL string.
:return: The ``Cursor`` object to allow chaining of operations.
"""
self.rowcount = -1
self._assert_valid()
self.impl.prepare(sql)
if parameters:
buffer = make_parameter_set(self.impl)
buffer.add_set(parameters)
buffer.flush()
return self._execute()
|
[
"def",
"execute",
"(",
"self",
",",
"sql",
",",
"parameters",
"=",
"None",
")",
":",
"self",
".",
"rowcount",
"=",
"-",
"1",
"self",
".",
"_assert_valid",
"(",
")",
"self",
".",
"impl",
".",
"prepare",
"(",
"sql",
")",
"if",
"parameters",
":",
"buffer",
"=",
"make_parameter_set",
"(",
"self",
".",
"impl",
")",
"buffer",
".",
"add_set",
"(",
"parameters",
")",
"buffer",
".",
"flush",
"(",
")",
"return",
"self",
".",
"_execute",
"(",
")"
] |
https://github.com/blue-yonder/turbodbc/blob/3cccd0af637944cf566c6c295c92f23ba90deffa/python/turbodbc/cursor.py#L118-L136
|
|
gem5/gem5
|
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
|
site_scons/gem5_scons/sources.py
|
python
|
with_all_tags
|
(*tags)
|
return SourceFilter(lambda env, stags: resolve_tags(env, tags) <= stags)
|
Return a list of sources with all of the supplied tags.
|
Return a list of sources with all of the supplied tags.
|
[
"Return",
"a",
"list",
"of",
"sources",
"with",
"all",
"of",
"the",
"supplied",
"tags",
"."
] |
def with_all_tags(*tags):
'''Return a list of sources with all of the supplied tags.'''
return SourceFilter(lambda env, stags: resolve_tags(env, tags) <= stags)
|
[
"def",
"with_all_tags",
"(",
"*",
"tags",
")",
":",
"return",
"SourceFilter",
"(",
"lambda",
"env",
",",
"stags",
":",
"resolve_tags",
"(",
"env",
",",
"tags",
")",
"<=",
"stags",
")"
] |
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/site_scons/gem5_scons/sources.py#L143-L145
|
|
WeitaoVan/L-GM-loss
|
598582f0631bac876b3eeb8d6c4cd1d780269e03
|
tensorflow/resnet_model.py
|
python
|
lgm_logits
|
(feat, num_classes, labels=None, alpha=0.1, lambda_=0.01)
|
return logits_with_margin, likelihood_reg_loss, means
|
The 3 input hyper-params are explained in the paper.\n
Support 2 modes: Train, Validation\n
(1)Train:\n
return logits, likelihood_reg_loss\n
(2)Validation:\n
Set labels=None\n
return logits\n
|
The 3 input hyper-params are explained in the paper.\n
Support 2 modes: Train, Validation\n
(1)Train:\n
return logits, likelihood_reg_loss\n
(2)Validation:\n
Set labels=None\n
return logits\n
|
[
"The",
"3",
"input",
"hyper",
"-",
"params",
"are",
"explained",
"in",
"the",
"paper",
".",
"\\",
"n",
"Support",
"2",
"modes",
":",
"Train",
"Validation",
"\\",
"n",
"(",
"1",
")",
"Train",
":",
"\\",
"n",
"return",
"logits",
"likelihood_reg_loss",
"\\",
"n",
"(",
"2",
")",
"Validation",
":",
"\\",
"n",
"Set",
"labels",
"=",
"None",
"\\",
"n",
"return",
"logits",
"\\",
"n"
] |
def lgm_logits(feat, num_classes, labels=None, alpha=0.1, lambda_=0.01):
'''
The 3 input hyper-params are explained in the paper.\n
Support 2 modes: Train, Validation\n
(1)Train:\n
return logits, likelihood_reg_loss\n
(2)Validation:\n
Set labels=None\n
return logits\n
'''
N = feat.get_shape().as_list()[0]
feat_len = feat.get_shape()[1]
means = tf.get_variable('rbf_centers', [num_classes, feat_len], dtype=tf.float32,
initializer=tf.contrib.layers.xavier_initializer())
XY = tf.matmul(feat, means, transpose_b=True)
XX = tf.reduce_sum(tf.square(feat), axis=1, keep_dims=True)
YY = tf.reduce_sum(tf.square(tf.transpose(means)), axis=0, keep_dims=True)
neg_sqr_dist = -0.5 * (XX - 2.0 * XY + YY)
if labels is None:
# Validation mode
psudo_labels = tf.argmax(neg_sqr_dist, axis=1)
means_batch = tf.gather(means, psudo_labels)
likelihood_reg_loss = lambda_ * tf.nn.l2_loss(feat - means_batch, name='likelihood_regularization') * (1. / N)
# In fact, in validation mode, we only need to output neg_sqr_dist.
# The likelihood_reg_loss and means are only for research purposes.
return neg_sqr_dist, likelihood_reg_loss, means
# *(1 + alpha)
ALPHA = tf.one_hot(labels, num_classes, on_value=alpha, dtype=tf.float32)
K = ALPHA + tf.ones([N, num_classes], dtype=tf.float32)
logits_with_margin = tf.multiply(neg_sqr_dist, K)
# likelihood regularization
means_batch = tf.gather(means, labels)
likelihood_reg_loss = lambda_ * tf.nn.l2_loss(feat - means_batch, name='center_regularization') * (1. / N)
print('LGM loss built with alpha=%f, lambda=%f\n' %(alpha, lambda_))
return logits_with_margin, likelihood_reg_loss, means
|
[
"def",
"lgm_logits",
"(",
"feat",
",",
"num_classes",
",",
"labels",
"=",
"None",
",",
"alpha",
"=",
"0.1",
",",
"lambda_",
"=",
"0.01",
")",
":",
"N",
"=",
"feat",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"0",
"]",
"feat_len",
"=",
"feat",
".",
"get_shape",
"(",
")",
"[",
"1",
"]",
"means",
"=",
"tf",
".",
"get_variable",
"(",
"'rbf_centers'",
",",
"[",
"num_classes",
",",
"feat_len",
"]",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"initializer",
"=",
"tf",
".",
"contrib",
".",
"layers",
".",
"xavier_initializer",
"(",
")",
")",
"XY",
"=",
"tf",
".",
"matmul",
"(",
"feat",
",",
"means",
",",
"transpose_b",
"=",
"True",
")",
"XX",
"=",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"square",
"(",
"feat",
")",
",",
"axis",
"=",
"1",
",",
"keep_dims",
"=",
"True",
")",
"YY",
"=",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"square",
"(",
"tf",
".",
"transpose",
"(",
"means",
")",
")",
",",
"axis",
"=",
"0",
",",
"keep_dims",
"=",
"True",
")",
"neg_sqr_dist",
"=",
"-",
"0.5",
"*",
"(",
"XX",
"-",
"2.0",
"*",
"XY",
"+",
"YY",
")",
"if",
"labels",
"is",
"None",
":",
"# Validation mode",
"psudo_labels",
"=",
"tf",
".",
"argmax",
"(",
"neg_sqr_dist",
",",
"axis",
"=",
"1",
")",
"means_batch",
"=",
"tf",
".",
"gather",
"(",
"means",
",",
"psudo_labels",
")",
"likelihood_reg_loss",
"=",
"lambda_",
"*",
"tf",
".",
"nn",
".",
"l2_loss",
"(",
"feat",
"-",
"means_batch",
",",
"name",
"=",
"'likelihood_regularization'",
")",
"*",
"(",
"1.",
"/",
"N",
")",
"# In fact, in validation mode, we only need to output neg_sqr_dist. ",
"# The likelihood_reg_loss and means are only for research purposes.",
"return",
"neg_sqr_dist",
",",
"likelihood_reg_loss",
",",
"means",
"# *(1 + alpha)",
"ALPHA",
"=",
"tf",
".",
"one_hot",
"(",
"labels",
",",
"num_classes",
",",
"on_value",
"=",
"alpha",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"K",
"=",
"ALPHA",
"+",
"tf",
".",
"ones",
"(",
"[",
"N",
",",
"num_classes",
"]",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"logits_with_margin",
"=",
"tf",
".",
"multiply",
"(",
"neg_sqr_dist",
",",
"K",
")",
"# likelihood regularization",
"means_batch",
"=",
"tf",
".",
"gather",
"(",
"means",
",",
"labels",
")",
"likelihood_reg_loss",
"=",
"lambda_",
"*",
"tf",
".",
"nn",
".",
"l2_loss",
"(",
"feat",
"-",
"means_batch",
",",
"name",
"=",
"'center_regularization'",
")",
"*",
"(",
"1.",
"/",
"N",
")",
"print",
"(",
"'LGM loss built with alpha=%f, lambda=%f\\n'",
"%",
"(",
"alpha",
",",
"lambda_",
")",
")",
"return",
"logits_with_margin",
",",
"likelihood_reg_loss",
",",
"means"
] |
https://github.com/WeitaoVan/L-GM-loss/blob/598582f0631bac876b3eeb8d6c4cd1d780269e03/tensorflow/resnet_model.py#L436-L472
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.