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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
NGSolve/ngsolve | 4a22558b6d5852f3d7e6cd86f1233b1ad716f395 | py_tutorials/cg.py | python | pcg | (mat, pre, rhs, maxits = 100) | return u | preconditioned conjugate gradient method | preconditioned conjugate gradient method | [
"preconditioned",
"conjugate",
"gradient",
"method"
] | def pcg(mat, pre, rhs, maxits = 100):
"""preconditioned conjugate gradient method"""
u = rhs.CreateVector()
d = rhs.CreateVector()
w = rhs.CreateVector()
s = rhs.CreateVector()
u[:] = 0.0
d.data = rhs - mat * u
w.data = pre * d
s.data = w
wdn = InnerProduct (w,d)
print ("|u0| = ", wdn)
for it in range(maxits):
w.data = mat * s
wd = wdn
Ass = InnerProduct (s, w)
alpha = wd / Ass
u.data += alpha * s
d.data += (-alpha) * w
w.data = pre * d
wdn = InnerProduct (w, d)
beta = wdn / wd
s *= beta
s.data += w
err = sqrt(wd)
if err < 1e-16:
break
print ("it = ", it, " err = ", err)
return u | [
"def",
"pcg",
"(",
"mat",
",",
"pre",
",",
"rhs",
",",
"maxits",
"=",
"100",
")",
":",
"u",
"=",
"rhs",
".",
"CreateVector",
"(",
")",
"d",
"=",
"rhs",
".",
"CreateVector",
"(",
")",
"w",
"=",
"rhs",
".",
"CreateVector",
"(",
")",
"s",
"=",
"... | https://github.com/NGSolve/ngsolve/blob/4a22558b6d5852f3d7e6cd86f1233b1ad716f395/py_tutorials/cg.py#L4-L39 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/layers/rnn_cell_wrapper_v2.py | python | _RNNCellWrapperV2.build | (self, inputs_shape) | Builds the wrapped cell. | Builds the wrapped cell. | [
"Builds",
"the",
"wrapped",
"cell",
"."
] | def build(self, inputs_shape):
"""Builds the wrapped cell."""
self.cell.build(inputs_shape)
self.built = True | [
"def",
"build",
"(",
"self",
",",
"inputs_shape",
")",
":",
"self",
".",
"cell",
".",
"build",
"(",
"inputs_shape",
")",
"self",
".",
"built",
"=",
"True"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/layers/rnn_cell_wrapper_v2.py#L70-L73 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mapreduce/mapreduce/namespace_range.py | python | NamespaceRange.split_range | (self) | return [NamespaceRange(self.namespace_start,
_ord_to_namespace(mid_point),
_app=self.app),
NamespaceRange(_ord_to_namespace(mid_point+1),
self.namespace_end,
_app=self.app)] | Splits the NamespaceRange into two nearly equal-sized ranges.
Returns:
If this NamespaceRange contains a single namespace then a list containing
this NamespaceRange is returned. Otherwise a two-element list containing
two NamespaceRanges whose total range is identical to this
NamespaceRange's is returned. | Splits the NamespaceRange into two nearly equal-sized ranges. | [
"Splits",
"the",
"NamespaceRange",
"into",
"two",
"nearly",
"equal",
"-",
"sized",
"ranges",
"."
] | def split_range(self):
"""Splits the NamespaceRange into two nearly equal-sized ranges.
Returns:
If this NamespaceRange contains a single namespace then a list containing
this NamespaceRange is returned. Otherwise a two-element list containing
two NamespaceRanges whose total range is identical to this
NamespaceRange's is returned.
"""
if self.is_single_namespace:
return [self]
mid_point = (_namespace_to_ord(self.namespace_start) +
_namespace_to_ord(self.namespace_end)) // 2
return [NamespaceRange(self.namespace_start,
_ord_to_namespace(mid_point),
_app=self.app),
NamespaceRange(_ord_to_namespace(mid_point+1),
self.namespace_end,
_app=self.app)] | [
"def",
"split_range",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_single_namespace",
":",
"return",
"[",
"self",
"]",
"mid_point",
"=",
"(",
"_namespace_to_ord",
"(",
"self",
".",
"namespace_start",
")",
"+",
"_namespace_to_ord",
"(",
"self",
".",
"namespa... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/namespace_range.py#L225-L245 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | site_scons/site_tools/ninja.py | python | get_inputs | (node, skip_unknown_types=False) | return [get_path(src_file(o)) for o in ninja_nodes] | Collect the Ninja inputs for node.
If the given node has inputs which can not be converted into something
Ninja can process, this will throw an exception. Optionally, those nodes
that are not processable can be skipped as inputs with the
skip_unknown_types keyword arg. | Collect the Ninja inputs for node. | [
"Collect",
"the",
"Ninja",
"inputs",
"for",
"node",
"."
] | def get_inputs(node, skip_unknown_types=False):
"""
Collect the Ninja inputs for node.
If the given node has inputs which can not be converted into something
Ninja can process, this will throw an exception. Optionally, those nodes
that are not processable can be skipped as inputs with the
skip_unknown_types keyword arg.
"""
executor = node.get_executor()
if executor is not None:
inputs = executor.get_all_sources()
else:
inputs = node.sources
# Some Nodes (e.g. Python.Value Nodes) won't have files associated. We allow these to be
# optionally skipped to enable the case where we will re-invoke SCons for things
# like TEMPLATE. Otherwise, we have no direct way to express the behavior for such
# Nodes in Ninja, so we raise a hard error
ninja_nodes = []
for input_node in inputs:
if isinstance(input_node, (SCons.Node.FS.Base, SCons.Node.Alias.Alias)):
ninja_nodes.append(input_node)
else:
if skip_unknown_types:
continue
raise Exception("Can't process {} node '{}' as an input for '{}'".format(
type(input_node),
str(input_node),
str(node)))
# convert node items into raw paths/aliases for ninja
return [get_path(src_file(o)) for o in ninja_nodes] | [
"def",
"get_inputs",
"(",
"node",
",",
"skip_unknown_types",
"=",
"False",
")",
":",
"executor",
"=",
"node",
".",
"get_executor",
"(",
")",
"if",
"executor",
"is",
"not",
"None",
":",
"inputs",
"=",
"executor",
".",
"get_all_sources",
"(",
")",
"else",
... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/site_scons/site_tools/ninja.py#L157-L189 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/kullback_leibler.py | python | RegisterKL.__init__ | (self, dist_cls_a, dist_cls_b) | Initialize the KL registrar.
Args:
dist_cls_a: the class of the first argument of the KL divergence.
dist_cls_b: the class of the second argument of the KL divergence.
Raises:
TypeError: if dist_cls_a or dist_cls_b are not subclasses of
Distribution. | Initialize the KL registrar. | [
"Initialize",
"the",
"KL",
"registrar",
"."
] | def __init__(self, dist_cls_a, dist_cls_b):
"""Initialize the KL registrar.
Args:
dist_cls_a: the class of the first argument of the KL divergence.
dist_cls_b: the class of the second argument of the KL divergence.
Raises:
TypeError: if dist_cls_a or dist_cls_b are not subclasses of
Distribution.
"""
if not issubclass(dist_cls_a, distribution.Distribution):
raise TypeError("%s is not a subclass of Distribution" % dist_cls_a)
if not issubclass(dist_cls_b, distribution.Distribution):
raise TypeError("%s is not a subclass of Distribution" % dist_cls_b)
self._key = (dist_cls_a, dist_cls_b) | [
"def",
"__init__",
"(",
"self",
",",
"dist_cls_a",
",",
"dist_cls_b",
")",
":",
"if",
"not",
"issubclass",
"(",
"dist_cls_a",
",",
"distribution",
".",
"Distribution",
")",
":",
"raise",
"TypeError",
"(",
"\"%s is not a subclass of Distribution\"",
"%",
"dist_cls_... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/kullback_leibler.py#L91-L107 | ||
psmoveservice/PSMoveService | 22bbe20e9de53f3f3581137bce7b88e2587a27e7 | misc/python/pypsmove/transformations.py | python | reflection_from_matrix | (matrix) | return point, normal | Return mirror plane point and normal vector from reflection matrix.
>>> v0 = numpy.random.random(3) - 0.5
>>> v1 = numpy.random.random(3) - 0.5
>>> M0 = reflection_matrix(v0, v1)
>>> point, normal = reflection_from_matrix(M0)
>>> M1 = reflection_matrix(point, normal)
>>> is_same_transform(M0, M1)
True | Return mirror plane point and normal vector from reflection matrix. | [
"Return",
"mirror",
"plane",
"point",
"and",
"normal",
"vector",
"from",
"reflection",
"matrix",
"."
] | def reflection_from_matrix(matrix):
"""Return mirror plane point and normal vector from reflection matrix.
>>> v0 = numpy.random.random(3) - 0.5
>>> v1 = numpy.random.random(3) - 0.5
>>> M0 = reflection_matrix(v0, v1)
>>> point, normal = reflection_from_matrix(M0)
>>> M1 = reflection_matrix(point, normal)
>>> is_same_transform(M0, M1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
# normal: unit eigenvector corresponding to eigenvalue -1
w, V = numpy.linalg.eig(M[:3, :3])
i = numpy.where(abs(numpy.real(w) + 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue -1")
normal = numpy.real(V[:, i[0]]).squeeze()
# point: any unit eigenvector corresponding to eigenvalue 1
w, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
point = numpy.real(V[:, i[-1]]).squeeze()
point /= point[3]
return point, normal | [
"def",
"reflection_from_matrix",
"(",
"matrix",
")",
":",
"M",
"=",
"numpy",
".",
"array",
"(",
"matrix",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"# normal: unit eigenvector corresponding to eigenvalue -1",
"w",
",",
"V",
"=... | https://github.com/psmoveservice/PSMoveService/blob/22bbe20e9de53f3f3581137bce7b88e2587a27e7/misc/python/pypsmove/transformations.py#L273-L299 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/pimp.py | python | PimpPackage_source.unpackPackageOnly | (self, output=None) | Unpack a source package and check that setup.py exists | Unpack a source package and check that setup.py exists | [
"Unpack",
"a",
"source",
"package",
"and",
"check",
"that",
"setup",
".",
"py",
"exists"
] | def unpackPackageOnly(self, output=None):
"""Unpack a source package and check that setup.py exists"""
PimpPackage.unpackPackageOnly(self, output)
# Test that a setup script has been create
self._buildDirname = os.path.join(self._db.preferences.buildDir, self.basename)
setupname = os.path.join(self._buildDirname, "setup.py")
if not os.path.exists(setupname) and not NO_EXECUTE:
return "no setup.py found after unpack of archive" | [
"def",
"unpackPackageOnly",
"(",
"self",
",",
"output",
"=",
"None",
")",
":",
"PimpPackage",
".",
"unpackPackageOnly",
"(",
"self",
",",
"output",
")",
"# Test that a setup script has been create",
"self",
".",
"_buildDirname",
"=",
"os",
".",
"path",
".",
"joi... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/pimp.py#L849-L856 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/TemplatePyMod/FeaturePython.py | python | Box.__init__ | (self, obj) | Add some custom properties to our box feature | Add some custom properties to our box feature | [
"Add",
"some",
"custom",
"properties",
"to",
"our",
"box",
"feature"
] | def __init__(self, obj):
PartFeature.__init__(self, obj)
''' Add some custom properties to our box feature '''
obj.addProperty("App::PropertyLength","Length","Box","Length of the box").Length=1.0
obj.addProperty("App::PropertyLength","Width","Box","Width of the box").Width=1.0
obj.addProperty("App::PropertyLength","Height","Box", "Height of the box").Height=1.0 | [
"def",
"__init__",
"(",
"self",
",",
"obj",
")",
":",
"PartFeature",
".",
"__init__",
"(",
"self",
",",
"obj",
")",
"obj",
".",
"addProperty",
"(",
"\"App::PropertyLength\"",
",",
"\"Length\"",
",",
"\"Box\"",
",",
"\"Length of the box\"",
")",
".",
"Length"... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/TemplatePyMod/FeaturePython.py#L17-L22 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py | python | getgeneratorstate | (generator) | return GEN_SUSPENDED | Get current state of a generator-iterator.
Possible states are:
GEN_CREATED: Waiting to start execution.
GEN_RUNNING: Currently being executed by the interpreter.
GEN_SUSPENDED: Currently suspended at a yield expression.
GEN_CLOSED: Execution has completed. | Get current state of a generator-iterator. | [
"Get",
"current",
"state",
"of",
"a",
"generator",
"-",
"iterator",
"."
] | def getgeneratorstate(generator):
"""Get current state of a generator-iterator.
Possible states are:
GEN_CREATED: Waiting to start execution.
GEN_RUNNING: Currently being executed by the interpreter.
GEN_SUSPENDED: Currently suspended at a yield expression.
GEN_CLOSED: Execution has completed.
"""
if generator.gi_running:
return GEN_RUNNING
if generator.gi_frame is None:
return GEN_CLOSED
if generator.gi_frame.f_lasti == -1:
return GEN_CREATED
return GEN_SUSPENDED | [
"def",
"getgeneratorstate",
"(",
"generator",
")",
":",
"if",
"generator",
".",
"gi_running",
":",
"return",
"GEN_RUNNING",
"if",
"generator",
".",
"gi_frame",
"is",
"None",
":",
"return",
"GEN_CLOSED",
"if",
"generator",
".",
"gi_frame",
".",
"f_lasti",
"==",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py#L1619-L1634 | |
ros-perception/image_pipeline | cd4aa7ab38726d88e8e0144aa0d45ad2f236535a | camera_calibration/src/camera_calibration/calibrator.py | python | StereoCalibrator.from_message | (self, msgs, alpha = 0.0) | Initialize the camera calibration from a pair of CameraInfo messages. | Initialize the camera calibration from a pair of CameraInfo messages. | [
"Initialize",
"the",
"camera",
"calibration",
"from",
"a",
"pair",
"of",
"CameraInfo",
"messages",
"."
] | def from_message(self, msgs, alpha = 0.0):
""" Initialize the camera calibration from a pair of CameraInfo messages. """
self.size = (msgs[0].width, msgs[0].height)
self.T = numpy.zeros((3, 1), dtype=numpy.float64)
self.R = numpy.eye(3, dtype=numpy.float64)
self.l.from_message(msgs[0])
self.r.from_message(msgs[1])
# Need to compute self.T and self.R here, using the monocular parameters above
if False:
self.set_alpha(0.0) | [
"def",
"from_message",
"(",
"self",
",",
"msgs",
",",
"alpha",
"=",
"0.0",
")",
":",
"self",
".",
"size",
"=",
"(",
"msgs",
"[",
"0",
"]",
".",
"width",
",",
"msgs",
"[",
"0",
"]",
".",
"height",
")",
"self",
".",
"T",
"=",
"numpy",
".",
"zer... | https://github.com/ros-perception/image_pipeline/blob/cd4aa7ab38726d88e8e0144aa0d45ad2f236535a/camera_calibration/src/camera_calibration/calibrator.py#L1232-L1243 | ||
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/site_packages/joblib2/numpy_pickle.py | python | NumpyUnpickler.load_build | (self) | This method is called to set the state of a newly created
object.
We capture it to replace our place-holder objects,
NDArrayWrapper, by the array we are interested in. We
replace them directly in the stack of pickler. | This method is called to set the state of a newly created
object. | [
"This",
"method",
"is",
"called",
"to",
"set",
"the",
"state",
"of",
"a",
"newly",
"created",
"object",
"."
] | def load_build(self):
""" This method is called to set the state of a newly created
object.
We capture it to replace our place-holder objects,
NDArrayWrapper, by the array we are interested in. We
replace them directly in the stack of pickler.
"""
Unpickler.load_build(self)
if isinstance(self.stack[-1], NDArrayWrapper):
if self.np is None:
raise ImportError('Trying to unpickle an ndarray, '
"but numpy didn't import correctly")
nd_array_wrapper = self.stack.pop()
array = nd_array_wrapper.read(self)
self.stack.append(array) | [
"def",
"load_build",
"(",
"self",
")",
":",
"Unpickler",
".",
"load_build",
"(",
"self",
")",
"if",
"isinstance",
"(",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"NDArrayWrapper",
")",
":",
"if",
"self",
".",
"np",
"is",
"None",
":",
"raise",
"... | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/joblib2/numpy_pickle.py#L276-L291 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/html.py | python | HtmlWindow.Create | (*args, **kwargs) | return _html.HtmlWindow_Create(*args, **kwargs) | Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, int style=HW_SCROLLBAR_AUTO,
String name=HtmlWindowNameStr) -> bool | Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, int style=HW_SCROLLBAR_AUTO,
String name=HtmlWindowNameStr) -> bool | [
"Create",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"int",
"style",
"=",
"HW_SCROLLBAR_AUTO",
"String",
"name",
"=",
"HtmlWindowNameStr",
")",
"-",
">",
"bool"
] | def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, int style=HW_SCROLLBAR_AUTO,
String name=HtmlWindowNameStr) -> bool
"""
return _html.HtmlWindow_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlWindow_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L974-L980 | |
dmlc/decord | 96b750c7221322391969929e855b942d2fdcd06b | python/decord/bridge/mxnet.py | python | from_mxnet | (mxnet_arr) | return _from_dlpack(mxnet_arr.to_dlpack_for_read()) | from mxnet to decord, no copy | from mxnet to decord, no copy | [
"from",
"mxnet",
"to",
"decord",
"no",
"copy"
] | def from_mxnet(mxnet_arr):
"""from mxnet to decord, no copy"""
return _from_dlpack(mxnet_arr.to_dlpack_for_read()) | [
"def",
"from_mxnet",
"(",
"mxnet_arr",
")",
":",
"return",
"_from_dlpack",
"(",
"mxnet_arr",
".",
"to_dlpack_for_read",
"(",
")",
")"
] | https://github.com/dmlc/decord/blob/96b750c7221322391969929e855b942d2fdcd06b/python/decord/bridge/mxnet.py#L23-L25 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/maximum-alternating-subsequence-sum.py | python | Solution.maxAlternatingSum | (self, nums) | return result | :type nums: List[int]
:rtype: int | :type nums: List[int]
:rtype: int | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def maxAlternatingSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = nums[0]
for i in xrange(len(nums)-1):
result += max(nums[i+1]-nums[i], 0)
return result | [
"def",
"maxAlternatingSum",
"(",
"self",
",",
"nums",
")",
":",
"result",
"=",
"nums",
"[",
"0",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"nums",
")",
"-",
"1",
")",
":",
"result",
"+=",
"max",
"(",
"nums",
"[",
"i",
"+",
"1",
"]",
"... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-alternating-subsequence-sum.py#L5-L13 | |
OpenVR-Advanced-Settings/OpenVR-AdvancedSettings | 522ba46ac6bcff8e82907715f7f0af7abbbe1e7b | build_scripts/win/common.py | python | say_error | (message: str) | Prints an error message to the console.
Not currently different from say, but put in incase somebody wanted to
do something fancy with outputting to stderr or something instead. | Prints an error message to the console. | [
"Prints",
"an",
"error",
"message",
"to",
"the",
"console",
"."
] | def say_error(message: str):
"""
Prints an error message to the console.
Not currently different from say, but put in incase somebody wanted to
do something fancy with outputting to stderr or something instead.
"""
global current_activity
print(current_activity + ": " + message) | [
"def",
"say_error",
"(",
"message",
":",
"str",
")",
":",
"global",
"current_activity",
"print",
"(",
"current_activity",
"+",
"\": \"",
"+",
"message",
")"
] | https://github.com/OpenVR-Advanced-Settings/OpenVR-AdvancedSettings/blob/522ba46ac6bcff8e82907715f7f0af7abbbe1e7b/build_scripts/win/common.py#L70-L78 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | relaxNGNewMemParserCtxt | (buffer, size) | return relaxNgParserCtxt(_obj=ret) | Create an XML RelaxNGs parse context for that memory buffer
expected to contain an XML RelaxNGs file. | Create an XML RelaxNGs parse context for that memory buffer
expected to contain an XML RelaxNGs file. | [
"Create",
"an",
"XML",
"RelaxNGs",
"parse",
"context",
"for",
"that",
"memory",
"buffer",
"expected",
"to",
"contain",
"an",
"XML",
"RelaxNGs",
"file",
"."
] | def relaxNGNewMemParserCtxt(buffer, size):
"""Create an XML RelaxNGs parse context for that memory buffer
expected to contain an XML RelaxNGs file. """
ret = libxml2mod.xmlRelaxNGNewMemParserCtxt(buffer, size)
if ret is None:raise parserError('xmlRelaxNGNewMemParserCtxt() failed')
return relaxNgParserCtxt(_obj=ret) | [
"def",
"relaxNGNewMemParserCtxt",
"(",
"buffer",
",",
"size",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRelaxNGNewMemParserCtxt",
"(",
"buffer",
",",
"size",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlRelaxNGNewMemParserCtxt() failed... | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L1587-L1592 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/adidas_utils/solvers/symmetric/qre_anneal_noaux.py | python | Solver.mirror_descent_step | (self, params, grads, t) | return new_params | Entropic mirror descent on exploitability.
Args:
params: tuple of variables to be updated (dist, anneal_steps)
grads: tuple of variable gradients (grad_dist, grad_anneal_steps)
t: int, solver iteration
Returns:
new_params: tuple of update params (new_dist, new_anneal_steps) | Entropic mirror descent on exploitability. | [
"Entropic",
"mirror",
"descent",
"on",
"exploitability",
"."
] | def mirror_descent_step(self, params, grads, t):
"""Entropic mirror descent on exploitability.
Args:
params: tuple of variables to be updated (dist, anneal_steps)
grads: tuple of variable gradients (grad_dist, grad_anneal_steps)
t: int, solver iteration
Returns:
new_params: tuple of update params (new_dist, new_anneal_steps)
"""
del t
lr_dist = self.lrs[0]
new_params = [np.log(np.clip(params[0], 0, np.inf)) - lr_dist * grads[0]]
new_params = mirror_project(*new_params)
new_params += (params[1] + grads[1],)
return new_params | [
"def",
"mirror_descent_step",
"(",
"self",
",",
"params",
",",
"grads",
",",
"t",
")",
":",
"del",
"t",
"lr_dist",
"=",
"self",
".",
"lrs",
"[",
"0",
"]",
"new_params",
"=",
"[",
"np",
".",
"log",
"(",
"np",
".",
"clip",
"(",
"params",
"[",
"0",
... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/symmetric/qre_anneal_noaux.py#L318-L333 | |
plaidml/plaidml | f3c6681db21460e5fdc11ae651d6d7b6c27f8262 | plaidml/edsl/__init__.py | python | TensorDim.__add__ | (self, other) | return TensorDim(_dim_op(lib.PLAIDML_INT_OP_ADD, self, other)) | Performs an addition between a TensorDim and another operand in a
polynomial expression.
Example:
>>> N, M = TensorDims(2)
>>> A = Placeholder(DType.FLOAT32, [3, 3])
>>> A.bind_dims(N, M)
>>> R = Contraction().outShape(N + 5) | Performs an addition between a TensorDim and another operand in a
polynomial expression. | [
"Performs",
"an",
"addition",
"between",
"a",
"TensorDim",
"and",
"another",
"operand",
"in",
"a",
"polynomial",
"expression",
"."
] | def __add__(self, other):
"""Performs an addition between a TensorDim and another operand in a
polynomial expression.
Example:
>>> N, M = TensorDims(2)
>>> A = Placeholder(DType.FLOAT32, [3, 3])
>>> A.bind_dims(N, M)
>>> R = Contraction().outShape(N + 5)
"""
return TensorDim(_dim_op(lib.PLAIDML_INT_OP_ADD, self, other)) | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"return",
"TensorDim",
"(",
"_dim_op",
"(",
"lib",
".",
"PLAIDML_INT_OP_ADD",
",",
"self",
",",
"other",
")",
")"
] | https://github.com/plaidml/plaidml/blob/f3c6681db21460e5fdc11ae651d6d7b6c27f8262/plaidml/edsl/__init__.py#L55-L65 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/genpy/src/genpy/rostime.py | python | Duration.__add__ | (self, other) | Add duration to this duration, or this duration to a time, creating a new time value as a result.
:param other: duration or time, ``Duration``/``Time``
:returns: :class:`Duration` if other is a :class:`Duration`
instance, :class:`Time` if other is a :class:`Time` | Add duration to this duration, or this duration to a time, creating a new time value as a result.
:param other: duration or time, ``Duration``/``Time``
:returns: :class:`Duration` if other is a :class:`Duration`
instance, :class:`Time` if other is a :class:`Time` | [
"Add",
"duration",
"to",
"this",
"duration",
"or",
"this",
"duration",
"to",
"a",
"time",
"creating",
"a",
"new",
"time",
"value",
"as",
"a",
"result",
".",
":",
"param",
"other",
":",
"duration",
"or",
"time",
"Duration",
"/",
"Time",
":",
"returns",
... | def __add__(self, other):
"""
Add duration to this duration, or this duration to a time, creating a new time value as a result.
:param other: duration or time, ``Duration``/``Time``
:returns: :class:`Duration` if other is a :class:`Duration`
instance, :class:`Time` if other is a :class:`Time`
"""
if isinstance(other, Time):
return other.__add__(self)
elif isinstance(other, Duration):
return Duration(self.secs+other.secs, self.nsecs+other.nsecs)
else:
return NotImplemented | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Time",
")",
":",
"return",
"other",
".",
"__add__",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"other",
",",
"Duration",
")",
":",
"return",
"Duration",
... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/genpy/src/genpy/rostime.py#L354-L366 | ||
pybox2d/pybox2d | 09643321fd363f0850087d1bde8af3f4afd82163 | library/Box2D/examples/framework.py | python | FrameworkBase.PreSolve | (self, contact, old_manifold) | This is a critical function when there are many contacts in the world.
It should be optimized as much as possible. | This is a critical function when there are many contacts in the world.
It should be optimized as much as possible. | [
"This",
"is",
"a",
"critical",
"function",
"when",
"there",
"are",
"many",
"contacts",
"in",
"the",
"world",
".",
"It",
"should",
"be",
"optimized",
"as",
"much",
"as",
"possible",
"."
] | def PreSolve(self, contact, old_manifold):
"""
This is a critical function when there are many contacts in the world.
It should be optimized as much as possible.
"""
if not (self.settings.drawContactPoints or
self.settings.drawContactNormals or self.using_contacts):
return
elif len(self.points) > self.settings.maxContactPoints:
return
manifold = contact.manifold
if manifold.pointCount == 0:
return
state1, state2 = b2GetPointStates(old_manifold, manifold)
if not state2:
return
worldManifold = contact.worldManifold
# TODO: find some way to speed all of this up.
self.points.extend([dict(fixtureA=contact.fixtureA,
fixtureB=contact.fixtureB,
position=worldManifold.points[i],
normal=worldManifold.normal.copy(),
state=state2[i],
)
for i, point in enumerate(state2)]) | [
"def",
"PreSolve",
"(",
"self",
",",
"contact",
",",
"old_manifold",
")",
":",
"if",
"not",
"(",
"self",
".",
"settings",
".",
"drawContactPoints",
"or",
"self",
".",
"settings",
".",
"drawContactNormals",
"or",
"self",
".",
"using_contacts",
")",
":",
"re... | https://github.com/pybox2d/pybox2d/blob/09643321fd363f0850087d1bde8af3f4afd82163/library/Box2D/examples/framework.py#L439-L467 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/sessions.py | python | Session.delete | (self, url, **kwargs) | return self.request('DELETE', url, **kwargs) | r"""Sends a DELETE request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response | r"""Sends a DELETE request. Returns :class:`Response` object. | [
"r",
"Sends",
"a",
"DELETE",
"request",
".",
"Returns",
":",
"class",
":",
"Response",
"object",
"."
] | def delete(self, url, **kwargs):
r"""Sends a DELETE request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('DELETE', url, **kwargs) | [
"def",
"delete",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"'DELETE'",
",",
"url",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/sessions.py#L607-L615 | |
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/generator/ninja.py | python | Target.PreActionInput | (self, flavor) | return self.FinalOutput() or self.preaction_stamp | Return the path, if any, that should be used as a dependency of
any dependent action step. | Return the path, if any, that should be used as a dependency of
any dependent action step. | [
"Return",
"the",
"path",
"if",
"any",
"that",
"should",
"be",
"used",
"as",
"a",
"dependency",
"of",
"any",
"dependent",
"action",
"step",
"."
] | def PreActionInput(self, flavor):
"""Return the path, if any, that should be used as a dependency of
any dependent action step."""
if self.UsesToc(flavor):
return self.FinalOutput() + '.TOC'
return self.FinalOutput() or self.preaction_stamp | [
"def",
"PreActionInput",
"(",
"self",
",",
"flavor",
")",
":",
"if",
"self",
".",
"UsesToc",
"(",
"flavor",
")",
":",
"return",
"self",
".",
"FinalOutput",
"(",
")",
"+",
"'.TOC'",
"return",
"self",
".",
"FinalOutput",
"(",
")",
"or",
"self",
".",
"p... | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/ninja.py#L163-L168 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/ContactStructuralMechanicsApplication/python_scripts/search_base_process.py | python | SearchBaseProcess._get_if_is_interval | (self) | Returns if we are inside the time interval or not
Keyword arguments:
self -- It signifies an instance of a class. | Returns if we are inside the time interval or not | [
"Returns",
"if",
"we",
"are",
"inside",
"the",
"time",
"interval",
"or",
"not"
] | def _get_if_is_interval(self):
""" Returns if we are inside the time interval or not
Keyword arguments:
self -- It signifies an instance of a class.
"""
current_time = self.main_model_part.ProcessInfo[KM.TIME]
if self.interval.IsInInterval(current_time):
return True
else:
return False | [
"def",
"_get_if_is_interval",
"(",
"self",
")",
":",
"current_time",
"=",
"self",
".",
"main_model_part",
".",
"ProcessInfo",
"[",
"KM",
".",
"TIME",
"]",
"if",
"self",
".",
"interval",
".",
"IsInInterval",
"(",
"current_time",
")",
":",
"return",
"True",
... | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ContactStructuralMechanicsApplication/python_scripts/search_base_process.py#L586-L596 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | EventLoopActivator.__init__ | (self, *args, **kwargs) | __init__(self, EventLoopBase evtLoop) -> EventLoopActivator | __init__(self, EventLoopBase evtLoop) -> EventLoopActivator | [
"__init__",
"(",
"self",
"EventLoopBase",
"evtLoop",
")",
"-",
">",
"EventLoopActivator"
] | def __init__(self, *args, **kwargs):
"""__init__(self, EventLoopBase evtLoop) -> EventLoopActivator"""
_core_.EventLoopActivator_swiginit(self,_core_.new_EventLoopActivator(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_core_",
".",
"EventLoopActivator_swiginit",
"(",
"self",
",",
"_core_",
".",
"new_EventLoopActivator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L8878-L8880 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | GDALRasterizeOptions.__init__ | (self, *args) | r"""__init__(GDALRasterizeOptions self, char ** options) -> GDALRasterizeOptions | r"""__init__(GDALRasterizeOptions self, char ** options) -> GDALRasterizeOptions | [
"r",
"__init__",
"(",
"GDALRasterizeOptions",
"self",
"char",
"**",
"options",
")",
"-",
">",
"GDALRasterizeOptions"
] | def __init__(self, *args):
r"""__init__(GDALRasterizeOptions self, char ** options) -> GDALRasterizeOptions"""
_gdal.GDALRasterizeOptions_swiginit(self, _gdal.new_GDALRasterizeOptions(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_gdal",
".",
"GDALRasterizeOptions_swiginit",
"(",
"self",
",",
"_gdal",
".",
"new_GDALRasterizeOptions",
"(",
"*",
"args",
")",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L4317-L4319 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py | python | TarInfo._apply_pax_info | (self, pax_headers, encoding, errors) | Replace fields with supplemental information from a previous
pax extended or global header. | Replace fields with supplemental information from a previous
pax extended or global header. | [
"Replace",
"fields",
"with",
"supplemental",
"information",
"from",
"a",
"previous",
"pax",
"extended",
"or",
"global",
"header",
"."
] | def _apply_pax_info(self, pax_headers, encoding, errors):
"""Replace fields with supplemental information from a previous
pax extended or global header.
"""
for keyword, value in pax_headers.items():
if keyword == "GNU.sparse.name":
setattr(self, "path", value)
elif keyword == "GNU.sparse.size":
setattr(self, "size", int(value))
elif keyword == "GNU.sparse.realsize":
setattr(self, "size", int(value))
elif keyword in PAX_FIELDS:
if keyword in PAX_NUMBER_FIELDS:
try:
value = PAX_NUMBER_FIELDS[keyword](value)
except ValueError:
value = 0
if keyword == "path":
value = value.rstrip("/")
setattr(self, keyword, value)
self.pax_headers = pax_headers.copy() | [
"def",
"_apply_pax_info",
"(",
"self",
",",
"pax_headers",
",",
"encoding",
",",
"errors",
")",
":",
"for",
"keyword",
",",
"value",
"in",
"pax_headers",
".",
"items",
"(",
")",
":",
"if",
"keyword",
"==",
"\"GNU.sparse.name\"",
":",
"setattr",
"(",
"self"... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py#L1518-L1539 | ||
PlatformLab/Arachne | e67391471007174dd4002dc2c160628e19c284e8 | scripts/cpplint.py | python | ProcessFile | (filename, vlevel, extra_check_functions=[]) | Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Does google-lint on a single file. | [
"Does",
"google",
"-",
"lint",
"on",
"a",
"single",
"file",
"."
] | def ProcessFile(filename, vlevel, extra_check_functions=[]):
"""Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
_SetVerboseLevel(vlevel)
_BackupFilters()
if not ProcessConfigOverrides(filename):
_RestoreFilters()
return
lf_lines = []
crlf_lines = []
try:
# Support the UNIX convention of using "-" for stdin. Note that
# we are not opening the file with universal newline support
# (which codecs doesn't support anyway), so the resulting lines do
# contain trailing '\r' characters if we are reading a file that
# has CRLF endings.
# If after the split a trailing '\r' is present, it is removed
# below.
if filename == '-':
lines = codecs.StreamReaderWriter(sys.stdin,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace').read().split('\n')
else:
lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
# Remove trailing '\r'.
# The -1 accounts for the extra trailing blank line we get from split()
for linenum in range(len(lines) - 1):
if lines[linenum].endswith('\r'):
lines[linenum] = lines[linenum].rstrip('\r')
crlf_lines.append(linenum + 1)
else:
lf_lines.append(linenum + 1)
except IOError:
sys.stderr.write(
"Skipping input '%s': Can't open for reading\n" % filename)
_RestoreFilters()
return
# Note, if no dot is found, this will give the entire filename as the ext.
file_extension = filename[filename.rfind('.') + 1:]
# When reading from stdin, the extension is unknown, so no cpplint tests
# should rely on the extension.
if filename != '-' and file_extension not in _valid_extensions:
sys.stderr.write('Ignoring %s; not a valid file name '
'(%s)\n' % (filename, ', '.join(_valid_extensions)))
else:
ProcessFileData(filename, file_extension, lines, Error,
extra_check_functions)
# If end-of-line sequences are a mix of LF and CR-LF, issue
# warnings on the lines with CR.
#
# Don't issue any warnings if all lines are uniformly LF or CR-LF,
# since critique can handle these just fine, and the style guide
# doesn't dictate a particular end of line sequence.
#
# We can't depend on os.linesep to determine what the desired
# end-of-line sequence should be, since that will return the
# server-side end-of-line sequence.
if lf_lines and crlf_lines:
# Warn on every line with CR. An alternative approach might be to
# check whether the file is mostly CRLF or just LF, and warn on the
# minority, we bias toward LF here since most tools prefer LF.
for linenum in crlf_lines:
Error(filename, linenum, 'whitespace/newline', 1,
'Unexpected \\r (^M) found; better to use only \\n')
sys.stderr.write('Done processing %s\n' % filename)
_RestoreFilters() | [
"def",
"ProcessFile",
"(",
"filename",
",",
"vlevel",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"_SetVerboseLevel",
"(",
"vlevel",
")",
"_BackupFilters",
"(",
")",
"if",
"not",
"ProcessConfigOverrides",
"(",
"filename",
")",
":",
"_RestoreFilters",
... | https://github.com/PlatformLab/Arachne/blob/e67391471007174dd4002dc2c160628e19c284e8/scripts/cpplint.py#L5729-L5814 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/serial/urlhandler/protocol_loop.py | python | Serial._update_break_state | (self) | \
Set break: Controls TXD. When active, to transmitting is
possible. | \
Set break: Controls TXD. When active, to transmitting is
possible. | [
"\\",
"Set",
"break",
":",
"Controls",
"TXD",
".",
"When",
"active",
"to",
"transmitting",
"is",
"possible",
"."
] | def _update_break_state(self):
"""\
Set break: Controls TXD. When active, to transmitting is
possible.
"""
if self.logger:
self.logger.info('_update_break_state({!r})'.format(self._break_state)) | [
"def",
"_update_break_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'_update_break_state({!r})'",
".",
"format",
"(",
"self",
".",
"_break_state",
")",
")"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/urlhandler/protocol_loop.py#L228-L234 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/codegen.py | python | CodeLibrary.get_function_cfg | (self, name) | return _CFG(dot) | Get control-flow graph of the LLVM function | Get control-flow graph of the LLVM function | [
"Get",
"control",
"-",
"flow",
"graph",
"of",
"the",
"LLVM",
"function"
] | def get_function_cfg(self, name):
"""
Get control-flow graph of the LLVM function
"""
self._sentry_cache_disable_inspection()
fn = self.get_function(name)
dot = ll.get_function_cfg(fn)
return _CFG(dot) | [
"def",
"get_function_cfg",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_sentry_cache_disable_inspection",
"(",
")",
"fn",
"=",
"self",
".",
"get_function",
"(",
"name",
")",
"dot",
"=",
"ll",
".",
"get_function_cfg",
"(",
"fn",
")",
"return",
"_CFG",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/codegen.py#L320-L327 | |
PaddlePaddle/PaddleOCR | b756bf5f8c90142e0d89d3db0163965c686b6ffe | ppocr/postprocess/east_postprocess.py | python | EASTPostProcess.detect | (self,
score_map,
geo_map,
score_thresh=0.8,
cover_thresh=0.1,
nms_thresh=0.2) | return boxes | restore text boxes from score map and geo map | restore text boxes from score map and geo map | [
"restore",
"text",
"boxes",
"from",
"score",
"map",
"and",
"geo",
"map"
] | def detect(self,
score_map,
geo_map,
score_thresh=0.8,
cover_thresh=0.1,
nms_thresh=0.2):
"""
restore text boxes from score map and geo map
"""
score_map = score_map[0]
geo_map = np.swapaxes(geo_map, 1, 0)
geo_map = np.swapaxes(geo_map, 1, 2)
# filter the score map
xy_text = np.argwhere(score_map > score_thresh)
if len(xy_text) == 0:
return []
# sort the text boxes via the y axis
xy_text = xy_text[np.argsort(xy_text[:, 0])]
#restore quad proposals
text_box_restored = self.restore_rectangle_quad(
xy_text[:, ::-1] * 4, geo_map[xy_text[:, 0], xy_text[:, 1], :])
boxes = np.zeros((text_box_restored.shape[0], 9), dtype=np.float32)
boxes[:, :8] = text_box_restored.reshape((-1, 8))
boxes[:, 8] = score_map[xy_text[:, 0], xy_text[:, 1]]
try:
import lanms
boxes = lanms.merge_quadrangle_n9(boxes, nms_thresh)
except:
print(
'you should install lanms by pip3 install lanms-nova to speed up nms_locality'
)
boxes = nms_locality(boxes.astype(np.float64), nms_thresh)
if boxes.shape[0] == 0:
return []
# Here we filter some low score boxes by the average score map,
# this is different from the orginal paper.
for i, box in enumerate(boxes):
mask = np.zeros_like(score_map, dtype=np.uint8)
cv2.fillPoly(mask, box[:8].reshape(
(-1, 4, 2)).astype(np.int32) // 4, 1)
boxes[i, 8] = cv2.mean(score_map, mask)[0]
boxes = boxes[boxes[:, 8] > cover_thresh]
return boxes | [
"def",
"detect",
"(",
"self",
",",
"score_map",
",",
"geo_map",
",",
"score_thresh",
"=",
"0.8",
",",
"cover_thresh",
"=",
"0.1",
",",
"nms_thresh",
"=",
"0.2",
")",
":",
"score_map",
"=",
"score_map",
"[",
"0",
"]",
"geo_map",
"=",
"np",
".",
"swapaxe... | https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppocr/postprocess/east_postprocess.py#L54-L98 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/radosgw_admin_rest.py | python | rgwadmin_rest | (connection, cmd, params=None, headers=None, raw=False) | perform a rest command | perform a rest command | [
"perform",
"a",
"rest",
"command"
] | def rgwadmin_rest(connection, cmd, params=None, headers=None, raw=False):
"""
perform a rest command
"""
log.info('radosgw-admin-rest: %s %s' % (cmd, params))
put_cmds = ['create', 'link', 'add']
post_cmds = ['unlink', 'modify']
delete_cmds = ['trim', 'rm', 'process']
get_cmds = ['check', 'info', 'show', 'list', '']
bucket_sub_resources = ['object', 'policy', 'index']
user_sub_resources = ['subuser', 'key', 'caps']
zone_sub_resources = ['pool', 'log', 'garbage']
def get_cmd_method_and_handler(cmd):
"""
Get the rest command and handler from information in cmd and
from the imported requests object.
"""
if cmd[1] in put_cmds:
return 'PUT', requests.put
elif cmd[1] in delete_cmds:
return 'DELETE', requests.delete
elif cmd[1] in post_cmds:
return 'POST', requests.post
elif cmd[1] in get_cmds:
return 'GET', requests.get
def get_resource(cmd):
"""
Get the name of the resource from information in cmd.
"""
if cmd[0] == 'bucket' or cmd[0] in bucket_sub_resources:
if cmd[0] == 'bucket':
return 'bucket', ''
else:
return 'bucket', cmd[0]
elif cmd[0] == 'user' or cmd[0] in user_sub_resources:
if cmd[0] == 'user':
return 'user', ''
else:
return 'user', cmd[0]
elif cmd[0] == 'usage':
return 'usage', ''
elif cmd[0] == 'info':
return 'info', ''
elif cmd[0] == 'ratelimit':
return 'ratelimit', ''
elif cmd[0] == 'zone' or cmd[0] in zone_sub_resources:
if cmd[0] == 'zone':
return 'zone', ''
else:
return 'zone', cmd[0]
def build_admin_request(conn, method, resource = '', headers=None, data='',
query_args=None, params=None):
"""
Build an administative request adapted from the build_request()
method of boto.connection
"""
path = conn.calling_format.build_path_base('admin', resource)
auth_path = conn.calling_format.build_auth_path('admin', resource)
host = conn.calling_format.build_host(conn.server_name(), 'admin')
if query_args:
path += '?' + query_args
boto.log.debug('path=%s' % path)
auth_path += '?' + query_args
boto.log.debug('auth_path=%s' % auth_path)
return AWSAuthConnection.build_base_http_request(conn, method, path,
auth_path, params, headers, data, host)
method, handler = get_cmd_method_and_handler(cmd)
resource, query_args = get_resource(cmd)
request = build_admin_request(connection, method, resource,
query_args=query_args, headers=headers)
url = '{protocol}://{host}{path}'.format(protocol=request.protocol,
host=request.host, path=request.path)
request.authorize(connection=connection)
result = handler(url, params=params, headers=request.headers)
if raw:
log.info(' text result: %s' % result.text)
return result.status_code, result.text
elif len(result.content) == 0:
# many admin requests return no body, so json() throws a JSONDecodeError
log.info(' empty result')
return result.status_code, None
else:
log.info(' json result: %s' % result.json())
return result.status_code, result.json() | [
"def",
"rgwadmin_rest",
"(",
"connection",
",",
"cmd",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"log",
".",
"info",
"(",
"'radosgw-admin-rest: %s %s'",
"%",
"(",
"cmd",
",",
"params",
")",
")",
"put_c... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/radosgw_admin_rest.py#L26-L118 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/idl/idl/parser.py | python | _parse_field | (ctxt, name, node) | return field | Parse a field in a struct/command in the IDL file. | Parse a field in a struct/command in the IDL file. | [
"Parse",
"a",
"field",
"in",
"a",
"struct",
"/",
"command",
"in",
"the",
"IDL",
"file",
"."
] | def _parse_field(ctxt, name, node):
# type: (errors.ParserContext, str, Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode]) -> syntax.Field
"""Parse a field in a struct/command in the IDL file."""
field = syntax.Field(ctxt.file_name, node.start_mark.line, node.start_mark.column)
field.name = name
_generic_parser(ctxt, node, "field", field, {
"description": _RuleDesc('scalar'),
"cpp_name": _RuleDesc('scalar'),
"type": _RuleDesc('scalar', _RuleDesc.REQUIRED),
"ignore": _RuleDesc("bool_scalar"),
"optional": _RuleDesc("bool_scalar"),
"default": _RuleDesc('scalar'),
"supports_doc_sequence": _RuleDesc("bool_scalar"),
})
return field | [
"def",
"_parse_field",
"(",
"ctxt",
",",
"name",
",",
"node",
")",
":",
"# type: (errors.ParserContext, str, Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode]) -> syntax.Field",
"field",
"=",
"syntax",
".",
"Field",
"(",
"ctxt",
".",
"file_name",
"... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/parser.py#L186-L202 | |
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | samples/python/efficientnet/image_batcher.py | python | ImageBatcher.__init__ | (self, input, shape, dtype, max_num_images=None, exact_batches=False, preprocessor="V2") | :param input: The input directory to read images from.
:param shape: The tensor shape of the batch to prepare, either in NCHW or NHWC format.
:param dtype: The (numpy) datatype to cast the batched data to.
:param max_num_images: The maximum number of images to read from the directory.
:param exact_batches: This defines how to handle a number of images that is not an exact multiple of the batch
size. If false, it will pad the final batch with zeros to reach the batch size. If true, it will *remove* the
last few images in excess of a batch size multiple, to guarantee batches are exact (useful for calibration).
:param preprocessor: Set the preprocessor to use, V1 or V2, depending on which network is being used. | :param input: The input directory to read images from.
:param shape: The tensor shape of the batch to prepare, either in NCHW or NHWC format.
:param dtype: The (numpy) datatype to cast the batched data to.
:param max_num_images: The maximum number of images to read from the directory.
:param exact_batches: This defines how to handle a number of images that is not an exact multiple of the batch
size. If false, it will pad the final batch with zeros to reach the batch size. If true, it will *remove* the
last few images in excess of a batch size multiple, to guarantee batches are exact (useful for calibration).
:param preprocessor: Set the preprocessor to use, V1 or V2, depending on which network is being used. | [
":",
"param",
"input",
":",
"The",
"input",
"directory",
"to",
"read",
"images",
"from",
".",
":",
"param",
"shape",
":",
"The",
"tensor",
"shape",
"of",
"the",
"batch",
"to",
"prepare",
"either",
"in",
"NCHW",
"or",
"NHWC",
"format",
".",
":",
"param"... | def __init__(self, input, shape, dtype, max_num_images=None, exact_batches=False, preprocessor="V2"):
"""
:param input: The input directory to read images from.
:param shape: The tensor shape of the batch to prepare, either in NCHW or NHWC format.
:param dtype: The (numpy) datatype to cast the batched data to.
:param max_num_images: The maximum number of images to read from the directory.
:param exact_batches: This defines how to handle a number of images that is not an exact multiple of the batch
size. If false, it will pad the final batch with zeros to reach the batch size. If true, it will *remove* the
last few images in excess of a batch size multiple, to guarantee batches are exact (useful for calibration).
:param preprocessor: Set the preprocessor to use, V1 or V2, depending on which network is being used.
"""
# Find images in the given input path
input = os.path.realpath(input)
self.images = []
extensions = [".jpg", ".jpeg", ".png", ".bmp"]
def is_image(path):
return os.path.isfile(path) and os.path.splitext(path)[1].lower() in extensions
if os.path.isdir(input):
self.images = [os.path.join(input, f) for f in os.listdir(input) if is_image(os.path.join(input, f))]
self.images.sort()
elif os.path.isfile(input):
if is_image(input):
self.images.append(input)
self.num_images = len(self.images)
if self.num_images < 1:
print("No valid {} images found in {}".format("/".join(extensions), input))
sys.exit(1)
# Handle Tensor Shape
self.dtype = dtype
self.shape = shape
assert len(self.shape) == 4
self.batch_size = shape[0]
assert self.batch_size > 0
self.format = None
self.width = -1
self.height = -1
if self.shape[1] == 3:
self.format = "NCHW"
self.height = self.shape[2]
self.width = self.shape[3]
elif self.shape[3] == 3:
self.format = "NHWC"
self.height = self.shape[1]
self.width = self.shape[2]
assert all([self.format, self.width > 0, self.height > 0])
# Adapt the number of images as needed
if max_num_images and 0 < max_num_images < len(self.images):
self.num_images = max_num_images
if exact_batches:
self.num_images = self.batch_size * (self.num_images // self.batch_size)
if self.num_images < 1:
print("Not enough images to create batches")
sys.exit(1)
self.images = self.images[0:self.num_images]
# Subdivide the list of images into batches
self.num_batches = 1 + int((self.num_images - 1) / self.batch_size)
self.batches = []
for i in range(self.num_batches):
start = i * self.batch_size
end = min(start + self.batch_size, self.num_images)
self.batches.append(self.images[start:end])
# Indices
self.image_index = 0
self.batch_index = 0
self.preprocessor = preprocessor | [
"def",
"__init__",
"(",
"self",
",",
"input",
",",
"shape",
",",
"dtype",
",",
"max_num_images",
"=",
"None",
",",
"exact_batches",
"=",
"False",
",",
"preprocessor",
"=",
"\"V2\"",
")",
":",
"# Find images in the given input path",
"input",
"=",
"os",
".",
... | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/efficientnet/image_batcher.py#L29-L101 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py | python | config_dict | (filename) | return cfgdict | Convert content of config-file into dictionary. | Convert content of config-file into dictionary. | [
"Convert",
"content",
"of",
"config",
"-",
"file",
"into",
"dictionary",
"."
] | def config_dict(filename):
"""Convert content of config-file into dictionary."""
f = open(filename, "r")
cfglines = f.readlines()
f.close()
cfgdict = {}
for line in cfglines:
line = line.strip()
if not line or line.startswith("#"):
continue
try:
key, value = line.split("=")
except:
print "Bad line in config-file %s:\n%s" % (filename,line)
continue
key = key.strip()
value = value.strip()
if value in ["True", "False", "None", "''", '""']:
value = eval(value)
else:
try:
if "." in value:
value = float(value)
else:
value = int(value)
except:
pass # value need not be converted
cfgdict[key] = value
return cfgdict | [
"def",
"config_dict",
"(",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"cfglines",
"=",
"f",
".",
"readlines",
"(",
")",
"f",
".",
"close",
"(",
")",
"cfgdict",
"=",
"{",
"}",
"for",
"line",
"in",
"cfglines",
":",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py#L183-L211 | |
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/common/system/zipfileset_mock.py | python | make_factory | (ziphashes) | return maker | ZipFileSet factory routine that looks up zipfiles in a dict;
each zipfile should also be a dict of member names -> contents. | ZipFileSet factory routine that looks up zipfiles in a dict;
each zipfile should also be a dict of member names -> contents. | [
"ZipFileSet",
"factory",
"routine",
"that",
"looks",
"up",
"zipfiles",
"in",
"a",
"dict",
";",
"each",
"zipfile",
"should",
"also",
"be",
"a",
"dict",
"of",
"member",
"names",
"-",
">",
"contents",
"."
] | def make_factory(ziphashes):
"""ZipFileSet factory routine that looks up zipfiles in a dict;
each zipfile should also be a dict of member names -> contents."""
class MockZipFileSet(object):
def __init__(self, url):
self._url = url
self._ziphash = ziphashes[url]
def namelist(self):
return self._ziphash.keys()
def read(self, member):
return self._ziphash[member]
def close(self):
pass
def maker(url):
# We return None because there's no tempfile to delete.
return (None, MockZipFileSet(url))
return maker | [
"def",
"make_factory",
"(",
"ziphashes",
")",
":",
"class",
"MockZipFileSet",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"url",
")",
":",
"self",
".",
"_url",
"=",
"url",
"self",
".",
"_ziphash",
"=",
"ziphashes",
"[",
"url",
"]",
... | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/common/system/zipfileset_mock.py#L30-L51 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | ListCtrl.GetItemState | (*args, **kwargs) | return _controls_.ListCtrl_GetItemState(*args, **kwargs) | GetItemState(self, long item, long stateMask) -> int | GetItemState(self, long item, long stateMask) -> int | [
"GetItemState",
"(",
"self",
"long",
"item",
"long",
"stateMask",
")",
"-",
">",
"int"
] | def GetItemState(*args, **kwargs):
"""GetItemState(self, long item, long stateMask) -> int"""
return _controls_.ListCtrl_GetItemState(*args, **kwargs) | [
"def",
"GetItemState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_GetItemState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4531-L4533 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | Dialog.IsModal | (*args, **kwargs) | return _windows_.Dialog_IsModal(*args, **kwargs) | IsModal(self) -> bool | IsModal(self) -> bool | [
"IsModal",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsModal(*args, **kwargs):
"""IsModal(self) -> bool"""
return _windows_.Dialog_IsModal(*args, **kwargs) | [
"def",
"IsModal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"Dialog_IsModal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L799-L801 | |
facebookresearch/habitat-sim | 63b6c71d9ca8adaefb140b198196f5d0ca1f1e34 | src_python/habitat_sim/utils/compare_profiles.py | python | create_arg_parser | () | return parser | For compare_profiles.py script. Includes print formatting options. | For compare_profiles.py script. Includes print formatting options. | [
"For",
"compare_profiles",
".",
"py",
"script",
".",
"Includes",
"print",
"formatting",
"options",
"."
] | def create_arg_parser() -> ArgumentParser:
"""For compare_profiles.py script. Includes print formatting options."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--sort-by",
default="inclusive",
choices=["inclusive", "exclusive"],
help="Sort rows by inclusive or exclusive time.",
)
parser.add_argument(
"--source-time-units-per-second",
type=int,
default=1000 * 1000 * 1000,
metavar="N",
help="If your source NVTX event times were recorded as nanoseconds, use 1000000000 here.",
)
parser.add_argument(
"--relative",
action="store_true",
default=False,
help="When comparing 2+ profiles, display times as relative to the first profile's times.",
)
parser.add_argument(
"--hide-counts",
action="store_true",
default=False,
help="Hide event counts.",
)
return parser | [
"def",
"create_arg_parser",
"(",
")",
"->",
"ArgumentParser",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"--sort-by\"",
",",
"default",
"=",
"\"inclusive\"",
",",
"choices",
"=",
"[",
"\"inclusive\"",
... | https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/src_python/habitat_sim/utils/compare_profiles.py#L286-L314 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/sessions.py | python | Session.get | (self, url, **kwargs) | return self.request('GET', url, **kwargs) | Sends a GET request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes. | Sends a GET request. Returns :class:`Response` object. | [
"Sends",
"a",
"GET",
"request",
".",
"Returns",
":",
"class",
":",
"Response",
"object",
"."
] | def get(self, url, **kwargs):
"""Sends a GET request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
"""
kwargs.setdefault('allow_redirects', True)
return self.request('GET', url, **kwargs) | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'allow_redirects'",
",",
"True",
")",
"return",
"self",
".",
"request",
"(",
"'GET'",
",",
"url",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/sessions.py#L469-L477 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/_pyio.py | python | BufferedReader.read | (self, n=None) | Read n bytes.
Returns exactly n bytes of data unless the underlying raw IO
stream reaches EOF or if the call would block in non-blocking
mode. If n is negative, read until EOF or until read() would
block. | Read n bytes. | [
"Read",
"n",
"bytes",
"."
] | def read(self, n=None):
"""Read n bytes.
Returns exactly n bytes of data unless the underlying raw IO
stream reaches EOF or if the call would block in non-blocking
mode. If n is negative, read until EOF or until read() would
block.
"""
if n is not None and n < -1:
raise ValueError("invalid number of bytes to read")
with self._read_lock:
return self._read_unlocked(n) | [
"def",
"read",
"(",
"self",
",",
"n",
"=",
"None",
")",
":",
"if",
"n",
"is",
"not",
"None",
"and",
"n",
"<",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"\"invalid number of bytes to read\"",
")",
"with",
"self",
".",
"_read_lock",
":",
"return",
"self... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/_pyio.py#L931-L942 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pdb.py | python | Pdb.do_disable | (self, arg) | disable bpnumber [bpnumber ...]
Disables the breakpoints given as a space separated list of
breakpoint numbers. Disabling a breakpoint means it cannot
cause the program to stop execution, but unlike clearing a
breakpoint, it remains in the list of breakpoints and can be
(re-)enabled. | disable bpnumber [bpnumber ...]
Disables the breakpoints given as a space separated list of
breakpoint numbers. Disabling a breakpoint means it cannot
cause the program to stop execution, but unlike clearing a
breakpoint, it remains in the list of breakpoints and can be
(re-)enabled. | [
"disable",
"bpnumber",
"[",
"bpnumber",
"...",
"]",
"Disables",
"the",
"breakpoints",
"given",
"as",
"a",
"space",
"separated",
"list",
"of",
"breakpoint",
"numbers",
".",
"Disabling",
"a",
"breakpoint",
"means",
"it",
"cannot",
"cause",
"the",
"program",
"to"... | def do_disable(self, arg):
"""disable bpnumber [bpnumber ...]
Disables the breakpoints given as a space separated list of
breakpoint numbers. Disabling a breakpoint means it cannot
cause the program to stop execution, but unlike clearing a
breakpoint, it remains in the list of breakpoints and can be
(re-)enabled.
"""
args = arg.split()
for i in args:
try:
bp = self.get_bpbynumber(i)
except ValueError as err:
self.error(err)
else:
bp.disable()
self.message('Disabled %s' % bp) | [
"def",
"do_disable",
"(",
"self",
",",
"arg",
")",
":",
"args",
"=",
"arg",
".",
"split",
"(",
")",
"for",
"i",
"in",
"args",
":",
"try",
":",
"bp",
"=",
"self",
".",
"get_bpbynumber",
"(",
"i",
")",
"except",
"ValueError",
"as",
"err",
":",
"sel... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pdb.py#L779-L795 | ||
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | _NestingState.InnermostClass | (self) | return None | Get class info on the top of the stack.
Returns:
A _ClassInfo object if we are inside a class, or None otherwise. | Get class info on the top of the stack. | [
"Get",
"class",
"info",
"on",
"the",
"top",
"of",
"the",
"stack",
"."
] | def InnermostClass(self):
"""Get class info on the top of the stack.
Returns:
A _ClassInfo object if we are inside a class, or None otherwise.
"""
for i in range(len(self.stack), 0, -1):
classinfo = self.stack[i - 1]
if isinstance(classinfo, _ClassInfo):
return classinfo
return None | [
"def",
"InnermostClass",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"stack",
")",
",",
"0",
",",
"-",
"1",
")",
":",
"classinfo",
"=",
"self",
".",
"stack",
"[",
"i",
"-",
"1",
"]",
"if",
"isinstance",
"(",
... | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1720-L1730 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/fast_gelu_grad.py | python | _fast_gelu_grad_tbe | () | return | FastGeLUGrad TBE register | FastGeLUGrad TBE register | [
"FastGeLUGrad",
"TBE",
"register"
] | def _fast_gelu_grad_tbe():
"""FastGeLUGrad TBE register"""
return | [
"def",
"_fast_gelu_grad_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/fast_gelu_grad.py#L39-L41 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/ciconfig/tags.py | python | TagsConfig.remove_tag | (self, test_kind, test_pattern, tag) | return False | Remove a tag. Return True if the tag was removed or False if the tag was not present. | Remove a tag. Return True if the tag was removed or False if the tag was not present. | [
"Remove",
"a",
"tag",
".",
"Return",
"True",
"if",
"the",
"tag",
"was",
"removed",
"or",
"False",
"if",
"the",
"tag",
"was",
"not",
"present",
"."
] | def remove_tag(self, test_kind, test_pattern, tag):
"""Remove a tag. Return True if the tag was removed or False if the tag was not present."""
patterns = self._conf.get(test_kind)
if not patterns or test_pattern not in patterns:
return False
tags = patterns.get(test_pattern)
if tags and tag in tags:
tags[:] = (value for value in tags if value != tag)
# Remove the pattern if there are no associated tags.
if not tags:
del patterns[test_pattern]
return True
return False | [
"def",
"remove_tag",
"(",
"self",
",",
"test_kind",
",",
"test_pattern",
",",
"tag",
")",
":",
"patterns",
"=",
"self",
".",
"_conf",
".",
"get",
"(",
"test_kind",
")",
"if",
"not",
"patterns",
"or",
"test_pattern",
"not",
"in",
"patterns",
":",
"return"... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/ciconfig/tags.py#L79-L91 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/core.py | python | as_axis | (axis_data) | return axis | Convert an AxisLike object into an Axis.
Args:
axis_data: Axis object or tuple (axis_name, axis_value) describing an axis.
Returns:
Axis object. This may be the original object if axis_data is an Axis. | Convert an AxisLike object into an Axis. | [
"Convert",
"an",
"AxisLike",
"object",
"into",
"an",
"Axis",
"."
] | def as_axis(axis_data):
"""Convert an AxisLike object into an Axis.
Args:
axis_data: Axis object or tuple (axis_name, axis_value) describing an axis.
Returns:
Axis object. This may be the original object if axis_data is an Axis.
"""
if isinstance(axis_data, Axis):
axis = axis_data
else:
axis = Axis(*axis_data)
return axis | [
"def",
"as_axis",
"(",
"axis_data",
")",
":",
"if",
"isinstance",
"(",
"axis_data",
",",
"Axis",
")",
":",
"axis",
"=",
"axis_data",
"else",
":",
"axis",
"=",
"Axis",
"(",
"*",
"axis_data",
")",
"return",
"axis"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/core.py#L183-L196 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextObject.FindPosition | (*args, **kwargs) | return _richtext.RichTextObject_FindPosition(*args, **kwargs) | FindPosition(self, DC dc, RichTextDrawingContext context, long index,
Point OUTPUT, int OUTPUT, bool forceLineStart) -> bool | FindPosition(self, DC dc, RichTextDrawingContext context, long index,
Point OUTPUT, int OUTPUT, bool forceLineStart) -> bool | [
"FindPosition",
"(",
"self",
"DC",
"dc",
"RichTextDrawingContext",
"context",
"long",
"index",
"Point",
"OUTPUT",
"int",
"OUTPUT",
"bool",
"forceLineStart",
")",
"-",
">",
"bool"
] | def FindPosition(*args, **kwargs):
"""
FindPosition(self, DC dc, RichTextDrawingContext context, long index,
Point OUTPUT, int OUTPUT, bool forceLineStart) -> bool
"""
return _richtext.RichTextObject_FindPosition(*args, **kwargs) | [
"def",
"FindPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextObject_FindPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L1187-L1192 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | tools/linter/clang_format_all.py | python | run_clang_format_on_file | (
filename: str,
semaphore: asyncio.Semaphore,
verbose: bool = False,
) | Run clang-format on the provided file. | Run clang-format on the provided file. | [
"Run",
"clang",
"-",
"format",
"on",
"the",
"provided",
"file",
"."
] | async def run_clang_format_on_file(
filename: str,
semaphore: asyncio.Semaphore,
verbose: bool = False,
) -> None:
"""
Run clang-format on the provided file.
"""
# -style=file picks up the closest .clang-format, -i formats the files inplace.
cmd = "{} -style=file -i {}".format(CLANG_FORMAT_PATH, filename)
async with semaphore:
proc = await asyncio.create_subprocess_shell(cmd)
_ = await proc.wait()
if verbose:
print("Formatted {}".format(filename)) | [
"async",
"def",
"run_clang_format_on_file",
"(",
"filename",
":",
"str",
",",
"semaphore",
":",
"asyncio",
".",
"Semaphore",
",",
"verbose",
":",
"bool",
"=",
"False",
",",
")",
"->",
"None",
":",
"# -style=file picks up the closest .clang-format, -i formats the files... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/tools/linter/clang_format_all.py#L47-L61 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/index.py | python | get_requirement_from_url | (url) | return package_to_requirement(egg_info) | Get a requirement from the URL, if possible. This looks for #egg
in the URL | Get a requirement from the URL, if possible. This looks for #egg
in the URL | [
"Get",
"a",
"requirement",
"from",
"the",
"URL",
"if",
"possible",
".",
"This",
"looks",
"for",
"#egg",
"in",
"the",
"URL"
] | def get_requirement_from_url(url):
"""Get a requirement from the URL, if possible. This looks for #egg
in the URL"""
link = Link(url)
egg_info = link.egg_fragment
if not egg_info:
egg_info = splitext(link.filename)[0]
return package_to_requirement(egg_info) | [
"def",
"get_requirement_from_url",
"(",
"url",
")",
":",
"link",
"=",
"Link",
"(",
"url",
")",
"egg_info",
"=",
"link",
".",
"egg_fragment",
"if",
"not",
"egg_info",
":",
"egg_info",
"=",
"splitext",
"(",
"link",
".",
"filename",
")",
"[",
"0",
"]",
"r... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/index.py#L977-L984 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | AcceleratorEntry.IsOk | (*args, **kwargs) | return _core_.AcceleratorEntry_IsOk(*args, **kwargs) | IsOk(self) -> bool | IsOk(self) -> bool | [
"IsOk",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsOk(*args, **kwargs):
"""IsOk(self) -> bool"""
return _core_.AcceleratorEntry_IsOk(*args, **kwargs) | [
"def",
"IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"AcceleratorEntry_IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L8956-L8958 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/hypertreelist.py | python | TreeListMainWindow.IsVirtual | (self) | return self.HasAGWFlag(TR_VIRTUAL) | Returns ``True`` if :class:`TreeListMainWindow` has the ``TR_VIRTUAL`` flag set. | Returns ``True`` if :class:`TreeListMainWindow` has the ``TR_VIRTUAL`` flag set. | [
"Returns",
"True",
"if",
":",
"class",
":",
"TreeListMainWindow",
"has",
"the",
"TR_VIRTUAL",
"flag",
"set",
"."
] | def IsVirtual(self):
""" Returns ``True`` if :class:`TreeListMainWindow` has the ``TR_VIRTUAL`` flag set. """
return self.HasAGWFlag(TR_VIRTUAL) | [
"def",
"IsVirtual",
"(",
"self",
")",
":",
"return",
"self",
".",
"HasAGWFlag",
"(",
"TR_VIRTUAL",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L2123-L2126 | |
wesnoth/wesnoth | 6ccac5a5e8ff75303c9190c0da60580925cb32c0 | data/tools/wesnoth/wmltools3.py | python | resolve_unit_cfg | (namespace, utype, resource=None) | return loc | Get the location of a specified unit in a specified scope. | Get the location of a specified unit in a specified scope. | [
"Get",
"the",
"location",
"of",
"a",
"specified",
"unit",
"in",
"a",
"specified",
"scope",
"."
] | def resolve_unit_cfg(namespace, utype, resource=None):
"Get the location of a specified unit in a specified scope."
if resource:
resource = os.path.join(utype, resource)
else:
resource = utype
loc = namespace_directory(namespace) + "units/" + resource
if not loc.endswith(".cfg"):
loc += ".cfg"
return loc | [
"def",
"resolve_unit_cfg",
"(",
"namespace",
",",
"utype",
",",
"resource",
"=",
"None",
")",
":",
"if",
"resource",
":",
"resource",
"=",
"os",
".",
"path",
".",
"join",
"(",
"utype",
",",
"resource",
")",
"else",
":",
"resource",
"=",
"utype",
"loc",... | https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmltools3.py#L1100-L1109 | |
Alexhuszagh/rust-lexical | 01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0 | lexical-benchmark/etc/plot.py | python | format_time | (time) | return f'{strip_zero(str(round(time, 3)))} s' | Format time to be a nice value. | Format time to be a nice value. | [
"Format",
"time",
"to",
"be",
"a",
"nice",
"value",
"."
] | def format_time(time):
'''Format time to be a nice value.'''
def strip_zero(value):
if value.endswith('.0'):
return value[:-2]
return value
if time < 1000:
return f'{strip_zero(str(round(time, 3)))} ns'
time /= 1000
if time < 1000:
return f'{strip_zero(str(round(time, 3)))} us'
time /= 1000
if time < 1000:
return f'{strip_zero(str(round(time, 3)))} ms'
time /= 1000
return f'{strip_zero(str(round(time, 3)))} s' | [
"def",
"format_time",
"(",
"time",
")",
":",
"def",
"strip_zero",
"(",
"value",
")",
":",
"if",
"value",
".",
"endswith",
"(",
"'.0'",
")",
":",
"return",
"value",
"[",
":",
"-",
"2",
"]",
"return",
"value",
"if",
"time",
"<",
"1000",
":",
"return"... | https://github.com/Alexhuszagh/rust-lexical/blob/01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0/lexical-benchmark/etc/plot.py#L55-L72 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py | python | MaskedArray.__init__ | (self, data, dtype=None, copy=True, order=False,
mask=nomask, fill_value=None) | array(data, dtype=None, copy=True, order=False, mask=nomask, fill_value=None)
If data already a numeric array, its dtype becomes the default value of dtype. | array(data, dtype=None, copy=True, order=False, mask=nomask, fill_value=None)
If data already a numeric array, its dtype becomes the default value of dtype. | [
"array",
"(",
"data",
"dtype",
"=",
"None",
"copy",
"=",
"True",
"order",
"=",
"False",
"mask",
"=",
"nomask",
"fill_value",
"=",
"None",
")",
"If",
"data",
"already",
"a",
"numeric",
"array",
"its",
"dtype",
"becomes",
"the",
"default",
"value",
"of",
... | def __init__(self, data, dtype=None, copy=True, order=False,
mask=nomask, fill_value=None):
"""array(data, dtype=None, copy=True, order=False, mask=nomask, fill_value=None)
If data already a numeric array, its dtype becomes the default value of dtype.
"""
if dtype is None:
tc = None
else:
tc = numeric.dtype(dtype)
need_data_copied = copy
if isinstance(data, MaskedArray):
c = data.data
if tc is None:
tc = c.dtype
elif tc != c.dtype:
need_data_copied = True
if mask is nomask:
mask = data.mask
elif mask is not nomask: #attempting to change the mask
need_data_copied = True
elif isinstance(data, ndarray):
c = data
if tc is None:
tc = c.dtype
elif tc != c.dtype:
need_data_copied = True
else:
need_data_copied = False #because I'll do it now
c = numeric.array(data, dtype=tc, copy=True, order=order)
tc = c.dtype
if need_data_copied:
if tc == c.dtype:
self._data = numeric.array(c, dtype=tc, copy=True, order=order)
else:
self._data = c.astype(tc)
else:
self._data = c
if mask is nomask:
self._mask = nomask
self._shared_mask = 0
else:
self._mask = make_mask (mask)
if self._mask is nomask:
self._shared_mask = 0
else:
self._shared_mask = (self._mask is mask)
nm = size(self._mask)
nd = size(self._data)
if nm != nd:
if nm == 1:
self._mask = fromnumeric.resize(self._mask, self._data.shape)
self._shared_mask = 0
elif nd == 1:
self._data = fromnumeric.resize(self._data, self._mask.shape)
self._data.shape = self._mask.shape
else:
raise MAError("Mask and data not compatible.")
elif nm == 1 and shape(self._mask) != shape(self._data):
self.unshare_mask()
self._mask.shape = self._data.shape
self.set_fill_value(fill_value) | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"dtype",
"=",
"None",
",",
"copy",
"=",
"True",
",",
"order",
"=",
"False",
",",
"mask",
"=",
"nomask",
",",
"fill_value",
"=",
"None",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"tc",
"=",
"None... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L554-L618 | ||
chatopera/clause | dee31153d5ffdef33deedb6bff03e7806c296968 | var/assets/clients/gen-py/clause/Serving.py | python | Iface.getCustomDict | (self, request) | Parameters:
- request | Parameters:
- request | [
"Parameters",
":",
"-",
"request"
] | def getCustomDict(self, request):
"""
Parameters:
- request
"""
pass | [
"def",
"getCustomDict",
"(",
"self",
",",
"request",
")",
":",
"pass"
] | https://github.com/chatopera/clause/blob/dee31153d5ffdef33deedb6bff03e7806c296968/var/assets/clients/gen-py/clause/Serving.py#L52-L58 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py | python | WriteAutoRegenerationRule | (params, root_makefile, makefile_name,
build_files) | Write the target to regenerate the Makefile. | Write the target to regenerate the Makefile. | [
"Write",
"the",
"target",
"to",
"regenerate",
"the",
"Makefile",
"."
] | def WriteAutoRegenerationRule(params, root_makefile, makefile_name,
build_files):
"""Write the target to regenerate the Makefile."""
options = params['options']
build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir)
for filename in params['build_files_arg']]
gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'],
options.toplevel_dir)
if not gyp_binary.startswith(os.sep):
gyp_binary = os.path.join('.', gyp_binary)
root_makefile.write(
"quiet_cmd_regen_makefile = ACTION Regenerating $@\n"
"cmd_regen_makefile = cd $(srcdir); %(cmd)s\n"
"%(makefile_name)s: %(deps)s\n"
"\t$(call do_cmd,regen_makefile)\n\n" % {
'makefile_name': makefile_name,
'deps': ' '.join(map(Sourceify, build_files)),
'cmd': gyp.common.EncodePOSIXShellList(
[gyp_binary, '-fmake'] +
gyp.RegenerateFlags(options) +
build_files_args)}) | [
"def",
"WriteAutoRegenerationRule",
"(",
"params",
",",
"root_makefile",
",",
"makefile_name",
",",
"build_files",
")",
":",
"options",
"=",
"params",
"[",
"'options'",
"]",
"build_files_args",
"=",
"[",
"gyp",
".",
"common",
".",
"RelativePath",
"(",
"filename"... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py#L1984-L2006 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/compatibility/ngraph/opset1/ops.py | python | interpolate | (
image: Node, output_shape: NodeInput, attrs: dict, name: Optional[str] = None
) | return _get_node_factory_opset1().create("Interpolate", [image, as_node(output_shape)], attrs) | Perform interpolation of independent slices in input tensor.
:param image: The node providing input tensor with data for interpolation.
:param output_shape: 1D tensor describing output shape for spatial axes.
:param attrs: The dictionary containing key, value pairs for attributes.
:param name: Optional name for the output node.
:return: Node representing interpolation operation.
Available attributes are:
* axes Specify spatial dimension indices where interpolation is applied.
Type: List of non-negative integer numbers.
Required: yes.
* mode Specifies type of interpolation.
Range of values: one of {nearest, linear, cubic, area}
Type: string
Required: yes
* align_corners A flag that specifies whether to align corners or not. True means the
alignment is applied, False means the alignment isn't applied.
Range of values: True or False. Default: True.
Required: no
* antialias A flag that specifies whether to perform anti-aliasing.
Range of values: False - do not perform anti-aliasing
True - perform anti-aliasing
Default value: False
Required: no
* pads_begin Specify the number of pixels to add to the beginning of the image being
interpolated. A scalar that specifies padding for each spatial dimension.
Range of values: list of non-negative integer numbers. Default value: 0
Required: no
* pads_end Specify the number of pixels to add to the beginning of the image being
interpolated. A scalar that specifies padding for each spatial dimension.
Range of values: list of non-negative integer numbers. Default value: 0
Required: no
Example of attribute dictionary:
.. code-block:: python
# just required ones
attrs = {
'axes': [2, 3],
'mode': 'cubic',
}
attrs = {
'axes': [2, 3],
'mode': 'cubic',
'antialias': True,
'pads_begin': [2, 2, 2],
}
Optional attributes which are absent from dictionary will be set with corresponding default. | Perform interpolation of independent slices in input tensor. | [
"Perform",
"interpolation",
"of",
"independent",
"slices",
"in",
"input",
"tensor",
"."
] | def interpolate(
image: Node, output_shape: NodeInput, attrs: dict, name: Optional[str] = None
) -> Node:
"""Perform interpolation of independent slices in input tensor.
:param image: The node providing input tensor with data for interpolation.
:param output_shape: 1D tensor describing output shape for spatial axes.
:param attrs: The dictionary containing key, value pairs for attributes.
:param name: Optional name for the output node.
:return: Node representing interpolation operation.
Available attributes are:
* axes Specify spatial dimension indices where interpolation is applied.
Type: List of non-negative integer numbers.
Required: yes.
* mode Specifies type of interpolation.
Range of values: one of {nearest, linear, cubic, area}
Type: string
Required: yes
* align_corners A flag that specifies whether to align corners or not. True means the
alignment is applied, False means the alignment isn't applied.
Range of values: True or False. Default: True.
Required: no
* antialias A flag that specifies whether to perform anti-aliasing.
Range of values: False - do not perform anti-aliasing
True - perform anti-aliasing
Default value: False
Required: no
* pads_begin Specify the number of pixels to add to the beginning of the image being
interpolated. A scalar that specifies padding for each spatial dimension.
Range of values: list of non-negative integer numbers. Default value: 0
Required: no
* pads_end Specify the number of pixels to add to the beginning of the image being
interpolated. A scalar that specifies padding for each spatial dimension.
Range of values: list of non-negative integer numbers. Default value: 0
Required: no
Example of attribute dictionary:
.. code-block:: python
# just required ones
attrs = {
'axes': [2, 3],
'mode': 'cubic',
}
attrs = {
'axes': [2, 3],
'mode': 'cubic',
'antialias': True,
'pads_begin': [2, 2, 2],
}
Optional attributes which are absent from dictionary will be set with corresponding default.
"""
requirements = [
("axes", True, np.integer, is_non_negative_value),
("mode", True, np.str_, None),
("align_corners", False, np.bool_, None),
("antialias", False, np.bool_, None),
("pads_begin", False, np.integer, is_non_negative_value),
("pads_end", False, np.integer, is_non_negative_value),
]
check_valid_attributes("Interpolate", attrs, requirements)
return _get_node_factory_opset1().create("Interpolate", [image, as_node(output_shape)], attrs) | [
"def",
"interpolate",
"(",
"image",
":",
"Node",
",",
"output_shape",
":",
"NodeInput",
",",
"attrs",
":",
"dict",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Node",
":",
"requirements",
"=",
"[",
"(",
"\"axes\"",
",",
"Tr... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/opset1/ops.py#L1173-L1246 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/eager/execution_callbacks.py | python | inf_callback | (op_type,
op_name,
attrs,
inputs,
outputs,
action=_DEFAULT_CALLBACK_ACTION) | A specialization of `inf_nan_callback` that checks for `inf`s only. | A specialization of `inf_nan_callback` that checks for `inf`s only. | [
"A",
"specialization",
"of",
"inf_nan_callback",
"that",
"checks",
"for",
"inf",
"s",
"only",
"."
] | def inf_callback(op_type,
op_name,
attrs,
inputs,
outputs,
action=_DEFAULT_CALLBACK_ACTION):
"""A specialization of `inf_nan_callback` that checks for `inf`s only."""
inf_nan_callback(
op_type, op_name, attrs, inputs, outputs, check_inf=True, check_nan=False,
action=action) | [
"def",
"inf_callback",
"(",
"op_type",
",",
"op_name",
",",
"attrs",
",",
"inputs",
",",
"outputs",
",",
"action",
"=",
"_DEFAULT_CALLBACK_ACTION",
")",
":",
"inf_nan_callback",
"(",
"op_type",
",",
"op_name",
",",
"attrs",
",",
"inputs",
",",
"outputs",
","... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/eager/execution_callbacks.py#L188-L197 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/stateless_random_ops.py | python | stateless_random_uniform | (shape,
seed,
minval=0,
maxval=None,
dtype=dtypes.float32,
name=None,
alg="auto_select") | Outputs deterministic pseudorandom values from a uniform distribution.
This is a stateless version of `tf.random.uniform`: if run twice with the
same seeds and shapes, it will produce the same pseudorandom numbers. The
output is consistent across multiple runs on the same hardware (and between
CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU
hardware.
The generated values follow a uniform distribution in the range
`[minval, maxval)`. The lower bound `minval` is included in the range, while
the upper bound `maxval` is excluded.
For floats, the default range is `[0, 1)`. For ints, at least `maxval` must
be specified explicitly.
In the integer case, the random integers are slightly biased unless
`maxval - minval` is an exact power of two. The bias is small for values of
`maxval - minval` significantly smaller than the range of the output (either
`2**32` or `2**64`).
For full-range (i.e. inclusive of both max and min) random integers, pass
`minval=None` and `maxval=None` with an integer `dtype`. For an integer dtype
either both `minval` and `maxval` must be `None` or neither may be `None`. For
example:
```python
ints = tf.random.stateless_uniform(
[10], seed=(2, 3), minval=None, maxval=None, dtype=tf.int32)
```
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
seed: A shape [2] Tensor, the seed to the random number generator. Must have
dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
minval: A Tensor or Python value of type `dtype`, broadcastable with
`shape` (for integer types, broadcasting is not supported, so it needs to
be a scalar). The lower bound on the range of random values to
generate. Pass `None` for full-range integers. Defaults to 0.
maxval: A Tensor or Python value of type `dtype`, broadcastable with
`shape` (for integer types, broadcasting is not supported, so it needs to
be a scalar). The upper bound on the range of random values to generate.
Defaults to 1 if `dtype` is floating point. Pass `None` for full-range
integers.
dtype: The type of the output: `float16`, `bfloat16`, `float32`, `float64`,
`int32`, or `int64`. For unbounded uniform ints (`minval`, `maxval` both
`None`), `uint32` and `uint64` may be used. Defaults to `float32`.
name: A name for the operation (optional).
alg: The RNG algorithm used to generate the random numbers. Valid
choices are `"philox"` for [the Philox
algorithm](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf),
`"threefry"` for [the ThreeFry
algorithm](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf),
and `"auto_select"` (default) for the system to automatically
select an algorithm based the device type. Values of
`tf.random.Algorithm` can also be used. Note that with
`"auto_select"`, the outputs of this function may change when
it is running on a different device.
Returns:
A tensor of the specified shape filled with random uniform values.
Raises:
ValueError: If `dtype` is integral and only one of `minval` or `maxval` is
specified. | Outputs deterministic pseudorandom values from a uniform distribution. | [
"Outputs",
"deterministic",
"pseudorandom",
"values",
"from",
"a",
"uniform",
"distribution",
"."
] | def stateless_random_uniform(shape,
seed,
minval=0,
maxval=None,
dtype=dtypes.float32,
name=None,
alg="auto_select"):
"""Outputs deterministic pseudorandom values from a uniform distribution.
This is a stateless version of `tf.random.uniform`: if run twice with the
same seeds and shapes, it will produce the same pseudorandom numbers. The
output is consistent across multiple runs on the same hardware (and between
CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU
hardware.
The generated values follow a uniform distribution in the range
`[minval, maxval)`. The lower bound `minval` is included in the range, while
the upper bound `maxval` is excluded.
For floats, the default range is `[0, 1)`. For ints, at least `maxval` must
be specified explicitly.
In the integer case, the random integers are slightly biased unless
`maxval - minval` is an exact power of two. The bias is small for values of
`maxval - minval` significantly smaller than the range of the output (either
`2**32` or `2**64`).
For full-range (i.e. inclusive of both max and min) random integers, pass
`minval=None` and `maxval=None` with an integer `dtype`. For an integer dtype
either both `minval` and `maxval` must be `None` or neither may be `None`. For
example:
```python
ints = tf.random.stateless_uniform(
[10], seed=(2, 3), minval=None, maxval=None, dtype=tf.int32)
```
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
seed: A shape [2] Tensor, the seed to the random number generator. Must have
dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
minval: A Tensor or Python value of type `dtype`, broadcastable with
`shape` (for integer types, broadcasting is not supported, so it needs to
be a scalar). The lower bound on the range of random values to
generate. Pass `None` for full-range integers. Defaults to 0.
maxval: A Tensor or Python value of type `dtype`, broadcastable with
`shape` (for integer types, broadcasting is not supported, so it needs to
be a scalar). The upper bound on the range of random values to generate.
Defaults to 1 if `dtype` is floating point. Pass `None` for full-range
integers.
dtype: The type of the output: `float16`, `bfloat16`, `float32`, `float64`,
`int32`, or `int64`. For unbounded uniform ints (`minval`, `maxval` both
`None`), `uint32` and `uint64` may be used. Defaults to `float32`.
name: A name for the operation (optional).
alg: The RNG algorithm used to generate the random numbers. Valid
choices are `"philox"` for [the Philox
algorithm](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf),
`"threefry"` for [the ThreeFry
algorithm](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf),
and `"auto_select"` (default) for the system to automatically
select an algorithm based the device type. Values of
`tf.random.Algorithm` can also be used. Note that with
`"auto_select"`, the outputs of this function may change when
it is running on a different device.
Returns:
A tensor of the specified shape filled with random uniform values.
Raises:
ValueError: If `dtype` is integral and only one of `minval` or `maxval` is
specified.
"""
dtype = dtypes.as_dtype(dtype)
accepted_dtypes = (dtypes.float16, dtypes.bfloat16, dtypes.float32,
dtypes.float64, dtypes.int32, dtypes.int64, dtypes.uint32,
dtypes.uint64)
if dtype not in accepted_dtypes:
raise ValueError(
f"Argument `dtype` got invalid value {dtype}. Accepted dtypes are "
f"{accepted_dtypes}.")
if dtype.is_integer:
if (minval is None) != (maxval is None):
raise ValueError(
f"For integer `dtype` argument {dtype}, argument `minval` and "
f"`maxval` must be both None or not None. Got `minval`={minval} and "
f"`maxval`={maxval}.")
if minval is not None and dtype in (dtypes.uint32, dtypes.uint64):
raise ValueError(
f"Argument `dtype` got invalid value {dtype} when argument `minval` "
f"is not None. Please don't use unsigned integers in this case.")
elif maxval is None:
maxval = 1
with ops.name_scope(name, "stateless_random_uniform",
[shape, seed, minval, maxval]) as name:
shape = tensor_util.shape_tensor(shape)
if dtype.is_integer and minval is None:
key, counter, alg = _get_key_counter_alg(seed, alg)
result = (
gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2(
shape, key=key, counter=counter, dtype=dtype, alg=alg, name=name))
else:
minval = ops.convert_to_tensor(minval, dtype=dtype, name="min")
maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max")
if dtype.is_integer:
key, counter, alg = _get_key_counter_alg(seed, alg)
result = gen_stateless_random_ops_v2.stateless_random_uniform_int_v2(
shape,
key=key,
counter=counter,
minval=minval,
maxval=maxval,
alg=alg,
name=name)
else:
key, counter, alg = _get_key_counter_alg(seed, alg)
rnd = gen_stateless_random_ops_v2.stateless_random_uniform_v2(
shape, key=key, counter=counter, dtype=dtype, alg=alg)
result = math_ops.add(rnd * (maxval - minval), minval, name=name)
tensor_util.maybe_set_static_shape(result, shape)
return result | [
"def",
"stateless_random_uniform",
"(",
"shape",
",",
"seed",
",",
"minval",
"=",
"0",
",",
"maxval",
"=",
"None",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"name",
"=",
"None",
",",
"alg",
"=",
"\"auto_select\"",
")",
":",
"dtype",
"=",
"dtype... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/stateless_random_ops.py#L246-L364 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/json_schema_compiler/cpp_type_generator.py | python | CppTypeGenerator.GetChoicesEnumType | (self, prop) | return cpp_util.Classname(prop.name) + 'Type' | Gets the type of the enum for the given model.Property.
e.g VarType | Gets the type of the enum for the given model.Property. | [
"Gets",
"the",
"type",
"of",
"the",
"enum",
"for",
"the",
"given",
"model",
".",
"Property",
"."
] | def GetChoicesEnumType(self, prop):
"""Gets the type of the enum for the given model.Property.
e.g VarType
"""
return cpp_util.Classname(prop.name) + 'Type' | [
"def",
"GetChoicesEnumType",
"(",
"self",
",",
"prop",
")",
":",
"return",
"cpp_util",
".",
"Classname",
"(",
"prop",
".",
"name",
")",
"+",
"'Type'"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/json_schema_compiler/cpp_type_generator.py#L103-L108 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/preprocessing/data.py | python | Binarizer.transform | (self, X, y=None, copy=None) | return binarize(X, threshold=self.threshold, copy=copy) | Binarize each element of X
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data to binarize, element by element.
scipy.sparse matrices should be in CSR format to avoid an
un-necessary copy. | Binarize each element of X | [
"Binarize",
"each",
"element",
"of",
"X"
] | def transform(self, X, y=None, copy=None):
"""Binarize each element of X
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data to binarize, element by element.
scipy.sparse matrices should be in CSR format to avoid an
un-necessary copy.
"""
copy = copy if copy is not None else self.copy
return binarize(X, threshold=self.threshold, copy=copy) | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"copy",
"=",
"None",
")",
":",
"copy",
"=",
"copy",
"if",
"copy",
"is",
"not",
"None",
"else",
"self",
".",
"copy",
"return",
"binarize",
"(",
"X",
",",
"threshold",
"=",
"sel... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/preprocessing/data.py#L1540-L1551 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | FileSystemHandler.GetProtocol | (*args, **kwargs) | return _core_.FileSystemHandler_GetProtocol(*args, **kwargs) | GetProtocol(String location) -> String | GetProtocol(String location) -> String | [
"GetProtocol",
"(",
"String",
"location",
")",
"-",
">",
"String"
] | def GetProtocol(*args, **kwargs):
"""GetProtocol(String location) -> String"""
return _core_.FileSystemHandler_GetProtocol(*args, **kwargs) | [
"def",
"GetProtocol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"FileSystemHandler_GetProtocol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2360-L2362 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/control_flow_ops.py | python | for_loop | (loop_fn, loop_fn_dtypes, iters, parallel_iterations=None) | Runs `loop_fn` `iters` times and stacks the outputs.
Runs `loop_fn` `iters` times, with input values from 0 to `iters - 1`, and
stacks corresponding outputs of the different runs.
Args:
loop_fn: A function that takes an int32 scalar tf.Tensor object representing
the iteration number, and returns a possibly nested structure of tensor
objects. The shape of these outputs should not depend on the input.
loop_fn_dtypes: dtypes for the outputs of loop_fn.
iters: Number of iterations for which to run loop_fn.
parallel_iterations: The number of iterations that can be dispatched in
parallel. This knob can be used to control the total memory usage.
Returns:
Returns a nested structure of stacked output tensor objects with the same
nested structure as the output of `loop_fn`. | Runs `loop_fn` `iters` times and stacks the outputs. | [
"Runs",
"loop_fn",
"iters",
"times",
"and",
"stacks",
"the",
"outputs",
"."
] | def for_loop(loop_fn, loop_fn_dtypes, iters, parallel_iterations=None):
"""Runs `loop_fn` `iters` times and stacks the outputs.
Runs `loop_fn` `iters` times, with input values from 0 to `iters - 1`, and
stacks corresponding outputs of the different runs.
Args:
loop_fn: A function that takes an int32 scalar tf.Tensor object representing
the iteration number, and returns a possibly nested structure of tensor
objects. The shape of these outputs should not depend on the input.
loop_fn_dtypes: dtypes for the outputs of loop_fn.
iters: Number of iterations for which to run loop_fn.
parallel_iterations: The number of iterations that can be dispatched in
parallel. This knob can be used to control the total memory usage.
Returns:
Returns a nested structure of stacked output tensor objects with the same
nested structure as the output of `loop_fn`.
"""
flat_loop_fn_dtypes = nest.flatten(loop_fn_dtypes)
is_none_list = []
def while_body(i, *ta_list):
"""Body of while loop."""
fn_output = nest.flatten(loop_fn(i))
if len(fn_output) != len(flat_loop_fn_dtypes):
raise ValueError(
"Number of expected outputs, %d, does not match the number of "
"actual outputs, %d, from loop_fn" % (len(flat_loop_fn_dtypes),
len(fn_output)))
outputs = []
del is_none_list[:]
is_none_list.extend([x is None for x in fn_output])
for out, ta in zip(fn_output, ta_list):
# TODO(agarwal): support returning Operation objects from loop_fn.
if out is not None:
# out may be a ref tensor, wrap it in identity to get a non-ref tensor.
ta = ta.write(i, array_ops.expand_dims(out, 0))
outputs.append(ta)
return tuple([i + 1] + outputs)
if parallel_iterations is not None:
extra_args = {"parallel_iterations": parallel_iterations}
else:
extra_args = {}
ta_list = control_flow_ops.while_loop(
lambda i, *ta: i < iters,
while_body,
[0] + [tensor_array_ops.TensorArray(dtype.base_dtype, iters)
for dtype in flat_loop_fn_dtypes],
**extra_args)[1:]
# TODO(rachelim): enable this for sparse tensors
output = [None if is_none else ta.concat()
for ta, is_none in zip(ta_list, is_none_list)]
assert len(output) in (0, len(flat_loop_fn_dtypes))
if not output:
# This may happen for the case where iters == 0.
return None
else:
return nest.pack_sequence_as(loop_fn_dtypes, output) | [
"def",
"for_loop",
"(",
"loop_fn",
",",
"loop_fn_dtypes",
",",
"iters",
",",
"parallel_iterations",
"=",
"None",
")",
":",
"flat_loop_fn_dtypes",
"=",
"nest",
".",
"flatten",
"(",
"loop_fn_dtypes",
")",
"is_none_list",
"=",
"[",
"]",
"def",
"while_body",
"(",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/control_flow_ops.py#L44-L107 | ||
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | pylib/utils.py | python | Git._log_pretty | (self, pretty_fmt, branch=None) | return self._do(cmd).strip() | Return information from the latest commit with a specified `pretty` format.
The log from a specified branch may be specified.
See `git log` man page for possible pretty formats. | Return information from the latest commit with a specified `pretty` format. | [
"Return",
"information",
"from",
"the",
"latest",
"commit",
"with",
"a",
"specified",
"pretty",
"format",
"."
] | def _log_pretty(self, pretty_fmt, branch=None):
"""Return information from the latest commit with a specified `pretty` format.
The log from a specified branch may be specified.
See `git log` man page for possible pretty formats.
"""
# Future directions: Rather than just the latest commit, allow the caller
# specify the number of commits. This requires additional parsing of the
# result to return a list, rather than just a single item.
# Additionally, the caller could pass a 'conversion' function which would
# convert the string into a a more useful data-type.
# As this method may be changed in the future, it is marked as a private
# function (for now).
cmd = ['log']
if branch is not None:
cmd.append(branch)
cmd.append('-1')
cmd.append('--pretty=format:{}'.format(pretty_fmt))
return self._do(cmd).strip() | [
"def",
"_log_pretty",
"(",
"self",
",",
"pretty_fmt",
",",
"branch",
"=",
"None",
")",
":",
"# Future directions: Rather than just the latest commit, allow the caller",
"# specify the number of commits. This requires additional parsing of the",
"# result to return a list, rather than jus... | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/pylib/utils.py#L295-L314 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/completer.py | python | protect_filename | (s) | Escape a string to protect certain characters. | Escape a string to protect certain characters. | [
"Escape",
"a",
"string",
"to",
"protect",
"certain",
"characters",
"."
] | def protect_filename(s):
"""Escape a string to protect certain characters."""
if set(s) & set(PROTECTABLES):
if sys.platform == "win32":
return '"' + s + '"'
else:
return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
else:
return s | [
"def",
"protect_filename",
"(",
"s",
")",
":",
"if",
"set",
"(",
"s",
")",
"&",
"set",
"(",
"PROTECTABLES",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"return",
"'\"'",
"+",
"s",
"+",
"'\"'",
"else",
":",
"return",
"\"\"",
".",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/completer.py#L75-L83 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/profiler/parser/integrator.py | python | Integrator._parse_aicore_detail_time | (self) | Parse the parsed AICORE operator time file. | Parse the parsed AICORE operator time file. | [
"Parse",
"the",
"parsed",
"AICORE",
"operator",
"time",
"file",
"."
] | def _parse_aicore_detail_time(self):
"""Parse the parsed AICORE operator time file."""
aicore_detail_file = os.path.join(
self._profiling_dir,
self._file_name_aicore_detail_time.format(self._device_id)
)
aicore_detail_file = validate_and_normalize_path(aicore_detail_file)
if not os.path.isfile(aicore_detail_file):
return
op_detail_file_name = 'aicore_intermediate_' + self._device_id + '_detail.csv'
op_detail_file_path = os.path.join(
self._profiling_dir, op_detail_file_name
)
with open(aicore_detail_file, 'r') as src_file:
row = src_file.readline()
if row.startswith('op_name'):
_ = src_file.readline()
elif row.startswith('====='):
_ = src_file.readline()
_ = src_file.readline()
else:
return
with open(op_detail_file_path, 'w') as detail_file:
csv_writer = csv.writer(detail_file)
csv_writer.writerow(self._header_aicore_detail)
while True:
row = src_file.readline()
if not row:
break
op_infos = row.split()
if op_infos[0] == 'total':
self._total_time = Decimal(op_infos[2])
continue
self._op_time_cache[op_infos[0]] = Decimal(op_infos[1])
csv_writer.writerow([op_infos[0], op_infos[1]]) | [
"def",
"_parse_aicore_detail_time",
"(",
"self",
")",
":",
"aicore_detail_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_profiling_dir",
",",
"self",
".",
"_file_name_aicore_detail_time",
".",
"format",
"(",
"self",
".",
"_device_id",
")",
")"... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/integrator.py#L134-L172 | ||
Tencent/TNN | 7acca99f54c55747b415a4c57677403eebc7b706 | third_party/flatbuffers/python/flatbuffers/flexbuffers.py | python | _LowerBound | (values, value, pred) | return first | Implementation of C++ std::lower_bound() algorithm. | Implementation of C++ std::lower_bound() algorithm. | [
"Implementation",
"of",
"C",
"++",
"std",
"::",
"lower_bound",
"()",
"algorithm",
"."
] | def _LowerBound(values, value, pred):
"""Implementation of C++ std::lower_bound() algorithm."""
first, last = 0, len(values)
count = last - first
while count > 0:
i = first
step = count // 2
i += step
if pred(values[i], value):
i += 1
first = i
count -= step + 1
else:
count = step
return first | [
"def",
"_LowerBound",
"(",
"values",
",",
"value",
",",
"pred",
")",
":",
"first",
",",
"last",
"=",
"0",
",",
"len",
"(",
"values",
")",
"count",
"=",
"last",
"-",
"first",
"while",
"count",
">",
"0",
":",
"i",
"=",
"first",
"step",
"=",
"count"... | https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/python/flatbuffers/flexbuffers.py#L136-L150 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/indexes/range.py | python | RangeIndex._format_attrs | (self) | return attrs | Return a list of tuples of the (attr, formatted_value) | Return a list of tuples of the (attr, formatted_value) | [
"Return",
"a",
"list",
"of",
"tuples",
"of",
"the",
"(",
"attr",
"formatted_value",
")"
] | def _format_attrs(self):
"""
Return a list of tuples of the (attr, formatted_value)
"""
attrs = self._get_data_as_items()
if self.name is not None:
attrs.append(('name', ibase.default_pprint(self.name)))
return attrs | [
"def",
"_format_attrs",
"(",
"self",
")",
":",
"attrs",
"=",
"self",
".",
"_get_data_as_items",
"(",
")",
"if",
"self",
".",
"name",
"is",
"not",
"None",
":",
"attrs",
".",
"append",
"(",
"(",
"'name'",
",",
"ibase",
".",
"default_pprint",
"(",
"self",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/range.py#L198-L205 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | StaticBoxSizer.GetStaticBox | (*args, **kwargs) | return _core_.StaticBoxSizer_GetStaticBox(*args, **kwargs) | GetStaticBox(self) -> StaticBox
Returns the static box associated with this sizer. | GetStaticBox(self) -> StaticBox | [
"GetStaticBox",
"(",
"self",
")",
"-",
">",
"StaticBox"
] | def GetStaticBox(*args, **kwargs):
"""
GetStaticBox(self) -> StaticBox
Returns the static box associated with this sizer.
"""
return _core_.StaticBoxSizer_GetStaticBox(*args, **kwargs) | [
"def",
"GetStaticBox",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"StaticBoxSizer_GetStaticBox",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L15154-L15160 | |
sundyCoder/DEye | f1b35e8ab20f10f669fdbc9a6f54e666f4d4e1da | extra/tensorflow-r1.4/gemmlowp/src/gemmlowp/meta/generators/quantized_mul_kernels_common.py | python | _Generate1xNLoadMultiplyAggregate | (emitter, registers, kernel_n, aggregators,
lhs, rhs, count) | Emit inner loop for 1 row x M cols multiplication. | Emit inner loop for 1 row x M cols multiplication. | [
"Emit",
"inner",
"loop",
"for",
"1",
"row",
"x",
"M",
"cols",
"multiplication",
"."
] | def _Generate1xNLoadMultiplyAggregate(emitter, registers, kernel_n, aggregators,
lhs, rhs, count):
"""Emit inner loop for 1 row x M cols multiplication."""
assert kernel_n in [5, 6, 7, 8]
emitter.EmitNewline()
emitter.EmitComment('General 1xM lanes loop.')
emitter.EmitNumericalLabel(1)
emitter.EmitNewline()
emitter.EmitComment('Subtract counter.')
emitter.EmitSubs(count, count, emitter.ImmediateConstant(8))
emitter.EmitNewline()
leftover = kernel_n - 4
rhs_load = [registers.DoubleRegister() for unused_i in range(4)]
lhs_load = registers.DoubleRegister()
emitter.EmitVLoadAE(8 * 4, 8, rhs_load, rhs, 64)
emitter.EmitVLoadE(8, 8, lhs_load, lhs, 64)
emitter.EmitPldOffset(lhs, emitter.ImmediateConstant(64))
results = [registers.QuadRegister() for unused_i in range(4)]
for i in range(4):
emitter.EmitVMull('u8', results[i], rhs_load[i], lhs_load)
emitter.EmitVLoadAE(8 * leftover, 8, rhs_load, rhs, 64)
emitter.EmitPldOffset(rhs, emitter.ImmediateConstant(128))
for i in range(4):
emitter.EmitVPadal('u16', aggregators[i], results[i])
for i in range(leftover):
emitter.EmitVMull('u8', results[i], rhs_load[i], lhs_load)
for i in range(leftover):
emitter.EmitVPadal('u16', aggregators[i + 4], results[i])
emitter.EmitNewline()
emitter.EmitComment('Loop break.')
emitter.EmitBgtBack(1)
registers.FreeRegisters([lhs_load] + rhs_load + results) | [
"def",
"_Generate1xNLoadMultiplyAggregate",
"(",
"emitter",
",",
"registers",
",",
"kernel_n",
",",
"aggregators",
",",
"lhs",
",",
"rhs",
",",
"count",
")",
":",
"assert",
"kernel_n",
"in",
"[",
"5",
",",
"6",
",",
"7",
",",
"8",
"]",
"emitter",
".",
... | https://github.com/sundyCoder/DEye/blob/f1b35e8ab20f10f669fdbc9a6f54e666f4d4e1da/extra/tensorflow-r1.4/gemmlowp/src/gemmlowp/meta/generators/quantized_mul_kernels_common.py#L449-L492 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/summary/event_accumulator.py | python | _Remap | (x, x0, x1, y0, y1) | return y0 + (x - x0) * float(y1 - y0) / (x1 - x0) | Linearly map from [x0, x1] unto [y0, y1]. | Linearly map from [x0, x1] unto [y0, y1]. | [
"Linearly",
"map",
"from",
"[",
"x0",
"x1",
"]",
"unto",
"[",
"y0",
"y1",
"]",
"."
] | def _Remap(x, x0, x1, y0, y1):
"""Linearly map from [x0, x1] unto [y0, y1]."""
return y0 + (x - x0) * float(y1 - y0) / (x1 - x0) | [
"def",
"_Remap",
"(",
"x",
",",
"x0",
",",
"x1",
",",
"y0",
",",
"y1",
")",
":",
"return",
"y0",
"+",
"(",
"x",
"-",
"x0",
")",
"*",
"float",
"(",
"y1",
"-",
"y0",
")",
"/",
"(",
"x1",
"-",
"x0",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/summary/event_accumulator.py#L661-L663 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings._GetIOSPostbuilds | (self, configname, output_binary) | return postbuilds | Return a shell command to codesign the iOS output binary so it can
be deployed to a device. This should be run as the very last step of the
build. | Return a shell command to codesign the iOS output binary so it can
be deployed to a device. This should be run as the very last step of the
build. | [
"Return",
"a",
"shell",
"command",
"to",
"codesign",
"the",
"iOS",
"output",
"binary",
"so",
"it",
"can",
"be",
"deployed",
"to",
"a",
"device",
".",
"This",
"should",
"be",
"run",
"as",
"the",
"very",
"last",
"step",
"of",
"the",
"build",
"."
] | def _GetIOSPostbuilds(self, configname, output_binary):
"""Return a shell command to codesign the iOS output binary so it can
be deployed to a device. This should be run as the very last step of the
build."""
if not (self.isIOS and
(self.spec['type'] == 'executable' or self._IsXCTest()) or
self.IsIosFramework()):
return []
postbuilds = []
product_name = self.GetFullProductName()
settings = self.xcode_settings[configname]
# Xcode expects XCTests to be copied into the TEST_HOST dir.
if self._IsXCTest():
source = os.path.join("${BUILT_PRODUCTS_DIR}", product_name)
test_host = os.path.dirname(settings.get('TEST_HOST'))
xctest_destination = os.path.join(test_host, 'PlugIns', product_name)
postbuilds.extend(['ditto %s %s' % (source, xctest_destination)])
key = self._GetIOSCodeSignIdentityKey(settings)
if not key:
return postbuilds
# Warn for any unimplemented signing xcode keys.
unimpl = ['OTHER_CODE_SIGN_FLAGS']
unimpl = set(unimpl) & set(self.xcode_settings[configname].keys())
if unimpl:
print('Warning: Some codesign keys not implemented, ignoring: %s' %
', '.join(sorted(unimpl)))
if self._IsXCTest():
# For device xctests, Xcode copies two extra frameworks into $TEST_HOST.
test_host = os.path.dirname(settings.get('TEST_HOST'))
frameworks_dir = os.path.join(test_host, 'Frameworks')
platform_root = self._XcodePlatformPath(configname)
frameworks = \
['Developer/Library/PrivateFrameworks/IDEBundleInjection.framework',
'Developer/Library/Frameworks/XCTest.framework']
for framework in frameworks:
source = os.path.join(platform_root, framework)
destination = os.path.join(frameworks_dir, os.path.basename(framework))
postbuilds.extend(['ditto %s %s' % (source, destination)])
# Then re-sign everything with 'preserve=True'
postbuilds.extend(['%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % (
os.path.join('${TARGET_BUILD_DIR}', 'gyp-mac-tool'), key,
settings.get('CODE_SIGN_ENTITLEMENTS', ''),
settings.get('PROVISIONING_PROFILE', ''), destination, True)
])
plugin_dir = os.path.join(test_host, 'PlugIns')
targets = [os.path.join(plugin_dir, product_name), test_host]
for target in targets:
postbuilds.extend(['%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % (
os.path.join('${TARGET_BUILD_DIR}', 'gyp-mac-tool'), key,
settings.get('CODE_SIGN_ENTITLEMENTS', ''),
settings.get('PROVISIONING_PROFILE', ''), target, True)
])
postbuilds.extend(['%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % (
os.path.join('${TARGET_BUILD_DIR}', 'gyp-mac-tool'), key,
settings.get('CODE_SIGN_ENTITLEMENTS', ''),
settings.get('PROVISIONING_PROFILE', ''),
os.path.join("${BUILT_PRODUCTS_DIR}", product_name), False)
])
return postbuilds | [
"def",
"_GetIOSPostbuilds",
"(",
"self",
",",
"configname",
",",
"output_binary",
")",
":",
"if",
"not",
"(",
"self",
".",
"isIOS",
"and",
"(",
"self",
".",
"spec",
"[",
"'type'",
"]",
"==",
"'executable'",
"or",
"self",
".",
"_IsXCTest",
"(",
")",
")"... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/xcode_emulation.py#L1066-L1131 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | SizerItem.SetRatioWH | (*args, **kwargs) | return _core_.SizerItem_SetRatioWH(*args, **kwargs) | SetRatioWH(self, int width, int height)
Set the ratio item attribute. | SetRatioWH(self, int width, int height) | [
"SetRatioWH",
"(",
"self",
"int",
"width",
"int",
"height",
")"
] | def SetRatioWH(*args, **kwargs):
"""
SetRatioWH(self, int width, int height)
Set the ratio item attribute.
"""
return _core_.SizerItem_SetRatioWH(*args, **kwargs) | [
"def",
"SetRatioWH",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SizerItem_SetRatioWH",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L14117-L14123 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | TextAttrDimension.__eq__ | (*args, **kwargs) | return _richtext.TextAttrDimension___eq__(*args, **kwargs) | __eq__(self, TextAttrDimension dim) -> bool | __eq__(self, TextAttrDimension dim) -> bool | [
"__eq__",
"(",
"self",
"TextAttrDimension",
"dim",
")",
"-",
">",
"bool"
] | def __eq__(*args, **kwargs):
"""__eq__(self, TextAttrDimension dim) -> bool"""
return _richtext.TextAttrDimension___eq__(*args, **kwargs) | [
"def",
"__eq__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"TextAttrDimension___eq__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L144-L146 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/fft/helper.py | python | _FFTCache.put_twiddle_factors | (self, n, factors) | Store twiddle factors for an FFT of length n in the cache.
Putting multiple twiddle factors for a certain n will store it multiple
times.
Parameters
----------
n : int
Data length for the FFT.
factors : ndarray
The actual twiddle values. | Store twiddle factors for an FFT of length n in the cache. | [
"Store",
"twiddle",
"factors",
"for",
"an",
"FFT",
"of",
"length",
"n",
"in",
"the",
"cache",
"."
] | def put_twiddle_factors(self, n, factors):
"""
Store twiddle factors for an FFT of length n in the cache.
Putting multiple twiddle factors for a certain n will store it multiple
times.
Parameters
----------
n : int
Data length for the FFT.
factors : ndarray
The actual twiddle values.
"""
with self._lock:
# Pop + later add to move it to the end for LRU behavior.
# Internally everything is stored in a dictionary whose values are
# lists.
try:
value = self._dict.pop(n)
except KeyError:
value = []
value.append(factors)
self._dict[n] = value
self._prune_cache() | [
"def",
"put_twiddle_factors",
"(",
"self",
",",
"n",
",",
"factors",
")",
":",
"with",
"self",
".",
"_lock",
":",
"# Pop + later add to move it to the end for LRU behavior.",
"# Internally everything is stored in a dictionary whose values are",
"# lists.",
"try",
":",
"value"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/fft/helper.py#L259-L283 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/math_grad.py | python | _LogGrad | (op, grad) | Returns grad * (1/x). | Returns grad * (1/x). | [
"Returns",
"grad",
"*",
"(",
"1",
"/",
"x",
")",
"."
] | def _LogGrad(op, grad):
"""Returns grad * (1/x)."""
x = op.inputs[0]
with ops.control_dependencies([grad.op]):
return grad * math_ops.inv(x) | [
"def",
"_LogGrad",
"(",
"op",
",",
"grad",
")",
":",
"x",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"grad",
".",
"op",
"]",
")",
":",
"return",
"grad",
"*",
"math_ops",
".",
"inv",
"(",
"x",
... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/math_grad.py#L295-L299 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pydoc.py | python | HTMLDoc.docother | (self, object, name=None, mod=None, *ignored) | return lhs + self.repr(object) | Produce HTML documentation for a data object. | Produce HTML documentation for a data object. | [
"Produce",
"HTML",
"documentation",
"for",
"a",
"data",
"object",
"."
] | def docother(self, object, name=None, mod=None, *ignored):
"""Produce HTML documentation for a data object."""
lhs = name and '<strong>%s</strong> = ' % name or ''
return lhs + self.repr(object) | [
"def",
"docother",
"(",
"self",
",",
"object",
",",
"name",
"=",
"None",
",",
"mod",
"=",
"None",
",",
"*",
"ignored",
")",
":",
"lhs",
"=",
"name",
"and",
"'<strong>%s</strong> = '",
"%",
"name",
"or",
"''",
"return",
"lhs",
"+",
"self",
".",
"repr"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pydoc.py#L934-L937 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | clang/bindings/python/clang/cindex.py | python | Cursor.enum_type | (self) | return self._enum_type | Return the integer type of an enum declaration.
Returns a Type corresponding to an integer. If the cursor is not for an
enum, this raises. | Return the integer type of an enum declaration. | [
"Return",
"the",
"integer",
"type",
"of",
"an",
"enum",
"declaration",
"."
] | def enum_type(self):
"""Return the integer type of an enum declaration.
Returns a Type corresponding to an integer. If the cursor is not for an
enum, this raises.
"""
if not hasattr(self, '_enum_type'):
assert self.kind == CursorKind.ENUM_DECL
self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
return self._enum_type | [
"def",
"enum_type",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_enum_type'",
")",
":",
"assert",
"self",
".",
"kind",
"==",
"CursorKind",
".",
"ENUM_DECL",
"self",
".",
"_enum_type",
"=",
"conf",
".",
"lib",
".",
"clang_getEnumDec... | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/bindings/python/clang/cindex.py#L1702-L1712 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/grid.py | python | GridTableBase.GetAttr | (*args, **kwargs) | return _grid.GridTableBase_GetAttr(*args, **kwargs) | GetAttr(self, int row, int col, int kind) -> GridCellAttr | GetAttr(self, int row, int col, int kind) -> GridCellAttr | [
"GetAttr",
"(",
"self",
"int",
"row",
"int",
"col",
"int",
"kind",
")",
"-",
">",
"GridCellAttr"
] | def GetAttr(*args, **kwargs):
"""GetAttr(self, int row, int col, int kind) -> GridCellAttr"""
return _grid.GridTableBase_GetAttr(*args, **kwargs) | [
"def",
"GetAttr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridTableBase_GetAttr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L906-L908 | |
yue/yue | 619d62c191b13c51c01be451dc48917c34a5aefc | building/tools/cpplint.py | python | ExpectingFunctionArgs | (clean_lines, linenum) | return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
(linenum >= 2 and
(Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
clean_lines.elided[linenum - 1]) or
Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
clean_lines.elided[linenum - 2]) or
Search(r'\bstd::m?function\s*\<\s*$',
clean_lines.elided[linenum - 1])))) | Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
of function types. | Checks whether where function type arguments are expected. | [
"Checks",
"whether",
"where",
"function",
"type",
"arguments",
"are",
"expected",
"."
] | def ExpectingFunctionArgs(clean_lines, linenum):
"""Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
of function types.
"""
line = clean_lines.elided[linenum]
return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
(linenum >= 2 and
(Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
clean_lines.elided[linenum - 1]) or
Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
clean_lines.elided[linenum - 2]) or
Search(r'\bstd::m?function\s*\<\s*$',
clean_lines.elided[linenum - 1])))) | [
"def",
"ExpectingFunctionArgs",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"return",
"(",
"Match",
"(",
"r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('",
",",
"line",
")",
"or",
"(",
"linenum",
">=",
... | https://github.com/yue/yue/blob/619d62c191b13c51c01be451dc48917c34a5aefc/building/tools/cpplint.py#L5308-L5327 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/psutil/psutil/__init__.py | python | Process.cmdline | (self) | return self._platform_impl.get_process_cmdline() | The command line process has been called with. | The command line process has been called with. | [
"The",
"command",
"line",
"process",
"has",
"been",
"called",
"with",
"."
] | def cmdline(self):
"""The command line process has been called with."""
return self._platform_impl.get_process_cmdline() | [
"def",
"cmdline",
"(",
"self",
")",
":",
"return",
"self",
".",
"_platform_impl",
".",
"get_process_cmdline",
"(",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/__init__.py#L344-L346 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/mac_tool.py | python | MacTool._GetCFBundleIdentifier | (self) | return info_plist_data['CFBundleIdentifier'] | Extracts CFBundleIdentifier value from Info.plist in the bundle.
Returns:
Value of CFBundleIdentifier in the Info.plist located in the bundle. | Extracts CFBundleIdentifier value from Info.plist in the bundle. | [
"Extracts",
"CFBundleIdentifier",
"value",
"from",
"Info",
".",
"plist",
"in",
"the",
"bundle",
"."
] | def _GetCFBundleIdentifier(self):
"""Extracts CFBundleIdentifier value from Info.plist in the bundle.
Returns:
Value of CFBundleIdentifier in the Info.plist located in the bundle.
"""
info_plist_path = os.path.join(
os.environ['TARGET_BUILD_DIR'],
os.environ['INFOPLIST_PATH'])
info_plist_data = self._LoadPlistMaybeBinary(info_plist_path)
return info_plist_data['CFBundleIdentifier'] | [
"def",
"_GetCFBundleIdentifier",
"(",
"self",
")",
":",
"info_plist_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"'TARGET_BUILD_DIR'",
"]",
",",
"os",
".",
"environ",
"[",
"'INFOPLIST_PATH'",
"]",
")",
"info_plist_data",
"=",
... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/mac_tool.py#L581-L591 | |
ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | LeetCode/python/1071.py | python | Solution.gcdOfStrings | (self, str1, str2) | return "" | :type str1: str
:type str2: str
:rtype: str | :type str1: str
:type str2: str
:rtype: str | [
":",
"type",
"str1",
":",
"str",
":",
"type",
"str2",
":",
"str",
":",
"rtype",
":",
"str"
] | def gcdOfStrings(self, str1, str2):
"""
:type str1: str
:type str2: str
:rtype: str
"""
m, n = len(str1), len(str2)
if m < n:
return self.gcdOfStrings(str2, str1)
for i in range(1, n + 1):
if n % i != 0 or m % (n // i) != 0:
continue
gcd = str2[:n // i]
s = len(gcd)
flag = True
for j in range(m // (n // i)):
if str1[j * s: j * s + s] != gcd:
flag = False
break
if flag:
return gcd
return "" | [
"def",
"gcdOfStrings",
"(",
"self",
",",
"str1",
",",
"str2",
")",
":",
"m",
",",
"n",
"=",
"len",
"(",
"str1",
")",
",",
"len",
"(",
"str2",
")",
"if",
"m",
"<",
"n",
":",
"return",
"self",
".",
"gcdOfStrings",
"(",
"str2",
",",
"str1",
")",
... | https://github.com/ZintrulCre/LeetCode_Archiver/blob/de23e16ead29336b5ee7aa1898a392a5d6463d27/LeetCode/python/1071.py#L2-L23 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/peakprocesshelper.py | python | PeakProcessRecord.get_peak_workspace | (self) | return peak_ws | Get peak workspace related
:return: | Get peak workspace related
:return: | [
"Get",
"peak",
"workspace",
"related",
":",
"return",
":"
] | def get_peak_workspace(self):
"""
Get peak workspace related
:return:
"""
peak_ws = AnalysisDataService.retrieve(self._myPeakWorkspaceName)
assert peak_ws
return peak_ws | [
"def",
"get_peak_workspace",
"(",
"self",
")",
":",
"peak_ws",
"=",
"AnalysisDataService",
".",
"retrieve",
"(",
"self",
".",
"_myPeakWorkspaceName",
")",
"assert",
"peak_ws",
"return",
"peak_ws"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/peakprocesshelper.py#L301-L308 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/docs.py | python | Library._print_formatted_docstring | (self, docstring, f) | Formats the given `docstring` as Markdown and prints it to `f`. | Formats the given `docstring` as Markdown and prints it to `f`. | [
"Formats",
"the",
"given",
"docstring",
"as",
"Markdown",
"and",
"prints",
"it",
"to",
"f",
"."
] | def _print_formatted_docstring(self, docstring, f):
"""Formats the given `docstring` as Markdown and prints it to `f`."""
lines = self._remove_docstring_indent(docstring)
# Output the lines, identifying "Args" and other section blocks.
i = 0
def _at_start_of_section():
"""Returns the header if lines[i] is at start of a docstring section."""
l = lines[i]
match = _section_re.match(l)
if match and i + 1 < len(
lines) and lines[i + 1].startswith(" "):
return match.group(1)
else:
return None
while i < len(lines):
l = lines[i]
section_header = _at_start_of_section()
if section_header:
if i == 0 or lines[i-1]:
print("", file=f)
# Use at least H4 to keep these out of the TOC.
print("##### " + section_header + ":", file=f)
print("", file=f)
i += 1
outputting_list = False
while i < len(lines):
l = lines[i]
# A new section header terminates the section.
if _at_start_of_section():
break
match = _arg_re.match(l)
if match:
if not outputting_list:
# We need to start a list. In Markdown, a blank line needs to
# precede a list.
print("", file=f)
outputting_list = True
suffix = l[len(match.group()):].lstrip()
print("* <b>`" + match.group(1) + "`</b>: " + suffix, file=f)
else:
# For lines that don't start with _arg_re, continue the list if it
# has enough indentation.
outputting_list &= l.startswith(" ")
print(l, file=f)
i += 1
else:
print(l, file=f)
i += 1 | [
"def",
"_print_formatted_docstring",
"(",
"self",
",",
"docstring",
",",
"f",
")",
":",
"lines",
"=",
"self",
".",
"_remove_docstring_indent",
"(",
"docstring",
")",
"# Output the lines, identifying \"Args\" and other section blocks.",
"i",
"=",
"0",
"def",
"_at_start_o... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/docs.py#L355-L406 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/util.py | python | has_leading_dir | (paths) | return True | Returns true if all the paths have the same leading path name
(i.e., everything is in one subdirectory in an archive) | Returns true if all the paths have the same leading path name
(i.e., everything is in one subdirectory in an archive) | [
"Returns",
"true",
"if",
"all",
"the",
"paths",
"have",
"the",
"same",
"leading",
"path",
"name",
"(",
"i",
".",
"e",
".",
"everything",
"is",
"in",
"one",
"subdirectory",
"in",
"an",
"archive",
")"
] | def has_leading_dir(paths):
"""Returns true if all the paths have the same leading path name
(i.e., everything is in one subdirectory in an archive)"""
common_prefix = None
for path in paths:
prefix, rest = split_leading_dir(path)
if not prefix:
return False
elif common_prefix is None:
common_prefix = prefix
elif prefix != common_prefix:
return False
return True | [
"def",
"has_leading_dir",
"(",
"paths",
")",
":",
"common_prefix",
"=",
"None",
"for",
"path",
"in",
"paths",
":",
"prefix",
",",
"rest",
"=",
"split_leading_dir",
"(",
"path",
")",
"if",
"not",
"prefix",
":",
"return",
"False",
"elif",
"common_prefix",
"i... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/util.py#L226-L238 | |
PaddlePaddle/PaddleOCR | b756bf5f8c90142e0d89d3db0163965c686b6ffe | ppstructure/vqa/xfun.py | python | XFUNDataset._read_encoded_inputs_sample | (self, info_str) | return encoded_inputs | parse label info | parse label info | [
"parse",
"label",
"info"
] | def _read_encoded_inputs_sample(self, info_str):
"""
parse label info
"""
# read text info
info_dict = json.loads(info_str)
height = info_dict["height"]
width = info_dict["width"]
words_list = []
bbox_list = []
input_ids_list = []
token_type_ids_list = []
gt_label_list = []
if self.contains_re:
# for re
entities = []
relations = []
id2label = {}
entity_id_to_index_map = {}
empty_entity = set()
for info in info_dict["ocr_info"]:
if self.contains_re:
# for re
if len(info["text"]) == 0:
empty_entity.add(info["id"])
continue
id2label[info["id"]] = info["label"]
relations.extend([tuple(sorted(l)) for l in info["linking"]])
# x1, y1, x2, y2
bbox = info["bbox"]
label = info["label"]
bbox[0] = int(bbox[0] * 1000.0 / width)
bbox[2] = int(bbox[2] * 1000.0 / width)
bbox[1] = int(bbox[1] * 1000.0 / height)
bbox[3] = int(bbox[3] * 1000.0 / height)
text = info["text"]
encode_res = self.tokenizer.encode(
text, pad_to_max_seq_len=False, return_attention_mask=True)
gt_label = []
if not self.add_special_ids:
# TODO: use tok.all_special_ids to remove
encode_res["input_ids"] = encode_res["input_ids"][1:-1]
encode_res["token_type_ids"] = encode_res["token_type_ids"][1:
-1]
encode_res["attention_mask"] = encode_res["attention_mask"][1:
-1]
if label.lower() == "other":
gt_label.extend([0] * len(encode_res["input_ids"]))
else:
gt_label.append(self.label2id_map[("b-" + label).upper()])
gt_label.extend([self.label2id_map[("i-" + label).upper()]] *
(len(encode_res["input_ids"]) - 1))
if self.contains_re:
if gt_label[0] != self.label2id_map["O"]:
entity_id_to_index_map[info["id"]] = len(entities)
entities.append({
"start": len(input_ids_list),
"end":
len(input_ids_list) + len(encode_res["input_ids"]),
"label": label.upper(),
})
input_ids_list.extend(encode_res["input_ids"])
token_type_ids_list.extend(encode_res["token_type_ids"])
bbox_list.extend([bbox] * len(encode_res["input_ids"]))
gt_label_list.extend(gt_label)
words_list.append(text)
encoded_inputs = {
"input_ids": input_ids_list,
"labels": gt_label_list,
"token_type_ids": token_type_ids_list,
"bbox": bbox_list,
"attention_mask": [1] * len(input_ids_list),
# "words_list": words_list,
}
encoded_inputs = self.pad_sentences(
encoded_inputs,
max_seq_len=self.max_seq_len,
return_attention_mask=self.return_attention_mask)
encoded_inputs = self.truncate_inputs(encoded_inputs)
if self.contains_re:
relations = self._relations(entities, relations, id2label,
empty_entity, entity_id_to_index_map)
encoded_inputs['relations'] = relations
encoded_inputs['entities'] = entities
return encoded_inputs | [
"def",
"_read_encoded_inputs_sample",
"(",
"self",
",",
"info_str",
")",
":",
"# read text info",
"info_dict",
"=",
"json",
".",
"loads",
"(",
"info_str",
")",
"height",
"=",
"info_dict",
"[",
"\"height\"",
"]",
"width",
"=",
"info_dict",
"[",
"\"width\"",
"]"... | https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppstructure/vqa/xfun.py#L220-L311 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/lib/utils.py | python | byte_bounds | (a) | return a_low, a_high | Returns pointers to the end-points of an array.
Parameters
----------
a : ndarray
Input array. It must conform to the Python-side of the array
interface.
Returns
-------
(low, high) : tuple of 2 integers
The first integer is the first byte of the array, the second
integer is just past the last byte of the array. If `a` is not
contiguous it will not use every byte between the (`low`, `high`)
values.
Examples
--------
>>> I = np.eye(2, dtype='f'); I.dtype
dtype('float32')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True
>>> I = np.eye(2, dtype='G'); I.dtype
dtype('complex192')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True | Returns pointers to the end-points of an array. | [
"Returns",
"pointers",
"to",
"the",
"end",
"-",
"points",
"of",
"an",
"array",
"."
] | def byte_bounds(a):
"""
Returns pointers to the end-points of an array.
Parameters
----------
a : ndarray
Input array. It must conform to the Python-side of the array
interface.
Returns
-------
(low, high) : tuple of 2 integers
The first integer is the first byte of the array, the second
integer is just past the last byte of the array. If `a` is not
contiguous it will not use every byte between the (`low`, `high`)
values.
Examples
--------
>>> I = np.eye(2, dtype='f'); I.dtype
dtype('float32')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True
>>> I = np.eye(2, dtype='G'); I.dtype
dtype('complex192')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True
"""
ai = a.__array_interface__
a_data = ai['data'][0]
astrides = ai['strides']
ashape = ai['shape']
bytes_a = asarray(a).dtype.itemsize
a_low = a_high = a_data
if astrides is None:
# contiguous case
a_high += a.size * bytes_a
else:
for shape, stride in zip(ashape, astrides):
if stride < 0:
a_low += (shape-1)*stride
else:
a_high += (shape-1)*stride
a_high += bytes_a
return a_low, a_high | [
"def",
"byte_bounds",
"(",
"a",
")",
":",
"ai",
"=",
"a",
".",
"__array_interface__",
"a_data",
"=",
"ai",
"[",
"'data'",
"]",
"[",
"0",
"]",
"astrides",
"=",
"ai",
"[",
"'strides'",
"]",
"ashape",
"=",
"ai",
"[",
"'shape'",
"]",
"bytes_a",
"=",
"a... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/utils.py#L179-L228 | |
flexflow/FlexFlow | 581fad8ba8d10a16a3102ee2b406b0319586df24 | examples/python/pytorch/resnet_torch.py | python | resnet34 | (pretrained: bool = False, progress: bool = True, **kwargs: Any) | return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
**kwargs) | r"""ResNet-34 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr | r"""ResNet-34 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_. | [
"r",
"ResNet",
"-",
"34",
"model",
"from",
"Deep",
"Residual",
"Learning",
"for",
"Image",
"Recognition",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1512",
".",
"03385",
".",
"pdf",
">",
"_",
"."
] | def resnet34(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
r"""ResNet-34 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
**kwargs) | [
"def",
"resnet34",
"(",
"pretrained",
":",
"bool",
"=",
"False",
",",
"progress",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"ResNet",
":",
"return",
"_resnet",
"(",
"'resnet34'",
",",
"BasicBlock",
",",
"[",
"3",
",",
... | https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/examples/python/pytorch/resnet_torch.py#L257-L266 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PropertyGridManager.Reparent | (*args, **kwargs) | return _propgrid.PropertyGridManager_Reparent(*args, **kwargs) | Reparent(self, wxWindowBase newParent) -> bool | Reparent(self, wxWindowBase newParent) -> bool | [
"Reparent",
"(",
"self",
"wxWindowBase",
"newParent",
")",
"-",
">",
"bool"
] | def Reparent(*args, **kwargs):
"""Reparent(self, wxWindowBase newParent) -> bool"""
return _propgrid.PropertyGridManager_Reparent(*args, **kwargs) | [
"def",
"Reparent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridManager_Reparent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L3637-L3639 | |
neo-ai/neo-ai-dlr | bf397aa0367a5207654c00d2985f900d94ad1543 | container/sagemaker-pytorch-inferentia-serving/src/sagemaker_pytorch_inferentia_serving_container/default_inference_handler.py | python | DefaultPytorchInferenceHandler.default_output_fn | (self, prediction, accept) | return encoded_prediction | A default output_fn for PyTorch. Serializes predictions from predict_fn to JSON, CSV or NPY format.
Args:
prediction: a prediction result from predict_fn
accept: type which the output data needs to be serialized
Returns: output data serialized | A default output_fn for PyTorch. Serializes predictions from predict_fn to JSON, CSV or NPY format.
Args:
prediction: a prediction result from predict_fn
accept: type which the output data needs to be serialized
Returns: output data serialized | [
"A",
"default",
"output_fn",
"for",
"PyTorch",
".",
"Serializes",
"predictions",
"from",
"predict_fn",
"to",
"JSON",
"CSV",
"or",
"NPY",
"format",
".",
"Args",
":",
"prediction",
":",
"a",
"prediction",
"result",
"from",
"predict_fn",
"accept",
":",
"type",
... | def default_output_fn(self, prediction, accept):
"""A default output_fn for PyTorch. Serializes predictions from predict_fn to JSON, CSV or NPY format.
Args:
prediction: a prediction result from predict_fn
accept: type which the output data needs to be serialized
Returns: output data serialized
"""
if type(prediction) == torch.Tensor:
prediction = prediction.detach().cpu().numpy().tolist()
encoded_prediction = encoder.encode(prediction, accept)
if accept == content_types.CSV:
encoded_prediction = encoded_prediction.encode("utf-8")
return encoded_prediction | [
"def",
"default_output_fn",
"(",
"self",
",",
"prediction",
",",
"accept",
")",
":",
"if",
"type",
"(",
"prediction",
")",
"==",
"torch",
".",
"Tensor",
":",
"prediction",
"=",
"prediction",
".",
"detach",
"(",
")",
".",
"cpu",
"(",
")",
".",
"numpy",
... | https://github.com/neo-ai/neo-ai-dlr/blob/bf397aa0367a5207654c00d2985f900d94ad1543/container/sagemaker-pytorch-inferentia-serving/src/sagemaker_pytorch_inferentia_serving_container/default_inference_handler.py#L65-L78 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py | python | TurtleScreenBase._onrelease | (self, item, fun, num=1, add=None) | Bind fun to mouse-button-release event on turtle.
fun must be a function with two arguments, the coordinates
of the point on the canvas where mouse button is released.
num, the number of the mouse-button defaults to 1
If a turtle is clicked, first _onclick-event will be performed,
then _onscreensclick-event. | Bind fun to mouse-button-release event on turtle.
fun must be a function with two arguments, the coordinates
of the point on the canvas where mouse button is released.
num, the number of the mouse-button defaults to 1 | [
"Bind",
"fun",
"to",
"mouse",
"-",
"button",
"-",
"release",
"event",
"on",
"turtle",
".",
"fun",
"must",
"be",
"a",
"function",
"with",
"two",
"arguments",
"the",
"coordinates",
"of",
"the",
"point",
"on",
"the",
"canvas",
"where",
"mouse",
"button",
"i... | def _onrelease(self, item, fun, num=1, add=None):
"""Bind fun to mouse-button-release event on turtle.
fun must be a function with two arguments, the coordinates
of the point on the canvas where mouse button is released.
num, the number of the mouse-button defaults to 1
If a turtle is clicked, first _onclick-event will be performed,
then _onscreensclick-event.
"""
if fun is None:
self.cv.tag_unbind(item, "<Button%s-ButtonRelease>" % num)
else:
def eventfun(event):
x, y = (self.cv.canvasx(event.x)/self.xscale,
-self.cv.canvasy(event.y)/self.yscale)
fun(x, y)
self.cv.tag_bind(item, "<Button%s-ButtonRelease>" % num,
eventfun, add) | [
"def",
"_onrelease",
"(",
"self",
",",
"item",
",",
"fun",
",",
"num",
"=",
"1",
",",
"add",
"=",
"None",
")",
":",
"if",
"fun",
"is",
"None",
":",
"self",
".",
"cv",
".",
"tag_unbind",
"(",
"item",
",",
"\"<Button%s-ButtonRelease>\"",
"%",
"num",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py#L620-L637 | ||
qt/qtbase | 81b9ee66b8e40ed145185fe46b7c91929688cafd | util/locale_database/ldml.py | python | LocaleScanner.__fromLdmlPath | (seq) | Convert LDML's [@name='value'] to our [name=value] form. | Convert LDML's [ | [
"Convert",
"LDML",
"s",
"["
] | def __fromLdmlPath(seq): # tool function for __xpathJoin()
"""Convert LDML's [@name='value'] to our [name=value] form."""
for it in seq:
# First dismember it:
attrs = it.split('[')
tag = attrs.pop(0)
if not attrs: # Short-cut the easy case:
yield it
continue
assert all(x.endswith(']') for x in attrs)
attrs = [x[:-1].split('=') for x in attrs]
# Then fix each attribute specification in it:
attrs = [(x[0][1:] if x[0].startswith('@') else x[0],
x[1][1:-1] if x[1].startswith("'") and x[1].endswith("'") else x[1])
for x in attrs]
# Finally, put it all back together:
attrs = ['='.join(x) + ']' for x in attrs]
attrs.insert(0, tag)
yield '['.join(attrs) | [
"def",
"__fromLdmlPath",
"(",
"seq",
")",
":",
"# tool function for __xpathJoin()",
"for",
"it",
"in",
"seq",
":",
"# First dismember it:",
"attrs",
"=",
"it",
".",
"split",
"(",
"'['",
")",
"tag",
"=",
"attrs",
".",
"pop",
"(",
"0",
")",
"if",
"not",
"a... | https://github.com/qt/qtbase/blob/81b9ee66b8e40ed145185fe46b7c91929688cafd/util/locale_database/ldml.py#L592-L611 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | MetafileDataObject.GetMetafile | (*args, **kwargs) | return _misc_.MetafileDataObject_GetMetafile(*args, **kwargs) | GetMetafile(self) -> MetaFile | GetMetafile(self) -> MetaFile | [
"GetMetafile",
"(",
"self",
")",
"-",
">",
"MetaFile"
] | def GetMetafile(*args, **kwargs):
"""GetMetafile(self) -> MetaFile"""
return _misc_.MetafileDataObject_GetMetafile(*args, **kwargs) | [
"def",
"GetMetafile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"MetafileDataObject_GetMetafile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L5473-L5475 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/queue.py | python | _PySimpleQueue.put | (self, item, block=True, timeout=None) | Put the item on the queue.
The optional 'block' and 'timeout' arguments are ignored, as this method
never blocks. They are provided for compatibility with the Queue class. | Put the item on the queue. | [
"Put",
"the",
"item",
"on",
"the",
"queue",
"."
] | def put(self, item, block=True, timeout=None):
'''Put the item on the queue.
The optional 'block' and 'timeout' arguments are ignored, as this method
never blocks. They are provided for compatibility with the Queue class.
'''
self._queue.append(item)
self._count.release() | [
"def",
"put",
"(",
"self",
",",
"item",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_queue",
".",
"append",
"(",
"item",
")",
"self",
".",
"_count",
".",
"release",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/queue.py#L272-L279 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/customtreectrl.py | python | CustomTreeCtrl.SetBackgroundImage | (self, image) | Sets the :class:`CustomTreeCtrl` background image.
:param `image`: if not ``None``, an instance of :class:`Bitmap`.
:note: At present, the background image can only be used in "tile" mode.
.. todo:: Support background images also in stretch and centered modes. | Sets the :class:`CustomTreeCtrl` background image. | [
"Sets",
"the",
":",
"class",
":",
"CustomTreeCtrl",
"background",
"image",
"."
] | def SetBackgroundImage(self, image):
"""
Sets the :class:`CustomTreeCtrl` background image.
:param `image`: if not ``None``, an instance of :class:`Bitmap`.
:note: At present, the background image can only be used in "tile" mode.
.. todo:: Support background images also in stretch and centered modes.
"""
self._backgroundImage = image
self.Refresh() | [
"def",
"SetBackgroundImage",
"(",
"self",
",",
"image",
")",
":",
"self",
".",
"_backgroundImage",
"=",
"image",
"self",
".",
"Refresh",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L4194-L4206 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py | python | Misc.winfo_containing | (self, rootX, rootY, displayof=0) | return self._nametowidget(name) | Return the widget which is at the root coordinates ROOTX, ROOTY. | Return the widget which is at the root coordinates ROOTX, ROOTY. | [
"Return",
"the",
"widget",
"which",
"is",
"at",
"the",
"root",
"coordinates",
"ROOTX",
"ROOTY",
"."
] | def winfo_containing(self, rootX, rootY, displayof=0):
"""Return the widget which is at the root coordinates ROOTX, ROOTY."""
args = ('winfo', 'containing') \
+ self._displayof(displayof) + (rootX, rootY)
name = self.tk.call(args)
if not name: return None
return self._nametowidget(name) | [
"def",
"winfo_containing",
"(",
"self",
",",
"rootX",
",",
"rootY",
",",
"displayof",
"=",
"0",
")",
":",
"args",
"=",
"(",
"'winfo'",
",",
"'containing'",
")",
"+",
"self",
".",
"_displayof",
"(",
"displayof",
")",
"+",
"(",
"rootX",
",",
"rootY",
"... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L757-L763 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/difflib.py | python | HtmlDiff._line_wrapper | (self,diffs) | Returns iterator that splits (wraps) mdiff text lines | Returns iterator that splits (wraps) mdiff text lines | [
"Returns",
"iterator",
"that",
"splits",
"(",
"wraps",
")",
"mdiff",
"text",
"lines"
] | def _line_wrapper(self,diffs):
"""Returns iterator that splits (wraps) mdiff text lines"""
# pull from/to data and flags from mdiff iterator
for fromdata,todata,flag in diffs:
# check for context separators and pass them through
if flag is None:
yield fromdata,todata,flag
continue
(fromline,fromtext),(toline,totext) = fromdata,todata
# for each from/to line split it at the wrap column to form
# list of text lines.
fromlist,tolist = [],[]
self._split_line(fromlist,fromline,fromtext)
self._split_line(tolist,toline,totext)
# yield from/to line in pairs inserting blank lines as
# necessary when one side has more wrapped lines
while fromlist or tolist:
if fromlist:
fromdata = fromlist.pop(0)
else:
fromdata = ('',' ')
if tolist:
todata = tolist.pop(0)
else:
todata = ('',' ')
yield fromdata,todata,flag | [
"def",
"_line_wrapper",
"(",
"self",
",",
"diffs",
")",
":",
"# pull from/to data and flags from mdiff iterator",
"for",
"fromdata",
",",
"todata",
",",
"flag",
"in",
"diffs",
":",
"# check for context separators and pass them through",
"if",
"flag",
"is",
"None",
":",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/difflib.py#L1811-L1837 | ||
cksystemsgroup/scal | fa2208a97a77d65f4e90f85fef3404c27c1f2ac2 | tools/cpplint.py | python | CheckCheck | (filename, clean_lines, linenum, error) | Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks the use of CHECK and EXPECT macros. | [
"Checks",
"the",
"use",
"of",
"CHECK",
"and",
"EXPECT",
"macros",
"."
] | def CheckCheck(filename, clean_lines, linenum, error):
"""Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Decide the set of replacement macros that should be suggested
lines = clean_lines.elided
(check_macro, start_pos) = FindCheckMacro(lines[linenum])
if not check_macro:
return
# Find end of the boolean expression by matching parentheses
(last_line, end_line, end_pos) = CloseExpression(
clean_lines, linenum, start_pos)
if end_pos < 0:
return
# If the check macro is followed by something other than a
# semicolon, assume users will log their own custom error messages
# and don't suggest any replacements.
if not Match(r'\s*;', last_line[end_pos:]):
return
if linenum == end_line:
expression = lines[linenum][start_pos + 1:end_pos - 1]
else:
expression = lines[linenum][start_pos + 1:]
for i in xrange(linenum + 1, end_line):
expression += lines[i]
expression += last_line[0:end_pos - 1]
# Parse expression so that we can take parentheses into account.
# This avoids false positives for inputs like "CHECK((a < 4) == b)",
# which is not replaceable by CHECK_LE.
lhs = ''
rhs = ''
operator = None
while expression:
matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
r'==|!=|>=|>|<=|<|\()(.*)$', expression)
if matched:
token = matched.group(1)
if token == '(':
# Parenthesized operand
expression = matched.group(2)
(end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
if end < 0:
return # Unmatched parenthesis
lhs += '(' + expression[0:end]
expression = expression[end:]
elif token in ('&&', '||'):
# Logical and/or operators. This means the expression
# contains more than one term, for example:
# CHECK(42 < a && a < b);
#
# These are not replaceable with CHECK_LE, so bail out early.
return
elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
# Non-relational operator
lhs += token
expression = matched.group(2)
else:
# Relational operator
operator = token
rhs = matched.group(2)
break
else:
# Unparenthesized operand. Instead of appending to lhs one character
# at a time, we do another regular expression match to consume several
# characters at once if possible. Trivial benchmark shows that this
# is more efficient when the operands are longer than a single
# character, which is generally the case.
matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
if not matched:
matched = Match(r'^(\s*\S)(.*)$', expression)
if not matched:
break
lhs += matched.group(1)
expression = matched.group(2)
# Only apply checks if we got all parts of the boolean expression
if not (lhs and operator and rhs):
return
# Check that rhs do not contain logical operators. We already know
# that lhs is fine since the loop above parses out && and ||.
if rhs.find('&&') > -1 or rhs.find('||') > -1:
return
# At least one of the operands must be a constant literal. This is
# to avoid suggesting replacements for unprintable things like
# CHECK(variable != iterator)
#
# The following pattern matches decimal, hex integers, strings, and
# characters (in that order).
lhs = lhs.strip()
rhs = rhs.strip()
match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
if Match(match_constant, lhs) or Match(match_constant, rhs):
# Note: since we know both lhs and rhs, we can provide a more
# descriptive error message like:
# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
# Instead of:
# Consider using CHECK_EQ instead of CHECK(a == b)
#
# We are still keeping the less descriptive message because if lhs
# or rhs gets long, the error message might become unreadable.
error(filename, linenum, 'readability/check', 2,
'Consider using %s instead of %s(a %s b)' % (
_CHECK_REPLACEMENT[check_macro][operator],
check_macro, operator)) | [
"def",
"CheckCheck",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Decide the set of replacement macros that should be suggested",
"lines",
"=",
"clean_lines",
".",
"elided",
"(",
"check_macro",
",",
"start_pos",
")",
"=",
"FindCheckM... | https://github.com/cksystemsgroup/scal/blob/fa2208a97a77d65f4e90f85fef3404c27c1f2ac2/tools/cpplint.py#L4201-L4316 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathOpGui.py | python | TaskPanelPage.updatePanelVisibility | (self, panelTitle, obj) | updatePanelVisibility(panelTitle, obj) ...
Function to call the `updateVisibility()` GUI method of the
page whose panel title is as indicated. | updatePanelVisibility(panelTitle, obj) ...
Function to call the `updateVisibility()` GUI method of the
page whose panel title is as indicated. | [
"updatePanelVisibility",
"(",
"panelTitle",
"obj",
")",
"...",
"Function",
"to",
"call",
"the",
"updateVisibility",
"()",
"GUI",
"method",
"of",
"the",
"page",
"whose",
"panel",
"title",
"is",
"as",
"indicated",
"."
] | def updatePanelVisibility(self, panelTitle, obj):
"""updatePanelVisibility(panelTitle, obj) ...
Function to call the `updateVisibility()` GUI method of the
page whose panel title is as indicated."""
if hasattr(self, "parent"):
parent = getattr(self, "parent")
if parent and hasattr(parent, "featurePages"):
for page in parent.featurePages:
if hasattr(page, "panelTitle"):
if page.panelTitle == panelTitle and hasattr(
page, "updateVisibility"
):
page.updateVisibility()
break | [
"def",
"updatePanelVisibility",
"(",
"self",
",",
"panelTitle",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"parent\"",
")",
":",
"parent",
"=",
"getattr",
"(",
"self",
",",
"\"parent\"",
")",
"if",
"parent",
"and",
"hasattr",
"(",
"parent... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathOpGui.py#L450-L463 | ||
senlinuc/caffe_ocr | 81642f61ea8f888e360cca30e08e05b7bc6d4556 | examples/pycaffe/tools.py | python | CaffeSolver.write | (self, filepath) | Export solver parameters to INPUT "filepath". Sorted alphabetically. | Export solver parameters to INPUT "filepath". Sorted alphabetically. | [
"Export",
"solver",
"parameters",
"to",
"INPUT",
"filepath",
".",
"Sorted",
"alphabetically",
"."
] | def write(self, filepath):
"""
Export solver parameters to INPUT "filepath". Sorted alphabetically.
"""
f = open(filepath, 'w')
for key, value in sorted(self.sp.items()):
if not(type(value) is str):
raise TypeError('All solver parameters must be strings')
f.write('%s: %s\n' % (key, value)) | [
"def",
"write",
"(",
"self",
",",
"filepath",
")",
":",
"f",
"=",
"open",
"(",
"filepath",
",",
"'w'",
")",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"self",
".",
"sp",
".",
"items",
"(",
")",
")",
":",
"if",
"not",
"(",
"type",
"(",
"... | https://github.com/senlinuc/caffe_ocr/blob/81642f61ea8f888e360cca30e08e05b7bc6d4556/examples/pycaffe/tools.py#L113-L121 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.