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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | Mass.getCom | (self) | return _robotsim.Mass_getCom(self) | r"""
getCom(Mass self)
Returns the COM as a list of 3 floats. | r"""
getCom(Mass self) | [
"r",
"getCom",
"(",
"Mass",
"self",
")"
] | def getCom(self) -> "void":
r"""
getCom(Mass self)
Returns the COM as a list of 3 floats.
"""
return _robotsim.Mass_getCom(self) | [
"def",
"getCom",
"(",
"self",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"Mass_getCom",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L3914-L3922 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/datetime.py | python | datetime.minute | (self) | return self._minute | minute (0-59) | minute (0-59) | [
"minute",
"(",
"0",
"-",
"59",
")"
] | def minute(self):
"""minute (0-59)"""
return self._minute | [
"def",
"minute",
"(",
"self",
")",
":",
"return",
"self",
".",
"_minute"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/datetime.py#L1559-L1561 | |
openfoamtutorials/OpenFOAM_Tutorials_ | 29e19833aea3f6ee87ecceae3d061b050ee3ed89 | InProgress/MultiElementWing/functions.py | python | addBoundary | (boundaryFilePath,bname,btype,bphysicaltype,startface,nfaces) | Adds a boundary entry to the constant/polyMesh/boundary file.
Returns a list of the new lines.
Assumes the following file format (for a file with N boundaries):
N
(
myBoundary
{
type myType;
...
}
...
) | Adds a boundary entry to the constant/polyMesh/boundary file.
Returns a list of the new lines.
Assumes the following file format (for a file with N boundaries):
N
(
myBoundary
{
type myType;
...
}
...
) | [
"Adds",
"a",
"boundary",
"entry",
"to",
"the",
"constant",
"/",
"polyMesh",
"/",
"boundary",
"file",
".",
"Returns",
"a",
"list",
"of",
"the",
"new",
"lines",
".",
"Assumes",
"the",
"following",
"file",
"format",
"(",
"for",
"a",
"file",
"with",
"N",
"... | def addBoundary(boundaryFilePath,bname,btype,bphysicaltype,startface,nfaces):
"""
Adds a boundary entry to the constant/polyMesh/boundary file.
Returns a list of the new lines.
Assumes the following file format (for a file with N boundaries):
N
(
myBoundary
{
type myType;
...
}
...
)
"""
#First create the boundary to insert.
entry = []
entry.append(bname+"\n")
entry.append("{\n")
entry.append("\ttype\t\t"+btype+";\n")
entry.append("\tphysicalType\t"+bphysicaltype+";\n")
entry.append("\tnFaces\t\t"+str(nfaces)+";\n")
entry.append("\tstartFace\t"+str(startface)+";\n")
entry.append("}\n")
entry = indentLines(entry)
lines = getLinesFromFile(boundaryFilePath)
for i in range(len(lines)):
if is_integer(lines[i].strip()):
lines[i] = str(int(lines[i].strip())+1)+"\n"
if lines[i].strip() == "(":
for newline in reversed(entry):
lines.insert(i+1,newline)
break
writeToFile(boundaryFilePath,lines) | [
"def",
"addBoundary",
"(",
"boundaryFilePath",
",",
"bname",
",",
"btype",
",",
"bphysicaltype",
",",
"startface",
",",
"nfaces",
")",
":",
"#First create the boundary to insert.",
"entry",
"=",
"[",
"]",
"entry",
".",
"append",
"(",
"bname",
"+",
"\"\\n\"",
"... | https://github.com/openfoamtutorials/OpenFOAM_Tutorials_/blob/29e19833aea3f6ee87ecceae3d061b050ee3ed89/InProgress/MultiElementWing/functions.py#L36-L71 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/tpu/session_support.py | python | WorkerHeartbeatManager.from_devices | (session, devices) | return WorkerHeartbeatManager(session, devices, heartbeat_ops,
request_placeholder) | Construct a heartbeat manager for the given devices. | Construct a heartbeat manager for the given devices. | [
"Construct",
"a",
"heartbeat",
"manager",
"for",
"the",
"given",
"devices",
"."
] | def from_devices(session, devices):
"""Construct a heartbeat manager for the given devices."""
if not devices:
logging.error('Trying to create heartbeat manager with no devices?')
logging.info('Creating heartbeat manager for %s', devices)
request_placeholder = array_ops.placeholder(
name='worker_heartbeat_request', dtype=dtypes.string)
heartbeat_ops = []
for device in devices:
with ops.device(device):
heartbeat_ops.append(tpu_ops.worker_heartbeat(request_placeholder))
return WorkerHeartbeatManager(session, devices, heartbeat_ops,
request_placeholder) | [
"def",
"from_devices",
"(",
"session",
",",
"devices",
")",
":",
"if",
"not",
"devices",
":",
"logging",
".",
"error",
"(",
"'Trying to create heartbeat manager with no devices?'",
")",
"logging",
".",
"info",
"(",
"'Creating heartbeat manager for %s'",
",",
"devices"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/session_support.py#L73-L88 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Image.Paste | (*args, **kwargs) | return _core_.Image_Paste(*args, **kwargs) | Paste(self, Image image, int x, int y)
Pastes ``image`` into this instance and takes care of the mask colour
and any out of bounds problems. | Paste(self, Image image, int x, int y) | [
"Paste",
"(",
"self",
"Image",
"image",
"int",
"x",
"int",
"y",
")"
] | def Paste(*args, **kwargs):
"""
Paste(self, Image image, int x, int y)
Pastes ``image`` into this instance and takes care of the mask colour
and any out of bounds problems.
"""
return _core_.Image_Paste(*args, **kwargs) | [
"def",
"Paste",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_Paste",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L3348-L3355 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/gensuitemodule.py | python | processfile_fromresource | (fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, dump=None, verbose=None) | Process all resources in a single file | Process all resources in a single file | [
"Process",
"all",
"resources",
"in",
"a",
"single",
"file"
] | def processfile_fromresource(fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, dump=None, verbose=None):
"""Process all resources in a single file"""
if not is_scriptable(fullname) and verbose:
print >>verbose, "Warning: app does not seem scriptable: %s" % fullname
cur = CurResFile()
if verbose:
print >>verbose, "Processing", fullname
rf = macresource.open_pathname(fullname)
try:
UseResFile(rf)
resources = []
for i in range(Count1Resources('aete')):
res = Get1IndResource('aete', 1+i)
resources.append(res)
for i in range(Count1Resources('aeut')):
res = Get1IndResource('aeut', 1+i)
resources.append(res)
if verbose:
print >>verbose, "\nLISTING aete+aeut RESOURCES IN", repr(fullname)
aetelist = []
for res in resources:
if verbose:
print >>verbose, "decoding", res.GetResInfo(), "..."
data = res.data
aete = decode(data, verbose)
aetelist.append((aete, res.GetResInfo()))
finally:
if rf != cur:
CloseResFile(rf)
UseResFile(cur)
# switch back (needed for dialogs in Python)
UseResFile(cur)
if dump:
dumpaetelist(aetelist, dump)
compileaetelist(aetelist, fullname, output=output,
basepkgname=basepkgname, edit_modnames=edit_modnames,
creatorsignature=creatorsignature, verbose=verbose) | [
"def",
"processfile_fromresource",
"(",
"fullname",
",",
"output",
"=",
"None",
",",
"basepkgname",
"=",
"None",
",",
"edit_modnames",
"=",
"None",
",",
"creatorsignature",
"=",
"None",
",",
"dump",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"if",... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/gensuitemodule.py#L147-L184 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/runtime.py | python | feature_list | () | return features | Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc
Returns
-------
list
List of :class:`.Feature` objects | Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc | [
"Check",
"the",
"library",
"for",
"compile",
"-",
"time",
"features",
".",
"The",
"list",
"of",
"features",
"are",
"maintained",
"in",
"libinfo",
".",
"h",
"and",
"libinfo",
".",
"cc"
] | def feature_list():
"""
Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc
Returns
-------
list
List of :class:`.Feature` objects
"""
lib_features_c_array = ctypes.POINTER(Feature)()
lib_features_size = ctypes.c_size_t()
check_call(_LIB.MXLibInfoFeatures(ctypes.byref(lib_features_c_array), ctypes.byref(lib_features_size)))
features = [lib_features_c_array[i] for i in range(lib_features_size.value)]
return features | [
"def",
"feature_list",
"(",
")",
":",
"lib_features_c_array",
"=",
"ctypes",
".",
"POINTER",
"(",
"Feature",
")",
"(",
")",
"lib_features_size",
"=",
"ctypes",
".",
"c_size_t",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXLibInfoFeatures",
"(",
"ctypes",
"."... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/runtime.py#L57-L70 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | createInputBuffer | (file, encoding) | return inputBuffer(_obj=ret) | Create a libxml2 input buffer from a Python file | Create a libxml2 input buffer from a Python file | [
"Create",
"a",
"libxml2",
"input",
"buffer",
"from",
"a",
"Python",
"file"
] | def createInputBuffer(file, encoding):
"""Create a libxml2 input buffer from a Python file """
ret = libxml2mod.xmlCreateInputBuffer(file, encoding)
if ret is None:raise treeError('xmlCreateInputBuffer() failed')
return inputBuffer(_obj=ret) | [
"def",
"createInputBuffer",
"(",
"file",
",",
"encoding",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlCreateInputBuffer",
"(",
"file",
",",
"encoding",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlCreateInputBuffer() failed'",
")",
"re... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L771-L775 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/Endoscopy/Endoscopy.py | python | EndoscopyWidget.flyTo | (self, f) | Apply the fth step in the path to the global camera | Apply the fth step in the path to the global camera | [
"Apply",
"the",
"fth",
"step",
"in",
"the",
"path",
"to",
"the",
"global",
"camera"
] | def flyTo(self, f):
""" Apply the fth step in the path to the global camera"""
if self.path:
f = int(f)
p = self.path[f]
wasModified = self.cameraNode.StartModify()
self.camera.SetPosition(*p)
foc = self.path[f+1]
self.camera.SetFocalPoint(*foc)
self.camera.OrthogonalizeViewUp()
toParent = vtk.vtkMatrix4x4()
self.transform.GetMatrixTransformToParent(toParent)
toParent.SetElement(0 ,3, p[0])
toParent.SetElement(1, 3, p[1])
toParent.SetElement(2, 3, p[2])
# Set up transform orientation component so that
# Z axis is aligned with view direction and
# Y vector is aligned with the curve's plane normal.
# This can be used for example to show a reformatted slice
# using with SlicerIGT extension's VolumeResliceDriver module.
import numpy as np
zVec = (foc-p)/np.linalg.norm(foc-p)
yVec = self.pathPlaneNormal
xVec = np.cross(yVec, zVec)
toParent.SetElement(0, 0, xVec[0])
toParent.SetElement(1, 0, xVec[1])
toParent.SetElement(2, 0, xVec[2])
toParent.SetElement(0, 1, yVec[0])
toParent.SetElement(1, 1, yVec[1])
toParent.SetElement(2, 1, yVec[2])
toParent.SetElement(0, 2, zVec[0])
toParent.SetElement(1, 2, zVec[1])
toParent.SetElement(2, 2, zVec[2])
self.transform.SetMatrixTransformToParent(toParent)
self.cameraNode.EndModify(wasModified)
self.cameraNode.ResetClippingRange() | [
"def",
"flyTo",
"(",
"self",
",",
"f",
")",
":",
"if",
"self",
".",
"path",
":",
"f",
"=",
"int",
"(",
"f",
")",
"p",
"=",
"self",
".",
"path",
"[",
"f",
"]",
"wasModified",
"=",
"self",
".",
"cameraNode",
".",
"StartModify",
"(",
")",
"self",
... | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/Endoscopy/Endoscopy.py#L274-L313 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py | python | IncrementalEncoder.encode | (self, input, final=False) | Encodes input and returns the resulting object. | Encodes input and returns the resulting object. | [
"Encodes",
"input",
"and",
"returns",
"the",
"resulting",
"object",
"."
] | def encode(self, input, final=False):
"""
Encodes input and returns the resulting object.
"""
raise NotImplementedError | [
"def",
"encode",
"(",
"self",
",",
"input",
",",
"final",
"=",
"False",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py#L173-L177 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/inspect.py | python | stack | (context=1) | return getouterframes(sys._getframe(1), context) | Return a list of records for the stack above the caller's frame. | Return a list of records for the stack above the caller's frame. | [
"Return",
"a",
"list",
"of",
"records",
"for",
"the",
"stack",
"above",
"the",
"caller",
"s",
"frame",
"."
] | def stack(context=1):
"""Return a list of records for the stack above the caller's frame."""
return getouterframes(sys._getframe(1), context) | [
"def",
"stack",
"(",
"context",
"=",
"1",
")",
":",
"return",
"getouterframes",
"(",
"sys",
".",
"_getframe",
"(",
"1",
")",
",",
"context",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/inspect.py#L1052-L1054 | |
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/build/virtual_target.py | python | AbstractFileTarget.action | (self) | return self.action_ | Returns the action. | Returns the action. | [
"Returns",
"the",
"action",
"."
] | def action (self):
""" Returns the action.
"""
return self.action_ | [
"def",
"action",
"(",
"self",
")",
":",
"return",
"self",
".",
"action_"
] | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/virtual_target.py#L429-L432 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextCtrl.EndListStyle | (*args, **kwargs) | return _richtext.RichTextCtrl_EndListStyle(*args, **kwargs) | EndListStyle(self) -> bool
End named list style. | EndListStyle(self) -> bool | [
"EndListStyle",
"(",
"self",
")",
"-",
">",
"bool"
] | def EndListStyle(*args, **kwargs):
"""
EndListStyle(self) -> bool
End named list style.
"""
return _richtext.RichTextCtrl_EndListStyle(*args, **kwargs) | [
"def",
"EndListStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_EndListStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L3601-L3607 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/logging/__init__.py | python | Formatter.format | (self, record) | return s | Format the specified record as text.
The record's attribute dictionary is used as the operand to a
string formatting operation which yields the returned string.
Before formatting the dictionary, a couple of preparatory steps
are carried out. The message attribute of the record is computed
using LogRecord.getMessage(). If the formatting string uses the
time (as determined by a call to usesTime(), formatTime() is
called to format the event time. If there is exception information,
it is formatted using formatException() and appended to the message. | Format the specified record as text. | [
"Format",
"the",
"specified",
"record",
"as",
"text",
"."
] | def format(self, record):
"""
Format the specified record as text.
The record's attribute dictionary is used as the operand to a
string formatting operation which yields the returned string.
Before formatting the dictionary, a couple of preparatory steps
are carried out. The message attribute of the record is computed
using LogRecord.getMessage(). If the formatting string uses the
time (as determined by a call to usesTime(), formatTime() is
called to format the event time. If there is exception information,
it is formatted using formatException() and appended to the message.
"""
record.message = record.getMessage()
if self.usesTime():
record.asctime = self.formatTime(record, self.datefmt)
s = self.formatMessage(record)
if record.exc_info:
# Cache the traceback text to avoid converting it multiple times
# (it's constant anyway)
if not record.exc_text:
record.exc_text = self.formatException(record.exc_info)
if record.exc_text:
if s[-1:] != "\n":
s = s + "\n"
s = s + record.exc_text
if record.stack_info:
if s[-1:] != "\n":
s = s + "\n"
s = s + self.formatStack(record.stack_info)
return s | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"record",
".",
"message",
"=",
"record",
".",
"getMessage",
"(",
")",
"if",
"self",
".",
"usesTime",
"(",
")",
":",
"record",
".",
"asctime",
"=",
"self",
".",
"formatTime",
"(",
"record",
",",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/__init__.py#L650-L680 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Checkbutton.select | (self) | Put the button in on-state. | Put the button in on-state. | [
"Put",
"the",
"button",
"in",
"on",
"-",
"state",
"."
] | def select(self):
"""Put the button in on-state."""
self.tk.call(self._w, 'select') | [
"def",
"select",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'select'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2427-L2429 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/ttk.py | python | OptionMenu.__init__ | (self, master, variable, default=None, *values, **kwargs) | Construct a themed OptionMenu widget with master as the parent,
the resource textvariable set to variable, the initially selected
value specified by the default parameter, the menu values given by
*values and additional keywords.
WIDGET-SPECIFIC OPTIONS
style: stylename
Menubutton style.
direction: 'above', 'below', 'left', 'right', or 'flush'
Menubutton direction.
command: callback
A callback that will be invoked after selecting an item. | Construct a themed OptionMenu widget with master as the parent,
the resource textvariable set to variable, the initially selected
value specified by the default parameter, the menu values given by
*values and additional keywords. | [
"Construct",
"a",
"themed",
"OptionMenu",
"widget",
"with",
"master",
"as",
"the",
"parent",
"the",
"resource",
"textvariable",
"set",
"to",
"variable",
"the",
"initially",
"selected",
"value",
"specified",
"by",
"the",
"default",
"parameter",
"the",
"menu",
"va... | def __init__(self, master, variable, default=None, *values, **kwargs):
"""Construct a themed OptionMenu widget with master as the parent,
the resource textvariable set to variable, the initially selected
value specified by the default parameter, the menu values given by
*values and additional keywords.
WIDGET-SPECIFIC OPTIONS
style: stylename
Menubutton style.
direction: 'above', 'below', 'left', 'right', or 'flush'
Menubutton direction.
command: callback
A callback that will be invoked after selecting an item.
"""
kw = {'textvariable': variable, 'style': kwargs.pop('style', None),
'direction': kwargs.pop('direction', None)}
Menubutton.__init__(self, master, **kw)
self['menu'] = tkinter.Menu(self, tearoff=False)
self._variable = variable
self._callback = kwargs.pop('command', None)
if kwargs:
raise tkinter.TclError('unknown option -%s' % (
next(iter(kwargs.keys()))))
self.set_menu(default, *values) | [
"def",
"__init__",
"(",
"self",
",",
"master",
",",
"variable",
",",
"default",
"=",
"None",
",",
"*",
"values",
",",
"*",
"*",
"kwargs",
")",
":",
"kw",
"=",
"{",
"'textvariable'",
":",
"variable",
",",
"'style'",
":",
"kwargs",
".",
"pop",
"(",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/ttk.py#L1624-L1650 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/html5lib/filters/sanitizer.py | python | Filter.__init__ | (self,
source,
allowed_elements=allowed_elements,
allowed_attributes=allowed_attributes,
allowed_css_properties=allowed_css_properties,
allowed_css_keywords=allowed_css_keywords,
allowed_svg_properties=allowed_svg_properties,
allowed_protocols=allowed_protocols,
allowed_content_types=allowed_content_types,
attr_val_is_uri=attr_val_is_uri,
svg_attr_val_allows_ref=svg_attr_val_allows_ref,
svg_allow_local_href=svg_allow_local_href) | Creates a Filter
:arg allowed_elements: set of elements to allow--everything else will
be escaped
:arg allowed_attributes: set of attributes to allow in
elements--everything else will be stripped
:arg allowed_css_properties: set of CSS properties to allow--everything
else will be stripped
:arg allowed_css_keywords: set of CSS keywords to allow--everything
else will be stripped
:arg allowed_svg_properties: set of SVG properties to allow--everything
else will be removed
:arg allowed_protocols: set of allowed protocols for URIs
:arg allowed_content_types: set of allowed content types for ``data`` URIs.
:arg attr_val_is_uri: set of attributes that have URI values--values
that have a scheme not listed in ``allowed_protocols`` are removed
:arg svg_attr_val_allows_ref: set of SVG attributes that can have
references
:arg svg_allow_local_href: set of SVG elements that can have local
hrefs--these are removed | Creates a Filter | [
"Creates",
"a",
"Filter"
] | def __init__(self,
source,
allowed_elements=allowed_elements,
allowed_attributes=allowed_attributes,
allowed_css_properties=allowed_css_properties,
allowed_css_keywords=allowed_css_keywords,
allowed_svg_properties=allowed_svg_properties,
allowed_protocols=allowed_protocols,
allowed_content_types=allowed_content_types,
attr_val_is_uri=attr_val_is_uri,
svg_attr_val_allows_ref=svg_attr_val_allows_ref,
svg_allow_local_href=svg_allow_local_href):
"""Creates a Filter
:arg allowed_elements: set of elements to allow--everything else will
be escaped
:arg allowed_attributes: set of attributes to allow in
elements--everything else will be stripped
:arg allowed_css_properties: set of CSS properties to allow--everything
else will be stripped
:arg allowed_css_keywords: set of CSS keywords to allow--everything
else will be stripped
:arg allowed_svg_properties: set of SVG properties to allow--everything
else will be removed
:arg allowed_protocols: set of allowed protocols for URIs
:arg allowed_content_types: set of allowed content types for ``data`` URIs.
:arg attr_val_is_uri: set of attributes that have URI values--values
that have a scheme not listed in ``allowed_protocols`` are removed
:arg svg_attr_val_allows_ref: set of SVG attributes that can have
references
:arg svg_allow_local_href: set of SVG elements that can have local
hrefs--these are removed
"""
super(Filter, self).__init__(source)
self.allowed_elements = allowed_elements
self.allowed_attributes = allowed_attributes
self.allowed_css_properties = allowed_css_properties
self.allowed_css_keywords = allowed_css_keywords
self.allowed_svg_properties = allowed_svg_properties
self.allowed_protocols = allowed_protocols
self.allowed_content_types = allowed_content_types
self.attr_val_is_uri = attr_val_is_uri
self.svg_attr_val_allows_ref = svg_attr_val_allows_ref
self.svg_allow_local_href = svg_allow_local_href | [
"def",
"__init__",
"(",
"self",
",",
"source",
",",
"allowed_elements",
"=",
"allowed_elements",
",",
"allowed_attributes",
"=",
"allowed_attributes",
",",
"allowed_css_properties",
"=",
"allowed_css_properties",
",",
"allowed_css_keywords",
"=",
"allowed_css_keywords",
"... | 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/html5lib/filters/sanitizer.py#L709-L762 | ||
apache/madlib | be297fe6beada0640f93317e8948834032718e32 | src/madpack/madpack.py | python | _check_db_port | (portid) | return False | Make sure we are connected to the expected DB platform
@param portid expected DB port id - to be validates | Make sure we are connected to the expected DB platform | [
"Make",
"sure",
"we",
"are",
"connected",
"to",
"the",
"expected",
"DB",
"platform"
] | def _check_db_port(portid):
"""
Make sure we are connected to the expected DB platform
@param portid expected DB port id - to be validates
"""
# Postgres
try:
row = _internal_run_query("SELECT version() AS version", True)
except:
error_(this, "Cannot validate DB platform type", True)
if row and row[0]['version'].lower().find(portid) >= 0:
if portid == 'postgres':
if row[0]['version'].lower().find('greenplum') < 0:
return True
elif portid == 'greenplum':
return True
return False | [
"def",
"_check_db_port",
"(",
"portid",
")",
":",
"# Postgres",
"try",
":",
"row",
"=",
"_internal_run_query",
"(",
"\"SELECT version() AS version\"",
",",
"True",
")",
"except",
":",
"error_",
"(",
"this",
",",
"\"Cannot validate DB platform type\"",
",",
"True",
... | https://github.com/apache/madlib/blob/be297fe6beada0640f93317e8948834032718e32/src/madpack/madpack.py#L341-L357 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | addon-sdk/source/python-lib/simplejson/decoder.py | python | JSONDecoder.__init__ | (self, encoding=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, strict=True) | ``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``.
``object_hook``, if specified, will be called with the result
of every JSON object decoded and its return value will be used in
place of the given ``dict``. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered. | ``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``. | [
"encoding",
"determines",
"the",
"encoding",
"used",
"to",
"interpret",
"any",
"str",
"objects",
"decoded",
"by",
"this",
"instance",
"(",
"utf",
"-",
"8",
"by",
"default",
")",
".",
"It",
"has",
"no",
"effect",
"when",
"decoding",
"unicode",
"objects",
".... | def __init__(self, encoding=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, strict=True):
"""
``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``.
``object_hook``, if specified, will be called with the result
of every JSON object decoded and its return value will be used in
place of the given ``dict``. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
"""
self.encoding = encoding
self.object_hook = object_hook
self.parse_float = parse_float
self.parse_int = parse_int
self.parse_constant = parse_constant
self.strict = strict | [
"def",
"__init__",
"(",
"self",
",",
"encoding",
"=",
"None",
",",
"object_hook",
"=",
"None",
",",
"parse_float",
"=",
"None",
",",
"parse_int",
"=",
"None",
",",
"parse_constant",
"=",
"None",
",",
"strict",
"=",
"True",
")",
":",
"self",
".",
"encod... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/addon-sdk/source/python-lib/simplejson/decoder.py#L279-L314 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_editv.py | python | EdEditorView.OnKillFocus | (self, evt) | Hide popups when focus is lost
@note: call to skip is necessary | Hide popups when focus is lost
@note: call to skip is necessary | [
"Hide",
"popups",
"when",
"focus",
"is",
"lost",
"@note",
":",
"call",
"to",
"skip",
"is",
"necessary"
] | def OnKillFocus(self, evt):
"""Hide popups when focus is lost
@note: call to skip is necessary
"""
self.HidePopups()
evt.Skip() | [
"def",
"OnKillFocus",
"(",
"self",
",",
"evt",
")",
":",
"self",
".",
"HidePopups",
"(",
")",
"evt",
".",
"Skip",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_editv.py#L403-L409 | ||
CanalTP/navitia | cb84ce9859070187e708818b058e6a7e0b7f891b | source/jormungandr/jormungandr/instance.py | python | Instance.get_id | (self, id_) | return self.send_and_receive(req, timeout=app.config.get('INSTANCE_FAST_TIMEOUT', 1000)) | Get the pt_object that have the given id | Get the pt_object that have the given id | [
"Get",
"the",
"pt_object",
"that",
"have",
"the",
"given",
"id"
] | def get_id(self, id_):
"""
Get the pt_object that have the given id
"""
req = request_pb2.Request()
req.requested_api = type_pb2.place_uri
req.place_uri.uri = id_
return self.send_and_receive(req, timeout=app.config.get('INSTANCE_FAST_TIMEOUT', 1000)) | [
"def",
"get_id",
"(",
"self",
",",
"id_",
")",
":",
"req",
"=",
"request_pb2",
".",
"Request",
"(",
")",
"req",
".",
"requested_api",
"=",
"type_pb2",
".",
"place_uri",
"req",
".",
"place_uri",
".",
"uri",
"=",
"id_",
"return",
"self",
".",
"send_and_r... | https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/jormungandr/jormungandr/instance.py#L786-L793 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/utils.py | python | address_in_network | (ip, net) | return (ipaddr & netmask) == (network & netmask) | This function allows you to check if on IP belongs to a network subnet
Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 | This function allows you to check if on IP belongs to a network subnet
Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 | [
"This",
"function",
"allows",
"you",
"to",
"check",
"if",
"on",
"IP",
"belongs",
"to",
"a",
"network",
"subnet",
"Example",
":",
"returns",
"True",
"if",
"ip",
"=",
"192",
".",
"168",
".",
"1",
".",
"1",
"and",
"net",
"=",
"192",
".",
"168",
".",
... | def address_in_network(ip, net):
"""
This function allows you to check if on IP belongs to a network subnet
Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
"""
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
netaddr, bits = net.split('/')
netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask) | [
"def",
"address_in_network",
"(",
"ip",
",",
"net",
")",
":",
"ipaddr",
"=",
"struct",
".",
"unpack",
"(",
"'=L'",
",",
"socket",
".",
"inet_aton",
"(",
"ip",
")",
")",
"[",
"0",
"]",
"netaddr",
",",
"bits",
"=",
"net",
".",
"split",
"(",
"'/'",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/utils.py#L437-L447 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_grad/grad_comm_ops.py | python | get_bprop_allswap | (self) | return bprop | Generate bprop for _AllSwap. | Generate bprop for _AllSwap. | [
"Generate",
"bprop",
"for",
"_AllSwap",
"."
] | def get_bprop_allswap(self):
"""Generate bprop for _AllSwap."""
all_swap_grad = _AllSwap(self.group)
if self.instance_name:
instance_name = "grad" + self.instance_name
all_swap_grad.set_prim_instance_name(instance_name)
def bprop(x, send_size, recv_size, out, dout):
dx = all_swap_grad(dout, recv_size, send_size)
return (dx, zeros_like(send_size), zeros_like(recv_size))
return bprop | [
"def",
"get_bprop_allswap",
"(",
"self",
")",
":",
"all_swap_grad",
"=",
"_AllSwap",
"(",
"self",
".",
"group",
")",
"if",
"self",
".",
"instance_name",
":",
"instance_name",
"=",
"\"grad\"",
"+",
"self",
".",
"instance_name",
"all_swap_grad",
".",
"set_prim_i... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_comm_ops.py#L356-L367 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py | python | tixCommand.tix_cget | (self, option) | return self.tk.call('tix', 'cget', option) | Returns the current value of the configuration
option given by option. Option may be any of the
options described in the CONFIGURATION OPTIONS section. | Returns the current value of the configuration
option given by option. Option may be any of the
options described in the CONFIGURATION OPTIONS section. | [
"Returns",
"the",
"current",
"value",
"of",
"the",
"configuration",
"option",
"given",
"by",
"option",
".",
"Option",
"may",
"be",
"any",
"of",
"the",
"options",
"described",
"in",
"the",
"CONFIGURATION",
"OPTIONS",
"section",
"."
] | def tix_cget(self, option):
"""Returns the current value of the configuration
option given by option. Option may be any of the
options described in the CONFIGURATION OPTIONS section.
"""
return self.tk.call('tix', 'cget', option) | [
"def",
"tix_cget",
"(",
"self",
",",
"option",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"'tix'",
",",
"'cget'",
",",
"option",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py#L101-L106 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/extensions_native/Mat3_extensions.py | python | pPrintValues | (self) | return "\n%s\n%s\n%s" % (
self.getRow(0).pPrintValues(), self.getRow(1).pPrintValues(), self.getRow(2).pPrintValues()) | Pretty print | Pretty print | [
"Pretty",
"print"
] | def pPrintValues(self):
"""
Pretty print
"""
return "\n%s\n%s\n%s" % (
self.getRow(0).pPrintValues(), self.getRow(1).pPrintValues(), self.getRow(2).pPrintValues()) | [
"def",
"pPrintValues",
"(",
"self",
")",
":",
"return",
"\"\\n%s\\n%s\\n%s\"",
"%",
"(",
"self",
".",
"getRow",
"(",
"0",
")",
".",
"pPrintValues",
"(",
")",
",",
"self",
".",
"getRow",
"(",
"1",
")",
".",
"pPrintValues",
"(",
")",
",",
"self",
".",
... | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/extensions_native/Mat3_extensions.py#L14-L19 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/saved_model/save.py | python | _verify_ops | (graph_def, namespace_whitelist) | Verifies that all namespaced ops in the graph are whitelisted.
Args:
graph_def: the GraphDef to validate.
namespace_whitelist: a list of namespaces to allow. If `None`, all will be
allowed. If an op does not have a namespace, it will be allowed.
Raises:
ValueError: If the graph contains ops that violate the whitelist. | Verifies that all namespaced ops in the graph are whitelisted. | [
"Verifies",
"that",
"all",
"namespaced",
"ops",
"in",
"the",
"graph",
"are",
"whitelisted",
"."
] | def _verify_ops(graph_def, namespace_whitelist):
"""Verifies that all namespaced ops in the graph are whitelisted.
Args:
graph_def: the GraphDef to validate.
namespace_whitelist: a list of namespaces to allow. If `None`, all will be
allowed. If an op does not have a namespace, it will be allowed.
Raises:
ValueError: If the graph contains ops that violate the whitelist.
"""
# By default, if the user has not specified a whitelist, we want to allow
# everything. We check for None directly rather than falseness, since the
# user may instead want to pass an empty list to disallow all custom
# namespaced ops.
if namespace_whitelist is None:
return
invalid_ops = []
invalid_namespaces = set()
all_operations = []
all_operations.extend(meta_graph.ops_used_by_graph_def(graph_def))
for op in all_operations:
if ">" in op:
namespace = op.split(">")[0]
if namespace not in namespace_whitelist:
invalid_ops.append(op)
invalid_namespaces.add(namespace)
if invalid_ops:
raise ValueError(
"Attempted to save ops from non-whitelisted namespaces to SavedModel: "
f"{invalid_ops}.\nPlease verify that these ops should be saved, since "
"they must be available when loading the SavedModel. If loading from "
"Python, you must import the library defining these ops. From C++, "
"link the custom ops to the serving binary. Once you've confirmed this,"
" add the following namespaces to the `namespace_whitelist` "
f"argument in tf.saved_model.SaveOptions: {invalid_namespaces}.") | [
"def",
"_verify_ops",
"(",
"graph_def",
",",
"namespace_whitelist",
")",
":",
"# By default, if the user has not specified a whitelist, we want to allow",
"# everything. We check for None directly rather than falseness, since the",
"# user may instead want to pass an empty list to disallow all ... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/save.py#L994-L1032 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/model/DrillModel.py | python | DrillModel.getAcquisitionMode | (self) | return self.acquisitionMode | Get the current acquisition mode.
Returns:
str: the acquisition mode | Get the current acquisition mode. | [
"Get",
"the",
"current",
"acquisition",
"mode",
"."
] | def getAcquisitionMode(self):
"""
Get the current acquisition mode.
Returns:
str: the acquisition mode
"""
return self.acquisitionMode | [
"def",
"getAcquisitionMode",
"(",
"self",
")",
":",
"return",
"self",
".",
"acquisitionMode"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/model/DrillModel.py#L195-L202 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/layers/python/layers/embedding_ops.py | python | embedding_lookup_unique | (params, ids, name=None) | Version of embedding_lookup that avoids duplicate lookups.
This can save communication in the case of repeated ids.
Same interface as embedding_lookup. Except it supports multi-dimensional `ids`
which allows to not reshape input/output to fit gather.
Args:
params: A list of tensors with the same shape and type, or a
`PartitionedVariable`. Shape `[index, d1, d2, ...]`.
ids: A one-dimensional `Tensor` with type `int32` or `int64` containing
the ids to be looked up in `params`. Shape `[ids1, ids2, ...]`.
name: A name for this operation (optional).
Returns:
A `Tensor` with the same type as the tensors in `params` and dimension of
`[ids1, ids2, d1, d2, ...]`.
Raises:
ValueError: If `params` is empty. | Version of embedding_lookup that avoids duplicate lookups. | [
"Version",
"of",
"embedding_lookup",
"that",
"avoids",
"duplicate",
"lookups",
"."
] | def embedding_lookup_unique(params, ids, name=None):
"""Version of embedding_lookup that avoids duplicate lookups.
This can save communication in the case of repeated ids.
Same interface as embedding_lookup. Except it supports multi-dimensional `ids`
which allows to not reshape input/output to fit gather.
Args:
params: A list of tensors with the same shape and type, or a
`PartitionedVariable`. Shape `[index, d1, d2, ...]`.
ids: A one-dimensional `Tensor` with type `int32` or `int64` containing
the ids to be looked up in `params`. Shape `[ids1, ids2, ...]`.
name: A name for this operation (optional).
Returns:
A `Tensor` with the same type as the tensors in `params` and dimension of
`[ids1, ids2, d1, d2, ...]`.
Raises:
ValueError: If `params` is empty.
"""
with ops.name_scope(name, "EmbeddingLookupUnique", [params, ids]):
ids = ops.convert_to_tensor(ids)
shape = array_ops.shape(ids)
ids_flat = array_ops.reshape(
ids, math_ops.reduce_prod(shape, keep_dims=True))
unique_ids, idx = array_ops.unique(ids_flat)
unique_embeddings = embedding_ops.embedding_lookup(params, unique_ids)
embeds_flat = array_ops.gather(unique_embeddings, idx)
embed_shape = array_ops.concat(
[shape, array_ops.shape(unique_embeddings)[1:]], 0)
embeds = array_ops.reshape(embeds_flat, embed_shape)
embeds.set_shape(ids.get_shape().concatenate(
unique_embeddings.get_shape()[1:]))
return embeds | [
"def",
"embedding_lookup_unique",
"(",
"params",
",",
"ids",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"EmbeddingLookupUnique\"",
",",
"[",
"params",
",",
"ids",
"]",
")",
":",
"ids",
"=",
"ops",
".",
"co... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/layers/python/layers/embedding_ops.py#L448-L482 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/conv_utils.py | python | conv_output_shape | (input_shape, kernel_shape, strides, padding) | return output_shape | Return the output shape of an N-D convolution.
Forces dimensions where input is empty (size 0) to remain empty.
Args:
input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the
input.
kernel_shape: tuple of size N, spatial shape of the convolutional kernel /
receptive field.
strides: tuple of size N, strides along each spatial dimension.
padding: type of padding, string `"same"` or `"valid"`.
Returns:
tuple of size N: `(d_out1, ..., d_outN)`, spatial shape of the output. | Return the output shape of an N-D convolution. | [
"Return",
"the",
"output",
"shape",
"of",
"an",
"N",
"-",
"D",
"convolution",
"."
] | def conv_output_shape(input_shape, kernel_shape, strides, padding):
"""Return the output shape of an N-D convolution.
Forces dimensions where input is empty (size 0) to remain empty.
Args:
input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the
input.
kernel_shape: tuple of size N, spatial shape of the convolutional kernel /
receptive field.
strides: tuple of size N, strides along each spatial dimension.
padding: type of padding, string `"same"` or `"valid"`.
Returns:
tuple of size N: `(d_out1, ..., d_outN)`, spatial shape of the output.
"""
dims = range(len(kernel_shape))
output_shape = [
conv_output_length(input_shape[d], kernel_shape[d], padding, strides[d])
for d in dims
]
output_shape = tuple(
[0 if input_shape[d] == 0 else output_shape[d] for d in dims])
return output_shape | [
"def",
"conv_output_shape",
"(",
"input_shape",
",",
"kernel_shape",
",",
"strides",
",",
"padding",
")",
":",
"dims",
"=",
"range",
"(",
"len",
"(",
"kernel_shape",
")",
")",
"output_shape",
"=",
"[",
"conv_output_length",
"(",
"input_shape",
"[",
"d",
"]",... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/conv_utils.py#L456-L479 | |
jiangxiluning/FOTS.PyTorch | b1851c170b4f1ad18406766352cb5171648ce603 | FOTS/data_loader/datautils.py | python | load_annoataion | (p) | load annotation from the text file
:param p:
:return: | load annotation from the text file
:param p:
:return: | [
"load",
"annotation",
"from",
"the",
"text",
"file",
":",
"param",
"p",
":",
":",
"return",
":"
] | def load_annoataion(p):
'''
load annotation from the text file
:param p:
:return:
'''
text_polys = []
text_tags = []
if not os.path.exists(p):
return np.array(text_polys, dtype = np.float32)
with open(p, 'r') as f:
reader = csv.reader(f)
for line in reader:
label = line[-1]
# strip BOM. \ufeff for python3, \xef\xbb\bf for python2
line = [i.strip('\ufeff').strip('\xef\xbb\xbf') for i in line]
x1, y1, x2, y2, x3, y3, x4, y4 = list(map(float, line[:8]))
text_polys.append([[x1, y1], [x2, y2], [x3, y3], [x4, y4]])
if label == '*' or label == '###':
text_tags.append(True)
else:
text_tags.append(False)
return np.array(text_polys, dtype = np.float32), np.array(text_tags, dtype = np.bool) | [
"def",
"load_annoataion",
"(",
"p",
")",
":",
"text_polys",
"=",
"[",
"]",
"text_tags",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"p",
")",
":",
"return",
"np",
".",
"array",
"(",
"text_polys",
",",
"dtype",
"=",
"np",
".... | https://github.com/jiangxiluning/FOTS.PyTorch/blob/b1851c170b4f1ad18406766352cb5171648ce603/FOTS/data_loader/datautils.py#L25-L48 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/framework/common_shapes.py | python | unchanged_shape_with_rank | (rank) | return _ShapeFunction | Returns a shape function for ops that constrain the rank of their input.
Args:
rank: The exact rank of the input and output.
Returns:
A shape function for ops that output a tensor of the same size as their
input, with a particular rank. | Returns a shape function for ops that constrain the rank of their input. | [
"Returns",
"a",
"shape",
"function",
"for",
"ops",
"that",
"constrain",
"the",
"rank",
"of",
"their",
"input",
"."
] | def unchanged_shape_with_rank(rank):
"""Returns a shape function for ops that constrain the rank of their input.
Args:
rank: The exact rank of the input and output.
Returns:
A shape function for ops that output a tensor of the same size as their
input, with a particular rank.
"""
def _ShapeFunction(op):
return [op.inputs[0].get_shape().with_rank(rank)]
return _ShapeFunction | [
"def",
"unchanged_shape_with_rank",
"(",
"rank",
")",
":",
"def",
"_ShapeFunction",
"(",
"op",
")",
":",
"return",
"[",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"rank",
")",
"]",
"return",
"_ShapeFunction"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/common_shapes.py#L33-L47 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | chrome/common/extensions/docs/examples/apps/hello-python/httplib2/__init__.py | python | Http.add_certificate | (self, key, cert, domain) | Add a key and cert that will be used
any time a request requires authentication. | Add a key and cert that will be used
any time a request requires authentication. | [
"Add",
"a",
"key",
"and",
"cert",
"that",
"will",
"be",
"used",
"any",
"time",
"a",
"request",
"requires",
"authentication",
"."
] | def add_certificate(self, key, cert, domain):
"""Add a key and cert that will be used
any time a request requires authentication."""
self.certificates.add(key, cert, domain) | [
"def",
"add_certificate",
"(",
"self",
",",
"key",
",",
"cert",
",",
"domain",
")",
":",
"self",
".",
"certificates",
".",
"add",
"(",
"key",
",",
"cert",
",",
"domain",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/common/extensions/docs/examples/apps/hello-python/httplib2/__init__.py#L848-L851 | ||
Harick1/caffe-yolo | eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3 | python/caffe/io.py | python | Transformer.preprocess | (self, in_, data) | return caffe_in | Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net | Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature | [
"Format",
"input",
"for",
"Caffe",
":",
"-",
"convert",
"to",
"single",
"-",
"resize",
"to",
"input",
"dimensions",
"(",
"preserving",
"number",
"of",
"channels",
")",
"-",
"transpose",
"dimensions",
"to",
"K",
"x",
"H",
"x",
"W",
"-",
"reorder",
"channe... | def preprocess(self, in_, data):
"""
Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net
"""
self.__check_input(in_)
caffe_in = data.astype(np.float32, copy=False)
transpose = self.transpose.get(in_)
channel_swap = self.channel_swap.get(in_)
raw_scale = self.raw_scale.get(in_)
mean = self.mean.get(in_)
input_scale = self.input_scale.get(in_)
in_dims = self.inputs[in_][2:]
if caffe_in.shape[:2] != in_dims:
caffe_in = resize_image(caffe_in, in_dims)
if transpose is not None:
caffe_in = caffe_in.transpose(transpose)
if channel_swap is not None:
caffe_in = caffe_in[channel_swap, :, :]
if raw_scale is not None:
caffe_in *= raw_scale
if mean is not None:
caffe_in -= mean
if input_scale is not None:
caffe_in *= input_scale
return caffe_in | [
"def",
"preprocess",
"(",
"self",
",",
"in_",
",",
"data",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"caffe_in",
"=",
"data",
".",
"astype",
"(",
"np",
".",
"float32",
",",
"copy",
"=",
"False",
")",
"transpose",
"=",
"self",
".",
"t... | https://github.com/Harick1/caffe-yolo/blob/eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3/python/caffe/io.py#L122-L162 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/cli/curses_widgets.py | python | CursesNavigationHistory.render | (self,
max_length,
backward_command,
forward_command,
latest_command_attribute="black_on_white",
old_command_attribute="magenta_on_white") | return debugger_cli_common.rich_text_lines_from_rich_line_list([output]) | Render the rich text content of the single-line navigation bar.
Args:
max_length: (`int`) Maximum length of the navigation bar, in characters.
backward_command: (`str`) command for going backward. Used to construct
the shortcut menu item.
forward_command: (`str`) command for going forward. Used to construct the
shortcut menu item.
latest_command_attribute: font attribute for lastest command.
old_command_attribute: font attribute for old (non-latest) command.
Returns:
(`debugger_cli_common.RichTextLines`) the navigation bar text with
attributes. | Render the rich text content of the single-line navigation bar. | [
"Render",
"the",
"rich",
"text",
"content",
"of",
"the",
"single",
"-",
"line",
"navigation",
"bar",
"."
] | def render(self,
max_length,
backward_command,
forward_command,
latest_command_attribute="black_on_white",
old_command_attribute="magenta_on_white"):
"""Render the rich text content of the single-line navigation bar.
Args:
max_length: (`int`) Maximum length of the navigation bar, in characters.
backward_command: (`str`) command for going backward. Used to construct
the shortcut menu item.
forward_command: (`str`) command for going forward. Used to construct the
shortcut menu item.
latest_command_attribute: font attribute for lastest command.
old_command_attribute: font attribute for old (non-latest) command.
Returns:
(`debugger_cli_common.RichTextLines`) the navigation bar text with
attributes.
"""
output = RL("| ")
output += RL(
self.BACK_ARROW_TEXT,
(debugger_cli_common.MenuItem(None, backward_command)
if self.can_go_back() else None))
output += RL(" ")
output += RL(
self.FORWARD_ARROW_TEXT,
(debugger_cli_common.MenuItem(None, forward_command)
if self.can_go_forward() else None))
if self._items:
command_attribute = (latest_command_attribute
if (self._pointer == (len(self._items) - 1))
else old_command_attribute)
output += RL(" | ")
if self._pointer != len(self._items) - 1:
output += RL("(-%d) " % (len(self._items) - 1 - self._pointer),
command_attribute)
if len(output) < max_length:
maybe_truncated_command = self._items[self._pointer].command[
:(max_length - len(output))]
output += RL(maybe_truncated_command, command_attribute)
return debugger_cli_common.rich_text_lines_from_rich_line_list([output]) | [
"def",
"render",
"(",
"self",
",",
"max_length",
",",
"backward_command",
",",
"forward_command",
",",
"latest_command_attribute",
"=",
"\"black_on_white\"",
",",
"old_command_attribute",
"=",
"\"magenta_on_white\"",
")",
":",
"output",
"=",
"RL",
"(",
"\"| \"",
")"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/cli/curses_widgets.py#L151-L198 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | clang/tools/scan-build-py/libscanbuild/report.py | python | assemble_cover | (args, prefix, fragments) | Put together the fragments into a final report. | Put together the fragments into a final report. | [
"Put",
"together",
"the",
"fragments",
"into",
"a",
"final",
"report",
"."
] | def assemble_cover(args, prefix, fragments):
""" Put together the fragments into a final report. """
import getpass
import socket
if args.html_title is None:
args.html_title = os.path.basename(prefix) + ' - analyzer results'
with open(os.path.join(args.output, 'index.html'), 'w') as handle:
indent = 0
handle.write(reindent("""
|<!DOCTYPE html>
|<html>
| <head>
| <title>{html_title}</title>
| <link type="text/css" rel="stylesheet" href="scanview.css"/>
| <script type='text/javascript' src="sorttable.js"></script>
| <script type='text/javascript' src='selectable.js'></script>
| </head>""", indent).format(html_title=args.html_title))
handle.write(comment('SUMMARYENDHEAD'))
handle.write(reindent("""
| <body>
| <h1>{html_title}</h1>
| <table>
| <tr><th>User:</th><td>{user_name}@{host_name}</td></tr>
| <tr><th>Working Directory:</th><td>{current_dir}</td></tr>
| <tr><th>Command Line:</th><td>{cmd_args}</td></tr>
| <tr><th>Clang Version:</th><td>{clang_version}</td></tr>
| <tr><th>Date:</th><td>{date}</td></tr>
| </table>""", indent).format(html_title=args.html_title,
user_name=getpass.getuser(),
host_name=socket.gethostname(),
current_dir=prefix,
cmd_args=' '.join(sys.argv),
clang_version=get_version(args.clang),
date=datetime.datetime.today(
).strftime('%c')))
for fragment in fragments:
# copy the content of fragments
with open(fragment, 'r') as input_handle:
shutil.copyfileobj(input_handle, handle)
handle.write(reindent("""
| </body>
|</html>""", indent)) | [
"def",
"assemble_cover",
"(",
"args",
",",
"prefix",
",",
"fragments",
")",
":",
"import",
"getpass",
"import",
"socket",
"if",
"args",
".",
"html_title",
"is",
"None",
":",
"args",
".",
"html_title",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"prefix... | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/tools/scan-build-py/libscanbuild/report.py#L63-L107 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | StatusBar.GetBorderY | (*args, **kwargs) | return _windows_.StatusBar_GetBorderY(*args, **kwargs) | GetBorderY(self) -> int | GetBorderY(self) -> int | [
"GetBorderY",
"(",
"self",
")",
"-",
">",
"int"
] | def GetBorderY(*args, **kwargs):
"""GetBorderY(self) -> int"""
return _windows_.StatusBar_GetBorderY(*args, **kwargs) | [
"def",
"GetBorderY",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"StatusBar_GetBorderY",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L1291-L1293 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/ext/django2jinja/django2jinja.py | python | Writer.start_variable | (self) | Start a variable. | Start a variable. | [
"Start",
"a",
"variable",
"."
] | def start_variable(self):
"""Start a variable."""
self.write(self.variable_start_string)
self._post_open() | [
"def",
"start_variable",
"(",
"self",
")",
":",
"self",
".",
"write",
"(",
"self",
".",
"variable_start_string",
")",
"self",
".",
"_post_open",
"(",
")"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/ext/django2jinja/django2jinja.py#L224-L227 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py | python | Decimal._isnan | (self) | return 0 | Returns whether the number is not actually one.
0 if a number
1 if NaN
2 if sNaN | Returns whether the number is not actually one. | [
"Returns",
"whether",
"the",
"number",
"is",
"not",
"actually",
"one",
"."
] | def _isnan(self):
"""Returns whether the number is not actually one.
0 if a number
1 if NaN
2 if sNaN
"""
if self._is_special:
exp = self._exp
if exp == 'n':
return 1
elif exp == 'N':
return 2
return 0 | [
"def",
"_isnan",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_special",
":",
"exp",
"=",
"self",
".",
"_exp",
"if",
"exp",
"==",
"'n'",
":",
"return",
"1",
"elif",
"exp",
"==",
"'N'",
":",
"return",
"2",
"return",
"0"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L717-L730 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/roslaunch/src/roslaunch/pmon.py | python | shutdown_process_monitor | (process_monitor) | @param process_monitor: process monitor to kill
@type process_monitor: L{ProcessMonitor}
@return: True if process_monitor was successfully
shutdown. False if it could not be shutdown cleanly or if there is
a problem with process_monitor
parameter. shutdown_process_monitor() does not throw any exceptions
as this is shutdown-critical code.
@rtype: bool | [] | def shutdown_process_monitor(process_monitor):
"""
@param process_monitor: process monitor to kill
@type process_monitor: L{ProcessMonitor}
@return: True if process_monitor was successfully
shutdown. False if it could not be shutdown cleanly or if there is
a problem with process_monitor
parameter. shutdown_process_monitor() does not throw any exceptions
as this is shutdown-critical code.
@rtype: bool
"""
try:
if process_monitor is None or process_monitor.is_shutdown:
return False
# I've decided to comment out use of logger until after
# critical section is done, just in case logger is already
# being torn down
#logger.debug("shutdown_process_monitor: shutting down ProcessMonitor")
process_monitor.shutdown()
#logger.debug("shutdown_process_monitor: joining ProcessMonitor")
process_monitor.join(20.0)
if process_monitor.isAlive():
logger.error("shutdown_process_monitor: ProcessMonitor shutdown failed!")
return False
else:
logger.debug("shutdown_process_monitor: ProcessMonitor shutdown succeeded")
return True
except Exception as e:
print("exception in shutdown_process_monitor: %s" % e, file=sys.stderr)
traceback.print_exc()
return False | [
"def",
"shutdown_process_monitor",
"(",
"process_monitor",
")",
":",
"try",
":",
"if",
"process_monitor",
"is",
"None",
"or",
"process_monitor",
".",
"is_shutdown",
":",
"return",
"False",
"# I've decided to comment out use of logger until after",
"# critical section is done,... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/pmon.py#L93-L125 | |||
tensorflow/io | 92b44e180674a8af0e12e405530f7343e3e693e4 | tensorflow_io/python/experimental/text_ops.py | python | re2_full_match | (input, pattern) | return core_ops.io_re2_full_match(input, pattern) | Extract regex groups
Args:
input: A `tf.string` tensor
pattern: A pattern string. | Extract regex groups | [
"Extract",
"regex",
"groups"
] | def re2_full_match(input, pattern): # pylint: disable=redefined-builtin
"""Extract regex groups
Args:
input: A `tf.string` tensor
pattern: A pattern string.
"""
return core_ops.io_re2_full_match(input, pattern) | [
"def",
"re2_full_match",
"(",
"input",
",",
"pattern",
")",
":",
"# pylint: disable=redefined-builtin",
"return",
"core_ops",
".",
"io_re2_full_match",
"(",
"input",
",",
"pattern",
")"
] | https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/experimental/text_ops.py#L41-L48 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/sparse_grad.py | python | _SparseReorderGrad | (op, unused_output_indices_grad, output_values_grad) | return (None,
array_ops.gather(output_values_grad, inverted_permutation),
None) | Gradients for the SparseReorder op.
Args:
op: the SparseReorder op
unused_output_indices_grad: the incoming gradients of the output indices
output_values_grad: the incoming gradients of the output values
Returns:
Gradient for each of the 3 input tensors:
(input_indices, input_values, input_shape)
The gradients for input_indices and input_shape is None. | Gradients for the SparseReorder op. | [
"Gradients",
"for",
"the",
"SparseReorder",
"op",
"."
] | def _SparseReorderGrad(op, unused_output_indices_grad, output_values_grad):
"""Gradients for the SparseReorder op.
Args:
op: the SparseReorder op
unused_output_indices_grad: the incoming gradients of the output indices
output_values_grad: the incoming gradients of the output values
Returns:
Gradient for each of the 3 input tensors:
(input_indices, input_values, input_shape)
The gradients for input_indices and input_shape is None.
"""
input_indices = op.inputs[0]
input_shape = op.inputs[2]
num_entries = array_ops.shape(input_indices)[0]
entry_indices = math_ops.range(num_entries)
sp_unordered = sparse_tensor.SparseTensor(
input_indices, entry_indices, input_shape)
sp_ordered = sparse_ops.sparse_reorder(sp_unordered)
inverted_permutation = array_ops.invert_permutation(sp_ordered.values)
return (None,
array_ops.gather(output_values_grad, inverted_permutation),
None) | [
"def",
"_SparseReorderGrad",
"(",
"op",
",",
"unused_output_indices_grad",
",",
"output_values_grad",
")",
":",
"input_indices",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"input_shape",
"=",
"op",
".",
"inputs",
"[",
"2",
"]",
"num_entries",
"=",
"array_ops",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/sparse_grad.py#L37-L62 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TCnCom.Len | (self) | return _snap.TCnCom_Len(self) | Len(TCnCom self) -> int
Parameters:
self: TCnCom const * | Len(TCnCom self) -> int | [
"Len",
"(",
"TCnCom",
"self",
")",
"-",
">",
"int"
] | def Len(self):
"""
Len(TCnCom self) -> int
Parameters:
self: TCnCom const *
"""
return _snap.TCnCom_Len(self) | [
"def",
"Len",
"(",
"self",
")",
":",
"return",
"_snap",
".",
"TCnCom_Len",
"(",
"self",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L806-L814 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/gtk/gizmos.py | python | TreeListCtrl.SelectAll | (*args, **kwargs) | return _gizmos.TreeListCtrl_SelectAll(*args, **kwargs) | SelectAll(self) | SelectAll(self) | [
"SelectAll",
"(",
"self",
")"
] | def SelectAll(*args, **kwargs):
"""SelectAll(self)"""
return _gizmos.TreeListCtrl_SelectAll(*args, **kwargs) | [
"def",
"SelectAll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_SelectAll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/gtk/gizmos.py#L903-L905 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | models/AI-Model-Zoo/caffe-xilinx/examples/pycaffe/tools.py | python | SimpleTransformer.set_scale | (self, scale) | Set the data scaling. | Set the data scaling. | [
"Set",
"the",
"data",
"scaling",
"."
] | def set_scale(self, scale):
"""
Set the data scaling.
"""
self.scale = scale | [
"def",
"set_scale",
"(",
"self",
",",
"scale",
")",
":",
"self",
".",
"scale",
"=",
"scale"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/examples/pycaffe/tools.py#L21-L25 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc._substitute | (self, *args) | return (e,) | Internal function. | Internal function. | [
"Internal",
"function",
"."
] | def _substitute(self, *args):
"""Internal function."""
if len(args) != len(self._subst_format): return args
getboolean = self.tk.getboolean
getint = int
def getint_event(s):
"""Tk changed behavior in 8.4.2, returning "??" rather more often."""
try:
return int(s)
except ValueError:
return s
nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
# Missing: (a, c, d, m, o, v, B, R)
e = Event()
# serial field: valid vor all events
# number of button: ButtonPress and ButtonRelease events only
# height field: Configure, ConfigureRequest, Create,
# ResizeRequest, and Expose events only
# keycode field: KeyPress and KeyRelease events only
# time field: "valid for events that contain a time field"
# width field: Configure, ConfigureRequest, Create, ResizeRequest,
# and Expose events only
# x field: "valid for events that contain a x field"
# y field: "valid for events that contain a y field"
# keysym as decimal: KeyPress and KeyRelease events only
# x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
# KeyRelease,and Motion events
e.serial = getint(nsign)
e.num = getint_event(b)
try: e.focus = getboolean(f)
except TclError: pass
e.height = getint_event(h)
e.keycode = getint_event(k)
e.state = getint_event(s)
e.time = getint_event(t)
e.width = getint_event(w)
e.x = getint_event(x)
e.y = getint_event(y)
e.char = A
try: e.send_event = getboolean(E)
except TclError: pass
e.keysym = K
e.keysym_num = getint_event(N)
e.type = T
try:
e.widget = self._nametowidget(W)
except KeyError:
e.widget = W
e.x_root = getint_event(X)
e.y_root = getint_event(Y)
try:
e.delta = getint(D)
except ValueError:
e.delta = 0
return (e,) | [
"def",
"_substitute",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"len",
"(",
"self",
".",
"_subst_format",
")",
":",
"return",
"args",
"getboolean",
"=",
"self",
".",
"tk",
".",
"getboolean",
"getint",
"=",
"int",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1174-L1230 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Build.py | python | ListContext.execute | (self) | In addition to printing the name of each build target,
a description column will include text for each task
generator which has a "description" field set.
See :py:func:`waflib.Build.BuildContext.execute`. | In addition to printing the name of each build target,
a description column will include text for each task
generator which has a "description" field set. | [
"In",
"addition",
"to",
"printing",
"the",
"name",
"of",
"each",
"build",
"target",
"a",
"description",
"column",
"will",
"include",
"text",
"for",
"each",
"task",
"generator",
"which",
"has",
"a",
"description",
"field",
"set",
"."
] | def execute(self):
"""
In addition to printing the name of each build target,
a description column will include text for each task
generator which has a "description" field set.
See :py:func:`waflib.Build.BuildContext.execute`.
"""
self.restore()
if not self.all_envs:
self.load_envs()
self.recurse([self.run_dir])
self.pre_build()
# display the time elapsed in the progress bar
self.timer = Utils.Timer()
for g in self.groups:
for tg in g:
try:
f = tg.post
except AttributeError:
pass
else:
f()
try:
# force the cache initialization
self.get_tgen_by_name('')
except Errors.WafError:
pass
targets = sorted(self.task_gen_cache_names)
# figure out how much to left-justify, for largest target name
line_just = max(len(t) for t in targets) if targets else 0
for target in targets:
tgen = self.task_gen_cache_names[target]
# Support displaying the description for the target
# if it was set on the tgen
descript = getattr(tgen, 'description', '')
if descript:
target = target.ljust(line_just)
descript = ': %s' % descript
Logs.pprint('GREEN', target, label=descript) | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"restore",
"(",
")",
"if",
"not",
"self",
".",
"all_envs",
":",
"self",
".",
"load_envs",
"(",
")",
"self",
".",
"recurse",
"(",
"[",
"self",
".",
"run_dir",
"]",
")",
"self",
".",
"pre_build",
... | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Build.py#L1336-L1384 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/utils/telemetry_utils.py | python | get_tid | () | return telemetry_params['TID'] | This function returns the ID of the database to send telemetry. | This function returns the ID of the database to send telemetry. | [
"This",
"function",
"returns",
"the",
"ID",
"of",
"the",
"database",
"to",
"send",
"telemetry",
"."
] | def get_tid():
"""
This function returns the ID of the database to send telemetry.
"""
return telemetry_params['TID'] | [
"def",
"get_tid",
"(",
")",
":",
"return",
"telemetry_params",
"[",
"'TID'",
"]"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/utils/telemetry_utils.py#L96-L100 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/mac/symbolicate_crash.py | python | CrashReport._ParseSpindumpStack | (self, fd) | Parses a spindump stack report. In this format, each thread stack has
both a user and kernel trace. Only the user traces are symbolicated. | Parses a spindump stack report. In this format, each thread stack has
both a user and kernel trace. Only the user traces are symbolicated. | [
"Parses",
"a",
"spindump",
"stack",
"report",
".",
"In",
"this",
"format",
"each",
"thread",
"stack",
"has",
"both",
"a",
"user",
"and",
"kernel",
"trace",
".",
"Only",
"the",
"user",
"traces",
"are",
"symbolicated",
"."
] | def _ParseSpindumpStack(self, fd):
"""Parses a spindump stack report. In this format, each thread stack has
both a user and kernel trace. Only the user traces are symbolicated."""
# The stack trace begins with the thread header, which is identified by a
# HEX number. The thread names appear to be incorrect in spindumps.
user_thread_re = re.compile('^ Thread ([0-9a-fx]+)')
# When this method is called, the fd has been walked right up to the first
# line.
line = fd.readline()
in_user_stack = False
in_kernel_stack = False
thread = None
frame_id = 0
while user_thread_re.match(line) or in_user_stack or in_kernel_stack:
# Check for the start of a thread.
matches = user_thread_re.match(line)
if not line.strip():
# A blank line indicates the start of a new thread. The blank line comes
# after the kernel stack before a new thread header.
in_kernel_stack = False
elif matches:
# This is the start of a thread header. The next line is the heading for
# the user stack, followed by the actual trace.
thread = CrashThread(matches.group(1))
frame_id = 0
self.threads.append(thread)
in_user_stack = True
line = fd.readline() # Read past the 'User stack:' header.
elif line.startswith(' Kernel stack:'):
# The kernel stack header comes immediately after the last frame (really
# the top frame) in the user stack, without a blank line.
in_user_stack = False
in_kernel_stack = True
elif in_user_stack:
# If this is a line while in the user stack, parse it as a stack frame.
thread.stack.append(self._ParseSpindumpStackFrame(line))
# Loop with the next line.
line = fd.readline()
# When the loop exits, the file has been read through the 'Binary images:'
# header. Seek backwards so that _ParseBinaryImages() does the right thing.
fd.seek(-len(line), os.SEEK_CUR) | [
"def",
"_ParseSpindumpStack",
"(",
"self",
",",
"fd",
")",
":",
"# The stack trace begins with the thread header, which is identified by a",
"# HEX number. The thread names appear to be incorrect in spindumps.",
"user_thread_re",
"=",
"re",
".",
"compile",
"(",
"'^ Thread ([0-9a-fx]... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/mac/symbolicate_crash.py#L180-L224 | ||
enjalot/adventures_in_opencl | c222d15c076ee3f5f81b529eb47e87c8d8057096 | python/part2/initialize.py | python | fountain_np | (num) | return pos, col, vel | numpy way of initializing data using ufuncs instead of loops | numpy way of initializing data using ufuncs instead of loops | [
"numpy",
"way",
"of",
"initializing",
"data",
"using",
"ufuncs",
"instead",
"of",
"loops"
] | def fountain_np(num):
"""numpy way of initializing data using ufuncs instead of loops"""
import numpy
pos = numpy.ndarray((num, 4), dtype=numpy.float32)
col = numpy.ndarray((num, 4), dtype=numpy.float32)
vel = numpy.ndarray((num, 4), dtype=numpy.float32)
pos[:,0] = numpy.sin(numpy.arange(0., num) * 2.001 * numpy.pi / num)
pos[:,0] *= numpy.random.random_sample((num,)) / 3. + .2
pos[:,1] = numpy.cos(numpy.arange(0., num) * 2.001 * numpy.pi / num)
pos[:,1] *= numpy.random.random_sample((num,)) / 3. + .2
pos[:,2] = 0.
pos[:,3] = 1.
col[:,0] = 0.
col[:,1] = 1.
col[:,2] = 0.
col[:,3] = 1.
vel[:,0] = pos[:,0] * 2.
vel[:,1] = pos[:,1] * 2.
vel[:,2] = 3.
vel[:,3] = numpy.random.random_sample((num, ))
return pos, col, vel | [
"def",
"fountain_np",
"(",
"num",
")",
":",
"import",
"numpy",
"pos",
"=",
"numpy",
".",
"ndarray",
"(",
"(",
"num",
",",
"4",
")",
",",
"dtype",
"=",
"numpy",
".",
"float32",
")",
"col",
"=",
"numpy",
".",
"ndarray",
"(",
"(",
"num",
",",
"4",
... | https://github.com/enjalot/adventures_in_opencl/blob/c222d15c076ee3f5f81b529eb47e87c8d8057096/python/part2/initialize.py#L8-L32 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/dynamodb/conditions.py | python | AttributeBase.lte | (self, value) | return LessThanEquals(self, value) | Creates a condition where the attribute is less than or equal to the
value.
:param value: The value that the attribute is less than or equal to. | Creates a condition where the attribute is less than or equal to the
value. | [
"Creates",
"a",
"condition",
"where",
"the",
"attribute",
"is",
"less",
"than",
"or",
"equal",
"to",
"the",
"value",
"."
] | def lte(self, value):
"""Creates a condition where the attribute is less than or equal to the
value.
:param value: The value that the attribute is less than or equal to.
"""
return LessThanEquals(self, value) | [
"def",
"lte",
"(",
"self",
",",
"value",
")",
":",
"return",
"LessThanEquals",
"(",
"self",
",",
"value",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/dynamodb/conditions.py#L88-L94 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | PyPreviewFrame.CreateCanvas | (*args, **kwargs) | return _windows_.PyPreviewFrame_CreateCanvas(*args, **kwargs) | CreateCanvas(self) | CreateCanvas(self) | [
"CreateCanvas",
"(",
"self",
")"
] | def CreateCanvas(*args, **kwargs):
"""CreateCanvas(self)"""
return _windows_.PyPreviewFrame_CreateCanvas(*args, **kwargs) | [
"def",
"CreateCanvas",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PyPreviewFrame_CreateCanvas",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L5756-L5758 | |
mickem/nscp | 79f89fdbb6da63f91bc9dedb7aea202fe938f237 | scripts/python/lib/google/protobuf/internal/python_message.py | python | _AddListFieldsMethod | (message_descriptor, cls) | Helper for _AddMessageMethods(). | Helper for _AddMessageMethods(). | [
"Helper",
"for",
"_AddMessageMethods",
"()",
"."
] | def _AddListFieldsMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def ListFields(self):
all_fields = [item for item in self._fields.iteritems() if _IsPresent(item)]
all_fields.sort(key = lambda item: item[0].number)
return all_fields
cls.ListFields = ListFields | [
"def",
"_AddListFieldsMethod",
"(",
"message_descriptor",
",",
"cls",
")",
":",
"def",
"ListFields",
"(",
"self",
")",
":",
"all_fields",
"=",
"[",
"item",
"for",
"item",
"in",
"self",
".",
"_fields",
".",
"iteritems",
"(",
")",
"if",
"_IsPresent",
"(",
... | https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/internal/python_message.py#L550-L558 | ||
chatopera/clause | dee31153d5ffdef33deedb6bff03e7806c296968 | var/assets/clients/gen-py/clause/Serving.py | python | Client.getSlots | (self, request) | return self.recv_getSlots() | Parameters:
- request | Parameters:
- request | [
"Parameters",
":",
"-",
"request"
] | def getSlots(self, request):
"""
Parameters:
- request
"""
self.send_getSlots(request)
return self.recv_getSlots() | [
"def",
"getSlots",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"send_getSlots",
"(",
"request",
")",
"return",
"self",
".",
"recv_getSlots",
"(",
")"
] | https://github.com/chatopera/clause/blob/dee31153d5ffdef33deedb6bff03e7806c296968/var/assets/clients/gen-py/clause/Serving.py#L1312-L1319 | |
pytorch/xla | 93174035e8149d5d03cee446486de861f56493e1 | torch_xla/utils/utils.py | python | parallel_work | (num_workers, fn, *args) | Executes fn in parallel threads with args and returns result list.
Args:
num_workers: number of workers in thread pool to execute work.
fn: python function for each thread to execute.
*args: arguments used to call executor.map with.
Raises:
Exception: re-raises any exceptions that may have been raised by workers. | Executes fn in parallel threads with args and returns result list. | [
"Executes",
"fn",
"in",
"parallel",
"threads",
"with",
"args",
"and",
"returns",
"result",
"list",
"."
] | def parallel_work(num_workers, fn, *args):
"""Executes fn in parallel threads with args and returns result list.
Args:
num_workers: number of workers in thread pool to execute work.
fn: python function for each thread to execute.
*args: arguments used to call executor.map with.
Raises:
Exception: re-raises any exceptions that may have been raised by workers.
"""
with futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
results = executor.map(fn, *args)
return [res for res in results] | [
"def",
"parallel_work",
"(",
"num_workers",
",",
"fn",
",",
"*",
"args",
")",
":",
"with",
"futures",
".",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"num_workers",
")",
"as",
"executor",
":",
"results",
"=",
"executor",
".",
"map",
"(",
"fn",
",",
"... | https://github.com/pytorch/xla/blob/93174035e8149d5d03cee446486de861f56493e1/torch_xla/utils/utils.py#L280-L293 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | uCSIsKanbun | (code) | return ret | Check whether the character is part of Kanbun UCS Block | Check whether the character is part of Kanbun UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Kanbun",
"UCS",
"Block"
] | def uCSIsKanbun(code):
"""Check whether the character is part of Kanbun UCS Block """
ret = libxml2mod.xmlUCSIsKanbun(code)
return ret | [
"def",
"uCSIsKanbun",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsKanbun",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L2577-L2580 | |
dmlc/cxxnet | 9c58c278d129d0a275427cb5c989f75fff182c28 | wrapper/cxxnet.py | python | DataIter.get_data | (self) | return ctypes2numpyT(ret, [x for x in oshape], 'float32', ostride.value) | get current batch data | get current batch data | [
"get",
"current",
"batch",
"data"
] | def get_data(self):
"""get current batch data"""
oshape = (ctypes.c_uint * 4)()
ostride = ctypes.c_uint()
ret = cxnlib.CXNIOGetData(self.handle,
oshape, ctypes.byref(ostride))
return ctypes2numpyT(ret, [x for x in oshape], 'float32', ostride.value) | [
"def",
"get_data",
"(",
"self",
")",
":",
"oshape",
"=",
"(",
"ctypes",
".",
"c_uint",
"*",
"4",
")",
"(",
")",
"ostride",
"=",
"ctypes",
".",
"c_uint",
"(",
")",
"ret",
"=",
"cxnlib",
".",
"CXNIOGetData",
"(",
"self",
".",
"handle",
",",
"oshape",... | https://github.com/dmlc/cxxnet/blob/9c58c278d129d0a275427cb5c989f75fff182c28/wrapper/cxxnet.py#L93-L99 | |
trailofbits/sienna-locomotive | 09bc1a0bea7d7a33089422c62e0d3c715ecb7ce0 | sl2/harness/config.py | python | validate_config | () | Check the (argv-supplanted) configuration, making sure that
all required keys are present and that all keys satisfy their
invariants. | Check the (argv-supplanted) configuration, making sure that
all required keys are present and that all keys satisfy their
invariants. | [
"Check",
"the",
"(",
"argv",
"-",
"supplanted",
")",
"configuration",
"making",
"sure",
"that",
"all",
"required",
"keys",
"are",
"present",
"and",
"that",
"all",
"keys",
"satisfy",
"their",
"invariants",
"."
] | def validate_config():
"""
Check the (argv-supplanted) configuration, making sure that
all required keys are present and that all keys satisfy their
invariants.
"""
for key in CONFIG_SCHEMA:
# If the key is required but not present, fail loudly.
if CONFIG_SCHEMA[key]["required"] and key not in config:
print("ERROR: Missing required key:", key)
sys.exit()
# If they key is present but doesn't validate, fail loudly.
if key in config:
if not CONFIG_SCHEMA[key]["test"](config[key]):
print("ERROR: Failed to validate %s: expected %s" % (key, CONFIG_SCHEMA[key]["expected"]))
sys.exit() | [
"def",
"validate_config",
"(",
")",
":",
"for",
"key",
"in",
"CONFIG_SCHEMA",
":",
"# If the key is required but not present, fail loudly.",
"if",
"CONFIG_SCHEMA",
"[",
"key",
"]",
"[",
"\"required\"",
"]",
"and",
"key",
"not",
"in",
"config",
":",
"print",
"(",
... | https://github.com/trailofbits/sienna-locomotive/blob/09bc1a0bea7d7a33089422c62e0d3c715ecb7ce0/sl2/harness/config.py#L372-L387 | ||
jeog/TDAmeritradeAPI | 91c738afd7d57b54f6231170bd64c2550fafd34d | python/tdma_api/get.py | python | QuotesGetter.get_symbols | (self) | return clib.get_strs(self._abi('GetSymbols'), self._obj) | Returns list of symbols being used. | Returns list of symbols being used. | [
"Returns",
"list",
"of",
"symbols",
"being",
"used",
"."
] | def get_symbols(self):
"""Returns list of symbols being used."""
return clib.get_strs(self._abi('GetSymbols'), self._obj) | [
"def",
"get_symbols",
"(",
"self",
")",
":",
"return",
"clib",
".",
"get_strs",
"(",
"self",
".",
"_abi",
"(",
"'GetSymbols'",
")",
",",
"self",
".",
"_obj",
")"
] | https://github.com/jeog/TDAmeritradeAPI/blob/91c738afd7d57b54f6231170bd64c2550fafd34d/python/tdma_api/get.py#L289-L291 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Utilities/Scripts/SlicerWizard/TemplateManager.py | python | TemplateManager.parseArguments | (self, args) | Automatically add paths and keys from |CLI| arguments.
:param args.templatePath: List of additional template paths.
:type args.templatePath: :class:`list` of :class:`str`
:param args.templateKey: List of user-specified template key mappings.
:type args.templateKey: :class:`list` of :class:`str`
This parses template-related command line arguments and updates the
collection accordingly:
* Additional template paths are provided in the form
``'[category=]path'``, and are added with either :meth:`.addPath` (if
``category`` is omitted) or :meth:`.addCategoryPath` (otherwise).
* Template keys are provided in the form ``'name=value'``, and are
registered using :meth:`.setKey`.
If a usage error is found, the application is terminated by calling
:func:`~.Utilities.die` with an appropriate error message.
.. seealso:: :meth:`.parseArguments`, :meth:`.addPath`,
:meth:`.addCategoryPath`, :meth:`.setKey` | Automatically add paths and keys from |CLI| arguments. | [
"Automatically",
"add",
"paths",
"and",
"keys",
"from",
"|CLI|",
"arguments",
"."
] | def parseArguments(self, args):
"""Automatically add paths and keys from |CLI| arguments.
:param args.templatePath: List of additional template paths.
:type args.templatePath: :class:`list` of :class:`str`
:param args.templateKey: List of user-specified template key mappings.
:type args.templateKey: :class:`list` of :class:`str`
This parses template-related command line arguments and updates the
collection accordingly:
* Additional template paths are provided in the form
``'[category=]path'``, and are added with either :meth:`.addPath` (if
``category`` is omitted) or :meth:`.addCategoryPath` (otherwise).
* Template keys are provided in the form ``'name=value'``, and are
registered using :meth:`.setKey`.
If a usage error is found, the application is terminated by calling
:func:`~.Utilities.die` with an appropriate error message.
.. seealso:: :meth:`.parseArguments`, :meth:`.addPath`,
:meth:`.addCategoryPath`, :meth:`.setKey`
"""
# Add user-specified template paths
if args.templatePath is not None:
for tp in args.templatePath:
tpParts = tp.split("=", 1)
if len(tpParts) == 1:
if not os.path.exists(tp):
die("template path '%s' does not exist" % tp)
if not os.path.isdir(tp):
die("template path '%s' is not a directory" % tp)
self.addPath(tp)
else:
if tpParts[0].lower() not in _templateCategories:
die(("'%s' is not a recognized template category" % tpParts[0],
"recognized categories: %s" % ", ".join(_templateCategories)))
if not os.path.exists(tpParts[1]):
die("template path '%s' does not exist" % tpParts[1])
if not os.path.isdir(tpParts[1]):
die("template path '%s' is not a directory" % tpParts[1])
self.addCategoryPath(tpParts[0].lower(),
os.path.realpath(tpParts[1]))
# Set user-specified template keys
if args.templateKey is not None:
for tk in args.templateKey:
tkParts = tk.split("=")
if len(tkParts) != 2:
die("template key '%s' malformatted: expected 'NAME=KEY'" % tk)
self.setKey(tkParts[0].lower(), tkParts[1]) | [
"def",
"parseArguments",
"(",
"self",
",",
"args",
")",
":",
"# Add user-specified template paths",
"if",
"args",
".",
"templatePath",
"is",
"not",
"None",
":",
"for",
"tp",
"in",
"args",
".",
"templatePath",
":",
"tpParts",
"=",
"tp",
".",
"split",
"(",
"... | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Utilities/Scripts/SlicerWizard/TemplateManager.py#L340-L397 | ||
microsoft/clang | 86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5 | tools/scan-build-py/libscanbuild/report.py | python | commonprefix_from | (filename) | Create file prefix from a compilation database entries. | Create file prefix from a compilation database entries. | [
"Create",
"file",
"prefix",
"from",
"a",
"compilation",
"database",
"entries",
"."
] | def commonprefix_from(filename):
""" Create file prefix from a compilation database entries. """
with open(filename, 'r') as handle:
return commonprefix(item['file'] for item in json.load(handle)) | [
"def",
"commonprefix_from",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"handle",
":",
"return",
"commonprefix",
"(",
"item",
"[",
"'file'",
"]",
"for",
"item",
"in",
"json",
".",
"load",
"(",
"handle",
")",
")"
] | https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/tools/scan-build-py/libscanbuild/report.py#L482-L486 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Window.ScreenToClient | (*args, **kwargs) | return _core_.Window_ScreenToClient(*args, **kwargs) | ScreenToClient(self, Point pt) -> Point
Converts from screen to client window coordinates. | ScreenToClient(self, Point pt) -> Point | [
"ScreenToClient",
"(",
"self",
"Point",
"pt",
")",
"-",
">",
"Point"
] | def ScreenToClient(*args, **kwargs):
"""
ScreenToClient(self, Point pt) -> Point
Converts from screen to client window coordinates.
"""
return _core_.Window_ScreenToClient(*args, **kwargs) | [
"def",
"ScreenToClient",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_ScreenToClient",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L11072-L11078 | |
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | core/src/plugins/filed/python/pyfiles/BareosFdPluginLocalFileset.py | python | BareosFdPluginLocalFileset.start_backup_job | (self) | At this point, plugin options were passed and checked already.
We try to read from filename and setup the list of file to backup
in self.files_to_backup | At this point, plugin options were passed and checked already.
We try to read from filename and setup the list of file to backup
in self.files_to_backup | [
"At",
"this",
"point",
"plugin",
"options",
"were",
"passed",
"and",
"checked",
"already",
".",
"We",
"try",
"to",
"read",
"from",
"filename",
"and",
"setup",
"the",
"list",
"of",
"file",
"to",
"backup",
"in",
"self",
".",
"files_to_backup"
] | def start_backup_job(self):
"""
At this point, plugin options were passed and checked already.
We try to read from filename and setup the list of file to backup
in self.files_to_backup
"""
bareosfd.DebugMessage(
100,
"Using %s to search for local files\n" % self.options["filename"],
)
if os.path.exists(self.options["filename"]):
try:
config_file = open(self.options["filename"], "r")
except:
bareosfd.DebugMessage(
100,
"Could not open file %s\n" % (self.options["filename"]),
)
return bareosfd.bRC_Error
else:
bareosfd.DebugMessage(
100, "File %s does not exist\n" % (self.options["filename"])
)
return bareosfd.bRC_Error
# Check, if we have allow or deny regular expressions defined
if "allow" in self.options:
self.allow = re.compile(self.options["allow"])
if "deny" in self.options:
self.deny = re.compile(self.options["deny"])
for listItem in config_file.read().splitlines():
if os.path.isfile(listItem) and self.filename_is_allowed(
listItem, self.allow, self.deny
):
self.append_file_to_backup(listItem)
if os.path.isdir(listItem):
fullDirName = listItem
# FD requires / at the end of a directory name
if not fullDirName.endswith(tuple("/")):
fullDirName += "/"
self.append_file_to_backup(fullDirName)
for topdir, dirNames, fileNames in os.walk(listItem):
for fileName in fileNames:
if self.filename_is_allowed(
os.path.join(topdir, fileName),
self.allow,
self.deny,
):
self.append_file_to_backup(os.path.join(topdir, fileName))
for dirName in dirNames:
fullDirName = os.path.join(topdir, dirName) + "/"
self.append_file_to_backup(fullDirName)
bareosfd.DebugMessage(150, "Filelist: %s\n" % (self.files_to_backup))
if not self.files_to_backup:
bareosfd.JobMessage(
bareosfd.M_ERROR,
"No (allowed) files to backup found\n",
)
return bareosfd.bRC_Error
else:
return bareosfd.bRC_OK | [
"def",
"start_backup_job",
"(",
"self",
")",
":",
"bareosfd",
".",
"DebugMessage",
"(",
"100",
",",
"\"Using %s to search for local files\\n\"",
"%",
"self",
".",
"options",
"[",
"\"filename\"",
"]",
",",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"se... | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/core/src/plugins/filed/python/pyfiles/BareosFdPluginLocalFileset.py#L73-L134 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/_inner_ops.py | python | TensorCopySlices.__init__ | (self) | Initialize TensorScatterUpdate | Initialize TensorScatterUpdate | [
"Initialize",
"TensorScatterUpdate"
] | def __init__(self):
"""Initialize TensorScatterUpdate"""
self.init_prim_io_names(inputs=['x', 'value', 'begin', 'end', 'strides'], outputs=['y']) | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"init_prim_io_names",
"(",
"inputs",
"=",
"[",
"'x'",
",",
"'value'",
",",
"'begin'",
",",
"'end'",
",",
"'strides'",
"]",
",",
"outputs",
"=",
"[",
"'y'",
"]",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/_inner_ops.py#L1201-L1203 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/calendar.py | python | CalendarEvent.__init__ | (self, *args, **kwargs) | __init__(self, Window win, DateTime dt, EventType type) -> CalendarEvent | __init__(self, Window win, DateTime dt, EventType type) -> CalendarEvent | [
"__init__",
"(",
"self",
"Window",
"win",
"DateTime",
"dt",
"EventType",
"type",
")",
"-",
">",
"CalendarEvent"
] | def __init__(self, *args, **kwargs):
"""__init__(self, Window win, DateTime dt, EventType type) -> CalendarEvent"""
_calendar.CalendarEvent_swiginit(self,_calendar.new_CalendarEvent(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_calendar",
".",
"CalendarEvent_swiginit",
"(",
"self",
",",
"_calendar",
".",
"new_CalendarEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/calendar.py#L195-L197 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/strings.py | python | cat_safe | (list_of_columns: List, sep: str) | return result | Auxiliary function for :meth:`str.cat`.
Same signature as cat_core, but handles TypeErrors in concatenation, which
happen if the arrays in list_of columns have the wrong dtypes or content.
Parameters
----------
list_of_columns : list of numpy arrays
List of arrays to be concatenated with sep;
these arrays may not contain NaNs!
sep : string
The separator string for concatenating the columns.
Returns
-------
nd.array
The concatenation of list_of_columns with sep. | Auxiliary function for :meth:`str.cat`. | [
"Auxiliary",
"function",
"for",
":",
"meth",
":",
"str",
".",
"cat",
"."
] | def cat_safe(list_of_columns: List, sep: str):
"""
Auxiliary function for :meth:`str.cat`.
Same signature as cat_core, but handles TypeErrors in concatenation, which
happen if the arrays in list_of columns have the wrong dtypes or content.
Parameters
----------
list_of_columns : list of numpy arrays
List of arrays to be concatenated with sep;
these arrays may not contain NaNs!
sep : string
The separator string for concatenating the columns.
Returns
-------
nd.array
The concatenation of list_of_columns with sep.
"""
try:
result = cat_core(list_of_columns, sep)
except TypeError:
# if there are any non-string values (wrong dtype or hidden behind
# object dtype), np.sum will fail; catch and return with better message
for column in list_of_columns:
dtype = lib.infer_dtype(column, skipna=True)
if dtype not in ["string", "empty"]:
raise TypeError(
"Concatenation requires list-likes containing only "
"strings (or missing values). Offending values found in "
f"column {dtype}"
) from None
return result | [
"def",
"cat_safe",
"(",
"list_of_columns",
":",
"List",
",",
"sep",
":",
"str",
")",
":",
"try",
":",
"result",
"=",
"cat_core",
"(",
"list_of_columns",
",",
"sep",
")",
"except",
"TypeError",
":",
"# if there are any non-string values (wrong dtype or hidden behind"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/strings.py#L86-L119 | |
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/serial/rfc2217.py | python | Serial._telnet_read_loop | (self) | Read loop for the socket. | Read loop for the socket. | [
"Read",
"loop",
"for",
"the",
"socket",
"."
] | def _telnet_read_loop(self):
"""Read loop for the socket."""
mode = M_NORMAL
suboption = None
try:
while self.is_open:
try:
data = self._socket.recv(1024)
except socket.timeout:
# just need to get out of recv form time to time to check if
# still alive
continue
except socket.error as e:
# connection fails -> terminate loop
if self.logger:
self.logger.debug("socket error in reader thread: {}".format(e))
break
if not data:
break # lost connection
for byte in iterbytes(data):
if mode == M_NORMAL:
# interpret as command or as data
if byte == IAC:
mode = M_IAC_SEEN
else:
# store data in read buffer or sub option buffer
# depending on state
if suboption is not None:
suboption += byte
else:
self._read_buffer.put(byte)
elif mode == M_IAC_SEEN:
if byte == IAC:
# interpret as command doubled -> insert character
# itself
if suboption is not None:
suboption += IAC
else:
self._read_buffer.put(IAC)
mode = M_NORMAL
elif byte == SB:
# sub option start
suboption = bytearray()
mode = M_NORMAL
elif byte == SE:
# sub option end -> process it now
self._telnet_process_subnegotiation(bytes(suboption))
suboption = None
mode = M_NORMAL
elif byte in (DO, DONT, WILL, WONT):
# negotiation
telnet_command = byte
mode = M_NEGOTIATE
else:
# other telnet commands
self._telnet_process_command(byte)
mode = M_NORMAL
elif mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following
self._telnet_negotiate_option(telnet_command, byte)
mode = M_NORMAL
finally:
self._thread = None
if self.logger:
self.logger.debug("read thread terminated") | [
"def",
"_telnet_read_loop",
"(",
"self",
")",
":",
"mode",
"=",
"M_NORMAL",
"suboption",
"=",
"None",
"try",
":",
"while",
"self",
".",
"is_open",
":",
"try",
":",
"data",
"=",
"self",
".",
"_socket",
".",
"recv",
"(",
"1024",
")",
"except",
"socket",
... | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/rfc2217.py#L725-L788 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/backend.py | python | max | (x, axis=None, keepdims=False) | return math_ops.reduce_max(x, axis, keepdims) | Maximum value in a tensor.
Args:
x: A tensor or variable.
axis: An integer, the axis to find maximum values.
keepdims: A boolean, whether to keep the dimensions or not.
If `keepdims` is `False`, the rank of the tensor is reduced
by 1. If `keepdims` is `True`,
the reduced dimension is retained with length 1.
Returns:
A tensor with maximum values of `x`. | Maximum value in a tensor. | [
"Maximum",
"value",
"in",
"a",
"tensor",
"."
] | def max(x, axis=None, keepdims=False):
"""Maximum value in a tensor.
Args:
x: A tensor or variable.
axis: An integer, the axis to find maximum values.
keepdims: A boolean, whether to keep the dimensions or not.
If `keepdims` is `False`, the rank of the tensor is reduced
by 1. If `keepdims` is `True`,
the reduced dimension is retained with length 1.
Returns:
A tensor with maximum values of `x`.
"""
return math_ops.reduce_max(x, axis, keepdims) | [
"def",
"max",
"(",
"x",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"return",
"math_ops",
".",
"reduce_max",
"(",
"x",
",",
"axis",
",",
"keepdims",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L2282-L2296 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextBuffer.SetFontTable | (*args, **kwargs) | return _richtext.RichTextBuffer_SetFontTable(*args, **kwargs) | SetFontTable(self, RichTextFontTable table) | SetFontTable(self, RichTextFontTable table) | [
"SetFontTable",
"(",
"self",
"RichTextFontTable",
"table",
")"
] | def SetFontTable(*args, **kwargs):
"""SetFontTable(self, RichTextFontTable table)"""
return _richtext.RichTextBuffer_SetFontTable(*args, **kwargs) | [
"def",
"SetFontTable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_SetFontTable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2233-L2235 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/factorization/python/ops/gmm_ops.py | python | GmmAlgorithm._define_partial_maximization_operation | (self, shard_id, shard) | Computes the partial statistics of the means and covariances.
Args:
shard_id: current shard id.
shard: current data shard, 1 X num_examples X dimensions. | Computes the partial statistics of the means and covariances. | [
"Computes",
"the",
"partial",
"statistics",
"of",
"the",
"means",
"and",
"covariances",
"."
] | def _define_partial_maximization_operation(self, shard_id, shard):
"""Computes the partial statistics of the means and covariances.
Args:
shard_id: current shard id.
shard: current data shard, 1 X num_examples X dimensions.
"""
# Soft assignment of each data point to each of the two clusters.
self._points_in_k[shard_id] = math_ops.reduce_sum(
self._w[shard_id], 0, keep_dims=True)
# Partial means.
w_mul_x = array_ops.expand_dims(
math_ops.matmul(
self._w[shard_id], array_ops.squeeze(shard, [0]), transpose_a=True),
1)
self._w_mul_x.append(w_mul_x)
# Partial covariances.
x = array_ops.concat([shard for _ in range(self._num_classes)], 0)
x_trans = array_ops.transpose(x, perm=[0, 2, 1])
x_mul_w = array_ops.concat([
array_ops.expand_dims(x_trans[k, :, :] * self._w[shard_id][:, k], 0)
for k in range(self._num_classes)
], 0)
self._w_mul_x2.append(math_ops.matmul(x_mul_w, x)) | [
"def",
"_define_partial_maximization_operation",
"(",
"self",
",",
"shard_id",
",",
"shard",
")",
":",
"# Soft assignment of each data point to each of the two clusters.",
"self",
".",
"_points_in_k",
"[",
"shard_id",
"]",
"=",
"math_ops",
".",
"reduce_sum",
"(",
"self",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L368-L391 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/fancy_getopt.py | python | FancyGetopt.generate_help | (self, header=None) | return lines | Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object. | Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object. | [
"Generate",
"help",
"text",
"(",
"a",
"list",
"of",
"strings",
"one",
"per",
"suggested",
"line",
"of",
"output",
")",
"from",
"the",
"option",
"table",
"for",
"this",
"FancyGetopt",
"object",
"."
] | def generate_help (self, header=None):
"""Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object.
"""
# Blithely assume the option table is good: probably wouldn't call
# 'generate_help()' unless you've already called 'getopt()'.
# First pass: determine maximum length of long option names
max_opt = 0
for option in self.option_table:
long = option[0]
short = option[1]
l = len(long)
if long[-1] == '=':
l = l - 1
if short is not None:
l = l + 5 # " (-x)" where short == 'x'
if l > max_opt:
max_opt = l
opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
# Typical help block looks like this:
# --foo controls foonabulation
# Help block for longest option looks like this:
# --flimflam set the flim-flam level
# and with wrapped text:
# --flimflam set the flim-flam level (must be between
# 0 and 100, except on Tuesdays)
# Options with short names will have the short name shown (but
# it doesn't contribute to max_opt):
# --foo (-f) controls foonabulation
# If adding the short option would make the left column too wide,
# we push the explanation off to the next line
# --flimflam (-l)
# set the flim-flam level
# Important parameters:
# - 2 spaces before option block start lines
# - 2 dashes for each long option name
# - min. 2 spaces between option and explanation (gutter)
# - 5 characters (incl. space) for short option name
# Now generate lines of help text. (If 80 columns were good enough
# for Jesus, then 78 columns are good enough for me!)
line_width = 78
text_width = line_width - opt_width
big_indent = ' ' * opt_width
if header:
lines = [header]
else:
lines = ['Option summary:']
for option in self.option_table:
long, short, help = option[:3]
text = wrap_text(help, text_width)
if long[-1] == '=':
long = long[0:-1]
# Case 1: no short option at all (makes life easy)
if short is None:
if text:
lines.append(" --%-*s %s" % (max_opt, long, text[0]))
else:
lines.append(" --%-*s " % (max_opt, long))
# Case 2: we have a short option, so we have to include it
# just after the long option
else:
opt_names = "%s (-%s)" % (long, short)
if text:
lines.append(" --%-*s %s" %
(max_opt, opt_names, text[0]))
else:
lines.append(" --%-*s" % opt_names)
for l in text[1:]:
lines.append(big_indent + l)
# for self.option_table
return lines | [
"def",
"generate_help",
"(",
"self",
",",
"header",
"=",
"None",
")",
":",
"# Blithely assume the option table is good: probably wouldn't call",
"# 'generate_help()' unless you've already called 'getopt()'.",
"# First pass: determine maximum length of long option names",
"max_opt",
"=",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/fancy_getopt.py#L309-L389 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | src/mem/slicc/parser.py | python | SLICC.t_NUMBER | (self, t) | return t | r'[0-9]+ | r'[0-9]+ | [
"r",
"[",
"0",
"-",
"9",
"]",
"+"
] | def t_NUMBER(self, t):
r'[0-9]+'
try:
t.value = int(t.value)
except ValueError:
raise ParseError("Illegal number", t)
return t | [
"def",
"t_NUMBER",
"(",
"self",
",",
"t",
")",
":",
"try",
":",
"t",
".",
"value",
"=",
"int",
"(",
"t",
".",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ParseError",
"(",
"\"Illegal number\"",
",",
"t",
")",
"return",
"t"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/mem/slicc/parser.py#L213-L219 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/image_ops.py | python | flip_up_down | (image) | return array_ops.reverse(image, [True, False, False]) | Flip an image horizontally (upside down).
Outputs the contents of `image` flipped along the first dimension, which is
`height`.
See also `reverse()`.
Args:
image: A 3-D tensor of shape `[height, width, channels].`
Returns:
A 3-D tensor of the same type and shape as `image`.
Raises:
ValueError: if the shape of `image` not supported. | Flip an image horizontally (upside down). | [
"Flip",
"an",
"image",
"horizontally",
"(",
"upside",
"down",
")",
"."
] | def flip_up_down(image):
"""Flip an image horizontally (upside down).
Outputs the contents of `image` flipped along the first dimension, which is
`height`.
See also `reverse()`.
Args:
image: A 3-D tensor of shape `[height, width, channels].`
Returns:
A 3-D tensor of the same type and shape as `image`.
Raises:
ValueError: if the shape of `image` not supported.
"""
image = ops.convert_to_tensor(image, name='image')
_Check3DImage(image, require_static=False)
return array_ops.reverse(image, [True, False, False]) | [
"def",
"flip_up_down",
"(",
"image",
")",
":",
"image",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"image",
",",
"name",
"=",
"'image'",
")",
"_Check3DImage",
"(",
"image",
",",
"require_static",
"=",
"False",
")",
"return",
"array_ops",
".",
"reverse",
"(... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/image_ops.py#L367-L386 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/pexpect/pexpect.py | python | run | (command, timeout=-1, withexitstatus=False, events=None,
extra_args=None, logfile=None, cwd=None, env=None) | This function runs the given command; waits for it to finish; then
returns all output as a string. STDERR is included in output. If the full
path to the command is not given then the path is searched.
Note that lines are terminated by CR/LF (\\r\\n) combination even on
UNIX-like systems because this is the standard for pseudottys. If you set
'withexitstatus' to true, then run will return a tuple of (command_output,
exitstatus). If 'withexitstatus' is false then this returns just
command_output.
The run() function can often be used instead of creating a spawn instance.
For example, the following code uses spawn::
from pexpect import *
child = spawn('scp foo user@example.com:.')
child.expect('(?i)password')
child.sendline(mypassword)
The previous code can be replace with the following::
from pexpect import *
run('scp foo user@example.com:.', events={'(?i)password': mypassword})
Examples
========
Start the apache daemon on the local machine::
from pexpect import *
run("/usr/local/apache/bin/apachectl start")
Check in a file using SVN::
from pexpect import *
run("svn ci -m 'automatic commit' my_file.py")
Run a command and capture exit status::
from pexpect import *
(command_output, exitstatus) = run('ls -l /bin', withexitstatus=1)
Tricky Examples
===============
The following will run SSH and execute 'ls -l' on the remote machine. The
password 'secret' will be sent if the '(?i)password' pattern is ever seen::
run("ssh username@machine.example.com 'ls -l'",
events={'(?i)password':'secret\\n'})
This will start mencoder to rip a video from DVD. This will also display
progress ticks every 5 seconds as it runs. For example::
from pexpect import *
def print_ticks(d):
print d['event_count'],
run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
events={TIMEOUT:print_ticks}, timeout=5)
The 'events' argument should be a dictionary of patterns and responses.
Whenever one of the patterns is seen in the command out run() will send the
associated response string. Note that you should put newlines in your
string if Enter is necessary. The responses may also contain callback
functions. Any callback is function that takes a dictionary as an argument.
The dictionary contains all the locals from the run() function, so you can
access the child spawn object or any other variable defined in run()
(event_count, child, and extra_args are the most useful). A callback may
return True to stop the current run process otherwise run() continues until
the next event. A callback may also return a string which will be sent to
the child. 'extra_args' is not used by directly run(). It provides a way to
pass data to a callback function through run() through the locals
dictionary passed to a callback. | This function runs the given command; waits for it to finish; then
returns all output as a string. STDERR is included in output. If the full
path to the command is not given then the path is searched. | [
"This",
"function",
"runs",
"the",
"given",
"command",
";",
"waits",
"for",
"it",
"to",
"finish",
";",
"then",
"returns",
"all",
"output",
"as",
"a",
"string",
".",
"STDERR",
"is",
"included",
"in",
"output",
".",
"If",
"the",
"full",
"path",
"to",
"th... | def run(command, timeout=-1, withexitstatus=False, events=None,
extra_args=None, logfile=None, cwd=None, env=None):
"""
This function runs the given command; waits for it to finish; then
returns all output as a string. STDERR is included in output. If the full
path to the command is not given then the path is searched.
Note that lines are terminated by CR/LF (\\r\\n) combination even on
UNIX-like systems because this is the standard for pseudottys. If you set
'withexitstatus' to true, then run will return a tuple of (command_output,
exitstatus). If 'withexitstatus' is false then this returns just
command_output.
The run() function can often be used instead of creating a spawn instance.
For example, the following code uses spawn::
from pexpect import *
child = spawn('scp foo user@example.com:.')
child.expect('(?i)password')
child.sendline(mypassword)
The previous code can be replace with the following::
from pexpect import *
run('scp foo user@example.com:.', events={'(?i)password': mypassword})
Examples
========
Start the apache daemon on the local machine::
from pexpect import *
run("/usr/local/apache/bin/apachectl start")
Check in a file using SVN::
from pexpect import *
run("svn ci -m 'automatic commit' my_file.py")
Run a command and capture exit status::
from pexpect import *
(command_output, exitstatus) = run('ls -l /bin', withexitstatus=1)
Tricky Examples
===============
The following will run SSH and execute 'ls -l' on the remote machine. The
password 'secret' will be sent if the '(?i)password' pattern is ever seen::
run("ssh username@machine.example.com 'ls -l'",
events={'(?i)password':'secret\\n'})
This will start mencoder to rip a video from DVD. This will also display
progress ticks every 5 seconds as it runs. For example::
from pexpect import *
def print_ticks(d):
print d['event_count'],
run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
events={TIMEOUT:print_ticks}, timeout=5)
The 'events' argument should be a dictionary of patterns and responses.
Whenever one of the patterns is seen in the command out run() will send the
associated response string. Note that you should put newlines in your
string if Enter is necessary. The responses may also contain callback
functions. Any callback is function that takes a dictionary as an argument.
The dictionary contains all the locals from the run() function, so you can
access the child spawn object or any other variable defined in run()
(event_count, child, and extra_args are the most useful). A callback may
return True to stop the current run process otherwise run() continues until
the next event. A callback may also return a string which will be sent to
the child. 'extra_args' is not used by directly run(). It provides a way to
pass data to a callback function through run() through the locals
dictionary passed to a callback. """
if timeout == -1:
child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env)
else:
child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile,
cwd=cwd, env=env)
if events is not None:
patterns = list(events.keys())
responses = list(events.values())
else:
# This assumes EOF or TIMEOUT will eventually cause run to terminate.
patterns = None
responses = None
child_result_list = []
event_count = 0
while True:
try:
index = child.expect(patterns)
if type(child.after) in types.StringTypes:
child_result_list.append(child.before + child.after)
else:
# child.after may have been a TIMEOUT or EOF,
# which we don't want appended to the list.
child_result_list.append(child.before)
if type(responses[index]) in types.StringTypes:
child.send(responses[index])
elif isinstance(responses[index], types.FunctionType):
callback_result = responses[index](locals())
sys.stdout.flush()
if type(callback_result) in types.StringTypes:
child.send(callback_result)
elif callback_result:
break
else:
raise TypeError('The callback must be a string or function.')
event_count = event_count + 1
except TIMEOUT as e:
child_result_list.append(child.before)
break
except EOF as e:
child_result_list.append(child.before)
break
child_result = ''.join(child_result_list)
if withexitstatus:
child.close()
return (child_result, child.exitstatus)
else:
return child_result | [
"def",
"run",
"(",
"command",
",",
"timeout",
"=",
"-",
"1",
",",
"withexitstatus",
"=",
"False",
",",
"events",
"=",
"None",
",",
"extra_args",
"=",
"None",
",",
"logfile",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/pexpect/pexpect.py#L151-L274 | ||
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/smtrace.py | python | Trace.get_registered_name | (cls, proxy, reggroup) | return proxy.SMProxy.GetSessionProxyManager().GetProxyName(reggroup, proxy.SMProxy) | Returns the registered name for `proxy` in the given `reggroup`. | Returns the registered name for `proxy` in the given `reggroup`. | [
"Returns",
"the",
"registered",
"name",
"for",
"proxy",
"in",
"the",
"given",
"reggroup",
"."
] | def get_registered_name(cls, proxy, reggroup):
"""Returns the registered name for `proxy` in the given `reggroup`."""
return proxy.SMProxy.GetSessionProxyManager().GetProxyName(reggroup, proxy.SMProxy) | [
"def",
"get_registered_name",
"(",
"cls",
",",
"proxy",
",",
"reggroup",
")",
":",
"return",
"proxy",
".",
"SMProxy",
".",
"GetSessionProxyManager",
"(",
")",
".",
"GetProxyName",
"(",
"reggroup",
",",
"proxy",
".",
"SMProxy",
")"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/smtrace.py#L134-L136 | |
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/mac_tool.py | python | MacTool._CopyXIBFile | (self, source, dest) | return ibtoolout.returncode | Compiles a XIB file with ibtool into a binary plist in the bundle. | Compiles a XIB file with ibtool into a binary plist in the bundle. | [
"Compiles",
"a",
"XIB",
"file",
"with",
"ibtool",
"into",
"a",
"binary",
"plist",
"in",
"the",
"bundle",
"."
] | def _CopyXIBFile(self, source, dest):
"""Compiles a XIB file with ibtool into a binary plist in the bundle."""
# ibtool sometimes crashes with relative paths. See crbug.com/314728.
base = os.path.dirname(os.path.realpath(__file__))
if os.path.relpath(source):
source = os.path.join(base, source)
if os.path.relpath(dest):
dest = os.path.join(base, dest)
args = ['xcrun', 'ibtool', '--errors', '--warnings', '--notices']
if os.environ['XCODE_VERSION_ACTUAL'] > '0700':
args.extend(['--auto-activate-custom-fonts'])
if 'IPHONEOS_DEPLOYMENT_TARGET' in os.environ:
args.extend([
'--target-device', 'iphone', '--target-device', 'ipad',
'--minimum-deployment-target',
os.environ['IPHONEOS_DEPLOYMENT_TARGET'],
])
else:
args.extend([
'--target-device', 'mac',
'--minimum-deployment-target',
os.environ['MACOSX_DEPLOYMENT_TARGET'],
])
args.extend(['--output-format', 'human-readable-text', '--compile', dest,
source])
ibtool_section_re = re.compile(r'/\*.*\*/')
ibtool_re = re.compile(r'.*note:.*is clipping its content')
ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE)
current_section_header = None
for line in ibtoolout.stdout:
if ibtool_section_re.match(line):
current_section_header = line
elif not ibtool_re.match(line):
if current_section_header:
sys.stdout.write(current_section_header)
current_section_header = None
sys.stdout.write(line)
return ibtoolout.returncode | [
"def",
"_CopyXIBFile",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"# ibtool sometimes crashes with relative paths. See crbug.com/314728.",
"base",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",... | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/mac_tool.py#L72-L114 | |
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/utils/ipnetwork.py | python | contain_any_prefix | (prefix, ip_networks) | return any(is_subnet_of(prefix, net) for net in ip_networks) | Utility function to check if prefix contain any of the prefixes/ips
:returns: True if prefix contains any of the ip_networks else False | Utility function to check if prefix contain any of the prefixes/ips | [
"Utility",
"function",
"to",
"check",
"if",
"prefix",
"contain",
"any",
"of",
"the",
"prefixes",
"/",
"ips"
] | def contain_any_prefix(prefix, ip_networks) -> bool:
"""
Utility function to check if prefix contain any of the prefixes/ips
:returns: True if prefix contains any of the ip_networks else False
"""
if ip_networks is None:
return True
prefix = ipaddress.ip_network(prefix)
return any(is_subnet_of(prefix, net) for net in ip_networks) | [
"def",
"contain_any_prefix",
"(",
"prefix",
",",
"ip_networks",
")",
"->",
"bool",
":",
"if",
"ip_networks",
"is",
"None",
":",
"return",
"True",
"prefix",
"=",
"ipaddress",
".",
"ip_network",
"(",
"prefix",
")",
"return",
"any",
"(",
"is_subnet_of",
"(",
... | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/utils/ipnetwork.py#L235-L245 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/symbolizer/__init__.py | python | Symbolizer.execute | (self) | Work your magic.
:return: None | Work your magic. | [
"Work",
"your",
"magic",
"."
] | def execute(self) -> None:
"""
Work your magic.
:return: None
"""
if self.download_symbols_only:
self._get_compile_artifacts()
else:
self._setup_symbols()
self._parse_mongosymb_args()
LOGGER.info("Invoking mongosymb...")
mongosymb.main(self.mongosym_args) | [
"def",
"execute",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"download_symbols_only",
":",
"self",
".",
"_get_compile_artifacts",
"(",
")",
"else",
":",
"self",
".",
"_setup_symbols",
"(",
")",
"self",
".",
"_parse_mongosymb_args",
"(",
")",
"... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/symbolizer/__init__.py#L189-L202 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/pyhit/pyhit.py | python | Node.fullpath | (self) | return '/'.join(reversed(out)) | Return the node full path as a string. | Return the node full path as a string. | [
"Return",
"the",
"node",
"full",
"path",
"as",
"a",
"string",
"."
] | def fullpath(self):
"""
Return the node full path as a string.
"""
out = []
node = self
while (node is not None):
out.append(node.name)
node = node.parent
return '/'.join(reversed(out)) | [
"def",
"fullpath",
"(",
"self",
")",
":",
"out",
"=",
"[",
"]",
"node",
"=",
"self",
"while",
"(",
"node",
"is",
"not",
"None",
")",
":",
"out",
".",
"append",
"(",
"node",
".",
"name",
")",
"node",
"=",
"node",
".",
"parent",
"return",
"'/'",
... | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/pyhit/pyhit.py#L41-L50 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/util.py | python | parse_name_and_version | (p) | return d['name'].strip().lower(), d['ver'] | A utility method used to get name and version from a string.
From e.g. a Provides-Dist value.
:param p: A value in a form 'foo (1.0)'
:return: The name and version as a tuple. | A utility method used to get name and version from a string. | [
"A",
"utility",
"method",
"used",
"to",
"get",
"name",
"and",
"version",
"from",
"a",
"string",
"."
] | def parse_name_and_version(p):
"""
A utility method used to get name and version from a string.
From e.g. a Provides-Dist value.
:param p: A value in a form 'foo (1.0)'
:return: The name and version as a tuple.
"""
m = NAME_VERSION_RE.match(p)
if not m:
raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
d = m.groupdict()
return d['name'].strip().lower(), d['ver'] | [
"def",
"parse_name_and_version",
"(",
"p",
")",
":",
"m",
"=",
"NAME_VERSION_RE",
".",
"match",
"(",
"p",
")",
"if",
"not",
"m",
":",
"raise",
"DistlibException",
"(",
"'Ill-formed name/version string: \\'%s\\''",
"%",
"p",
")",
"d",
"=",
"m",
".",
"groupdic... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/util.py#L867-L880 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/util/runcommand.py | python | RunCommand.wait_for_process | (self) | return self.send_to_process() | Wait for a running processs to end and return stdout, stderr. | Wait for a running processs to end and return stdout, stderr. | [
"Wait",
"for",
"a",
"running",
"processs",
"to",
"end",
"and",
"return",
"stdout",
"stderr",
"."
] | def wait_for_process(self):
"""Wait for a running processs to end and return stdout, stderr."""
return self.send_to_process() | [
"def",
"wait_for_process",
"(",
"self",
")",
":",
"return",
"self",
".",
"send_to_process",
"(",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/util/runcommand.py#L82-L84 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/graphy/graphy/backends/google_chart_api/encoders.py | python | BaseChartEncoder._GetColors | (self, chart) | return util.JoinLists(color = colors) | Color series color parameter. | Color series color parameter. | [
"Color",
"series",
"color",
"parameter",
"."
] | def _GetColors(self, chart):
"""Color series color parameter."""
colors = []
for series in chart.data:
if not series.data:
continue
colors.append(series.style.color)
return util.JoinLists(color = colors) | [
"def",
"_GetColors",
"(",
"self",
",",
"chart",
")",
":",
"colors",
"=",
"[",
"]",
"for",
"series",
"in",
"chart",
".",
"data",
":",
"if",
"not",
"series",
".",
"data",
":",
"continue",
"colors",
".",
"append",
"(",
"series",
".",
"style",
".",
"co... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/graphy/graphy/backends/google_chart_api/encoders.py#L134-L141 | |
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/sarray.py | python | SArray.rolling_mean | (self, window_start, window_end, min_observations=None) | return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations)) | Calculate a new SArray of the mean of different subsets over this
SArray.
Also known as a "moving average" or "running average". The subset that
the mean is calculated over is defined as an inclusive range relative
to the position to each value in the SArray, using `window_start` and
`window_end`. For a better understanding of this, see the examples
below.
Parameters
----------
window_start : int
The start of the subset to calculate the mean relative to the
current value.
window_end : int
The end of the subset to calculate the mean relative to the current
value. Must be greater than `window_start`.
min_observations : int
Minimum number of non-missing observations in window required to
calculate the mean (otherwise result is None). None signifies that
the entire window must not include a missing value. A negative
number throws an error.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,4,5])
>>> series = pandas.Series([1,2,3,4,5])
A rolling mean with a window including the previous 2 entries including
the current:
>>> sa.rolling_mean(-2,0)
dtype: float
Rows: 5
[None, None, 2.0, 3.0, 4.0]
Pandas equivalent:
>>> pandas.rolling_mean(series, 3)
0 NaN
1 NaN
2 2
3 3
4 4
dtype: float64
Same rolling mean operation, but 2 minimum observations:
>>> sa.rolling_mean(-2,0,min_observations=2)
dtype: float
Rows: 5
[None, 1.5, 2.0, 3.0, 4.0]
Pandas equivalent:
>>> pandas.rolling_mean(series, 3, min_periods=2)
0 NaN
1 1.5
2 2.0
3 3.0
4 4.0
dtype: float64
A rolling mean with a size of 3, centered around the current:
>>> sa.rolling_mean(-1,1)
dtype: float
Rows: 5
[None, 2.0, 3.0, 4.0, None]
Pandas equivalent:
>>> pandas.rolling_mean(series, 3, center=True)
0 NaN
1 2
2 3
3 4
4 NaN
dtype: float64
A rolling mean with a window including the current and the 2 entries
following:
>>> sa.rolling_mean(0,2)
dtype: float
Rows: 5
[2.0, 3.0, 4.0, None, None]
A rolling mean with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_mean(-2,-1)
dtype: float
Rows: 5
[None, None, 1.5, 2.5, 3.5] | Calculate a new SArray of the mean of different subsets over this
SArray. | [
"Calculate",
"a",
"new",
"SArray",
"of",
"the",
"mean",
"of",
"different",
"subsets",
"over",
"this",
"SArray",
"."
] | def rolling_mean(self, window_start, window_end, min_observations=None):
"""
Calculate a new SArray of the mean of different subsets over this
SArray.
Also known as a "moving average" or "running average". The subset that
the mean is calculated over is defined as an inclusive range relative
to the position to each value in the SArray, using `window_start` and
`window_end`. For a better understanding of this, see the examples
below.
Parameters
----------
window_start : int
The start of the subset to calculate the mean relative to the
current value.
window_end : int
The end of the subset to calculate the mean relative to the current
value. Must be greater than `window_start`.
min_observations : int
Minimum number of non-missing observations in window required to
calculate the mean (otherwise result is None). None signifies that
the entire window must not include a missing value. A negative
number throws an error.
Returns
-------
out : SArray
Examples
--------
>>> import pandas
>>> sa = SArray([1,2,3,4,5])
>>> series = pandas.Series([1,2,3,4,5])
A rolling mean with a window including the previous 2 entries including
the current:
>>> sa.rolling_mean(-2,0)
dtype: float
Rows: 5
[None, None, 2.0, 3.0, 4.0]
Pandas equivalent:
>>> pandas.rolling_mean(series, 3)
0 NaN
1 NaN
2 2
3 3
4 4
dtype: float64
Same rolling mean operation, but 2 minimum observations:
>>> sa.rolling_mean(-2,0,min_observations=2)
dtype: float
Rows: 5
[None, 1.5, 2.0, 3.0, 4.0]
Pandas equivalent:
>>> pandas.rolling_mean(series, 3, min_periods=2)
0 NaN
1 1.5
2 2.0
3 3.0
4 4.0
dtype: float64
A rolling mean with a size of 3, centered around the current:
>>> sa.rolling_mean(-1,1)
dtype: float
Rows: 5
[None, 2.0, 3.0, 4.0, None]
Pandas equivalent:
>>> pandas.rolling_mean(series, 3, center=True)
0 NaN
1 2
2 3
3 4
4 NaN
dtype: float64
A rolling mean with a window including the current and the 2 entries
following:
>>> sa.rolling_mean(0,2)
dtype: float
Rows: 5
[2.0, 3.0, 4.0, None, None]
A rolling mean with a window including the previous 2 entries NOT
including the current:
>>> sa.rolling_mean(-2,-1)
dtype: float
Rows: 5
[None, None, 1.5, 2.5, 3.5]
"""
min_observations = self.__check_min_observations(min_observations)
agg_op = None
if self.dtype() is array.array:
agg_op = '__builtin__vector__avg__'
else:
agg_op = '__builtin__avg__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations)) | [
"def",
"rolling_mean",
"(",
"self",
",",
"window_start",
",",
"window_end",
",",
"min_observations",
"=",
"None",
")",
":",
"min_observations",
"=",
"self",
".",
"__check_min_observations",
"(",
"min_observations",
")",
"agg_op",
"=",
"None",
"if",
"self",
".",
... | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L3305-L3408 | |
OAID/Caffe-HRT | aae71e498ab842c6f92bcc23fc668423615a4d65 | python/caffe/detector.py | python | Detector.crop | (self, im, window) | return crop | Crop a window from the image for detection. Include surrounding context
according to the `context_pad` configuration.
Parameters
----------
im: H x W x K image ndarray to crop.
window: bounding box coordinates as ymin, xmin, ymax, xmax.
Returns
-------
crop: cropped window. | Crop a window from the image for detection. Include surrounding context
according to the `context_pad` configuration. | [
"Crop",
"a",
"window",
"from",
"the",
"image",
"for",
"detection",
".",
"Include",
"surrounding",
"context",
"according",
"to",
"the",
"context_pad",
"configuration",
"."
] | def crop(self, im, window):
"""
Crop a window from the image for detection. Include surrounding context
according to the `context_pad` configuration.
Parameters
----------
im: H x W x K image ndarray to crop.
window: bounding box coordinates as ymin, xmin, ymax, xmax.
Returns
-------
crop: cropped window.
"""
# Crop window from the image.
crop = im[window[0]:window[2], window[1]:window[3]]
if self.context_pad:
box = window.copy()
crop_size = self.blobs[self.inputs[0]].width # assumes square
scale = crop_size / (1. * crop_size - self.context_pad * 2)
# Crop a box + surrounding context.
half_h = (box[2] - box[0] + 1) / 2.
half_w = (box[3] - box[1] + 1) / 2.
center = (box[0] + half_h, box[1] + half_w)
scaled_dims = scale * np.array((-half_h, -half_w, half_h, half_w))
box = np.round(np.tile(center, 2) + scaled_dims)
full_h = box[2] - box[0] + 1
full_w = box[3] - box[1] + 1
scale_h = crop_size / full_h
scale_w = crop_size / full_w
pad_y = round(max(0, -box[0]) * scale_h) # amount out-of-bounds
pad_x = round(max(0, -box[1]) * scale_w)
# Clip box to image dimensions.
im_h, im_w = im.shape[:2]
box = np.clip(box, 0., [im_h, im_w, im_h, im_w])
clip_h = box[2] - box[0] + 1
clip_w = box[3] - box[1] + 1
assert(clip_h > 0 and clip_w > 0)
crop_h = round(clip_h * scale_h)
crop_w = round(clip_w * scale_w)
if pad_y + crop_h > crop_size:
crop_h = crop_size - pad_y
if pad_x + crop_w > crop_size:
crop_w = crop_size - pad_x
# collect with context padding and place in input
# with mean padding
context_crop = im[box[0]:box[2], box[1]:box[3]]
context_crop = caffe.io.resize_image(context_crop, (crop_h, crop_w))
crop = np.ones(self.crop_dims, dtype=np.float32) * self.crop_mean
crop[pad_y:(pad_y + crop_h), pad_x:(pad_x + crop_w)] = context_crop
return crop | [
"def",
"crop",
"(",
"self",
",",
"im",
",",
"window",
")",
":",
"# Crop window from the image.",
"crop",
"=",
"im",
"[",
"window",
"[",
"0",
"]",
":",
"window",
"[",
"2",
"]",
",",
"window",
"[",
"1",
"]",
":",
"window",
"[",
"3",
"]",
"]",
"if",... | https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/python/caffe/detector.py#L125-L179 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/selectionDataModel.py | python | _PrimSelection.getPrimPaths | (self) | return list(self._selection.keys()) | Get a list of paths that are at least partially selected. | Get a list of paths that are at least partially selected. | [
"Get",
"a",
"list",
"of",
"paths",
"that",
"are",
"at",
"least",
"partially",
"selected",
"."
] | def getPrimPaths(self):
"""Get a list of paths that are at least partially selected."""
return list(self._selection.keys()) | [
"def",
"getPrimPaths",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"_selection",
".",
"keys",
"(",
")",
")"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/selectionDataModel.py#L224-L227 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/ast.py | python | _Unparser.visit | (self, node) | return "".join(self._source) | Outputs a source code string that, if converted back to an ast
(using ast.parse) will generate an AST equivalent to *node* | Outputs a source code string that, if converted back to an ast
(using ast.parse) will generate an AST equivalent to *node* | [
"Outputs",
"a",
"source",
"code",
"string",
"that",
"if",
"converted",
"back",
"to",
"an",
"ast",
"(",
"using",
"ast",
".",
"parse",
")",
"will",
"generate",
"an",
"AST",
"equivalent",
"to",
"*",
"node",
"*"
] | def visit(self, node):
"""Outputs a source code string that, if converted back to an ast
(using ast.parse) will generate an AST equivalent to *node*"""
self._source = []
self.traverse(node)
return "".join(self._source) | [
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"_source",
"=",
"[",
"]",
"self",
".",
"traverse",
"(",
"node",
")",
"return",
"\"\"",
".",
"join",
"(",
"self",
".",
"_source",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ast.py#L797-L802 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_2_0_3.py | python | MiroInterpreter.do_rm | (self, line) | rm <name> -- Removes an item by name in the feed/playlist selected. | rm <name> -- Removes an item by name in the feed/playlist selected. | [
"rm",
"<name",
">",
"--",
"Removes",
"an",
"item",
"by",
"name",
"in",
"the",
"feed",
"/",
"playlist",
"selected",
"."
] | def do_rm(self, line):
"""rm <name> -- Removes an item by name in the feed/playlist selected."""
if self.selection_type is None:
print "Error: No feed/playlist selected"
return
item = self._find_item(line)
if item is None:
print "No item named %r" % line
return
if item.is_downloaded():
item.expire()
else:
print '%s is not downloaded' % item.get_title() | [
"def",
"do_rm",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"selection_type",
"is",
"None",
":",
"print",
"\"Error: No feed/playlist selected\"",
"return",
"item",
"=",
"self",
".",
"_find_item",
"(",
"line",
")",
"if",
"item",
"is",
"None",
":"... | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_2_0_3.py#L653-L665 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/registry.py | python | Registry.lookup | (self, name) | Looks up "name".
Args:
name: a string specifying the registry key for the candidate.
Returns:
Registered object if found
Raises:
LookupError: if "name" has not been registered. | Looks up "name". | [
"Looks",
"up",
"name",
"."
] | def lookup(self, name):
"""Looks up "name".
Args:
name: a string specifying the registry key for the candidate.
Returns:
Registered object if found
Raises:
LookupError: if "name" has not been registered.
"""
name = compat.as_str(name)
if name in self._registry:
return self._registry[name][_TYPE_TAG]
else:
raise LookupError(
"%s registry has no entry for: %s" % (self._name, name)) | [
"def",
"lookup",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"compat",
".",
"as_str",
"(",
"name",
")",
"if",
"name",
"in",
"self",
".",
"_registry",
":",
"return",
"self",
".",
"_registry",
"[",
"name",
"]",
"[",
"_TYPE_TAG",
"]",
"else",
":"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/registry.py#L82-L97 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | TextEntryBase.CanPaste | (*args, **kwargs) | return _core_.TextEntryBase_CanPaste(*args, **kwargs) | CanPaste(self) -> bool
Returns True if the text field is editable and there is text on the
clipboard that can be pasted into the text field. | CanPaste(self) -> bool | [
"CanPaste",
"(",
"self",
")",
"-",
">",
"bool"
] | def CanPaste(*args, **kwargs):
"""
CanPaste(self) -> bool
Returns True if the text field is editable and there is text on the
clipboard that can be pasted into the text field.
"""
return _core_.TextEntryBase_CanPaste(*args, **kwargs) | [
"def",
"CanPaste",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"TextEntryBase_CanPaste",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13202-L13209 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | PyDataViewVirtualListModel._setCallbackInfo | (*args, **kwargs) | return _dataview.PyDataViewVirtualListModel__setCallbackInfo(*args, **kwargs) | _setCallbackInfo(self, PyObject self, PyObject _class) | _setCallbackInfo(self, PyObject self, PyObject _class) | [
"_setCallbackInfo",
"(",
"self",
"PyObject",
"self",
"PyObject",
"_class",
")"
] | def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _dataview.PyDataViewVirtualListModel__setCallbackInfo(*args, **kwargs) | [
"def",
"_setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"PyDataViewVirtualListModel__setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1091-L1093 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/distribution/logistic.py | python | Logistic._entropy | (self, loc=None, scale=None) | return self.log(scale) + 2. | r"""
Evaluate entropy.
.. math::
H(X) = \log(scale) + 2. | r"""
Evaluate entropy. | [
"r",
"Evaluate",
"entropy",
"."
] | def _entropy(self, loc=None, scale=None):
r"""
Evaluate entropy.
.. math::
H(X) = \log(scale) + 2.
"""
loc, scale = self._check_param_type(loc, scale)
return self.log(scale) + 2. | [
"def",
"_entropy",
"(",
"self",
",",
"loc",
"=",
"None",
",",
"scale",
"=",
"None",
")",
":",
"loc",
",",
"scale",
"=",
"self",
".",
"_check_param_type",
"(",
"loc",
",",
"scale",
")",
"return",
"self",
".",
"log",
"(",
"scale",
")",
"+",
"2."
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/logistic.py#L262-L270 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tempfile.py | python | mkdtemp | (suffix=None, prefix=None, dir=None) | User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, and searchable only by the
creating user.
Caller is responsible for deleting the directory when done with it. | User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory. | [
"User",
"-",
"callable",
"function",
"to",
"create",
"and",
"return",
"a",
"unique",
"temporary",
"directory",
".",
"The",
"return",
"value",
"is",
"the",
"pathname",
"of",
"the",
"directory",
"."
] | def mkdtemp(suffix=None, prefix=None, dir=None):
"""User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, and searchable only by the
creating user.
Caller is responsible for deleting the directory when done with it.
"""
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
names = _get_candidate_names()
if output_type is bytes:
names = map(_os.fsencode, names)
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, prefix + name + suffix)
try:
_os.mkdir(file, 0o700)
except FileExistsError:
continue # try again
except PermissionError:
# This exception is thrown when a directory with the chosen name
# already exists on windows.
if (_os.name == 'nt' and _os.path.isdir(dir) and
_os.access(dir, _os.W_OK)):
continue
else:
raise
return file
raise FileExistsError(_errno.EEXIST,
"No usable temporary directory name found") | [
"def",
"mkdtemp",
"(",
"suffix",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"dir",
"=",
"None",
")",
":",
"prefix",
",",
"suffix",
",",
"dir",
",",
"output_type",
"=",
"_sanitize_params",
"(",
"prefix",
",",
"suffix",
",",
"dir",
")",
"names",
"="... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tempfile.py#L343-L380 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageChops.py | python | logical_or | (image1, image2) | return image1._new(image1.im.chop_or(image2.im)) | Logical OR between two images. At least one of the images must have
mode "1".
.. code-block:: python
out = ((image1 or image2) % MAX)
:rtype: :py:class:`~PIL.Image.Image` | Logical OR between two images. At least one of the images must have
mode "1". | [
"Logical",
"OR",
"between",
"two",
"images",
".",
"At",
"least",
"one",
"of",
"the",
"images",
"must",
"have",
"mode",
"1",
"."
] | def logical_or(image1, image2):
"""Logical OR between two images. At least one of the images must have
mode "1".
.. code-block:: python
out = ((image1 or image2) % MAX)
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_or(image2.im)) | [
"def",
"logical_or",
"(",
"image1",
",",
"image2",
")",
":",
"image1",
".",
"load",
"(",
")",
"image2",
".",
"load",
"(",
")",
"return",
"image1",
".",
"_new",
"(",
"image1",
".",
"im",
".",
"chop_or",
"(",
"image2",
".",
"im",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageChops.py#L262-L275 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_groups.py | python | moveToGroup | (group) | Place the selected objects in the chosen group. | Place the selected objects in the chosen group. | [
"Place",
"the",
"selected",
"objects",
"in",
"the",
"chosen",
"group",
"."
] | def moveToGroup(group):
"""
Place the selected objects in the chosen group.
"""
for obj in Gui.Selection.getSelection():
try:
#retrieve group's visibility
obj.ViewObject.Visibility = group.ViewObject.Visibility
group.addObject(obj)
except Exception:
pass
App.activeDocument().recompute(None, True, True) | [
"def",
"moveToGroup",
"(",
"group",
")",
":",
"for",
"obj",
"in",
"Gui",
".",
"Selection",
".",
"getSelection",
"(",
")",
":",
"try",
":",
"#retrieve group's visibility",
"obj",
".",
"ViewObject",
".",
"Visibility",
"=",
"group",
".",
"ViewObject",
".",
"V... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_groups.py#L138-L152 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/_extends/graph_kernel/model/graph_split.py | python | GraphSplitByPattern.split_output_reshapes | (self) | Force split the output Reshapes into other new area | Force split the output Reshapes into other new area | [
"Force",
"split",
"the",
"output",
"Reshapes",
"into",
"other",
"new",
"area"
] | def split_output_reshapes(self):
"""Force split the output Reshapes into other new area"""
def _remove_output_reshape(reshape_ops, other_ops):
def _run():
for op in reshape_ops:
if any([to_op in other_ops for to_op in op.output.to_ops]):
reshape_ops.remove(op)
other_ops.append(op)
return True
return False
while _run():
pass
new_areas = []
for area in self.areas:
reshape_ops = [op for op in area.ops if PrimLib.iter_type(op) == PrimLib.RESHAPE]
other_ops = [op for op in area.ops if op not in reshape_ops]
if not other_ops or not reshape_ops:
continue
# remove the output reshape from "reshape_ops" and add it into "other_ops"
_remove_output_reshape(reshape_ops, other_ops)
if not reshape_ops:
continue
for op in reshape_ops:
a = self.Area(op, False, 0, self.reach_tab)
self.set_default_mode(a)
new_areas.append(a)
area.ops = other_ops
if len(other_ops) == 1:
self.set_default_mode(area)
if new_areas:
self.areas += new_areas | [
"def",
"split_output_reshapes",
"(",
"self",
")",
":",
"def",
"_remove_output_reshape",
"(",
"reshape_ops",
",",
"other_ops",
")",
":",
"def",
"_run",
"(",
")",
":",
"for",
"op",
"in",
"reshape_ops",
":",
"if",
"any",
"(",
"[",
"to_op",
"in",
"other_ops",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/graph_kernel/model/graph_split.py#L484-L517 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextAttr.Copy | (*args, **kwargs) | return _richtext.RichTextAttr_Copy(*args, **kwargs) | Copy(self, RichTextAttr attr) | Copy(self, RichTextAttr attr) | [
"Copy",
"(",
"self",
"RichTextAttr",
"attr",
")"
] | def Copy(*args, **kwargs):
"""Copy(self, RichTextAttr attr)"""
return _richtext.RichTextAttr_Copy(*args, **kwargs) | [
"def",
"Copy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextAttr_Copy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L869-L871 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/SANSUtility.py | python | deprecated | (obj) | Decorator to apply to functions or classes that we think are not being (or
should not be) used anymore. Prints a warning to the log. | Decorator to apply to functions or classes that we think are not being (or
should not be) used anymore. Prints a warning to the log. | [
"Decorator",
"to",
"apply",
"to",
"functions",
"or",
"classes",
"that",
"we",
"think",
"are",
"not",
"being",
"(",
"or",
"should",
"not",
"be",
")",
"used",
"anymore",
".",
"Prints",
"a",
"warning",
"to",
"the",
"log",
"."
] | def deprecated(obj):
"""
Decorator to apply to functions or classes that we think are not being (or
should not be) used anymore. Prints a warning to the log.
"""
if inspect.isfunction(obj) or inspect.ismethod(obj):
if inspect.isfunction(obj):
obj_desc = "\"%s\" function" % obj.__name__
else:
obj_desc = "\"%s\" class" % obj.__self__.__class__.__name__
def print_warning_wrapper(*args, **kwargs):
sanslog.warning("The %s has been marked as deprecated and may be "
"removed in a future version of Mantid. If you "
"believe this to have been marked in error, please "
"contact the member of the Mantid team responsible "
"for ISIS SANS." % obj_desc)
return obj(*args, **kwargs)
return print_warning_wrapper
# Add a @deprecated decorator to each of the member functions in the class
# (by recursion).
if inspect.isclass(obj):
for name, fn in inspect.getmembers(obj):
if isinstance(fn, types.MethodType):
setattr(obj, name, deprecated(fn))
return obj
assert False, "Programming error. You have incorrectly applied the "\
"@deprecated decorator. This is only for use with functions "\
"or classes." | [
"def",
"deprecated",
"(",
"obj",
")",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"or",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
":",
"obj_desc",
"=",
"\"\\\"%s\\\" function\"",
... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/SANSUtility.py#L36-L66 | ||
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | src/python/interface/src/mesos/interface/__init__.py | python | ExecutorDriver.sendFrameworkMessage | (self, data) | Sends a message to the framework scheduler. These messages are best
effort; do not expect a framework message to be retransmitted in any
reliable fashion. | Sends a message to the framework scheduler. These messages are best
effort; do not expect a framework message to be retransmitted in any
reliable fashion. | [
"Sends",
"a",
"message",
"to",
"the",
"framework",
"scheduler",
".",
"These",
"messages",
"are",
"best",
"effort",
";",
"do",
"not",
"expect",
"a",
"framework",
"message",
"to",
"be",
"retransmitted",
"in",
"any",
"reliable",
"fashion",
"."
] | def sendFrameworkMessage(self, data):
"""
Sends a message to the framework scheduler. These messages are best
effort; do not expect a framework message to be retransmitted in any
reliable fashion.
""" | [
"def",
"sendFrameworkMessage",
"(",
"self",
",",
"data",
")",
":"
] | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/src/python/interface/src/mesos/interface/__init__.py#L428-L433 | ||
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/v7.9.317/third_party/jinja2/utils.py | python | urlize | (text, trim_url_limit=None, rel=None, target=None) | return u''.join(words) | Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text will be limited
to trim_url_limit characters.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
If target is not None, a target attribute will be added to the link. | Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing. | [
"Converts",
"any",
"URLs",
"in",
"text",
"into",
"clickable",
"links",
".",
"Works",
"on",
"http",
":",
"//",
"https",
":",
"//",
"and",
"www",
".",
"links",
".",
"Links",
"can",
"have",
"trailing",
"punctuation",
"(",
"periods",
"commas",
"close",
"-",
... | def urlize(text, trim_url_limit=None, rel=None, target=None):
"""Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text will be limited
to trim_url_limit characters.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
If target is not None, a target attribute will be added to the link.
"""
trim_url = lambda x, limit=trim_url_limit: limit is not None \
and (x[:limit] + (len(x) >=limit and '...'
or '')) or x
words = _word_split_re.split(text_type(escape(text)))
rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ''
target_attr = target and ' target="%s"' % escape(target) or ''
for i, word in enumerate(words):
match = _punctuation_re.match(word)
if match:
lead, middle, trail = match.groups()
if middle.startswith('www.') or (
'@' not in middle and
not middle.startswith('http://') and
not middle.startswith('https://') and
len(middle) > 0 and
middle[0] in _letters + _digits and (
middle.endswith('.org') or
middle.endswith('.net') or
middle.endswith('.com')
)):
middle = '<a href="http://%s"%s%s>%s</a>' % (middle,
rel_attr, target_attr, trim_url(middle))
if middle.startswith('http://') or \
middle.startswith('https://'):
middle = '<a href="%s"%s%s>%s</a>' % (middle,
rel_attr, target_attr, trim_url(middle))
if '@' in middle and not middle.startswith('www.') and \
not ':' in middle and _simple_email_re.match(middle):
middle = '<a href="mailto:%s">%s</a>' % (middle, middle)
if lead + middle + trail != word:
words[i] = lead + middle + trail
return u''.join(words) | [
"def",
"urlize",
"(",
"text",
",",
"trim_url_limit",
"=",
"None",
",",
"rel",
"=",
"None",
",",
"target",
"=",
"None",
")",
":",
"trim_url",
"=",
"lambda",
"x",
",",
"limit",
"=",
"trim_url_limit",
":",
"limit",
"is",
"not",
"None",
"and",
"(",
"x",
... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/utils.py#L189-L235 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/rebuild_mondb.py | python | _push_directory | (path, remote, remote_dir) | local_temp_path=`mktemp`
tar czf $local_temp_path $path
ssh remote mkdir -p remote_dir
remote_temp_path=`mktemp`
scp $local_temp_path $remote_temp_path
rm $local_temp_path
tar xzf $remote_temp_path -C $remote_dir
ssh remote:$remote_temp_path | local_temp_path=`mktemp`
tar czf $local_temp_path $path
ssh remote mkdir -p remote_dir
remote_temp_path=`mktemp`
scp $local_temp_path $remote_temp_path
rm $local_temp_path
tar xzf $remote_temp_path -C $remote_dir
ssh remote:$remote_temp_path | [
"local_temp_path",
"=",
"mktemp",
"tar",
"czf",
"$local_temp_path",
"$path",
"ssh",
"remote",
"mkdir",
"-",
"p",
"remote_dir",
"remote_temp_path",
"=",
"mktemp",
"scp",
"$local_temp_path",
"$remote_temp_path",
"rm",
"$local_temp_path",
"tar",
"xzf",
"$remote_temp_path",... | def _push_directory(path, remote, remote_dir):
"""
local_temp_path=`mktemp`
tar czf $local_temp_path $path
ssh remote mkdir -p remote_dir
remote_temp_path=`mktemp`
scp $local_temp_path $remote_temp_path
rm $local_temp_path
tar xzf $remote_temp_path -C $remote_dir
ssh remote:$remote_temp_path
"""
fd, local_temp_path = tempfile.mkstemp(suffix='.tgz',
prefix='rebuild_mondb-')
os.close(fd)
cmd = ' '.join(['tar', 'cz',
'-f', local_temp_path,
'-C', path,
'--', '.'])
teuthology.sh(cmd)
_, fname = os.path.split(local_temp_path)
fd, remote_temp_path = tempfile.mkstemp(suffix='.tgz',
prefix='rebuild_mondb-')
os.close(fd)
remote.put_file(local_temp_path, remote_temp_path)
os.remove(local_temp_path)
remote.run(args=['sudo',
'tar', 'xz',
'-C', remote_dir,
'-f', remote_temp_path])
remote.run(args=['sudo', 'rm', '-fr', remote_temp_path]) | [
"def",
"_push_directory",
"(",
"path",
",",
"remote",
",",
"remote_dir",
")",
":",
"fd",
",",
"local_temp_path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"'.tgz'",
",",
"prefix",
"=",
"'rebuild_mondb-'",
")",
"os",
".",
"close",
"(",
"fd",
")... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/rebuild_mondb.py#L17-L46 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/gtk/gizmos.py | python | TreeListCtrl.AssignStateImageList | (*args, **kwargs) | return _gizmos.TreeListCtrl_AssignStateImageList(*args, **kwargs) | AssignStateImageList(self, ImageList imageList) | AssignStateImageList(self, ImageList imageList) | [
"AssignStateImageList",
"(",
"self",
"ImageList",
"imageList",
")"
] | def AssignStateImageList(*args, **kwargs):
"""AssignStateImageList(self, ImageList imageList)"""
return _gizmos.TreeListCtrl_AssignStateImageList(*args, **kwargs) | [
"def",
"AssignStateImageList",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_AssignStateImageList",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/gtk/gizmos.py#L547-L549 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.