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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py | python | Makefile._is_framework | (self, mod) | return (self.config.qt_framework and (self.config.qt_version >= 0x040200 or mod != "QtAssistant")) | Return true if the given Qt module is a framework. | Return true if the given Qt module is a framework. | [
"Return",
"true",
"if",
"the",
"given",
"Qt",
"module",
"is",
"a",
"framework",
"."
] | def _is_framework(self, mod):
"""Return true if the given Qt module is a framework.
"""
return (self.config.qt_framework and (self.config.qt_version >= 0x040200 or mod != "QtAssistant")) | [
"def",
"_is_framework",
"(",
"self",
",",
"mod",
")",
":",
"return",
"(",
"self",
".",
"config",
".",
"qt_framework",
"and",
"(",
"self",
".",
"config",
".",
"qt_version",
">=",
"0x040200",
"or",
"mod",
"!=",
"\"QtAssistant\"",
")",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py#L916-L919 | |
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/framework/interfaces/face/face.py | python | GenericStub.future_stream_unary | (self,
group,
method,
request_iterator,
timeout,
metadata=None,
protocol_options=None) | Invokes a stream-request-unary-response method.
Args:
group: The group identifier of the RPC.
method: The method identifier of the RPC.
request_iterator: An iterator that yields request values for the RPC.
timeout: A duration of time in seconds to allow for the RPC.
metadata: A metadata value to be passed to the service-side of the RPC.
protocol_options: A value specified by the provider of a Face interface
implementation affording custom state and behavior.
Returns:
An object that is both a Call for the RPC and a future.Future. In the
event of RPC completion, the return Future's result value will be the
response value of the RPC. In the event of RPC abortion, the returned
Future's exception value will be an AbortionError. | Invokes a stream-request-unary-response method. | [
"Invokes",
"a",
"stream",
"-",
"request",
"-",
"unary",
"-",
"response",
"method",
"."
] | def future_stream_unary(self,
group,
method,
request_iterator,
timeout,
metadata=None,
protocol_options=None):
"""Invokes a stream-request-unary-response method.
Args:
group: The group identifier of the RPC.
method: The method identifier of the RPC.
request_iterator: An iterator that yields request values for the RPC.
timeout: A duration of time in seconds to allow for the RPC.
metadata: A metadata value to be passed to the service-side of the RPC.
protocol_options: A value specified by the provider of a Face interface
implementation affording custom state and behavior.
Returns:
An object that is both a Call for the RPC and a future.Future. In the
event of RPC completion, the return Future's result value will be the
response value of the RPC. In the event of RPC abortion, the returned
Future's exception value will be an AbortionError.
"""
raise NotImplementedError() | [
"def",
"future_stream_unary",
"(",
"self",
",",
"group",
",",
"method",
",",
"request_iterator",
",",
"timeout",
",",
"metadata",
"=",
"None",
",",
"protocol_options",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/framework/interfaces/face/face.py#L816-L840 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/math_grad.py | python | _ExpintGrad | (op, grad) | Compute gradient of expint(x) with respect to its argument. | Compute gradient of expint(x) with respect to its argument. | [
"Compute",
"gradient",
"of",
"expint",
"(",
"x",
")",
"with",
"respect",
"to",
"its",
"argument",
"."
] | def _ExpintGrad(op, grad):
"""Compute gradient of expint(x) with respect to its argument."""
x = op.inputs[0]
with ops.control_dependencies([grad]):
return grad * math_ops.exp(x) / x | [
"def",
"_ExpintGrad",
"(",
"op",
",",
"grad",
")",
":",
"x",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"grad",
"]",
")",
":",
"return",
"grad",
"*",
"math_ops",
".",
"exp",
"(",
"x",
")",
"/",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_grad.py#L893-L897 | ||
takemaru/graphillion | 51879f92bb96b53ef8f914ef37a05252ce383617 | graphillion/graphset.py | python | GraphSet.__init__ | (self, graphset_or_constraints=None) | Initializes a GraphSet object with a set of graphs or constraints.
Examples:
>>> graph1 = [(1, 4)]
>>> graph2 = [(1, 2), (2, 3)]
>>> GraphSet([graph1, graph2])
GraphSet([[(1, 4)], [(1, 2), (2, 3)]])
>>> GraphSet({'include': graph1, 'exclude': graph2})
GraphSet([[(1, 4)], [(1, 4), (2, 5)], [(1, 4), (3, 6)], ...
Args:
graphset_or_constraints: A set of graphs represented by a
list of graphs (a list of edge lists):
[[(1, 4)], [(1, 2), (2, 3)]]
Or constraints represented by a dict of included or
excluded edge lists (not-specified edges are not cared):
{'include': [(1, 4)], 'exclude': [(1, 2), (2, 3)]}
If no argument is given, it is treated as an empty list
`[]` and an empty GraphSet is returned. An empty dict
`{}` means that no constraint is specified, and so a
GraphSet including all possible graphs in the universe is
returned (let N the number of edges in the universe, 2^N
graphs are stored in the new object).
Raises:
KeyError: If given edges are not found in the universe.
See Also:
copy() | Initializes a GraphSet object with a set of graphs or constraints. | [
"Initializes",
"a",
"GraphSet",
"object",
"with",
"a",
"set",
"of",
"graphs",
"or",
"constraints",
"."
] | def __init__(self, graphset_or_constraints=None):
"""Initializes a GraphSet object with a set of graphs or constraints.
Examples:
>>> graph1 = [(1, 4)]
>>> graph2 = [(1, 2), (2, 3)]
>>> GraphSet([graph1, graph2])
GraphSet([[(1, 4)], [(1, 2), (2, 3)]])
>>> GraphSet({'include': graph1, 'exclude': graph2})
GraphSet([[(1, 4)], [(1, 4), (2, 5)], [(1, 4), (3, 6)], ...
Args:
graphset_or_constraints: A set of graphs represented by a
list of graphs (a list of edge lists):
[[(1, 4)], [(1, 2), (2, 3)]]
Or constraints represented by a dict of included or
excluded edge lists (not-specified edges are not cared):
{'include': [(1, 4)], 'exclude': [(1, 2), (2, 3)]}
If no argument is given, it is treated as an empty list
`[]` and an empty GraphSet is returned. An empty dict
`{}` means that no constraint is specified, and so a
GraphSet including all possible graphs in the universe is
returned (let N the number of edges in the universe, 2^N
graphs are stored in the new object).
Raises:
KeyError: If given edges are not found in the universe.
See Also:
copy()
"""
obj = graphset_or_constraints
if isinstance(obj, GraphSet):
self._ss = obj._ss.copy()
elif isinstance(obj, setset):
self._ss = obj.copy()
else:
if obj is None:
obj = []
elif isinstance(obj, (set, frozenset, list)): # a list of graphs [graph+]
l = []
for g in obj:
edges = GraphSet.converters['to_edges'](g)
l.append(set([GraphSet._conv_edge(e) for e in edges]))
obj = l
elif isinstance(obj, dict): # constraints
d = {}
for k, l in viewitems(obj):
d[k] = [GraphSet._conv_edge(e) for e in l]
obj = d
self._ss = setset(obj)
methods = ['graphs', 'connected_components', 'cliques', 'trees',
'forests', 'cycles', 'paths']
for method in methods:
setattr(self, method, partial(getattr(GraphSet, method), graphset=self)) | [
"def",
"__init__",
"(",
"self",
",",
"graphset_or_constraints",
"=",
"None",
")",
":",
"obj",
"=",
"graphset_or_constraints",
"if",
"isinstance",
"(",
"obj",
",",
"GraphSet",
")",
":",
"self",
".",
"_ss",
"=",
"obj",
".",
"_ss",
".",
"copy",
"(",
")",
... | https://github.com/takemaru/graphillion/blob/51879f92bb96b53ef8f914ef37a05252ce383617/graphillion/graphset.py#L84-L142 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mhlib.py | python | Folder.getsequencesfilename | (self) | return os.path.join(self.getfullname(), MH_SEQUENCES) | Return the full pathname of the folder's sequences file. | Return the full pathname of the folder's sequences file. | [
"Return",
"the",
"full",
"pathname",
"of",
"the",
"folder",
"s",
"sequences",
"file",
"."
] | def getsequencesfilename(self):
"""Return the full pathname of the folder's sequences file."""
return os.path.join(self.getfullname(), MH_SEQUENCES) | [
"def",
"getsequencesfilename",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"getfullname",
"(",
")",
",",
"MH_SEQUENCES",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mhlib.py#L264-L266 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | native_client_sdk/src/build_tools/manifest_util.py | python | Bundle.GetHostOSArchive | (self) | return self.GetArchive(GetHostOS()) | Retrieve the archive for the current host os. | Retrieve the archive for the current host os. | [
"Retrieve",
"the",
"archive",
"for",
"the",
"current",
"host",
"os",
"."
] | def GetHostOSArchive(self):
"""Retrieve the archive for the current host os."""
return self.GetArchive(GetHostOS()) | [
"def",
"GetHostOSArchive",
"(",
"self",
")",
":",
"return",
"self",
".",
"GetArchive",
"(",
"GetHostOS",
"(",
")",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/manifest_util.py#L272-L274 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Rect.GetLeft | (*args, **kwargs) | return _core_.Rect_GetLeft(*args, **kwargs) | GetLeft(self) -> int | GetLeft(self) -> int | [
"GetLeft",
"(",
"self",
")",
"-",
">",
"int"
] | def GetLeft(*args, **kwargs):
"""GetLeft(self) -> int"""
return _core_.Rect_GetLeft(*args, **kwargs) | [
"def",
"GetLeft",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect_GetLeft",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L1353-L1355 | |
interpretml/interpret | 29466bffc04505fe4f836a83fcfebfd313ac8454 | python/interpret-core/interpret/visual/interactive.py | python | show | (explanation, key=-1, **kwargs) | return None | Provides an interactive visualization for a given explanation(s).
By default, visualization provided is not preserved when the notebook exits.
Args:
explanation: Either a scalar Explanation or list of Explanations to render as visualization.
key: Specific index of explanation to visualize.
**kwargs: Kwargs passed down to provider's render() call.
Returns:
None. | Provides an interactive visualization for a given explanation(s). | [
"Provides",
"an",
"interactive",
"visualization",
"for",
"a",
"given",
"explanation",
"(",
"s",
")",
"."
] | def show(explanation, key=-1, **kwargs):
""" Provides an interactive visualization for a given explanation(s).
By default, visualization provided is not preserved when the notebook exits.
Args:
explanation: Either a scalar Explanation or list of Explanations to render as visualization.
key: Specific index of explanation to visualize.
**kwargs: Kwargs passed down to provider's render() call.
Returns:
None.
"""
try:
# Get explanation key
key = _get_integer_key(key, explanation)
# Set default render if needed
if this.visualize_provider is None:
this.visualize_provider = AutoVisualizeProvider()
# Render
this.visualize_provider.render(explanation, key=key, **kwargs)
except Exception as e: # pragma: no cover
log.error(e, exc_info=True)
raise e
return None | [
"def",
"show",
"(",
"explanation",
",",
"key",
"=",
"-",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# Get explanation key",
"key",
"=",
"_get_integer_key",
"(",
"key",
",",
"explanation",
")",
"# Set default render if needed",
"if",
"this",
".",
... | https://github.com/interpretml/interpret/blob/29466bffc04505fe4f836a83fcfebfd313ac8454/python/interpret-core/interpret/visual/interactive.py#L146-L174 | |
Tokutek/mongo | 0653eabe2c5b9d12b4814617cb7fb2d799937a0f | src/third_party/v8/tools/grokdump.py | python | FullDump | (reader, heap) | Dump all available memory regions. | Dump all available memory regions. | [
"Dump",
"all",
"available",
"memory",
"regions",
"."
] | def FullDump(reader, heap):
"""Dump all available memory regions."""
def dump_region(reader, start, size, location):
print
while start & 3 != 0:
start += 1
size -= 1
location += 1
is_executable = reader.IsProbableExecutableRegion(location, size)
is_ascii = reader.IsProbableASCIIRegion(location, size)
if is_executable is not False:
lines = reader.GetDisasmLines(start, size)
for line in lines:
print FormatDisasmLine(start, heap, line)
print
if is_ascii is not False:
# Output in the same format as the Unix hd command
addr = start
for slot in xrange(location, location + size, 16):
hex_line = ""
asc_line = ""
for i in xrange(0, 16):
if slot + i < location + size:
byte = ctypes.c_uint8.from_buffer(reader.minidump, slot + i).value
if byte >= 0x20 and byte < 0x7f:
asc_line += chr(byte)
else:
asc_line += "."
hex_line += " %02x" % (byte)
else:
hex_line += " "
if i == 7:
hex_line += " "
print "%s %s |%s|" % (reader.FormatIntPtr(addr),
hex_line,
asc_line)
addr += 16
if is_executable is not True and is_ascii is not True:
print "%s - %s" % (reader.FormatIntPtr(start),
reader.FormatIntPtr(start + size))
for slot in xrange(start,
start + size,
reader.PointerSize()):
maybe_address = reader.ReadUIntPtr(slot)
heap_object = heap.FindObject(maybe_address)
print "%s: %s" % (reader.FormatIntPtr(slot),
reader.FormatIntPtr(maybe_address))
if heap_object:
heap_object.Print(Printer())
print
reader.ForEachMemoryRegion(dump_region) | [
"def",
"FullDump",
"(",
"reader",
",",
"heap",
")",
":",
"def",
"dump_region",
"(",
"reader",
",",
"start",
",",
"size",
",",
"location",
")",
":",
"print",
"while",
"start",
"&",
"3",
"!=",
"0",
":",
"start",
"+=",
"1",
"size",
"-=",
"1",
"locatio... | https://github.com/Tokutek/mongo/blob/0653eabe2c5b9d12b4814617cb7fb2d799937a0f/src/third_party/v8/tools/grokdump.py#L109-L163 | ||
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/maya/scripts/AEwalterStandinTemplate.py | python | WalterLayersModel.executeAction | (self, action, index) | We are here because user pressed by one of the actions. | We are here because user pressed by one of the actions. | [
"We",
"are",
"here",
"because",
"user",
"pressed",
"by",
"one",
"of",
"the",
"actions",
"."
] | def executeAction(self, action, index):
"""We are here because user pressed by one of the actions."""
if not index.isValid():
return
if action == walterWidgets.LayersItem.ACTION_OPEN:
startingDirectory = \
os.path.dirname(index.data(QtCore.Qt.DisplayRole)) or None
# File modes:
# 0 Any file, whether it exists or not.
# 1 A single existing file.
# 2 The name of a directory. Both directories and files are
# displayed in the dialog.
# 3 The name of a directory. Only directories are displayed in the
# dialog.
# 4 Then names of one or more existing files.
# Display Styles:
# 1 On Windows or Mac OS X will use a native style file dialog.
# 2 Use a custom file dialog with a style that is consistent across
# platforms.
archive = cmds.fileDialog2(
fileFilter=
"Alembic/USD Files (*.abc *.usd *.usda *.usdb *.usdc)",
startingDirectory=startingDirectory,
fileMode=1,
dialogStyle=2)
if not archive:
return
# Get filename
archive = archive[0]
# Set it to the item
self.setData(index, archive)
# Update the Maya object
self.updateCurrentNode(attribute="cacheFileName")
elif action == walterWidgets.LayersItem.ACTION_VISIBLE:
item = index.internalPointer()
item.visible = not item.visible
# Update the Maya object
self.updateCurrentNode(attribute="visibilities")
elif action == walterWidgets.LayersItem.ACTION_RENDERABLE:
item = index.internalPointer()
item.renderable = not item.renderable
# Update the Maya object
self.updateCurrentNode(attribute="renderables") | [
"def",
"executeAction",
"(",
"self",
",",
"action",
",",
"index",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"if",
"action",
"==",
"walterWidgets",
".",
"LayersItem",
".",
"ACTION_OPEN",
":",
"startingDirectory",
"=",
"os",
... | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/AEwalterStandinTemplate.py#L132-L184 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/Tools/python/GenObject.py | python | GenObject._rootDiffObject | (obj1, obj2, rootObj = 0) | return rootObj | Given to GOs, it will create and fill the corresponding
root diff object | Given to GOs, it will create and fill the corresponding
root diff object | [
"Given",
"to",
"GOs",
"it",
"will",
"create",
"and",
"fill",
"the",
"corresponding",
"root",
"diff",
"object"
] | def _rootDiffObject (obj1, obj2, rootObj = 0):
"""Given to GOs, it will create and fill the corresponding
root diff object"""
objName = obj1._objName
# if we don't already have a root object, create one
if not rootObj:
diffName = GenObject.rootDiffClassName( objName )
rootObj = GenObject._rootClassDict[diffName]()
for varName in GenObject._objsDict [objName].keys():
if varName.startswith ("_"): continue
goType = GenObject._objsDict[objName][varName]['varType']
if not goType in GenObject._basicSet:
# not yet
continue
setattr( rootObj, varName, obj1 (varName) )
if goType == GenObject.types.string:
# string
otherName = 'other_' + varName
if obj1 (varName) != obj2 (varName):
# don't agree
setattr( rootObj, otherName, obj2 (varName) )
else:
# agree
setattr( rootObj, otherName, '' )
else:
# float, long, or int
deltaName = 'delta_' + varName
setattr( rootObj, deltaName,
obj2 (varName) - obj1 (varName) )
return rootObj | [
"def",
"_rootDiffObject",
"(",
"obj1",
",",
"obj2",
",",
"rootObj",
"=",
"0",
")",
":",
"objName",
"=",
"obj1",
".",
"_objName",
"# if we don't already have a root object, create one",
"if",
"not",
"rootObj",
":",
"diffName",
"=",
"GenObject",
".",
"rootDiffClassN... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/Tools/python/GenObject.py#L745-L774 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/metrics.py | python | TotalTransferSize | (trace) | return TransferSize(trace.request_track.GetEvents()) | Returns the total transfer size (uploaded, downloaded) from a trace. | Returns the total transfer size (uploaded, downloaded) from a trace. | [
"Returns",
"the",
"total",
"transfer",
"size",
"(",
"uploaded",
"downloaded",
")",
"from",
"a",
"trace",
"."
] | def TotalTransferSize(trace):
"""Returns the total transfer size (uploaded, downloaded) from a trace."""
return TransferSize(trace.request_track.GetEvents()) | [
"def",
"TotalTransferSize",
"(",
"trace",
")",
":",
"return",
"TransferSize",
"(",
"trace",
".",
"request_track",
".",
"GetEvents",
"(",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/metrics.py#L56-L58 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/sping/pid.py | python | Canvas.__init__ | (self, size=(300, 300), name="PIDDLE") | Initialize the canvas, and set default drawing parameters.
Derived classes should be sure to call this method. | Initialize the canvas, and set default drawing parameters.
Derived classes should be sure to call this method. | [
"Initialize",
"the",
"canvas",
"and",
"set",
"default",
"drawing",
"parameters",
".",
"Derived",
"classes",
"should",
"be",
"sure",
"to",
"call",
"this",
"method",
"."
] | def __init__(self, size=(300, 300), name="PIDDLE"):
"""Initialize the canvas, and set default drawing parameters.
Derived classes should be sure to call this method."""
# defaults used when drawing
self.defaultLineColor = black
self.defaultFillColor = transparent
self.defaultLineWidth = 1
self.defaultFont = Font()
# set up null event handlers
# onClick: x,y is Canvas coordinates of mouseclick
def ignoreClick(canvas, x, y):
pass
self.onClick = ignoreClick
# onOver: x,y is Canvas location of mouse
def ignoreOver(canvas, x, y):
pass
self.onOver = ignoreOver
# onKey: key is printable character or one of the constants above;
# modifiers is a tuple containing any of (modShift, modControl)
def ignoreKey(canvas, key, modifiers):
pass
self.onKey = ignoreKey
# size and name, for user's reference
self.size, self.name = size, name | [
"def",
"__init__",
"(",
"self",
",",
"size",
"=",
"(",
"300",
",",
"300",
")",
",",
"name",
"=",
"\"PIDDLE\"",
")",
":",
"# defaults used when drawing",
"self",
".",
"defaultLineColor",
"=",
"black",
"self",
".",
"defaultFillColor",
"=",
"transparent",
"self... | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/pid.py#L205-L236 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/compiler/xla/python/xla_client.py | python | ComputationBuilder.SortKeyVal | (self, keys, values, dimension=-1) | return ops.Sort(self._builder, [keys, values], dimension) | Enqueues a key-value sort operation onto the computation.
Deprecated. Use `Sort` instead. | Enqueues a key-value sort operation onto the computation. | [
"Enqueues",
"a",
"key",
"-",
"value",
"sort",
"operation",
"onto",
"the",
"computation",
"."
] | def SortKeyVal(self, keys, values, dimension=-1):
"""Enqueues a key-value sort operation onto the computation.
Deprecated. Use `Sort` instead.
"""
return ops.Sort(self._builder, [keys, values], dimension) | [
"def",
"SortKeyVal",
"(",
"self",
",",
"keys",
",",
"values",
",",
"dimension",
"=",
"-",
"1",
")",
":",
"return",
"ops",
".",
"Sort",
"(",
"self",
".",
"_builder",
",",
"[",
"keys",
",",
"values",
"]",
",",
"dimension",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/compiler/xla/python/xla_client.py#L1493-L1498 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/xml/sax/handler.py | python | ContentHandler.startElementNS | (self, name, qname, attrs) | Signals the start of an element in namespace mode.
The name parameter contains the name of the element type as a
(uri, localname) tuple, the qname parameter the raw XML 1.0
name used in the source document, and the attrs parameter
holds an instance of the Attributes class containing the
attributes of the element.
The uri part of the name tuple is None for elements which have
no namespace. | Signals the start of an element in namespace mode. | [
"Signals",
"the",
"start",
"of",
"an",
"element",
"in",
"namespace",
"mode",
"."
] | def startElementNS(self, name, qname, attrs):
"""Signals the start of an element in namespace mode.
The name parameter contains the name of the element type as a
(uri, localname) tuple, the qname parameter the raw XML 1.0
name used in the source document, and the attrs parameter
holds an instance of the Attributes class containing the
attributes of the element.
The uri part of the name tuple is None for elements which have
no namespace.""" | [
"def",
"startElementNS",
"(",
"self",
",",
"name",
",",
"qname",
",",
"attrs",
")",
":"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/xml/sax/handler.py#L140-L150 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | docs/sphinxext/mantiddoc/directives/attributes.py | python | AttributesDirective._create_attributes_table | (self) | return True | Populates the ReST table with algorithm properties.
If it is done as a part of a multiline description, each line
will describe a single attribute as a semicolon separated list
Name;Type;Default;Description | Populates the ReST table with algorithm properties. | [
"Populates",
"the",
"ReST",
"table",
"with",
"algorithm",
"properties",
"."
] | def _create_attributes_table(self):
"""
Populates the ReST table with algorithm properties.
If it is done as a part of a multiline description, each line
will describe a single attribute as a semicolon separated list
Name;Type;Default;Description
"""
if self.algorithm_version() is None: # This is an IFunction
ifunc = self.create_mantid_ifunction(self.algorithm_name())
if ifunc.nAttributes() <= 0:
return False
# Stores each property of the algorithm in a tuple.
attributes = []
# names for the table headers.
header = ('Name', 'Type', 'Default', 'Description')
if len(self.content) > 0:
for line in self.content:
args = tuple(line.split(";"))
args = [item.strip() for item in args]
if len(args) != len(header):
raise RuntimeError("Expected %d items in line '%s'" % (len(header), str(args)))
else:
attributes.append(args)
else:
for name in ifunc.attributeNames():
attributes.append((name, "", "", ""))
self.add_rst(self.make_header("Attributes (non-fitting parameters)"))
else:
raise RuntimeError("Document does not appear to describe a fit function")
self.add_rst(self._build_table(header, attributes))
return True | [
"def",
"_create_attributes_table",
"(",
"self",
")",
":",
"if",
"self",
".",
"algorithm_version",
"(",
")",
"is",
"None",
":",
"# This is an IFunction",
"ifunc",
"=",
"self",
".",
"create_mantid_ifunction",
"(",
"self",
".",
"algorithm_name",
"(",
")",
")",
"i... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/docs/sphinxext/mantiddoc/directives/attributes.py#L26-L62 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Utilities/RelMon/python/progressbar.py | python | ProgressBar._need_update | (self) | return self._time_sensitive and delta > self.poll | Returns whether the ProgressBar should redraw the line. | Returns whether the ProgressBar should redraw the line. | [
"Returns",
"whether",
"the",
"ProgressBar",
"should",
"redraw",
"the",
"line",
"."
] | def _need_update(self):
'Returns whether the ProgressBar should redraw the line.'
if self.currval >= self.next_update or self.finished: return True
delta = time.time() - self.last_update_time
return self._time_sensitive and delta > self.poll | [
"def",
"_need_update",
"(",
"self",
")",
":",
"if",
"self",
".",
"currval",
">=",
"self",
".",
"next_update",
"or",
"self",
".",
"finished",
":",
"return",
"True",
"delta",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"last_update_time",
"retu... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Utilities/RelMon/python/progressbar.py#L336-L341 | |
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/generator/ninja.py | python | _AddWinLinkRules | (master_ninja, embed_manifest) | Adds link rules for Windows platform to |master_ninja|. | Adds link rules for Windows platform to |master_ninja|. | [
"Adds",
"link",
"rules",
"for",
"Windows",
"platform",
"to",
"|master_ninja|",
"."
] | def _AddWinLinkRules(master_ninja, embed_manifest):
"""Adds link rules for Windows platform to |master_ninja|."""
def FullLinkCommand(ldcmd, out, binary_type):
resource_name = {
'exe': '1',
'dll': '2',
}[binary_type]
return '%(python)s gyp-win-tool link-with-manifests $arch %(embed)s ' \
'%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' \
'$manifests' % {
'python': sys.executable,
'out': out,
'ldcmd': ldcmd,
'resname': resource_name,
'embed': embed_manifest }
rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest)
use_separate_mspdbsrv = (
int(os.environ.get('GYP_USE_SEPARATE_MSPDBSRV', '0')) != 0)
dlldesc = 'LINK%s(DLL) $binary' % rule_name_suffix.upper()
dllcmd = ('%s gyp-win-tool link-wrapper $arch %s '
'$ld /nologo $implibflag /DLL /OUT:$binary '
'@$binary.rsp' % (sys.executable, use_separate_mspdbsrv))
dllcmd = FullLinkCommand(dllcmd, '$binary', 'dll')
master_ninja.rule('solink' + rule_name_suffix,
description=dlldesc, command=dllcmd,
rspfile='$binary.rsp',
rspfile_content='$libs $in_newline $ldflags',
restat=True,
pool='link_pool')
master_ninja.rule('solink_module' + rule_name_suffix,
description=dlldesc, command=dllcmd,
rspfile='$binary.rsp',
rspfile_content='$libs $in_newline $ldflags',
restat=True,
pool='link_pool')
# Note that ldflags goes at the end so that it has the option of
# overriding default settings earlier in the command line.
exe_cmd = ('%s gyp-win-tool link-wrapper $arch %s '
'$ld /nologo /OUT:$binary @$binary.rsp' %
(sys.executable, use_separate_mspdbsrv))
exe_cmd = FullLinkCommand(exe_cmd, '$binary', 'exe')
master_ninja.rule('link' + rule_name_suffix,
description='LINK%s $binary' % rule_name_suffix.upper(),
command=exe_cmd,
rspfile='$binary.rsp',
rspfile_content='$in_newline $libs $ldflags',
pool='link_pool') | [
"def",
"_AddWinLinkRules",
"(",
"master_ninja",
",",
"embed_manifest",
")",
":",
"def",
"FullLinkCommand",
"(",
"ldcmd",
",",
"out",
",",
"binary_type",
")",
":",
"resource_name",
"=",
"{",
"'exe'",
":",
"'1'",
",",
"'dll'",
":",
"'2'",
",",
"}",
"[",
"b... | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/ninja.py#L1729-L1775 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/importlib/abc.py | python | ResourceReader.open_resource | (self, resource) | Return an opened, file-like object for binary reading.
The 'resource' argument is expected to represent only a file name
and thus not contain any subdirectory components.
If the resource cannot be found, FileNotFoundError is raised. | Return an opened, file-like object for binary reading. | [
"Return",
"an",
"opened",
"file",
"-",
"like",
"object",
"for",
"binary",
"reading",
"."
] | def open_resource(self, resource):
"""Return an opened, file-like object for binary reading.
The 'resource' argument is expected to represent only a file name
and thus not contain any subdirectory components.
If the resource cannot be found, FileNotFoundError is raised.
"""
raise FileNotFoundError | [
"def",
"open_resource",
"(",
"self",
",",
"resource",
")",
":",
"raise",
"FileNotFoundError"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/importlib/abc.py#L355-L363 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | DataHandler.WriteImmediateCmdSet | (self, func, file) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteImmediateCmdSet(self, func, file):
"""Overrriden from TypeHandler."""
copy_args = func.MakeCmdArgString("_", False)
file.Write(" void* Set(void* cmd%s) {\n" %
func.MakeTypedCmdArgString("_", True))
self.WriteImmediateCmdGetTotalSize(func, file)
file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
"cmd, total_size);\n")
file.Write(" }\n")
file.Write("\n") | [
"def",
"WriteImmediateCmdSet",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"copy_args",
"=",
"func",
".",
"MakeCmdArgString",
"(",
"\"_\"",
",",
"False",
")",
"file",
".",
"Write",
"(",
"\" void* Set(void* cmd%s) {\\n\"",
"%",
"func",
".",
"MakeTypedCmdA... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L2631-L2641 | ||
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/lists.py | python | ListsHandler.get_next_list_info_on_level | (self, iter_start, level) | return ret_val | Given a level check for next list number on the level or None | Given a level check for next list number on the level or None | [
"Given",
"a",
"level",
"check",
"for",
"next",
"list",
"number",
"on",
"the",
"level",
"or",
"None"
] | def get_next_list_info_on_level(self, iter_start, level):
"""Given a level check for next list number on the level or None"""
ret_val = None
while iter_start:
if not self.char_iter_forward_to_newline(iter_start):
break
list_info = self.get_paragraph_list_info(iter_start)
if not list_info:
break
if list_info["level"] == level:
ret_val = list_info
break
return ret_val | [
"def",
"get_next_list_info_on_level",
"(",
"self",
",",
"iter_start",
",",
"level",
")",
":",
"ret_val",
"=",
"None",
"while",
"iter_start",
":",
"if",
"not",
"self",
".",
"char_iter_forward_to_newline",
"(",
"iter_start",
")",
":",
"break",
"list_info",
"=",
... | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/lists.py#L215-L227 | |
nci/drishti | 89cd8b740239c5b2c8222dffd4e27432fde170a1 | bin/assets/scripts/unet++/myutils.py | python | reconstruct_from_patches | (img_arr, org_img_size, stride=None, size=None) | return np.stack(images_list) | [summary]
Args:
img_arr (numpy.ndarray): [description]
org_img_size (tuple): [description]
stride ([type], optional): [description]. Defaults to None.
size ([type], optional): [description]. Defaults to None.
Raises:
ValueError: [description]
Returns:
numpy.ndarray: [description] | [summary]
Args:
img_arr (numpy.ndarray): [description]
org_img_size (tuple): [description]
stride ([type], optional): [description]. Defaults to None.
size ([type], optional): [description]. Defaults to None.
Raises:
ValueError: [description]
Returns:
numpy.ndarray: [description] | [
"[",
"summary",
"]",
"Args",
":",
"img_arr",
"(",
"numpy",
".",
"ndarray",
")",
":",
"[",
"description",
"]",
"org_img_size",
"(",
"tuple",
")",
":",
"[",
"description",
"]",
"stride",
"(",
"[",
"type",
"]",
"optional",
")",
":",
"[",
"description",
... | def reconstruct_from_patches(img_arr, org_img_size, stride=None, size=None):
"""[summary]
Args:
img_arr (numpy.ndarray): [description]
org_img_size (tuple): [description]
stride ([type], optional): [description]. Defaults to None.
size ([type], optional): [description]. Defaults to None.
Raises:
ValueError: [description]
Returns:
numpy.ndarray: [description]
"""
#print('Img_Arr : ',img_arr.shape)
#print('Orig_Img_Size : ',org_img_size)
# check parameters
if type(org_img_size) is not tuple:
raise ValueError("org_image_size must be a tuple")
if img_arr.ndim == 3:
img_arr = np.expand_dims(img_arr, axis=0)
if size is None:
size = img_arr.shape[1]
if stride is None:
stride = size
nm_layers = img_arr.shape[3]
i_max = org_img_size[0] // stride
if i_max*stride < org_img_size[0] :
i_max = i_max + 1
j_max = org_img_size[1] // stride
if j_max*stride < org_img_size[1] :
j_max = j_max + 1
#total_nm_images = img_arr.shape[0] // (i_max ** 2)
total_nm_images = img_arr.shape[0] // (i_max * j_max)
nm_images = img_arr.shape[0]
images_list = []
kk = 0
for img_count in range(total_nm_images):
img_r = np.zeros(
(i_max*stride, j_max*stride, nm_layers), dtype=img_arr[0].dtype
)
for i in range(i_max):
for j in range(j_max):
for layer in range(nm_layers):
img_r[
i * stride : i * stride + size,
j * stride : j * stride + size,
layer,
] = img_arr[kk, :, :, layer]
kk += 1
img_bg = np.zeros(
(org_img_size[0], org_img_size[1], nm_layers), dtype=img_arr[0].dtype
)
img_bg = img_r[0:org_img_size[0], 0:org_img_size[1], 0:]
images_list.append(img_bg)
return np.stack(images_list) | [
"def",
"reconstruct_from_patches",
"(",
"img_arr",
",",
"org_img_size",
",",
"stride",
"=",
"None",
",",
"size",
"=",
"None",
")",
":",
"#print('Img_Arr : ',img_arr.shape)",
"#print('Orig_Img_Size : ',org_img_size)",
"# check parameters",
"if",
"type",
"(",
"org_img_size"... | https://github.com/nci/drishti/blob/89cd8b740239c5b2c8222dffd4e27432fde170a1/bin/assets/scripts/unet++/myutils.py#L87-L156 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/masked/maskededit.py | python | MaskedEditMixin._Undo | (self, value=None, prev=None, just_return_results=False) | Provides an Undo() method in base controls. | Provides an Undo() method in base controls. | [
"Provides",
"an",
"Undo",
"()",
"method",
"in",
"base",
"controls",
"."
] | def _Undo(self, value=None, prev=None, just_return_results=False):
""" Provides an Undo() method in base controls. """
## dbg("MaskedEditMixin::_Undo", indent=1)
if value is None:
value = self._GetValue()
if prev is None:
prev = self._prevValue
## dbg('current value: "%s"' % value)
## dbg('previous value: "%s"' % prev)
if prev is None:
## dbg('no previous value', indent=0)
return
elif value != prev:
# Determine what to select: (relies on fixed-length strings)
# (This is a lot harder than it would first appear, because
# of mask chars that stay fixed, and so break up the "diff"...)
# Determine where they start to differ:
i = 0
length = len(value) # (both are same length in masked control)
while( value[:i] == prev[:i] ):
i += 1
sel_start = i - 1
# handle signed values carefully, so undo from signed to unsigned or vice-versa
# works properly:
if self._signOk:
text, signpos, right_signpos = self._getSignedValue(candidate=prev)
if self._useParens:
if prev[signpos] == '(' and prev[right_signpos] == ')':
self._isNeg = True
else:
self._isNeg = False
# eliminate source of "far-end" undo difference if using balanced parens:
value = value.replace(')', ' ')
prev = prev.replace(')', ' ')
elif prev[signpos] == '-':
self._isNeg = True
else:
self._isNeg = False
# Determine where they stop differing in "undo" result:
sm = difflib.SequenceMatcher(None, a=value, b=prev)
i, j, k = sm.find_longest_match(sel_start, length, sel_start, length)
## dbg('i,j,k = ', (i,j,k), 'value[i:i+k] = "%s"' % value[i:i+k], 'prev[j:j+k] = "%s"' % prev[j:j+k] )
if k == 0: # no match found; select to end
sel_to = length
else:
code_5tuples = sm.get_opcodes()
for op, i1, i2, j1, j2 in code_5tuples:
## dbg("%7s value[%d:%d] (%s) prev[%d:%d] (%s)" % (op, i1, i2, value[i1:i2], j1, j2, prev[j1:j2]))
pass
diff_found = False
# look backward through operations needed to produce "previous" value;
# first change wins:
for next_op in range(len(code_5tuples)-1, -1, -1):
op, i1, i2, j1, j2 = code_5tuples[next_op]
## dbg('value[i1:i2]: "%s"' % value[i1:i2], 'template[i1:i2] "%s"' % self._template[i1:i2])
field = self._FindField(i2)
if op == 'insert' and prev[j1:j2] != self._template[j1:j2]:
## dbg('insert found: selection =>', (j1, j2))
sel_start = j1
sel_to = j2
diff_found = True
break
elif op == 'delete' and value[i1:i2] != self._template[i1:i2]:
edit_start, edit_end = field._extent
if field._insertRight and (field._allowInsert or i2 == edit_end):
sel_start = i2
sel_to = i2
else:
sel_start = i1
sel_to = j1
## dbg('delete found: selection =>', (sel_start, sel_to))
diff_found = True
break
elif op == 'replace':
if not prev[i1:i2].strip() and field._insertRight:
sel_start = sel_to = j2
else:
sel_start = j1
sel_to = j2
## dbg('replace found: selection =>', (sel_start, sel_to))
diff_found = True
break
if diff_found:
# now go forwards, looking for earlier changes:
## dbg('searching forward...')
for next_op in range(len(code_5tuples)):
op, i1, i2, j1, j2 = code_5tuples[next_op]
field = self._FindField(i1)
if op == 'equal':
continue
elif op == 'replace':
if field._insertRight:
# if replace with spaces in an insert-right control, ignore "forward" replace
if not prev[i1:i2].strip():
continue
elif j1 < i1:
## dbg('setting sel_start to', j1)
sel_start = j1
else:
## dbg('setting sel_start to', i1)
sel_start = i1
else:
## dbg('setting sel_start to', i1)
sel_start = i1
## dbg('saw replace; breaking')
break
elif op == 'insert' and not value[i1:i2]:
## dbg('forward %s found' % op)
if prev[j1:j2].strip():
## dbg('item to insert non-empty; setting sel_start to', j1)
sel_start = j1
break
elif not field._insertRight:
## dbg('setting sel_start to inserted space:', j1)
sel_start = j1
break
elif op == 'delete':
## dbg('delete; field._insertRight?', field._insertRight, 'value[%d:%d].lstrip: "%s"' % (i1,i2,value[i1:i2].lstrip()))
if field._insertRight:
if value[i1:i2].lstrip():
## dbg('setting sel_start to ', j1)
sel_start = j1
## dbg('breaking loop')
break
else:
continue
else:
## dbg('saw delete; breaking')
break
else:
## dbg('unknown code!')
# we've got what we need
break
if not diff_found:
## dbg('no insert,delete or replace found (!)')
# do "left-insert"-centric processing of difference based on l.c.s.:
if i == j and j != sel_start: # match starts after start of selection
sel_to = sel_start + (j-sel_start) # select to start of match
else:
sel_to = j # (change ends at j)
# There are several situations where the calculated difference is
# not what we want to select. If changing sign, or just adding
# group characters, we really don't want to highlight the characters
# changed, but instead leave the cursor where it is.
# Also, there a situations in which the difference can be ambiguous;
# Consider:
#
# current value: 11234
# previous value: 1111234
#
# Where did the cursor actually lie and which 1s were selected on the delete
# operation?
#
# Also, difflib can "get it wrong;" Consider:
#
# current value: " 128.66"
# previous value: " 121.86"
#
# difflib produces the following opcodes, which are sub-optimal:
# equal value[0:9] ( 12) prev[0:9] ( 12)
# insert value[9:9] () prev[9:11] (1.)
# equal value[9:10] (8) prev[11:12] (8)
# delete value[10:11] (.) prev[12:12] ()
# equal value[11:12] (6) prev[12:13] (6)
# delete value[12:13] (6) prev[13:13] ()
#
# This should have been:
# equal value[0:9] ( 12) prev[0:9] ( 12)
# replace value[9:11] (8.6) prev[9:11] (1.8)
# equal value[12:13] (6) prev[12:13] (6)
#
# But it didn't figure this out!
#
# To get all this right, we use the previous selection recorded to help us...
if (sel_start, sel_to) != self._prevSelection:
## dbg('calculated selection', (sel_start, sel_to), "doesn't match previous", self._prevSelection)
prev_sel_start, prev_sel_to = self._prevSelection
field = self._FindField(sel_start)
if( self._signOk
and sel_start < self._masklength
and (prev[sel_start] in ('-', '(', ')')
or value[sel_start] in ('-', '(', ')')) ):
# change of sign; leave cursor alone...
## dbg("prev[sel_start] in ('-', '(', ')')?", prev[sel_start] in ('-', '(', ')'))
## dbg("value[sel_start] in ('-', '(', ')')?", value[sel_start] in ('-', '(', ')'))
## dbg('setting selection to previous one')
sel_start, sel_to = self._prevSelection
elif field._groupdigits and (value[sel_start:sel_to] == field._groupChar
or prev[sel_start:sel_to] == field._groupChar):
# do not highlight grouping changes
## dbg('value[sel_start:sel_to] == field._groupChar?', value[sel_start:sel_to] == field._groupChar)
## dbg('prev[sel_start:sel_to] == field._groupChar?', prev[sel_start:sel_to] == field._groupChar)
## dbg('setting selection to previous one')
sel_start, sel_to = self._prevSelection
else:
calc_select_len = sel_to - sel_start
prev_select_len = prev_sel_to - prev_sel_start
## dbg('sel_start == prev_sel_start', sel_start == prev_sel_start)
## dbg('sel_to > prev_sel_to', sel_to > prev_sel_to)
if prev_select_len >= calc_select_len:
# old selection was bigger; trust it:
## dbg('prev_select_len >= calc_select_len?', prev_select_len >= calc_select_len)
if not field._insertRight:
## dbg('setting selection to previous one')
sel_start, sel_to = self._prevSelection
else:
sel_to = self._prevSelection[1]
## dbg('setting selection to', (sel_start, sel_to))
elif( sel_to > prev_sel_to # calculated select past last selection
and prev_sel_to < len(self._template) # and prev_sel_to not at end of control
and sel_to == len(self._template) ): # and calculated selection goes to end of control
i, j, k = sm.find_longest_match(prev_sel_to, length, prev_sel_to, length)
## dbg('i,j,k = ', (i,j,k), 'value[i:i+k] = "%s"' % value[i:i+k], 'prev[j:j+k] = "%s"' % prev[j:j+k] )
if k > 0:
# difflib must not have optimized opcodes properly;
sel_to = j
else:
# look for possible ambiguous diff:
# if last change resulted in no selection, test from resulting cursor position:
if prev_sel_start == prev_sel_to:
calc_select_len = sel_to - sel_start
field = self._FindField(prev_sel_start)
# determine which way to search from last cursor position for ambiguous change:
if field._insertRight:
test_sel_start = prev_sel_start
test_sel_to = prev_sel_start + calc_select_len
else:
test_sel_start = prev_sel_start - calc_select_len
test_sel_to = prev_sel_start
else:
test_sel_start, test_sel_to = prev_sel_start, prev_sel_to
## dbg('test selection:', (test_sel_start, test_sel_to))
## dbg('calc change: "%s"' % prev[sel_start:sel_to])
## dbg('test change: "%s"' % prev[test_sel_start:test_sel_to])
# if calculated selection spans characters, and same characters
# "before" the previous insertion point are present there as well,
# select the ones related to the last known selection instead.
if( sel_start != sel_to
and test_sel_to < len(self._template)
and prev[test_sel_start:test_sel_to] == prev[sel_start:sel_to] ):
sel_start, sel_to = test_sel_start, test_sel_to
# finally, make sure that the old and new values are
# different where we say they're different:
while( sel_to - 1 > 0
and sel_to > sel_start
and value[sel_to-1:] == prev[sel_to-1:]):
sel_to -= 1
while( sel_start + 1 < self._masklength
and sel_start < sel_to
and value[:sel_start+1] == prev[:sel_start+1]):
sel_start += 1
## dbg('sel_start, sel_to:', sel_start, sel_to)
## dbg('previous value: "%s"' % prev)
## dbg(indent=0)
if just_return_results:
return prev, (sel_start, sel_to)
# else...
self._SetValue(prev)
self._SetInsertionPoint(sel_start)
self._SetSelection(sel_start, sel_to)
else:
## dbg('no difference between previous value')
## dbg(indent=0)
if just_return_results:
return prev, self._GetSelection() | [
"def",
"_Undo",
"(",
"self",
",",
"value",
"=",
"None",
",",
"prev",
"=",
"None",
",",
"just_return_results",
"=",
"False",
")",
":",
"## dbg(\"MaskedEditMixin::_Undo\", indent=1)",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"self",
".",
"_GetValue... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/maskededit.py#L5997-L6292 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/signal/filter_design.py | python | _nearest_real_complex_idx | (fro, to, which) | return order[np.where(mask)[0][0]] | Get the next closest real or complex element based on distance | Get the next closest real or complex element based on distance | [
"Get",
"the",
"next",
"closest",
"real",
"or",
"complex",
"element",
"based",
"on",
"distance"
] | def _nearest_real_complex_idx(fro, to, which):
"""Get the next closest real or complex element based on distance"""
assert which in ('real', 'complex')
order = np.argsort(np.abs(fro - to))
mask = np.isreal(fro[order])
if which == 'complex':
mask = ~mask
return order[np.where(mask)[0][0]] | [
"def",
"_nearest_real_complex_idx",
"(",
"fro",
",",
"to",
",",
"which",
")",
":",
"assert",
"which",
"in",
"(",
"'real'",
",",
"'complex'",
")",
"order",
"=",
"np",
".",
"argsort",
"(",
"np",
".",
"abs",
"(",
"fro",
"-",
"to",
")",
")",
"mask",
"=... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/filter_design.py#L890-L897 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/parfor.py | python | _can_reorder_stmts | (stmt, next_stmt, func_ir, call_table, alias_map) | return False | Check dependencies to determine if a parfor can be reordered in the IR block
with a non-parfor statement. | Check dependencies to determine if a parfor can be reordered in the IR block
with a non-parfor statement. | [
"Check",
"dependencies",
"to",
"determine",
"if",
"a",
"parfor",
"can",
"be",
"reordered",
"in",
"the",
"IR",
"block",
"with",
"a",
"non",
"-",
"parfor",
"statement",
"."
] | def _can_reorder_stmts(stmt, next_stmt, func_ir, call_table, alias_map):
"""
Check dependencies to determine if a parfor can be reordered in the IR block
with a non-parfor statement.
"""
# swap only parfors with non-parfors
# don't reorder calls with side effects (e.g. file close)
# only read-read dependencies are OK
# make sure there is no write-write, write-read dependencies
if (isinstance(
stmt, Parfor) and not isinstance(
next_stmt, Parfor) and not isinstance(
next_stmt, ir.Print)
and (not isinstance(next_stmt, ir.Assign)
or has_no_side_effect(
next_stmt.value, set(), call_table)
or guard(is_assert_equiv, func_ir, next_stmt.value))):
stmt_accesses = expand_aliases({v.name for v in stmt.list_vars()}, alias_map)
stmt_writes = expand_aliases(get_parfor_writes(stmt), alias_map)
next_accesses = expand_aliases({v.name for v in next_stmt.list_vars()}, alias_map)
next_writes = expand_aliases(get_stmt_writes(next_stmt), alias_map)
if len((stmt_writes & next_accesses)
| (next_writes & stmt_accesses)) == 0:
return True
return False | [
"def",
"_can_reorder_stmts",
"(",
"stmt",
",",
"next_stmt",
",",
"func_ir",
",",
"call_table",
",",
"alias_map",
")",
":",
"# swap only parfors with non-parfors",
"# don't reorder calls with side effects (e.g. file close)",
"# only read-read dependencies are OK",
"# make sure there... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/parfor.py#L3373-L3397 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/walls-and-gates.py | python | Solution.wallsAndGates | (self, rooms) | :type rooms: List[List[int]]
:rtype: void Do not return anything, modify rooms in-place instead. | :type rooms: List[List[int]]
:rtype: void Do not return anything, modify rooms in-place instead. | [
":",
"type",
"rooms",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"void",
"Do",
"not",
"return",
"anything",
"modify",
"rooms",
"in",
"-",
"place",
"instead",
"."
] | def wallsAndGates(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: void Do not return anything, modify rooms in-place instead.
"""
INF = 2147483647
q = deque([(i, j) for i, row in enumerate(rooms) for j, r in enumerate(row) if not r])
while q:
(i, j) = q.popleft()
for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1):
if 0 <= I < len(rooms) and 0 <= J < len(rooms[0]) and \
rooms[I][J] == INF:
rooms[I][J] = rooms[i][j] + 1
q.append((I, J)) | [
"def",
"wallsAndGates",
"(",
"self",
",",
"rooms",
")",
":",
"INF",
"=",
"2147483647",
"q",
"=",
"deque",
"(",
"[",
"(",
"i",
",",
"j",
")",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"rooms",
")",
"for",
"j",
",",
"r",
"in",
"enumerate",
... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/walls-and-gates.py#L7-L20 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/core/tensor/array_method.py | python | ArrayMethodMixin.transpose | (self, *args) | return _transpose(self, _expand_args(args)) | r"""See :func:`~.transpose`. | r"""See :func:`~.transpose`. | [
"r",
"See",
":",
"func",
":",
"~",
".",
"transpose",
"."
] | def transpose(self, *args):
r"""See :func:`~.transpose`."""
if self.ndim == 0:
assert (
len(args) == 0
), "transpose for scalar does not accept additional args"
ret = self.to(self.device)
return ret
if not args:
args = range(self.ndim)[::-1]
return _transpose(self, _expand_args(args)) | [
"def",
"transpose",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"ndim",
"==",
"0",
":",
"assert",
"(",
"len",
"(",
"args",
")",
"==",
"0",
")",
",",
"\"transpose for scalar does not accept additional args\"",
"ret",
"=",
"self",
".",
"to"... | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/core/tensor/array_method.py#L474-L484 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/ir_utils.py | python | fill_callee_prologue | (block, inputs, label_next) | return block | Fill a new block *block* that unwraps arguments using names in *inputs* and
then jumps to *label_next*.
Expected to use with *fill_block_with_call()* | Fill a new block *block* that unwraps arguments using names in *inputs* and
then jumps to *label_next*. | [
"Fill",
"a",
"new",
"block",
"*",
"block",
"*",
"that",
"unwraps",
"arguments",
"using",
"names",
"in",
"*",
"inputs",
"*",
"and",
"then",
"jumps",
"to",
"*",
"label_next",
"*",
"."
] | def fill_callee_prologue(block, inputs, label_next):
"""
Fill a new block *block* that unwraps arguments using names in *inputs* and
then jumps to *label_next*.
Expected to use with *fill_block_with_call()*
"""
scope = block.scope
loc = block.loc
# load args
args = [ir.Arg(name=k, index=i, loc=loc)
for i, k in enumerate(inputs)]
for aname, aval in zip(inputs, args):
tmp = ir.Var(scope=scope, name=aname, loc=loc)
block.append(ir.Assign(target=tmp, value=aval, loc=loc))
# jump to loop entry
block.append(ir.Jump(target=label_next, loc=loc))
return block | [
"def",
"fill_callee_prologue",
"(",
"block",
",",
"inputs",
",",
"label_next",
")",
":",
"scope",
"=",
"block",
".",
"scope",
"loc",
"=",
"block",
".",
"loc",
"# load args",
"args",
"=",
"[",
"ir",
".",
"Arg",
"(",
"name",
"=",
"k",
",",
"index",
"="... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/ir_utils.py#L1842-L1859 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py | python | IPv6Address.teredo | (self) | return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
IPv4Address(~self._ip & 0xFFFFFFFF)) | Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn't appear to be a teredo address (doesn't start with
2001::/32) | Tuple of embedded teredo IPs. | [
"Tuple",
"of",
"embedded",
"teredo",
"IPs",
"."
] | def teredo(self):
"""Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn't appear to be a teredo address (doesn't start with
2001::/32)
"""
if (self._ip >> 96) != 0x20010000:
return None
return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
IPv4Address(~self._ip & 0xFFFFFFFF)) | [
"def",
"teredo",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_ip",
">>",
"96",
")",
"!=",
"0x20010000",
":",
"return",
"None",
"return",
"(",
"IPv4Address",
"(",
"(",
"self",
".",
"_ip",
">>",
"64",
")",
"&",
"0xFFFFFFFF",
")",
",",
"IPv4Addres... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L2149-L2161 | |
Constellation/iv | 64c3a9c7c517063f29d90d449180ea8f6f4d946f | tools/cpplint.py | python | CleansedLines.NumLines | (self) | return self.num_lines | Returns the number of lines represented. | Returns the number of lines represented. | [
"Returns",
"the",
"number",
"of",
"lines",
"represented",
"."
] | def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines | [
"def",
"NumLines",
"(",
"self",
")",
":",
"return",
"self",
".",
"num_lines"
] | https://github.com/Constellation/iv/blob/64c3a9c7c517063f29d90d449180ea8f6f4d946f/tools/cpplint.py#L1192-L1194 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/gradients_util.py | python | _AggregatedGrads | (grads,
op,
gradient_uid,
loop_state,
aggregation_method=None) | return out_grads | Get the aggregated gradients for op.
Args:
grads: The map of memoized gradients.
op: The op to get gradients for.
gradient_uid: A unique identifier within the graph indicating
which invocation of gradients is being executed. Used to cluster
ops for compilation.
loop_state: An object for maintaining the state of the while loops in the
graph. It is of type ControlFlowState. None if the graph
contains no while loops.
aggregation_method: Specifies the method used to combine gradient terms.
Accepted values are constants defined in the class `AggregationMethod`.
Returns:
A list of gradients, one per each output of `op`. If the gradients
for a particular output is a list, this function aggregates it
before returning.
Raises:
TypeError: if the incoming grads are not Tensors or IndexedSlices.
ValueError: if the arguments are invalid. | Get the aggregated gradients for op. | [
"Get",
"the",
"aggregated",
"gradients",
"for",
"op",
"."
] | def _AggregatedGrads(grads,
op,
gradient_uid,
loop_state,
aggregation_method=None):
"""Get the aggregated gradients for op.
Args:
grads: The map of memoized gradients.
op: The op to get gradients for.
gradient_uid: A unique identifier within the graph indicating
which invocation of gradients is being executed. Used to cluster
ops for compilation.
loop_state: An object for maintaining the state of the while loops in the
graph. It is of type ControlFlowState. None if the graph
contains no while loops.
aggregation_method: Specifies the method used to combine gradient terms.
Accepted values are constants defined in the class `AggregationMethod`.
Returns:
A list of gradients, one per each output of `op`. If the gradients
for a particular output is a list, this function aggregates it
before returning.
Raises:
TypeError: if the incoming grads are not Tensors or IndexedSlices.
ValueError: if the arguments are invalid.
"""
if aggregation_method is None:
aggregation_method = AggregationMethod.DEFAULT
if aggregation_method not in [
AggregationMethod.ADD_N, AggregationMethod.EXPERIMENTAL_TREE,
AggregationMethod.EXPERIMENTAL_ACCUMULATE_N
]:
raise ValueError(
"Invalid aggregation_method specified %s." % aggregation_method)
out_grads = _GetGrads(grads, op)
for i, out_grad in enumerate(out_grads):
if loop_state:
if isinstance(out_grad, (ops.Tensor, ops.IndexedSlices)):
assert control_flow_util.IsLoopSwitch(op)
continue
# Grads have to be Tensors or IndexedSlices
if (isinstance(out_grad, collections_abc.Sequence) and not all(
isinstance(g, (ops.Tensor, ops.IndexedSlices))
for g in out_grad
if g is not None)):
raise TypeError("gradients have to be either all Tensors "
"or all IndexedSlices")
# Aggregate multiple gradients, and convert [] to None.
if out_grad:
if len(out_grad) < 2:
used = "nop"
out_grads[i] = out_grad[0]
elif all(isinstance(g, ops.Tensor) for g in out_grad if g is not None):
tensor_shape = _AccumulatorShape(out_grad)
if (aggregation_method == AggregationMethod.EXPERIMENTAL_ACCUMULATE_N
and len(out_grad) > 2 and tensor_shape.is_fully_defined()):
# The benefit of using AccumulateN is that its inputs can be combined
# in any order and this can allow the expression to be evaluated with
# a smaller memory footprint. When used with gpu_allocator_retry,
# it is possible to compute a sum of terms which are much larger than
# total GPU memory.
# AccumulateN can currently only be used if we know the shape for
# an accumulator variable. If this is not known, or if we only have
# 2 grads then we fall through to the "tree" case below.
used = "accumulate_n"
out_grads[i] = math_ops.accumulate_n(out_grad)
elif aggregation_method in [
AggregationMethod.EXPERIMENTAL_TREE,
AggregationMethod.EXPERIMENTAL_ACCUMULATE_N
]:
# Aggregate all gradients by doing pairwise sums: this may
# reduce performance, but it can improve memory because the
# gradients can be released earlier.
#
# TODO(vrv): Consider replacing this with a version of
# tf.AddN() that eagerly frees its inputs as soon as they are
# ready, so the order of this tree does not become a problem.
used = "tree"
with ops.name_scope(op.name + "_gradient_sum"):
running_sum = out_grad[0]
for grad in out_grad[1:]:
running_sum = math_ops.add_n([running_sum, grad])
out_grads[i] = running_sum
else:
used = "add_n"
out_grads[i] = _MultiDeviceAddN(out_grad, gradient_uid)
logging.vlog(2, " _AggregatedGrads %d x %s using %s", len(out_grad),
tensor_shape, used)
else:
out_grads[i] = backprop.aggregate_indexed_slices_gradients(out_grad) # pylint: disable=protected-access
else: # not out_grad
# out_grads[i] is [], thus its aggregation is simply None.
out_grads[i] = None
return out_grads | [
"def",
"_AggregatedGrads",
"(",
"grads",
",",
"op",
",",
"gradient_uid",
",",
"loop_state",
",",
"aggregation_method",
"=",
"None",
")",
":",
"if",
"aggregation_method",
"is",
"None",
":",
"aggregation_method",
"=",
"AggregationMethod",
".",
"DEFAULT",
"if",
"ag... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/gradients_util.py#L920-L1016 | |
twhui/LiteFlowNet | 00925aebf2db9ac50f4b1666f718688b10dd10d1 | python/caffe/net_spec.py | python | Top.to_proto | (self) | return to_proto(self) | Generate a NetParameter that contains all layers needed to compute
this top. | Generate a NetParameter that contains all layers needed to compute
this top. | [
"Generate",
"a",
"NetParameter",
"that",
"contains",
"all",
"layers",
"needed",
"to",
"compute",
"this",
"top",
"."
] | def to_proto(self):
"""Generate a NetParameter that contains all layers needed to compute
this top."""
return to_proto(self) | [
"def",
"to_proto",
"(",
"self",
")",
":",
"return",
"to_proto",
"(",
"self",
")"
] | https://github.com/twhui/LiteFlowNet/blob/00925aebf2db9ac50f4b1666f718688b10dd10d1/python/caffe/net_spec.py#L90-L94 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | DropSource.GetDataObject | (*args, **kwargs) | return _misc_.DropSource_GetDataObject(*args, **kwargs) | GetDataObject(self) -> DataObject | GetDataObject(self) -> DataObject | [
"GetDataObject",
"(",
"self",
")",
"-",
">",
"DataObject"
] | def GetDataObject(*args, **kwargs):
"""GetDataObject(self) -> DataObject"""
return _misc_.DropSource_GetDataObject(*args, **kwargs) | [
"def",
"GetDataObject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DropSource_GetDataObject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L5508-L5510 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/distutils/command/sdist.py | python | sdist.write_manifest | (self) | Write the file list in 'self.filelist' (presumably as filled in
by 'add_defaults()' and 'read_template()') to the manifest file
named by 'self.manifest'. | Write the file list in 'self.filelist' (presumably as filled in
by 'add_defaults()' and 'read_template()') to the manifest file
named by 'self.manifest'. | [
"Write",
"the",
"file",
"list",
"in",
"self",
".",
"filelist",
"(",
"presumably",
"as",
"filled",
"in",
"by",
"add_defaults",
"()",
"and",
"read_template",
"()",
")",
"to",
"the",
"manifest",
"file",
"named",
"by",
"self",
".",
"manifest",
"."
] | def write_manifest(self):
"""Write the file list in 'self.filelist' (presumably as filled in
by 'add_defaults()' and 'read_template()') to the manifest file
named by 'self.manifest'.
"""
if self._manifest_is_not_generated():
log.info("not writing to manually maintained "
"manifest file '%s'" % self.manifest)
return
content = self.filelist.files[:]
content.insert(0, '# file GENERATED by distutils, do NOT edit')
self.execute(file_util.write_file, (self.manifest, content),
"writing manifest file '%s'" % self.manifest) | [
"def",
"write_manifest",
"(",
"self",
")",
":",
"if",
"self",
".",
"_manifest_is_not_generated",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"not writing to manually maintained \"",
"\"manifest file '%s'\"",
"%",
"self",
".",
"manifest",
")",
"return",
"content",
"=... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/command/sdist.py#L359-L372 | ||
alibaba/weex_js_engine | 2bdf4b6f020c1fc99c63f649718f6faf7e27fdde | jni/v8core/v8/build/gyp/pylib/gyp/MSVSVersion.py | python | _ConvertToCygpath | (path) | return path | Convert to cygwin path if we are using cygwin. | Convert to cygwin path if we are using cygwin. | [
"Convert",
"to",
"cygwin",
"path",
"if",
"we",
"are",
"using",
"cygwin",
"."
] | def _ConvertToCygpath(path):
"""Convert to cygwin path if we are using cygwin."""
if sys.platform == 'cygwin':
p = subprocess.Popen(['cygpath', path], stdout=subprocess.PIPE)
path = p.communicate()[0].strip()
return path | [
"def",
"_ConvertToCygpath",
"(",
"path",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'cygwin'",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'cygpath'",
",",
"path",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"path",
"=",
"p... | https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/MSVSVersion.py#L270-L275 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | clang/tools/scan-build-py/lib/libscanbuild/intercept.py | python | parse_exec_trace | (filename) | Parse the file generated by the 'libear' preloaded library.
Given filename points to a file which contains the basic report
generated by the interception library or wrapper command. A single
report file _might_ contain multiple process creation info. | Parse the file generated by the 'libear' preloaded library. | [
"Parse",
"the",
"file",
"generated",
"by",
"the",
"libear",
"preloaded",
"library",
"."
] | def parse_exec_trace(filename):
""" Parse the file generated by the 'libear' preloaded library.
Given filename points to a file which contains the basic report
generated by the interception library or wrapper command. A single
report file _might_ contain multiple process creation info. """
logging.debug('parse exec trace file: %s', filename)
with open(filename, 'r') as handler:
content = handler.read()
for group in filter(bool, content.split(GS)):
records = group.split(RS)
yield {
'pid': records[0],
'ppid': records[1],
'function': records[2],
'directory': records[3],
'command': records[4].split(US)[:-1]
} | [
"def",
"parse_exec_trace",
"(",
"filename",
")",
":",
"logging",
".",
"debug",
"(",
"'parse exec trace file: %s'",
",",
"filename",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"handler",
":",
"content",
"=",
"handler",
".",
"read",
"(",
")... | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/tools/scan-build-py/lib/libscanbuild/intercept.py#L183-L201 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | build/android/android_commands.py | python | AndroidCommands.DropRamCaches | (self) | Drops the filesystem ram caches for performance testing. | Drops the filesystem ram caches for performance testing. | [
"Drops",
"the",
"filesystem",
"ram",
"caches",
"for",
"performance",
"testing",
"."
] | def DropRamCaches(self):
"""Drops the filesystem ram caches for performance testing."""
self.RunShellCommand('echo 3 > ' + DROP_CACHES) | [
"def",
"DropRamCaches",
"(",
"self",
")",
":",
"self",
".",
"RunShellCommand",
"(",
"'echo 3 > '",
"+",
"DROP_CACHES",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/build/android/android_commands.py#L523-L525 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/array_ops.py | python | placeholder | (dtype, shape=None, name=None) | return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name) | Inserts a placeholder for a tensor that will be always fed.
**Important**: This tensor will produce an error if evaluated. Its value must
be fed using the `feed_dict` optional argument to `Session.run()`,
`Tensor.eval()`, or `Operation.run()`.
For example:
```python
x = tf.compat.v1.placeholder(tf.float32, shape=(1024, 1024))
y = tf.matmul(x, x)
with tf.compat.v1.Session() as sess:
print(sess.run(y)) # ERROR: will fail because x was not fed.
rand_array = np.random.rand(1024, 1024)
print(sess.run(y, feed_dict={x: rand_array})) # Will succeed.
```
Args:
dtype: The type of elements in the tensor to be fed.
shape: The shape of the tensor to be fed (optional). If the shape is not
specified, you can feed a tensor of any shape.
name: A name for the operation (optional).
Returns:
A `Tensor` that may be used as a handle for feeding a value, but not
evaluated directly.
Raises:
RuntimeError: if eager execution is enabled
@compatibility(TF2)
This API is not compatible with eager execution and `tf.function`. To migrate
to TF2, rewrite the code to be compatible with eager execution. Check the
[migration
guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls)
on replacing `Session.run` calls. In TF2, you can just pass tensors directly
into ops and layers. If you want to explicitly set up your inputs, also see
[Keras functional API](https://www.tensorflow.org/guide/keras/functional) on
how to use `tf.keras.Input` to replace `tf.compat.v1.placeholder`.
`tf.function` arguments also do the job of `tf.compat.v1.placeholder`.
For more details please read [Better
performance with tf.function](https://www.tensorflow.org/guide/function).
@end_compatibility | Inserts a placeholder for a tensor that will be always fed. | [
"Inserts",
"a",
"placeholder",
"for",
"a",
"tensor",
"that",
"will",
"be",
"always",
"fed",
"."
] | def placeholder(dtype, shape=None, name=None):
"""Inserts a placeholder for a tensor that will be always fed.
**Important**: This tensor will produce an error if evaluated. Its value must
be fed using the `feed_dict` optional argument to `Session.run()`,
`Tensor.eval()`, or `Operation.run()`.
For example:
```python
x = tf.compat.v1.placeholder(tf.float32, shape=(1024, 1024))
y = tf.matmul(x, x)
with tf.compat.v1.Session() as sess:
print(sess.run(y)) # ERROR: will fail because x was not fed.
rand_array = np.random.rand(1024, 1024)
print(sess.run(y, feed_dict={x: rand_array})) # Will succeed.
```
Args:
dtype: The type of elements in the tensor to be fed.
shape: The shape of the tensor to be fed (optional). If the shape is not
specified, you can feed a tensor of any shape.
name: A name for the operation (optional).
Returns:
A `Tensor` that may be used as a handle for feeding a value, but not
evaluated directly.
Raises:
RuntimeError: if eager execution is enabled
@compatibility(TF2)
This API is not compatible with eager execution and `tf.function`. To migrate
to TF2, rewrite the code to be compatible with eager execution. Check the
[migration
guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls)
on replacing `Session.run` calls. In TF2, you can just pass tensors directly
into ops and layers. If you want to explicitly set up your inputs, also see
[Keras functional API](https://www.tensorflow.org/guide/keras/functional) on
how to use `tf.keras.Input` to replace `tf.compat.v1.placeholder`.
`tf.function` arguments also do the job of `tf.compat.v1.placeholder`.
For more details please read [Better
performance with tf.function](https://www.tensorflow.org/guide/function).
@end_compatibility
"""
if context.executing_eagerly():
raise RuntimeError("tf.placeholder() is not compatible with "
"eager execution.")
return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name) | [
"def",
"placeholder",
"(",
"dtype",
",",
"shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"context",
".",
"executing_eagerly",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"tf.placeholder() is not compatible with \"",
"\"eager execution.\"",
")",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/array_ops.py#L3295-L3346 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/math/vectorops.py | python | madd | (a,b,c) | return [ai+c*bi for ai,bi in zip(a,b)] | Return a+c*b where a and b are vectors. | Return a+c*b where a and b are vectors. | [
"Return",
"a",
"+",
"c",
"*",
"b",
"where",
"a",
"and",
"b",
"are",
"vectors",
"."
] | def madd(a,b,c):
"""Return a+c*b where a and b are vectors."""
if len(a)!=len(b):
raise RuntimeError('Vector dimensions not equal')
return [ai+c*bi for ai,bi in zip(a,b)] | [
"def",
"madd",
"(",
"a",
",",
"b",
",",
"c",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"raise",
"RuntimeError",
"(",
"'Vector dimensions not equal'",
")",
"return",
"[",
"ai",
"+",
"c",
"*",
"bi",
"for",
"ai",
",",
... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/vectorops.py#L14-L18 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | third-party/benchmark/tools/gbench/util.py | python | classify_input_file | (filename) | return ftype, err_msg | Return a tuple (type, msg) where 'type' specifies the classified type
of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable
string represeting the error. | Return a tuple (type, msg) where 'type' specifies the classified type
of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable
string represeting the error. | [
"Return",
"a",
"tuple",
"(",
"type",
"msg",
")",
"where",
"type",
"specifies",
"the",
"classified",
"type",
"of",
"filename",
".",
"If",
"type",
"is",
"IT_Invalid",
"then",
"msg",
"is",
"a",
"human",
"readable",
"string",
"represeting",
"the",
"error",
"."... | def classify_input_file(filename):
"""
Return a tuple (type, msg) where 'type' specifies the classified type
of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable
string represeting the error.
"""
ftype = IT_Invalid
err_msg = None
if not os.path.exists(filename):
err_msg = "'%s' does not exist" % filename
elif not os.path.isfile(filename):
err_msg = "'%s' does not name a file" % filename
elif is_executable_file(filename):
ftype = IT_Executable
elif is_json_file(filename):
ftype = IT_JSON
else:
err_msg = "'%s' does not name a valid benchmark executable or JSON file" % filename
return ftype, err_msg | [
"def",
"classify_input_file",
"(",
"filename",
")",
":",
"ftype",
"=",
"IT_Invalid",
"err_msg",
"=",
"None",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"err_msg",
"=",
"\"'%s' does not exist\"",
"%",
"filename",
"elif",
"not",
... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/third-party/benchmark/tools/gbench/util.py#L57-L75 | |
mlivesu/cinolib | e2dfe9c8fdcca241c752dbc7cf239f052c277904 | external/eigen/debug/gdb/printers.py | python | EigenSparseMatrixPrinter.__init__ | (self, val) | Extract all the necessary information | Extract all the necessary information | [
"Extract",
"all",
"the",
"necessary",
"information"
] | def __init__(self, val):
"Extract all the necessary information"
type = val.type
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
self.type = type.unqualified().strip_typedefs()
tag = self.type.tag
regex = re.compile('\<.*\>')
m = regex.findall(tag)[0][1:-1]
template_params = m.split(',')
template_params = [x.replace(" ", "") for x in template_params]
self.options = 0
if len(template_params) > 1:
self.options = template_params[1];
self.rowMajor = (int(self.options) & 0x1)
self.innerType = self.type.template_argument(0)
self.val = val
self.data = self.val['m_data']
self.data = self.data.cast(self.innerType.pointer()) | [
"def",
"__init__",
"(",
"self",
",",
"val",
")",
":",
"type",
"=",
"val",
".",
"type",
"if",
"type",
".",
"code",
"==",
"gdb",
".",
"TYPE_CODE_REF",
":",
"type",
"=",
"type",
".",
"target",
"(",
")",
"self",
".",
"type",
"=",
"type",
".",
"unqual... | https://github.com/mlivesu/cinolib/blob/e2dfe9c8fdcca241c752dbc7cf239f052c277904/external/eigen/debug/gdb/printers.py#L145-L169 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/fit_function_options_view.py | python | FitFunctionOptionsView.evaluation_type | (self) | return str(self.evaluation_combo.currentText()) | Returns the selected evaluation type. | Returns the selected evaluation type. | [
"Returns",
"the",
"selected",
"evaluation",
"type",
"."
] | def evaluation_type(self) -> str:
"""Returns the selected evaluation type."""
return str(self.evaluation_combo.currentText()) | [
"def",
"evaluation_type",
"(",
"self",
")",
"->",
"str",
":",
"return",
"str",
"(",
"self",
".",
"evaluation_combo",
".",
"currentText",
"(",
")",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/fit_function_options_view.py#L299-L301 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/random.py | python | __init__ | (self, x=None) | Initialize an instance.
Optional argument x controls seeding, as for Random.seed(). | Initialize an instance. | [
"Initialize",
"an",
"instance",
"."
] | def __init__(self, x=None):
"""Initialize an instance.
Optional argument x controls seeding, as for Random.seed().
"""
self.seed(x)
self.gauss_next = None | [
"def",
"__init__",
"(",
"self",
",",
"x",
"=",
"None",
")",
":",
"self",
".",
"seed",
"(",
"x",
")",
"self",
".",
"gauss_next",
"=",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/random.py#L117-L124 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py | python | _div_nearest | (a, b) | return q + (2*r + (q&1) > b) | Closest integer to a/b, a and b positive integers; rounds to even
in the case of a tie. | Closest integer to a/b, a and b positive integers; rounds to even
in the case of a tie. | [
"Closest",
"integer",
"to",
"a",
"/",
"b",
"a",
"and",
"b",
"positive",
"integers",
";",
"rounds",
"to",
"even",
"in",
"the",
"case",
"of",
"a",
"tie",
"."
] | def _div_nearest(a, b):
"""Closest integer to a/b, a and b positive integers; rounds to even
in the case of a tie.
"""
q, r = divmod(a, b)
return q + (2*r + (q&1) > b) | [
"def",
"_div_nearest",
"(",
"a",
",",
"b",
")",
":",
"q",
",",
"r",
"=",
"divmod",
"(",
"a",
",",
"b",
")",
"return",
"q",
"+",
"(",
"2",
"*",
"r",
"+",
"(",
"q",
"&",
"1",
")",
">",
"b",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L5538-L5544 | |
shogun-toolbox/shogun | 9b8d856971af5a295dd6ad70623ae45647a6334c | examples/meta/generator/parse.py | python | FastParser.p_string | (self, p) | string : STRINGLITERAL | string : STRINGLITERAL | [
"string",
":",
"STRINGLITERAL"
] | def p_string(self, p):
"string : STRINGLITERAL"
# Strip leading and trailing quotes
p[0] = {"StringLiteral": p[1][1:-1]} | [
"def",
"p_string",
"(",
"self",
",",
"p",
")",
":",
"# Strip leading and trailing quotes",
"p",
"[",
"0",
"]",
"=",
"{",
"\"StringLiteral\"",
":",
"p",
"[",
"1",
"]",
"[",
"1",
":",
"-",
"1",
"]",
"}"
] | https://github.com/shogun-toolbox/shogun/blob/9b8d856971af5a295dd6ad70623ae45647a6334c/examples/meta/generator/parse.py#L254-L257 | ||
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/utils/depend.py | python | depend_base.update_auto | (self) | Automatic update routine.
Updates the value when get has been called and self has been tainted. | Automatic update routine. | [
"Automatic",
"update",
"routine",
"."
] | def update_auto(self):
"""Automatic update routine.
Updates the value when get has been called and self has been tainted.
"""
if not self._synchro is None:
if (not self._name == self._synchro.manual):
self.set(self._func[self._synchro.manual](), manual=False)
else:
warning(self._name + " probably shouldn't be tainted (synchro)", verbosity.low)
elif not self._func is None:
self.set(self._func(), manual=False)
else:
warning(self._name + " probably shouldn't be tainted (value)", verbosity.low) | [
"def",
"update_auto",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_synchro",
"is",
"None",
":",
"if",
"(",
"not",
"self",
".",
"_name",
"==",
"self",
".",
"_synchro",
".",
"manual",
")",
":",
"self",
".",
"set",
"(",
"self",
".",
"_func",
"... | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/utils/depend.py#L239-L253 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/fixer_util.py | python | Subscript | (index_node) | return Node(syms.trailer, [Leaf(token.LBRACE, u"["),
index_node,
Leaf(token.RBRACE, u"]")]) | A numeric or string subscript | A numeric or string subscript | [
"A",
"numeric",
"or",
"string",
"subscript"
] | def Subscript(index_node):
"""A numeric or string subscript"""
return Node(syms.trailer, [Leaf(token.LBRACE, u"["),
index_node,
Leaf(token.RBRACE, u"]")]) | [
"def",
"Subscript",
"(",
"index_node",
")",
":",
"return",
"Node",
"(",
"syms",
".",
"trailer",
",",
"[",
"Leaf",
"(",
"token",
".",
"LBRACE",
",",
"u\"[\"",
")",
",",
"index_node",
",",
"Leaf",
"(",
"token",
".",
"RBRACE",
",",
"u\"]\"",
")",
"]",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/fixer_util.py#L79-L83 | |
eldar/deepcut-cnn | 928bf2f224fce132f6e4404b4c95fb017297a5e0 | scripts/cpp_lint.py | python | CheckInvalidIncrement | (filename, clean_lines, linenum, error) | Checks for invalid increment *count++.
For example following function:
void increment_counter(int* count) {
*count++;
}
is invalid, because it effectively does count++, moving pointer, and should
be replaced with ++*count, (*count)++ or *count += 1.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for invalid increment *count++. | [
"Checks",
"for",
"invalid",
"increment",
"*",
"count",
"++",
"."
] | def CheckInvalidIncrement(filename, clean_lines, linenum, error):
"""Checks for invalid increment *count++.
For example following function:
void increment_counter(int* count) {
*count++;
}
is invalid, because it effectively does count++, moving pointer, and should
be replaced with ++*count, (*count)++ or *count += 1.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if _RE_PATTERN_INVALID_INCREMENT.match(line):
error(filename, linenum, 'runtime/invalid_increment', 5,
'Changing pointer instead of value (or unused value of operator*).') | [
"def",
"CheckInvalidIncrement",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"_RE_PATTERN_INVALID_INCREMENT",
".",
"match",
"(",
"line",
")",
":",
"error",
... | https://github.com/eldar/deepcut-cnn/blob/928bf2f224fce132f6e4404b4c95fb017297a5e0/scripts/cpp_lint.py#L1733-L1752 | ||
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/utility.py | python | ArrayManager.plus_di | (self, n: int, array: bool = False) | return result[-1] | PLUS_DI. | PLUS_DI. | [
"PLUS_DI",
"."
] | def plus_di(self, n: int, array: bool = False) -> Union[float, np.ndarray]:
"""
PLUS_DI.
"""
result = talib.PLUS_DI(self.high, self.low, self.close, n)
if array:
return result
return result[-1] | [
"def",
"plus_di",
"(",
"self",
",",
"n",
":",
"int",
",",
"array",
":",
"bool",
"=",
"False",
")",
"->",
"Union",
"[",
"float",
",",
"np",
".",
"ndarray",
"]",
":",
"result",
"=",
"talib",
".",
"PLUS_DI",
"(",
"self",
".",
"high",
",",
"self",
... | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/utility.py#L768-L775 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/cli/analyzer_cli.py | python | DebugAnalyzer.list_inputs | (self, args, screen_info=None) | return output | Command handler for inputs.
Show inputs to a given node.
Args:
args: Command-line arguments, excluding the command prefix, as a list of
str.
screen_info: Optional dict input containing screen information such as
cols.
Returns:
Output text lines as a RichTextLines object. | Command handler for inputs. | [
"Command",
"handler",
"for",
"inputs",
"."
] | def list_inputs(self, args, screen_info=None):
"""Command handler for inputs.
Show inputs to a given node.
Args:
args: Command-line arguments, excluding the command prefix, as a list of
str.
screen_info: Optional dict input containing screen information such as
cols.
Returns:
Output text lines as a RichTextLines object.
"""
# Screen info not currently used by this handler. Include this line to
# mute pylint.
_ = screen_info
# TODO(cais): Use screen info to format the output lines more prettily,
# e.g., hanging indent of long node names.
parsed = self._arg_parsers["list_inputs"].parse_args(args)
output = self._list_inputs_or_outputs(
parsed.recursive,
parsed.node_name,
parsed.depth,
parsed.control,
parsed.op_type,
do_outputs=False)
node_name = debug_data.get_node_name(parsed.node_name)
_add_main_menu(output, node_name=node_name, enable_list_inputs=False)
return output | [
"def",
"list_inputs",
"(",
"self",
",",
"args",
",",
"screen_info",
"=",
"None",
")",
":",
"# Screen info not currently used by this handler. Include this line to",
"# mute pylint.",
"_",
"=",
"screen_info",
"# TODO(cais): Use screen info to format the output lines more prettily,",... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/cli/analyzer_cli.py#L757-L791 | |
xbmc/xbmc | 091211a754589fc40a2a1f239b0ce9f4ee138268 | xbmc/addons/kodi-dev-kit/tools/code-generator/src/generateCMake__CMAKE_TREEDATA_COMMON_addon_dev_kit_txt.py | python | GenerateCMake__CMAKE_TREEDATA_COMMON_addon_dev_kit_txt_RelatedCheck | (filename) | return True if filename == "cmake/treedata/common/addon_dev_kit.txt" else False | This function is called by git update to be able to assign changed files to the dev kit. | This function is called by git update to be able to assign changed files to the dev kit. | [
"This",
"function",
"is",
"called",
"by",
"git",
"update",
"to",
"be",
"able",
"to",
"assign",
"changed",
"files",
"to",
"the",
"dev",
"kit",
"."
] | def GenerateCMake__CMAKE_TREEDATA_COMMON_addon_dev_kit_txt_RelatedCheck(filename):
"""
This function is called by git update to be able to assign changed files to the dev kit.
"""
return True if filename == "cmake/treedata/common/addon_dev_kit.txt" else False | [
"def",
"GenerateCMake__CMAKE_TREEDATA_COMMON_addon_dev_kit_txt_RelatedCheck",
"(",
"filename",
")",
":",
"return",
"True",
"if",
"filename",
"==",
"\"cmake/treedata/common/addon_dev_kit.txt\"",
"else",
"False"
] | https://github.com/xbmc/xbmc/blob/091211a754589fc40a2a1f239b0ce9f4ee138268/xbmc/addons/kodi-dev-kit/tools/code-generator/src/generateCMake__CMAKE_TREEDATA_COMMON_addon_dev_kit_txt.py#L17-L21 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/cgi.py | python | FieldStorage.__contains__ | (self, key) | return any(item.name == key for item in self.list) | Dictionary style __contains__ method. | Dictionary style __contains__ method. | [
"Dictionary",
"style",
"__contains__",
"method",
"."
] | def __contains__(self, key):
"""Dictionary style __contains__ method."""
if self.list is None:
raise TypeError, "not indexable"
return any(item.name == key for item in self.list) | [
"def",
"__contains__",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"list",
"is",
"None",
":",
"raise",
"TypeError",
",",
"\"not indexable\"",
"return",
"any",
"(",
"item",
".",
"name",
"==",
"key",
"for",
"item",
"in",
"self",
".",
"list",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/cgi.py#L591-L595 | |
tensorflow/deepmath | b5b721f54de1d5d6a02d78f5da5995237f9995f9 | deepmath/deephol/utilities/proof_checker_lib.py | python | ocaml_proof_header | () | return [
'set_jrh_lexer;;', 'open Lib;;', 'open Printer;;',
'open Theorem_fingerprint;;', 'open Import_proofs;;', 'open Tactics;;',
'', 'Printer.current_encoding := Printer.Sexp;;', ''
] | Creates the prelude to the OCaml file; enabling the proofs to be loaded. | Creates the prelude to the OCaml file; enabling the proofs to be loaded. | [
"Creates",
"the",
"prelude",
"to",
"the",
"OCaml",
"file",
";",
"enabling",
"the",
"proofs",
"to",
"be",
"loaded",
"."
] | def ocaml_proof_header():
"""Creates the prelude to the OCaml file; enabling the proofs to be loaded."""
return [
'set_jrh_lexer;;', 'open Lib;;', 'open Printer;;',
'open Theorem_fingerprint;;', 'open Import_proofs;;', 'open Tactics;;',
'', 'Printer.current_encoding := Printer.Sexp;;', ''
] | [
"def",
"ocaml_proof_header",
"(",
")",
":",
"return",
"[",
"'set_jrh_lexer;;'",
",",
"'open Lib;;'",
",",
"'open Printer;;'",
",",
"'open Theorem_fingerprint;;'",
",",
"'open Import_proofs;;'",
",",
"'open Tactics;;'",
",",
"''",
",",
"'Printer.current_encoding := Printer.S... | https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/utilities/proof_checker_lib.py#L166-L172 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py | python | TarFile.extractfile | (self, member) | Extract a member from the archive as a file object. `member' may be
a filename or a TarInfo object. If `member' is a regular file, a
file-like object is returned. If `member' is a link, a file-like
object is constructed from the link's target. If `member' is none of
the above, None is returned.
The file-like object is read-only and provides the following
methods: read(), readline(), readlines(), seek() and tell() | Extract a member from the archive as a file object. `member' may be | [
"Extract",
"a",
"member",
"from",
"the",
"archive",
"as",
"a",
"file",
"object",
".",
"member",
"may",
"be"
] | def extractfile(self, member):
"""Extract a member from the archive as a file object. `member' may be
a filename or a TarInfo object. If `member' is a regular file, a
file-like object is returned. If `member' is a link, a file-like
object is constructed from the link's target. If `member' is none of
the above, None is returned.
The file-like object is read-only and provides the following
methods: read(), readline(), readlines(), seek() and tell()
"""
self._check("r")
if isinstance(member, str):
tarinfo = self.getmember(member)
else:
tarinfo = member
if tarinfo.isreg():
return self.fileobject(self, tarinfo)
elif tarinfo.type not in SUPPORTED_TYPES:
# If a member's type is unknown, it is treated as a
# regular file.
return self.fileobject(self, tarinfo)
elif tarinfo.islnk() or tarinfo.issym():
if isinstance(self.fileobj, _Stream):
# A small but ugly workaround for the case that someone tries
# to extract a (sym)link as a file-object from a non-seekable
# stream of tar blocks.
raise StreamError("cannot extract (sym)link as file object")
else:
# A (sym)link's file object is its target's file object.
return self.extractfile(self._find_link_target(tarinfo))
else:
# If there's no data associated with the member (directory, chrdev,
# blkdev, etc.), return None instead of a file object.
return None | [
"def",
"extractfile",
"(",
"self",
",",
"member",
")",
":",
"self",
".",
"_check",
"(",
"\"r\"",
")",
"if",
"isinstance",
"(",
"member",
",",
"str",
")",
":",
"tarinfo",
"=",
"self",
".",
"getmember",
"(",
"member",
")",
"else",
":",
"tarinfo",
"=",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L4397-L4469 | ||
rprichard/CxxCodeBrowser | a2fa83d2fe06119f0a7a1827b8167fab88b53561 | third_party/libre2/lib/codereview/codereview.py | python | pending | (ui, repo, *pats, **opts) | show pending changes
Lists pending changes followed by a list of unassigned but modified files. | show pending changes | [
"show",
"pending",
"changes"
] | def pending(ui, repo, *pats, **opts):
"""show pending changes
Lists pending changes followed by a list of unassigned but modified files.
"""
if codereview_disabled:
return codereview_disabled
quick = opts.get('quick', False)
short = opts.get('short', False)
m = LoadAllCL(ui, repo, web=not quick and not short)
names = m.keys()
names.sort()
for name in names:
cl = m[name]
if short:
ui.write(name + "\t" + line1(cl.desc) + "\n")
else:
ui.write(cl.PendingText(quick=quick) + "\n")
if short:
return
files = DefaultFiles(ui, repo, [])
if len(files) > 0:
s = "Changed files not in any CL:\n"
for f in files:
s += "\t" + f + "\n"
ui.write(s) | [
"def",
"pending",
"(",
"ui",
",",
"repo",
",",
"*",
"pats",
",",
"*",
"*",
"opts",
")",
":",
"if",
"codereview_disabled",
":",
"return",
"codereview_disabled",
"quick",
"=",
"opts",
".",
"get",
"(",
"'quick'",
",",
"False",
")",
"short",
"=",
"opts",
... | https://github.com/rprichard/CxxCodeBrowser/blob/a2fa83d2fe06119f0a7a1827b8167fab88b53561/third_party/libre2/lib/codereview/codereview.py#L1850-L1877 | ||
Cantera/cantera | 0119484b261967ccb55a0066c020599cacc312e4 | interfaces/cython/cantera/ctml2yaml.py | python | Phase.__init__ | (
self,
phase: etree.Element,
species_data: Dict[str, List["Species"]],
reaction_data: Dict[str, List["Reaction"]],
) | Represent an XML ``phase`` node.
:param phase:
XML node containing a phase definition.
:param species_data:
Mapping of species data sources to lists of `Species` instances.
:param reaction_data:
Mapping of reaction data sources to lists of `Reaction` instances.
This class processes the XML node of a phase definition and generates a mapping
for the YAML output. The mapping is stored in the ``attribs`` instance
attribute and automatically formatted to YAML by the `~Phase.to_yaml` class
method. | Represent an XML ``phase`` node. | [
"Represent",
"an",
"XML",
"phase",
"node",
"."
] | def __init__(
self,
phase: etree.Element,
species_data: Dict[str, List["Species"]],
reaction_data: Dict[str, List["Reaction"]],
):
"""Represent an XML ``phase`` node.
:param phase:
XML node containing a phase definition.
:param species_data:
Mapping of species data sources to lists of `Species` instances.
:param reaction_data:
Mapping of reaction data sources to lists of `Reaction` instances.
This class processes the XML node of a phase definition and generates a mapping
for the YAML output. The mapping is stored in the ``attribs`` instance
attribute and automatically formatted to YAML by the `~Phase.to_yaml` class
method.
"""
phase_name = phase.get("id")
if phase_name is None:
raise MissingXMLAttribute(
"The 'phase' node requires an 'id' attribute.", phase
)
self.attribs = BlockMap({"name": phase_name})
elem_text = phase.findtext("elementArray")
if elem_text is not None:
elements = elem_text.replace("\n", "").strip().split()
# This second check is necessary because self-closed tags
# have an empty text when checked with 'findtext' but
# have 'None' when 'find().text' is used
if elements:
self.attribs["elements"] = FlowList(elements)
species = []
speciesArray_nodes = phase.findall("speciesArray")
for sA_node in speciesArray_nodes:
species.append(self.get_species_array(sA_node))
species_skip = sA_node.find("skip")
if species_skip is not None:
element_skip = species_skip.get("element", "")
if element_skip == "undeclared":
self.attribs["skip-undeclared-elements"] = True
if species:
if len(species) == 1 and "species" in species[0]:
self.attribs.update(species[0])
else:
self.attribs["species"] = species
phase_thermo = phase.find("thermo")
if phase_thermo is None:
raise MissingXMLNode("The 'phase' node requires a 'thermo' node.", phase)
phase_thermo_model = phase_thermo.get("model")
if phase_thermo_model is None:
raise MissingXMLAttribute(
"The 'thermo' node requires a 'model' attribute.", phase_thermo
)
self.attribs["thermo"] = self.thermo_model_mapping[phase_thermo_model]
phases_text = phase.findtext("phaseArray")
if phases_text is not None:
adjacent_phases = phases_text.replace("\n", " ").strip().split()
if adjacent_phases:
self.attribs["adjacent-phases"] = FlowList(adjacent_phases)
if phase_thermo_model == "PureFluid":
pure_fluid_type = phase_thermo.get("fluid_type")
if pure_fluid_type is None:
raise MissingXMLAttribute(
"The 'PureFluid' model requires the 'fluid_type' attribute.",
phase_thermo,
)
self.attribs["pure-fluid-name"] = self.pure_fluid_mapping[pure_fluid_type]
elif phase_thermo_model == "HMW":
activity_coefficients = phase_thermo.find("activityCoefficients")
if activity_coefficients is None:
raise MissingXMLNode(
"The 'HMW' thermo model requires the 'activityCoefficients' node.",
phase_thermo,
)
self.attribs["activity-data"] = self.hmw_electrolyte(activity_coefficients)
elif phase_thermo_model == "DebyeHuckel":
activity_coefficients = phase_thermo.find("activityCoefficients")
if activity_coefficients is None:
raise MissingXMLNode(
"The 'DebyeHuckel' thermo model requires the "
"'activityCoefficients' node.",
phase_thermo,
)
self.attribs["activity-data"] = self.debye_huckel(
species, activity_coefficients, species_data
)
elif phase_thermo_model == "StoichSubstance":
self.move_density_to_species(species, phase_thermo, species_data)
elif phase_thermo_model == "RedlichKwongMFTP":
activity_coefficients = phase_thermo.find("activityCoefficients")
if activity_coefficients is not None:
self.move_RK_coeffs_to_species(
species, activity_coefficients, species_data
)
elif phase_thermo_model == "MaskellSolidSolnPhase":
try:
self.move_density_to_species(species, phase_thermo, species_data)
except MissingXMLNode:
pass
excess_h_node = phase_thermo.find("h_mix")
if excess_h_node is not None:
self.attribs["excess-enthalpy"] = get_float_or_quantity(excess_h_node)
product_spec_node = phase_thermo.find("product_species")
if product_spec_node is not None:
self.attribs["product-species"] = clean_node_text(product_spec_node)
elif phase_thermo_model == "IonsFromNeutralMolecule":
neutral_phase_node = phase_thermo.find("neutralMoleculePhase")
if neutral_phase_node is None:
raise MissingXMLNode(
"The 'IonsFromNeutralMolecule' phase requires the "
"'neutralMoleculePhase' node.",
phase_thermo,
)
neutral_phase_src = neutral_phase_node.get("datasrc")
if neutral_phase_src is None:
raise MissingXMLAttribute(
"The 'neutralMoleculePhase' requires the 'datasrc' attribute.",
neutral_phase_node,
)
filename, location = neutral_phase_src.split("#")
filename = str(Path(filename).with_suffix(".yaml"))
self.attribs["neutral-phase"] = "{}/{}".format(filename, location)
elif phase_thermo_model == "Redlich-Kister":
activity_coefficients = phase_thermo.find("activityCoefficients")
if activity_coefficients is None:
raise MissingXMLNode(
"The 'RedlichKister' thermo model requires the "
"'activityCoefficients' node.",
phase_thermo,
)
self.attribs["interactions"] = self.redlich_kister(activity_coefficients)
elif phase_thermo_model == "LatticeSolid":
lattice_array_node = phase_thermo.find("LatticeArray")
if lattice_array_node is None:
raise MissingXMLNode(
"The 'LatticeSolid' phase thermo requires a 'LatticeArray' node.",
phase_thermo,
)
self.lattice_nodes = [] # type: List[Phase]
for lattice_phase_node in lattice_array_node.findall("phase"):
self.lattice_nodes.append(
Phase(lattice_phase_node, species_data, reaction_data)
)
lattice_stoich_node = phase_thermo.find("LatticeStoichiometry")
if lattice_stoich_node is None:
raise MissingXMLNode(
"The 'LatticeSolid' phase thermo requires a "
"'LatticeStoichiometry' node.",
phase_thermo,
)
self.attribs["composition"] = {}
for phase_ratio in clean_node_text(lattice_stoich_node).split():
p_name, ratio = phase_ratio.rsplit(":", 1)
self.attribs["composition"][p_name.strip()] = float(ratio)
elif phase_thermo_model == "Margules":
activity_coefficients = phase_thermo.find("activityCoefficients")
if activity_coefficients is not None:
margules_interactions = self.margules(activity_coefficients)
if margules_interactions:
self.attribs["interactions"] = margules_interactions
elif phase_thermo_model == "IdealMolalSolution":
activity_coefficients = phase_thermo.find("activityCoefficients")
if activity_coefficients is not None:
ideal_molal_cutoff = self.ideal_molal_solution(activity_coefficients)
if ideal_molal_cutoff:
self.attribs["cutoff"] = ideal_molal_cutoff
for node in phase_thermo:
if node.tag == "site_density":
self.attribs["site-density"] = get_float_or_quantity(node)
elif node.tag == "density":
if self.attribs["thermo"] == "electron-cloud":
self.attribs["density"] = get_float_or_quantity(node)
elif node.tag == "tabulatedSpecies":
self.attribs["tabulated-species"] = node.get("name")
elif node.tag == "tabulatedThermo":
self.attribs["tabulated-thermo"] = self.get_tabulated_thermo(node)
transport_node = phase.find("transport")
if transport_node is not None:
transport_model = self.transport_model_mapping[transport_node.get("model")]
if transport_model is not None:
self.attribs["transport"] = transport_model
# The phase requires both a kinetics model and a set of
# reactions to include the kinetics
kinetics_node = phase.find("kinetics")
has_reactionArray = phase.find("reactionArray") is not None
if kinetics_node is not None and has_reactionArray:
kinetics_model = self.kinetics_model_mapping[kinetics_node.get("model", "")]
if kinetics_node.get("model", "").lower() == "solidkinetics":
warnings.warn(
"The SolidKinetics type is not implemented and will not be "
"included in the YAML output."
)
reactions = []
for rA_node in phase.iterfind("reactionArray"):
# If the reaction list associated with the datasrc for this
# reactionArray is missing or empty, don't do anything.
datasrc = rA_node.get("datasrc", "")
if datasrc.startswith("#") and not reaction_data.get(datasrc[1:]):
continue
reactions.append(self.get_reaction_array(rA_node, reaction_data))
# The reactions list may be empty, don't include any kinetics stuff
# if it is
if reactions and kinetics_model is not None:
self.attribs["kinetics"] = kinetics_model
# If there is one reactionArray and the datasrc was reaction_data
# (munged to just reactions) the output should be 'reactions: all',
# so we use update. Otherwise, there needs to be a list
# of mappings.
if len(reactions) == 1 and "reactions" in reactions[0]:
self.attribs.update(reactions[0])
else:
self.attribs["reactions"] = reactions
state_node = phase.find("state")
if state_node is not None:
phase_state = FlowMap()
for prop in state_node:
property_name = self.state_properties_mapping[prop.tag]
if prop.tag in [
"moleFractions",
"massFractions",
"coverages",
"soluteMolalities",
]:
composition = split_species_value_string(prop)
phase_state[property_name] = composition
else:
value = get_float_or_quantity(prop)
phase_state[property_name] = value
if phase_state:
self.attribs["state"] = phase_state
std_conc_node = phase.find("standardConc")
if std_conc_node is not None:
model = std_conc_node.get("model")
if model == "solvent_volume":
model = "solvent-molar-volume"
elif model == "molar_volume":
model = "species-molar-volume"
self.attribs["standard-concentration-basis"] = model
self.check_elements(species, species_data) | [
"def",
"__init__",
"(",
"self",
",",
"phase",
":",
"etree",
".",
"Element",
",",
"species_data",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"\"Species\"",
"]",
"]",
",",
"reaction_data",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"\"Reaction\"",
"]",
... | https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/ctml2yaml.py#L398-L652 | ||
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/generator/ninja.py | python | AddArch | (output, arch) | return '%s.%s%s' % (output, arch, extension) | Adds an arch string to an output path. | Adds an arch string to an output path. | [
"Adds",
"an",
"arch",
"string",
"to",
"an",
"output",
"path",
"."
] | def AddArch(output, arch):
"""Adds an arch string to an output path."""
output, extension = os.path.splitext(output)
return '%s.%s%s' % (output, arch, extension) | [
"def",
"AddArch",
"(",
"output",
",",
"arch",
")",
":",
"output",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"output",
")",
"return",
"'%s.%s%s'",
"%",
"(",
"output",
",",
"arch",
",",
"extension",
")"
] | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/ninja.py#L95-L98 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | AboutDialogInfo._GetWebSiteDescription | (*args, **kwargs) | return _misc_.AboutDialogInfo__GetWebSiteDescription(*args, **kwargs) | _GetWebSiteDescription(self) -> String | _GetWebSiteDescription(self) -> String | [
"_GetWebSiteDescription",
"(",
"self",
")",
"-",
">",
"String"
] | def _GetWebSiteDescription(*args, **kwargs):
"""_GetWebSiteDescription(self) -> String"""
return _misc_.AboutDialogInfo__GetWebSiteDescription(*args, **kwargs) | [
"def",
"_GetWebSiteDescription",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"AboutDialogInfo__GetWebSiteDescription",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L6771-L6773 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/util/_validators.py | python | validate_args_and_kwargs | (fname, args, kwargs, max_fname_arg_count, compat_args) | Checks whether parameters passed to the *args and **kwargs argument in a
function `fname` are valid parameters as specified in `*compat_args`
and whether or not they are set to their default values.
Parameters
----------
fname: str
The name of the function being passed the `**kwargs` parameter
args: tuple
The `*args` parameter passed into a function
kwargs: dict
The `**kwargs` parameter passed into `fname`
max_fname_arg_count: int
The minimum number of arguments that the function `fname`
requires, excluding those in `args`. Used for displaying
appropriate error messages. Must be non-negative.
compat_args: dict
A dictionary of keys that `kwargs` is allowed to
have and their associated default values.
Raises
------
TypeError if `args` contains more values than there are
`compat_args` OR `kwargs` contains keys not in `compat_args`
ValueError if `args` contains values not at the default value (`None`)
`kwargs` contains keys in `compat_args` that do not map to the default
value as specified in `compat_args`
See Also
--------
validate_args : Purely args validation.
validate_kwargs : Purely kwargs validation. | Checks whether parameters passed to the *args and **kwargs argument in a
function `fname` are valid parameters as specified in `*compat_args`
and whether or not they are set to their default values. | [
"Checks",
"whether",
"parameters",
"passed",
"to",
"the",
"*",
"args",
"and",
"**",
"kwargs",
"argument",
"in",
"a",
"function",
"fname",
"are",
"valid",
"parameters",
"as",
"specified",
"in",
"*",
"compat_args",
"and",
"whether",
"or",
"not",
"they",
"are",... | def validate_args_and_kwargs(fname, args, kwargs, max_fname_arg_count, compat_args):
"""
Checks whether parameters passed to the *args and **kwargs argument in a
function `fname` are valid parameters as specified in `*compat_args`
and whether or not they are set to their default values.
Parameters
----------
fname: str
The name of the function being passed the `**kwargs` parameter
args: tuple
The `*args` parameter passed into a function
kwargs: dict
The `**kwargs` parameter passed into `fname`
max_fname_arg_count: int
The minimum number of arguments that the function `fname`
requires, excluding those in `args`. Used for displaying
appropriate error messages. Must be non-negative.
compat_args: dict
A dictionary of keys that `kwargs` is allowed to
have and their associated default values.
Raises
------
TypeError if `args` contains more values than there are
`compat_args` OR `kwargs` contains keys not in `compat_args`
ValueError if `args` contains values not at the default value (`None`)
`kwargs` contains keys in `compat_args` that do not map to the default
value as specified in `compat_args`
See Also
--------
validate_args : Purely args validation.
validate_kwargs : Purely kwargs validation.
"""
# Check that the total number of arguments passed in (i.e.
# args and kwargs) does not exceed the length of compat_args
_check_arg_length(
fname, args + tuple(kwargs.values()), max_fname_arg_count, compat_args
)
# Check there is no overlap with the positional and keyword
# arguments, similar to what is done in actual Python functions
args_dict = dict(zip(compat_args, args))
for key in args_dict:
if key in kwargs:
raise TypeError(
f"{fname}() got multiple values for keyword argument '{key}'"
)
kwargs.update(args_dict)
validate_kwargs(fname, kwargs, compat_args) | [
"def",
"validate_args_and_kwargs",
"(",
"fname",
",",
"args",
",",
"kwargs",
",",
"max_fname_arg_count",
",",
"compat_args",
")",
":",
"# Check that the total number of arguments passed in (i.e.",
"# args and kwargs) does not exceed the length of compat_args",
"_check_arg_length",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/util/_validators.py#L151-L204 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_Shutdown_REQUEST.toTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def toTpm(self, buf):
""" TpmMarshaller method """
buf.writeShort(self.shutdownType) | [
"def",
"toTpm",
"(",
"self",
",",
"buf",
")",
":",
"buf",
".",
"writeShort",
"(",
"self",
".",
"shutdownType",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L9100-L9102 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/altgraph/altgraph/Graph.py | python | Graph.__init__ | (self, edges=None) | Initialization | Initialization | [
"Initialization"
] | def __init__(self, edges=None):
"""
Initialization
"""
self.next_edge = 0
self.nodes, self.edges = {}, {}
self.hidden_edges, self.hidden_nodes = {}, {}
if edges is not None:
for item in edges:
if len(item) == 2:
head, tail = item
self.add_edge(head, tail)
elif len(item) == 3:
head, tail, data = item
self.add_edge(head, tail, data)
else:
raise GraphError("Cannot create edge from %s"%(item,)) | [
"def",
"__init__",
"(",
"self",
",",
"edges",
"=",
"None",
")",
":",
"self",
".",
"next_edge",
"=",
"0",
"self",
".",
"nodes",
",",
"self",
".",
"edges",
"=",
"{",
"}",
",",
"{",
"}",
"self",
".",
"hidden_edges",
",",
"self",
".",
"hidden_nodes",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/altgraph/altgraph/Graph.py#L39-L57 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/XRCed/component.py | python | Container.getChildObject | (self, node, obj, index) | Get index'th child of a tested interface element. | Get index'th child of a tested interface element. | [
"Get",
"index",
"th",
"child",
"of",
"a",
"tested",
"interface",
"element",
"."
] | def getChildObject(self, node, obj, index):
"""Get index'th child of a tested interface element."""
if isinstance(obj, wx.Window) and obj.GetSizer():
return obj.GetSizer()
try:
return obj.GetChildren()[index]
except IndexError:
return None | [
"def",
"getChildObject",
"(",
"self",
",",
"node",
",",
"obj",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"wx",
".",
"Window",
")",
"and",
"obj",
".",
"GetSizer",
"(",
")",
":",
"return",
"obj",
".",
"GetSizer",
"(",
")",
"try",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/XRCed/component.py#L426-L433 | ||
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/google/protobuf/message.py | python | Message.IsInitialized | (self) | Checks if the message is initialized.
Returns:
The method returns True if the message is initialized (i.e. all of its
required fields are set). | Checks if the message is initialized. | [
"Checks",
"if",
"the",
"message",
"is",
"initialized",
"."
] | def IsInitialized(self):
"""Checks if the message is initialized.
Returns:
The method returns True if the message is initialized (i.e. all of its
required fields are set).
"""
raise NotImplementedError | [
"def",
"IsInitialized",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/message.py#L133-L140 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.BeginStyle | (*args, **kwargs) | return _richtext.RichTextCtrl_BeginStyle(*args, **kwargs) | BeginStyle(self, RichTextAttr style) -> bool
Begin using a style | BeginStyle(self, RichTextAttr style) -> bool | [
"BeginStyle",
"(",
"self",
"RichTextAttr",
"style",
")",
"-",
">",
"bool"
] | def BeginStyle(*args, **kwargs):
"""
BeginStyle(self, RichTextAttr style) -> bool
Begin using a style
"""
return _richtext.RichTextCtrl_BeginStyle(*args, **kwargs) | [
"def",
"BeginStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_BeginStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3315-L3321 | |
lawy623/SVS | b7c7ae367c82a4797ff4a896a2ff304f02e7f724 | caffe/scripts/cpp_lint.py | python | RemoveMultiLineComments | (filename, lines, error) | Removes multiline (c-style) comments from lines. | Removes multiline (c-style) comments from lines. | [
"Removes",
"multiline",
"(",
"c",
"-",
"style",
")",
"comments",
"from",
"lines",
"."
] | def RemoveMultiLineComments(filename, lines, error):
"""Removes multiline (c-style) comments from lines."""
lineix = 0
while lineix < len(lines):
lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
if lineix_begin >= len(lines):
return
lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
if lineix_end >= len(lines):
error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
'Could not find end of multi-line comment')
return
RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
lineix = lineix_end + 1 | [
"def",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"lineix",
"=",
"0",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"lineix_begin",
"=",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
"if",
... | https://github.com/lawy623/SVS/blob/b7c7ae367c82a4797ff4a896a2ff304f02e7f724/caffe/scripts/cpp_lint.py#L1151-L1164 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/input.py | python | _enqueue | (queue, tensor_list, threads, enqueue_many, keep_input) | Enqueue `tensor_list` in `queue`. | Enqueue `tensor_list` in `queue`. | [
"Enqueue",
"tensor_list",
"in",
"queue",
"."
] | def _enqueue(queue, tensor_list, threads, enqueue_many, keep_input):
"""Enqueue `tensor_list` in `queue`."""
if enqueue_many:
enqueue_fn = queue.enqueue_many
else:
enqueue_fn = queue.enqueue
if keep_input.shape.ndims == 1:
enqueue_ops = [
enqueue_fn(_select_which_to_enqueue(tensor_list, keep_input))] * threads
else:
enqueue_ops = [utils.smart_cond(
keep_input,
lambda: enqueue_fn(tensor_list),
control_flow_ops.no_op)] * threads
queue_runner.add_queue_runner(queue_runner.QueueRunner(queue, enqueue_ops)) | [
"def",
"_enqueue",
"(",
"queue",
",",
"tensor_list",
",",
"threads",
",",
"enqueue_many",
",",
"keep_input",
")",
":",
"if",
"enqueue_many",
":",
"enqueue_fn",
"=",
"queue",
".",
"enqueue_many",
"else",
":",
"enqueue_fn",
"=",
"queue",
".",
"enqueue",
"if",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/input.py#L735-L749 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextParagraphLayoutBox.CopyFragment | (*args, **kwargs) | return _richtext.RichTextParagraphLayoutBox_CopyFragment(*args, **kwargs) | CopyFragment(self, RichTextRange range, RichTextParagraphLayoutBox fragment) -> bool | CopyFragment(self, RichTextRange range, RichTextParagraphLayoutBox fragment) -> bool | [
"CopyFragment",
"(",
"self",
"RichTextRange",
"range",
"RichTextParagraphLayoutBox",
"fragment",
")",
"-",
">",
"bool"
] | def CopyFragment(*args, **kwargs):
"""CopyFragment(self, RichTextRange range, RichTextParagraphLayoutBox fragment) -> bool"""
return _richtext.RichTextParagraphLayoutBox_CopyFragment(*args, **kwargs) | [
"def",
"CopyFragment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextParagraphLayoutBox_CopyFragment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L1814-L1816 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/longest-duplicate-substring.py | python | Solution.longestDupSubstring | (self, S) | return S[result:result + right] | :type S: str
:rtype: str | :type S: str
:rtype: str | [
":",
"type",
"S",
":",
"str",
":",
"rtype",
":",
"str"
] | def longestDupSubstring(self, S):
"""
:type S: str
:rtype: str
"""
M = 10**9+7
D = 26
def check(S, L):
p = pow(D, L, M)
curr = reduce(lambda x, y: (D*x+ord(y)-ord('a')) % M, S[:L], 0)
lookup = collections.defaultdict(list)
lookup[curr].append(L-1)
for i in xrange(L, len(S)):
curr = ((D*curr) % M + ord(S[i])-ord('a') -
((ord(S[i-L])-ord('a'))*p) % M) % M
if curr in lookup:
for j in lookup[curr]: # check if string is the same when hash is the same
if S[j-L+1:j+1] == S[i-L+1:i+1]:
return i-L+1
lookup[curr].append(i)
return 0
left, right = 1, len(S)-1
while left <= right:
mid = left + (right-left)//2
if not check(S, mid):
right = mid-1
else:
left = mid+1
result = check(S, right)
return S[result:result + right] | [
"def",
"longestDupSubstring",
"(",
"self",
",",
"S",
")",
":",
"M",
"=",
"10",
"**",
"9",
"+",
"7",
"D",
"=",
"26",
"def",
"check",
"(",
"S",
",",
"L",
")",
":",
"p",
"=",
"pow",
"(",
"D",
",",
"L",
",",
"M",
")",
"curr",
"=",
"reduce",
"... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/longest-duplicate-substring.py#L13-L44 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/ndarray/sparse.py | python | BaseSparseNDArray.__repr__ | (self) | return '\n<%s %s @%s>' % (self.__class__.__name__,
shape_info, self.context) | Returns a string representation of the sparse array. | Returns a string representation of the sparse array. | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"sparse",
"array",
"."
] | def __repr__(self):
"""Returns a string representation of the sparse array."""
shape_info = 'x'.join(['%d' % x for x in self.shape])
# The data content is not displayed since the array usually has big shape
return '\n<%s %s @%s>' % (self.__class__.__name__,
shape_info, self.context) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"shape_info",
"=",
"'x'",
".",
"join",
"(",
"[",
"'%d'",
"%",
"x",
"for",
"x",
"in",
"self",
".",
"shape",
"]",
")",
"# The data content is not displayed since the array usually has big shape",
"return",
"'\\n<%s %s @%s>'"... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/ndarray/sparse.py#L110-L115 | |
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/service_reflection.py | python | _ServiceBuilder.__init__ | (self, service_descriptor) | Initializes an instance of the service class builder.
Args:
service_descriptor: ServiceDescriptor to use when constructing the
service class. | Initializes an instance of the service class builder. | [
"Initializes",
"an",
"instance",
"of",
"the",
"service",
"class",
"builder",
"."
] | def __init__(self, service_descriptor):
"""Initializes an instance of the service class builder.
Args:
service_descriptor: ServiceDescriptor to use when constructing the
service class.
"""
self.descriptor = service_descriptor | [
"def",
"__init__",
"(",
"self",
",",
"service_descriptor",
")",
":",
"self",
".",
"descriptor",
"=",
"service_descriptor"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/service_reflection.py#L127-L134 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/package_index.py | python | distros_for_url | (url, metadata=None) | Yield egg or source distribution objects that might be found at a URL | Yield egg or source distribution objects that might be found at a URL | [
"Yield",
"egg",
"or",
"source",
"distribution",
"objects",
"that",
"might",
"be",
"found",
"at",
"a",
"URL"
] | def distros_for_url(url, metadata=None):
"""Yield egg or source distribution objects that might be found at a URL"""
base, fragment = egg_info_for_url(url)
for dist in distros_for_location(url, base, metadata):
yield dist
if fragment:
match = EGG_FRAGMENT.match(fragment)
if match:
for dist in interpret_distro_name(
url, match.group(1), metadata, precedence=CHECKOUT_DIST
):
yield dist | [
"def",
"distros_for_url",
"(",
"url",
",",
"metadata",
"=",
"None",
")",
":",
"base",
",",
"fragment",
"=",
"egg_info_for_url",
"(",
"url",
")",
"for",
"dist",
"in",
"distros_for_location",
"(",
"url",
",",
"base",
",",
"metadata",
")",
":",
"yield",
"di... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/package_index.py#L97-L108 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | utils/indigo-service/service/v2/imago_api.py | python | pass_to_res | (self, args, time=None) | return task_id | Parent task to remove_task and pass_args. Used to return id of pass_args
and launch time limit in seconds for task's results existence if it was passed in request.
:param self:
:param args: list of imago console commands
:param time: time limit in seconds of task existence
:return: task id for retrieving results by POST request | Parent task to remove_task and pass_args. Used to return id of pass_args
and launch time limit in seconds for task's results existence if it was passed in request.
:param self:
:param args: list of imago console commands
:param time: time limit in seconds of task existence
:return: task id for retrieving results by POST request | [
"Parent",
"task",
"to",
"remove_task",
"and",
"pass_args",
".",
"Used",
"to",
"return",
"id",
"of",
"pass_args",
"and",
"launch",
"time",
"limit",
"in",
"seconds",
"for",
"task",
"s",
"results",
"existence",
"if",
"it",
"was",
"passed",
"in",
"request",
".... | def pass_to_res(self, args, time=None):
"""
Parent task to remove_task and pass_args. Used to return id of pass_args
and launch time limit in seconds for task's results existence if it was passed in request.
:param self:
:param args: list of imago console commands
:param time: time limit in seconds of task existence
:return: task id for retrieving results by POST request
"""
task_id = pass_args.apply_async(args=(args,)).id
if time:
# launch deleting task results after certain
remove_task.apply_async(
kwargs={"task_id": task_id, "args": args}, countdown=time
)
return task_id | [
"def",
"pass_to_res",
"(",
"self",
",",
"args",
",",
"time",
"=",
"None",
")",
":",
"task_id",
"=",
"pass_args",
".",
"apply_async",
"(",
"args",
"=",
"(",
"args",
",",
")",
")",
".",
"id",
"if",
"time",
":",
"# launch deleting task results after certain",... | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/utils/indigo-service/service/v2/imago_api.py#L75-L90 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/extras/msvs.py | python | options | (ctx) | If the msvs option is used, try to detect if the build is made from visual studio | If the msvs option is used, try to detect if the build is made from visual studio | [
"If",
"the",
"msvs",
"option",
"is",
"used",
"try",
"to",
"detect",
"if",
"the",
"build",
"is",
"made",
"from",
"visual",
"studio"
] | def options(ctx):
"""
If the msvs option is used, try to detect if the build is made from visual studio
"""
ctx.add_option('--execsolution', action='store', help='when building with visual studio, use a build state file')
old = BuildContext.execute
def override_build_state(ctx):
def lock(rm, add):
uns = ctx.options.execsolution.replace('.sln', rm)
uns = ctx.root.make_node(uns)
try:
uns.delete()
except:
pass
uns = ctx.options.execsolution.replace('.sln', add)
uns = ctx.root.make_node(uns)
try:
uns.write('')
except:
pass
if ctx.options.execsolution:
ctx.launch_dir = Context.top_dir # force a build for the whole project (invalid cwd when called by visual studio)
lock('.lastbuildstate', '.unsuccessfulbuild')
old(ctx)
lock('.unsuccessfulbuild', '.lastbuildstate')
else:
old(ctx)
BuildContext.execute = override_build_state | [
"def",
"options",
"(",
"ctx",
")",
":",
"ctx",
".",
"add_option",
"(",
"'--execsolution'",
",",
"action",
"=",
"'store'",
",",
"help",
"=",
"'when building with visual studio, use a build state file'",
")",
"old",
"=",
"BuildContext",
".",
"execute",
"def",
"overr... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/msvs.py#L980-L1010 | ||
google/mediapipe | e6c19885c6d3c6f410c730952aeed2852790d306 | mediapipe/python/solutions/selfie_segmentation.py | python | SelfieSegmentation.__init__ | (self, model_selection=0) | Initializes a MediaPipe Selfie Segmentation object.
Args:
model_selection: 0 or 1. 0 to select a general-purpose model, and 1 to
select a model more optimized for landscape images. See details in
https://solutions.mediapipe.dev/selfie_segmentation#model_selection. | Initializes a MediaPipe Selfie Segmentation object. | [
"Initializes",
"a",
"MediaPipe",
"Selfie",
"Segmentation",
"object",
"."
] | def __init__(self, model_selection=0):
"""Initializes a MediaPipe Selfie Segmentation object.
Args:
model_selection: 0 or 1. 0 to select a general-purpose model, and 1 to
select a model more optimized for landscape images. See details in
https://solutions.mediapipe.dev/selfie_segmentation#model_selection.
"""
super().__init__(
binary_graph_path=_BINARYPB_FILE_PATH,
side_inputs={
'model_selection': model_selection,
},
outputs=['segmentation_mask']) | [
"def",
"__init__",
"(",
"self",
",",
"model_selection",
"=",
"0",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"binary_graph_path",
"=",
"_BINARYPB_FILE_PATH",
",",
"side_inputs",
"=",
"{",
"'model_selection'",
":",
"model_selection",
",",
"}",
",",
"o... | https://github.com/google/mediapipe/blob/e6c19885c6d3c6f410c730952aeed2852790d306/mediapipe/python/solutions/selfie_segmentation.py#L46-L59 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/variable_scope.py | python | _pure_variable_scope | (name_or_scope,
reuse=None,
initializer=None,
regularizer=None,
caching_device=None,
partitioner=None,
custom_getter=None,
old_name_scope=None,
dtype=dtypes.float32) | Creates a context for the variable_scope, see `variable_scope` for docs.
Note: this does not create a name scope.
Args:
name_or_scope: `string` or `VariableScope`: the scope to open.
reuse: `True` or `None`; if `True`, we go into reuse mode for this scope as
well as all sub-scopes; if `None`, we just inherit the parent scope reuse.
initializer: default initializer for variables within this scope.
regularizer: default regularizer for variables within this scope.
caching_device: default caching device for variables within this scope.
partitioner: default partitioner for variables within this scope.
custom_getter: default custom getter for variables within this scope.
old_name_scope: the original name scope when re-entering a variable scope.
dtype: type of the variables within this scope (defaults to `DT_FLOAT`).
Yields:
A scope that can be to captured and reused.
Raises:
ValueError: when trying to reuse within a create scope, or create within
a reuse scope, or if reuse is not `None` or `True`.
TypeError: when the types of some arguments are not appropriate. | Creates a context for the variable_scope, see `variable_scope` for docs. | [
"Creates",
"a",
"context",
"for",
"the",
"variable_scope",
"see",
"variable_scope",
"for",
"docs",
"."
] | def _pure_variable_scope(name_or_scope,
reuse=None,
initializer=None,
regularizer=None,
caching_device=None,
partitioner=None,
custom_getter=None,
old_name_scope=None,
dtype=dtypes.float32):
"""Creates a context for the variable_scope, see `variable_scope` for docs.
Note: this does not create a name scope.
Args:
name_or_scope: `string` or `VariableScope`: the scope to open.
reuse: `True` or `None`; if `True`, we go into reuse mode for this scope as
well as all sub-scopes; if `None`, we just inherit the parent scope reuse.
initializer: default initializer for variables within this scope.
regularizer: default regularizer for variables within this scope.
caching_device: default caching device for variables within this scope.
partitioner: default partitioner for variables within this scope.
custom_getter: default custom getter for variables within this scope.
old_name_scope: the original name scope when re-entering a variable scope.
dtype: type of the variables within this scope (defaults to `DT_FLOAT`).
Yields:
A scope that can be to captured and reused.
Raises:
ValueError: when trying to reuse within a create scope, or create within
a reuse scope, or if reuse is not `None` or `True`.
TypeError: when the types of some arguments are not appropriate.
"""
get_variable_scope() # Ensure that a default exists, then get a pointer.
# Get the reference to the collection as we want to modify it in place.
default_varscope = ops.get_collection_ref(_VARSCOPE_KEY)
old = default_varscope[0]
var_store = _get_default_variable_store()
if isinstance(name_or_scope, VariableScope):
new_name = name_or_scope.name
else:
new_name = old.name + "/" + name_or_scope if old.name else name_or_scope
try:
var_store.open_variable_scope(new_name)
if isinstance(name_or_scope, VariableScope):
name_scope = name_or_scope._name_scope # pylint: disable=protected-access
# Handler for the case when we jump to a shared scope.
# We create a new VariableScope (default_varscope[0]) that contains
# a copy of the provided shared scope, possibly with changed reuse
# and initializer, if the user requested this.
default_varscope[0] = VariableScope(
name_or_scope.reuse if reuse is None else reuse,
name=new_name,
initializer=name_or_scope.initializer,
regularizer=name_or_scope.regularizer,
caching_device=name_or_scope.caching_device,
partitioner=name_or_scope.partitioner,
dtype=name_or_scope.dtype,
custom_getter=name_or_scope.custom_getter,
name_scope=name_scope)
if initializer is not None:
default_varscope[0].set_initializer(initializer)
if regularizer is not None:
default_varscope[0].set_regularizer(regularizer)
if caching_device is not None:
default_varscope[0].set_caching_device(caching_device)
if partitioner is not None:
default_varscope[0].set_partitioner(partitioner)
if custom_getter is not None:
default_varscope[0].set_custom_getter(custom_getter)
if dtype is not None:
default_varscope[0].set_dtype(dtype)
yield default_varscope[0]
else:
# Handler for the case when we just prolong current variable scope.
# VariableScope with name extended by the provided one, and inherited
# reuse and initializer (except if the user provided values to set).
reuse = reuse or old.reuse # Re-using is inherited by sub-scopes.
default_varscope[0] = VariableScope(
reuse,
name=new_name,
initializer=old.initializer,
regularizer=old.regularizer,
caching_device=old.caching_device,
partitioner=old.partitioner,
dtype=old.dtype,
custom_getter=old.custom_getter,
name_scope=old_name_scope or name_or_scope)
if initializer is not None:
default_varscope[0].set_initializer(initializer)
if regularizer is not None:
default_varscope[0].set_regularizer(regularizer)
if caching_device is not None:
default_varscope[0].set_caching_device(caching_device)
if partitioner is not None:
default_varscope[0].set_partitioner(partitioner)
if custom_getter is not None:
default_varscope[0].set_custom_getter(custom_getter)
if dtype is not None:
default_varscope[0].set_dtype(dtype)
yield default_varscope[0]
finally:
var_store.close_variable_subscopes(new_name)
default_varscope[0] = old | [
"def",
"_pure_variable_scope",
"(",
"name_or_scope",
",",
"reuse",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"regularizer",
"=",
"None",
",",
"caching_device",
"=",
"None",
",",
"partitioner",
"=",
"None",
",",
"custom_getter",
"=",
"None",
",",
"ol... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/variable_scope.py#L1131-L1235 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/ops.py | python | Graph.finalize | (self) | Finalizes this graph, making it read-only.
After calling `g.finalize()`, no new operations can be added to
`g`. This method is used to ensure that no operations are added
to a graph when it is shared between multiple threads, for example
when using a [`QueueRunner`](../../api_docs/python/train.md#QueueRunner). | Finalizes this graph, making it read-only. | [
"Finalizes",
"this",
"graph",
"making",
"it",
"read",
"-",
"only",
"."
] | def finalize(self):
"""Finalizes this graph, making it read-only.
After calling `g.finalize()`, no new operations can be added to
`g`. This method is used to ensure that no operations are added
to a graph when it is shared between multiple threads, for example
when using a [`QueueRunner`](../../api_docs/python/train.md#QueueRunner).
"""
self._finalized = True | [
"def",
"finalize",
"(",
"self",
")",
":",
"self",
".",
"_finalized",
"=",
"True"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/ops.py#L2072-L2080 | ||
interpretml/interpret | 29466bffc04505fe4f836a83fcfebfd313ac8454 | python/interpret-core/interpret/blackbox/partialdependence.py | python | PDPExplanation.__init__ | (
self,
explanation_type,
internal_obj,
feature_names=None,
feature_types=None,
name=None,
selector=None,
) | Initializes class.
Args:
explanation_type: Type of explanation.
internal_obj: A jsonable object that backs the explanation.
feature_names: List of feature names.
feature_types: List of feature types.
name: User-defined name of explanation.
selector: A dataframe whose indices correspond to explanation entries. | Initializes class. | [
"Initializes",
"class",
"."
] | def __init__(
self,
explanation_type,
internal_obj,
feature_names=None,
feature_types=None,
name=None,
selector=None,
):
""" Initializes class.
Args:
explanation_type: Type of explanation.
internal_obj: A jsonable object that backs the explanation.
feature_names: List of feature names.
feature_types: List of feature types.
name: User-defined name of explanation.
selector: A dataframe whose indices correspond to explanation entries.
"""
self.explanation_type = explanation_type
self._internal_obj = internal_obj
self.feature_names = feature_names
self.feature_types = feature_types
self.name = name
self.selector = selector | [
"def",
"__init__",
"(",
"self",
",",
"explanation_type",
",",
"internal_obj",
",",
"feature_names",
"=",
"None",
",",
"feature_types",
"=",
"None",
",",
"name",
"=",
"None",
",",
"selector",
"=",
"None",
",",
")",
":",
"self",
".",
"explanation_type",
"=",... | https://github.com/interpretml/interpret/blob/29466bffc04505fe4f836a83fcfebfd313ac8454/python/interpret-core/interpret/blackbox/partialdependence.py#L180-L204 | ||
citizenfx/fivem | 88276d40cc7baf8285d02754cc5ae42ec7a8563f | vendor/chromium/mojo/public/tools/bindings/pylib/mojom/parse/parser.py | python | Parser.p_constant | (self, p) | constant : literal
| identifier_wrapped | constant : literal
| identifier_wrapped | [
"constant",
":",
"literal",
"|",
"identifier_wrapped"
] | def p_constant(self, p):
"""constant : literal
| identifier_wrapped"""
p[0] = p[1] | [
"def",
"p_constant",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] | https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/mojo/public/tools/bindings/pylib/mojom/parse/parser.py#L400-L403 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiManager.RestorePane | (*args, **kwargs) | return _aui.AuiManager_RestorePane(*args, **kwargs) | RestorePane(self, AuiPaneInfo paneInfo) | RestorePane(self, AuiPaneInfo paneInfo) | [
"RestorePane",
"(",
"self",
"AuiPaneInfo",
"paneInfo",
")"
] | def RestorePane(*args, **kwargs):
"""RestorePane(self, AuiPaneInfo paneInfo)"""
return _aui.AuiManager_RestorePane(*args, **kwargs) | [
"def",
"RestorePane",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiManager_RestorePane",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L695-L697 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/vis/glprogram.py | python | GLProgram.displayfunc | (self) | return True | All OpenGL calls go here. May be overridden, although you
may wish to override display() and display_screen() instead. | All OpenGL calls go here. May be overridden, although you
may wish to override display() and display_screen() instead. | [
"All",
"OpenGL",
"calls",
"go",
"here",
".",
"May",
"be",
"overridden",
"although",
"you",
"may",
"wish",
"to",
"override",
"display",
"()",
"and",
"display_screen",
"()",
"instead",
"."
] | def displayfunc(self):
"""All OpenGL calls go here. May be overridden, although you
may wish to override display() and display_screen() instead."""
if self.view.w == 0 or self.view.h == 0:
#hidden?
print("GLProgram.displayfunc called on hidden window?")
return False
self.prepare_GL()
self.display()
self.prepare_screen_GL()
self.display_screen()
return True | [
"def",
"displayfunc",
"(",
"self",
")",
":",
"if",
"self",
".",
"view",
".",
"w",
"==",
"0",
"or",
"self",
".",
"view",
".",
"h",
"==",
"0",
":",
"#hidden?",
"print",
"(",
"\"GLProgram.displayfunc called on hidden window?\"",
")",
"return",
"False",
"self"... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/glprogram.py#L133-L144 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | TextAttr.GetCharacterStyleName | (*args, **kwargs) | return _controls_.TextAttr_GetCharacterStyleName(*args, **kwargs) | GetCharacterStyleName(self) -> String | GetCharacterStyleName(self) -> String | [
"GetCharacterStyleName",
"(",
"self",
")",
"-",
">",
"String"
] | def GetCharacterStyleName(*args, **kwargs):
"""GetCharacterStyleName(self) -> String"""
return _controls_.TextAttr_GetCharacterStyleName(*args, **kwargs) | [
"def",
"GetCharacterStyleName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_GetCharacterStyleName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L1708-L1710 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/crywaflib/compile_rules_linux_x64_linux_x64_gcc.py | python | load_profile_linux_x64_linux_x64_gcc_settings | (conf) | Setup all compiler and linker settings shared over all linux_x64_linux_x64_gcc configurations for
the 'profile' configuration | Setup all compiler and linker settings shared over all linux_x64_linux_x64_gcc configurations for
the 'profile' configuration | [
"Setup",
"all",
"compiler",
"and",
"linker",
"settings",
"shared",
"over",
"all",
"linux_x64_linux_x64_gcc",
"configurations",
"for",
"the",
"profile",
"configuration"
] | def load_profile_linux_x64_linux_x64_gcc_settings(conf):
"""
Setup all compiler and linker settings shared over all linux_x64_linux_x64_gcc configurations for
the 'profile' configuration
"""
v = conf.env
conf.load_linux_x64_linux_x64_gcc_common_settings()
# Load addional shared settings
conf.load_profile_cryengine_settings()
conf.load_profile_gcc_settings()
conf.load_profile_linux_settings()
conf.load_profile_linux_x64_settings() | [
"def",
"load_profile_linux_x64_linux_x64_gcc_settings",
"(",
"conf",
")",
":",
"v",
"=",
"conf",
".",
"env",
"conf",
".",
"load_linux_x64_linux_x64_gcc_common_settings",
"(",
")",
"# Load addional shared settings",
"conf",
".",
"load_profile_cryengine_settings",
"(",
")",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/compile_rules_linux_x64_linux_x64_gcc.py#L45-L57 | ||
google/or-tools | 2cb85b4eead4c38e1c54b48044f92087cf165bce | ortools/sat/samples/rabbits_and_pheasants_sat.py | python | RabbitsAndPheasantsSat | () | Solves the rabbits + pheasants problem. | Solves the rabbits + pheasants problem. | [
"Solves",
"the",
"rabbits",
"+",
"pheasants",
"problem",
"."
] | def RabbitsAndPheasantsSat():
"""Solves the rabbits + pheasants problem."""
model = cp_model.CpModel()
r = model.NewIntVar(0, 100, 'r')
p = model.NewIntVar(0, 100, 'p')
# 20 heads.
model.Add(r + p == 20)
# 56 legs.
model.Add(4 * r + 2 * p == 56)
# Solves and prints out the solution.
solver = cp_model.CpSolver()
status = solver.Solve(model)
if status == cp_model.OPTIMAL:
print('%i rabbits and %i pheasants' %
(solver.Value(r), solver.Value(p))) | [
"def",
"RabbitsAndPheasantsSat",
"(",
")",
":",
"model",
"=",
"cp_model",
".",
"CpModel",
"(",
")",
"r",
"=",
"model",
".",
"NewIntVar",
"(",
"0",
",",
"100",
",",
"'r'",
")",
"p",
"=",
"model",
".",
"NewIntVar",
"(",
"0",
",",
"100",
",",
"'p'",
... | https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/samples/rabbits_and_pheasants_sat.py#L19-L37 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBTypeFormat.SetFormat | (self, arg2) | return _lldb.SBTypeFormat_SetFormat(self, arg2) | SetFormat(SBTypeFormat self, lldb::Format arg2) | SetFormat(SBTypeFormat self, lldb::Format arg2) | [
"SetFormat",
"(",
"SBTypeFormat",
"self",
"lldb",
"::",
"Format",
"arg2",
")"
] | def SetFormat(self, arg2):
"""SetFormat(SBTypeFormat self, lldb::Format arg2)"""
return _lldb.SBTypeFormat_SetFormat(self, arg2) | [
"def",
"SetFormat",
"(",
"self",
",",
"arg2",
")",
":",
"return",
"_lldb",
".",
"SBTypeFormat_SetFormat",
"(",
"self",
",",
"arg2",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L13594-L13596 | |
libornovax/master_thesis_code | 6eca474ed3cae673afde010caef338cf7349f839 | scripts/data/shared/geometry.py | python | R3x3_z | (gamma) | return R | Rotation matrix around z axis in 3D. | Rotation matrix around z axis in 3D. | [
"Rotation",
"matrix",
"around",
"z",
"axis",
"in",
"3D",
"."
] | def R3x3_z(gamma):
"""
Rotation matrix around z axis in 3D.
"""
R = np.asmatrix([[np.cos(gamma), -np.sin(gamma), 0.0],
[np.sin(gamma), np.cos(gamma), 0.0],
[0.0, 0.0, 1.0]])
return R | [
"def",
"R3x3_z",
"(",
"gamma",
")",
":",
"R",
"=",
"np",
".",
"asmatrix",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"gamma",
")",
",",
"-",
"np",
".",
"sin",
"(",
"gamma",
")",
",",
"0.0",
"]",
",",
"[",
"np",
".",
"sin",
"(",
"gamma",
")",
"... | https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/scripts/data/shared/geometry.py#L38-L45 | |
omnisci/omniscidb | b9c95f1bd602b4ffc8b0edf18bfad61031e08d86 | Benchmarks/run_benchmark.py | python | execute_query | (**kwargs) | return query_execution | Executes a query against the connected db using pymapd
https://pymapd.readthedocs.io/en/latest/usage.html#querying
Kwargs:
query_name(str): Name of query
query_mapdql(str): Query to run
iteration(int): Iteration number
con(class): Connection class
Returns:
query_execution(dict):::
result_count(int): Number of results returned
execution_time(float): Time (in ms) that pymapd reports
backend spent on query.
connect_time(float): Time (in ms) for overhead of query, calculated
by subtracting backend execution time
from time spent on the execution function.
results_iter_time(float): Time (in ms) it took to for
pymapd.fetchone() to iterate through all
of the results.
total_time(float): Time (in ms) from adding all above times.
False(bool): The query failed. Exception should be logged. | Executes a query against the connected db using pymapd
https://pymapd.readthedocs.io/en/latest/usage.html#querying | [
"Executes",
"a",
"query",
"against",
"the",
"connected",
"db",
"using",
"pymapd",
"https",
":",
"//",
"pymapd",
".",
"readthedocs",
".",
"io",
"/",
"en",
"/",
"latest",
"/",
"usage",
".",
"html#querying"
] | def execute_query(**kwargs):
"""
Executes a query against the connected db using pymapd
https://pymapd.readthedocs.io/en/latest/usage.html#querying
Kwargs:
query_name(str): Name of query
query_mapdql(str): Query to run
iteration(int): Iteration number
con(class): Connection class
Returns:
query_execution(dict):::
result_count(int): Number of results returned
execution_time(float): Time (in ms) that pymapd reports
backend spent on query.
connect_time(float): Time (in ms) for overhead of query, calculated
by subtracting backend execution time
from time spent on the execution function.
results_iter_time(float): Time (in ms) it took to for
pymapd.fetchone() to iterate through all
of the results.
total_time(float): Time (in ms) from adding all above times.
False(bool): The query failed. Exception should be logged.
"""
start_time = timeit.default_timer()
try:
# Run the query
query_result = kwargs["con"].execute(kwargs["query_mapdql"])
logging.debug(
"Completed iteration "
+ str(kwargs["iteration"])
+ " of query "
+ kwargs["query_name"]
)
except (pymapd.exceptions.ProgrammingError, pymapd.exceptions.Error):
logging.exception(
"Error running query "
+ kwargs["query_name"]
+ " during iteration "
+ str(kwargs["iteration"])
)
return False
# Calculate times
query_elapsed_time = (timeit.default_timer() - start_time) * 1000
execution_time = query_result._result.execution_time_ms
debug_info = query_result._result.debug
connect_time = round((query_elapsed_time - execution_time), 1)
# Iterate through each result from the query
logging.debug(
"Counting results from query"
+ kwargs["query_name"]
+ " iteration "
+ str(kwargs["iteration"])
)
result_count = 0
start_time = timeit.default_timer()
while query_result.fetchone():
result_count += 1
results_iter_time = round(
((timeit.default_timer() - start_time) * 1000), 1
)
query_execution = {
"result_count": result_count,
"execution_time": execution_time,
"connect_time": connect_time,
"results_iter_time": results_iter_time,
"total_time": execution_time + connect_time + results_iter_time,
"debug_info": debug_info,
}
logging.debug(
"Execution results for query"
+ kwargs["query_name"]
+ " iteration "
+ str(kwargs["iteration"])
+ ": "
+ str(query_execution)
)
return query_execution | [
"def",
"execute_query",
"(",
"*",
"*",
"kwargs",
")",
":",
"start_time",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"try",
":",
"# Run the query",
"query_result",
"=",
"kwargs",
"[",
"\"con\"",
"]",
".",
"execute",
"(",
"kwargs",
"[",
"\"query_mapdql\"",... | https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/Benchmarks/run_benchmark.py#L441-L520 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/training/session_run_hook.py | python | SessionRunHook.end | (self, session) | Called at the end of session.
The `session` argument can be used in case the hook wants to run final ops,
such as saving a last checkpoint.
Args:
session: A TensorFlow Session that will be soon closed. | Called at the end of session. | [
"Called",
"at",
"the",
"end",
"of",
"session",
"."
] | def end(self, session): # pylint: disable=unused-argument
"""Called at the end of session.
The `session` argument can be used in case the hook wants to run final ops,
such as saving a last checkpoint.
Args:
session: A TensorFlow Session that will be soon closed.
"""
pass | [
"def",
"end",
"(",
"self",
",",
"session",
")",
":",
"# pylint: disable=unused-argument",
"pass"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/session_run_hook.py#L141-L150 | ||
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/llvm/bindings/python/llvm/object.py | python | Section.__init__ | (self, ptr) | Construct a new section instance.
Section instances can currently only be created from an ObjectFile
instance. Therefore, this constructor should not be used outside of
this module. | Construct a new section instance. | [
"Construct",
"a",
"new",
"section",
"instance",
"."
] | def __init__(self, ptr):
"""Construct a new section instance.
Section instances can currently only be created from an ObjectFile
instance. Therefore, this constructor should not be used outside of
this module.
"""
LLVMObject.__init__(self, ptr)
self.expired = False | [
"def",
"__init__",
"(",
"self",
",",
"ptr",
")",
":",
"LLVMObject",
".",
"__init__",
"(",
"self",
",",
"ptr",
")",
"self",
".",
"expired",
"=",
"False"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/llvm/bindings/python/llvm/object.py#L181-L190 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py | python | PlaceHolder.append | (self, alogger) | Add the specified logger as a child of this placeholder. | Add the specified logger as a child of this placeholder. | [
"Add",
"the",
"specified",
"logger",
"as",
"a",
"child",
"of",
"this",
"placeholder",
"."
] | def append(self, alogger):
"""
Add the specified logger as a child of this placeholder.
"""
if alogger not in self.loggerMap:
self.loggerMap[alogger] = None | [
"def",
"append",
"(",
"self",
",",
"alogger",
")",
":",
"if",
"alogger",
"not",
"in",
"self",
".",
"loggerMap",
":",
"self",
".",
"loggerMap",
"[",
"alogger",
"]",
"=",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py#L1170-L1175 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/sync-webkit-git.py | python | GetWebKitRev | () | return locals['vars']['webkit_revision'] | Extract the 'webkit_revision' variable out of DEPS. | Extract the 'webkit_revision' variable out of DEPS. | [
"Extract",
"the",
"webkit_revision",
"variable",
"out",
"of",
"DEPS",
"."
] | def GetWebKitRev():
"""Extract the 'webkit_revision' variable out of DEPS."""
locals = {'Var': lambda _: locals["vars"][_],
'From': lambda *args: None}
execfile('DEPS', {}, locals)
return locals['vars']['webkit_revision'] | [
"def",
"GetWebKitRev",
"(",
")",
":",
"locals",
"=",
"{",
"'Var'",
":",
"lambda",
"_",
":",
"locals",
"[",
"\"vars\"",
"]",
"[",
"_",
"]",
",",
"'From'",
":",
"lambda",
"*",
"args",
":",
"None",
"}",
"execfile",
"(",
"'DEPS'",
",",
"{",
"}",
",",... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/sync-webkit-git.py#L63-L68 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/polynomial/legendre.py | python | legvander | (x, deg) | return np.rollaxis(v, 0, v.ndim) | Vandermonde matrix of given degree.
Returns the Vandermonde matrix of degree `deg` and sample points `x`.
This isn't a true Vandermonde matrix because `x` can be an arbitrary
ndarray and the Legendre polynomials aren't powers. If ``V`` is the
returned matrix and `x` is a 2d array, then the elements of ``V`` are
``V[i,j,k] = P_k(x[i,j])``, where ``P_k`` is the Legendre polynomial
of degree ``k``.
Parameters
----------
x : array_like
Array of points. The values are converted to double or complex
doubles. If x is scalar it is converted to a 1D array.
deg : integer
Degree of the resulting matrix.
Returns
-------
vander : Vandermonde matrix.
The shape of the returned matrix is ``x.shape + (deg+1,)``. The last
index is the degree. | Vandermonde matrix of given degree. | [
"Vandermonde",
"matrix",
"of",
"given",
"degree",
"."
] | def legvander(x, deg) :
"""Vandermonde matrix of given degree.
Returns the Vandermonde matrix of degree `deg` and sample points `x`.
This isn't a true Vandermonde matrix because `x` can be an arbitrary
ndarray and the Legendre polynomials aren't powers. If ``V`` is the
returned matrix and `x` is a 2d array, then the elements of ``V`` are
``V[i,j,k] = P_k(x[i,j])``, where ``P_k`` is the Legendre polynomial
of degree ``k``.
Parameters
----------
x : array_like
Array of points. The values are converted to double or complex
doubles. If x is scalar it is converted to a 1D array.
deg : integer
Degree of the resulting matrix.
Returns
-------
vander : Vandermonde matrix.
The shape of the returned matrix is ``x.shape + (deg+1,)``. The last
index is the degree.
"""
ideg = int(deg)
if ideg != deg:
raise ValueError("deg must be integer")
if ideg < 0:
raise ValueError("deg must be non-negative")
x = np.array(x, copy=0, ndmin=1) + 0.0
v = np.empty((ideg + 1,) + x.shape, dtype=x.dtype)
# Use forward recursion to generate the entries. This is not as accurate
# as reverse recursion in this application but it is more efficient.
v[0] = x*0 + 1
if ideg > 0 :
v[1] = x
for i in range(2, ideg + 1) :
v[i] = (v[i-1]*x*(2*i - 1) - v[i-2]*(i - 1))/i
return np.rollaxis(v, 0, v.ndim) | [
"def",
"legvander",
"(",
"x",
",",
"deg",
")",
":",
"ideg",
"=",
"int",
"(",
"deg",
")",
"if",
"ideg",
"!=",
"deg",
":",
"raise",
"ValueError",
"(",
"\"deg must be integer\"",
")",
"if",
"ideg",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"deg must be... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/legendre.py#L875-L915 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/callback.py | python | log_train_metric | (period, auto_reset=False) | return _callback | Callback to log the training evaluation result every period.
Parameters
----------
period : int
The number of batch to log the training evaluation metric.
auto_reset : bool
Reset the metric after each log.
Returns
-------
callback : function
The callback function that can be passed as iter_epoch_callback to fit. | Callback to log the training evaluation result every period. | [
"Callback",
"to",
"log",
"the",
"training",
"evaluation",
"result",
"every",
"period",
"."
] | def log_train_metric(period, auto_reset=False):
"""Callback to log the training evaluation result every period.
Parameters
----------
period : int
The number of batch to log the training evaluation metric.
auto_reset : bool
Reset the metric after each log.
Returns
-------
callback : function
The callback function that can be passed as iter_epoch_callback to fit.
"""
def _callback(param):
"""The checkpoint function."""
if param.nbatch % period == 0 and param.eval_metric is not None:
name_value = param.eval_metric.get_name_value()
for name, value in name_value:
logging.info('Iter[%d] Batch[%d] Train-%s=%f',
param.epoch, param.nbatch, name, value)
if auto_reset:
param.eval_metric.reset()
return _callback | [
"def",
"log_train_metric",
"(",
"period",
",",
"auto_reset",
"=",
"False",
")",
":",
"def",
"_callback",
"(",
"param",
")",
":",
"\"\"\"The checkpoint function.\"\"\"",
"if",
"param",
".",
"nbatch",
"%",
"period",
"==",
"0",
"and",
"param",
".",
"eval_metric",... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/callback.py#L93-L117 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | snapx/snapx/algorithms/dag.py | python | topological_sort | (G) | PORTED FROM NETWORKX
Returns a generator of nodes in topologically sorted order.
A topological sort is a nonunique permutation of the nodes such that an
edge from u to v implies that u appears before v in the topological sort
order.
Parameters
----------
G : SnapX digraph
A directed acyclic graph (DAG)
Returns
-------
iterable
An iterable of node names in topological sorted order.
Raises
------
SnapXError
Topological sort is defined for directed graphs only. If the graph `G`
is undirected, a :exc:`SnapXError` is raised.
SnapXUnfeasible
If `G` is not a directed acyclic graph (DAG) no topological sort exists
and a :exc:`SnapXUnfeasible` exception is raised. This can also be
raised if `G` is changed while the returned iterator is being processed
RuntimeError
If `G` is changed while the returned iterator is being processed.
Examples
--------
To get the reverse order of the topological sort:
>>> DG = sx.DiGraph([(1, 2), (2, 3)])
>>> list(reversed(list(sx.topological_sort(DG))))
[3, 2, 1]
--- DISREGARD BELOW ---
If your DiGraph naturally has the edges representing tasks/inputs
and nodes representing people/processes that initiate tasks, then
topological_sort is not quite what you need. You will have to change
the tasks to nodes with dependence reflected by edges. The result is
a kind of topological sort of the edges. This can be done
with :func:`networkx.line_graph` as follows:
>>> list(nx.topological_sort(nx.line_graph(DG)))
[(1, 2), (2, 3)]
Notes
-----
This algorithm is based on a description and proof in
"Introduction to Algorithms: A Creative Approach" [1]_ .
See also
--------
is_directed_acyclic_graph, lexicographical_topological_sort
References
----------
.. [1] Manber, U. (1989).
*Introduction to Algorithms - A Creative Approach.* Addison-Wesley. | PORTED FROM NETWORKX
Returns a generator of nodes in topologically sorted order. | [
"PORTED",
"FROM",
"NETWORKX",
"Returns",
"a",
"generator",
"of",
"nodes",
"in",
"topologically",
"sorted",
"order",
"."
] | def topological_sort(G):
"""PORTED FROM NETWORKX
Returns a generator of nodes in topologically sorted order.
A topological sort is a nonunique permutation of the nodes such that an
edge from u to v implies that u appears before v in the topological sort
order.
Parameters
----------
G : SnapX digraph
A directed acyclic graph (DAG)
Returns
-------
iterable
An iterable of node names in topological sorted order.
Raises
------
SnapXError
Topological sort is defined for directed graphs only. If the graph `G`
is undirected, a :exc:`SnapXError` is raised.
SnapXUnfeasible
If `G` is not a directed acyclic graph (DAG) no topological sort exists
and a :exc:`SnapXUnfeasible` exception is raised. This can also be
raised if `G` is changed while the returned iterator is being processed
RuntimeError
If `G` is changed while the returned iterator is being processed.
Examples
--------
To get the reverse order of the topological sort:
>>> DG = sx.DiGraph([(1, 2), (2, 3)])
>>> list(reversed(list(sx.topological_sort(DG))))
[3, 2, 1]
--- DISREGARD BELOW ---
If your DiGraph naturally has the edges representing tasks/inputs
and nodes representing people/processes that initiate tasks, then
topological_sort is not quite what you need. You will have to change
the tasks to nodes with dependence reflected by edges. The result is
a kind of topological sort of the edges. This can be done
with :func:`networkx.line_graph` as follows:
>>> list(nx.topological_sort(nx.line_graph(DG)))
[(1, 2), (2, 3)]
Notes
-----
This algorithm is based on a description and proof in
"Introduction to Algorithms: A Creative Approach" [1]_ .
See also
--------
is_directed_acyclic_graph, lexicographical_topological_sort
References
----------
.. [1] Manber, U. (1989).
*Introduction to Algorithms - A Creative Approach.* Addison-Wesley.
"""
if not G.is_directed():
raise sx.SnapXError("Topological sort not defined on undirected graphs.")
indegree_map = {v: d for v, d in G.in_degree() if d > 0}
# These nodes have zero indegree and ready to be returned.
zero_indegree = [v for v, d in G.in_degree() if d == 0]
while zero_indegree:
node = zero_indegree.pop()
if node not in G:
raise RuntimeError("Graph changed during iteration")
for _, child in G.edges(node):
try:
indegree_map[child] -= 1
except KeyError as e:
raise RuntimeError("Graph changed during iteration") from e
if indegree_map[child] == 0:
zero_indegree.append(child)
del indegree_map[child]
yield node
if indegree_map:
raise sx.SnapXUnfeasible(
"Graph contains a cycle or graph changed " "during iteration"
) | [
"def",
"topological_sort",
"(",
"G",
")",
":",
"if",
"not",
"G",
".",
"is_directed",
"(",
")",
":",
"raise",
"sx",
".",
"SnapXError",
"(",
"\"Topological sort not defined on undirected graphs.\"",
")",
"indegree_map",
"=",
"{",
"v",
":",
"d",
"for",
"v",
","... | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/snapx/snapx/algorithms/dag.py#L113-L203 | ||
lmb-freiburg/ogn | 974f72ef4bf840d6f6693d22d1843a79223e77ce | scripts/cpp_lint.py | python | CleansedLines._CollapseStrings | (elided) | return elided | Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings. | Collapses strings and chars on a line to simple "" or '' blocks. | [
"Collapses",
"strings",
"and",
"chars",
"on",
"a",
"line",
"to",
"simple",
"or",
"blocks",
"."
] | def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if not _RE_PATTERN_INCLUDE.match(elided):
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
return elided | [
"def",
"_CollapseStrings",
"(",
"elided",
")",
":",
"if",
"not",
"_RE_PATTERN_INCLUDE",
".",
"match",
"(",
"elided",
")",
":",
"# Remove escaped characters first to make quote/single quote collapsing",
"# basic. Things that look like escaped characters shouldn't occur",
"# outside... | https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/scripts/cpp_lint.py#L1209-L1227 | |
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/AI/ShipDesignAI.py | python | ShipDesigner.optimize_design | (
self,
additional_parts=(),
additional_hulls: Sequence = (),
loc: Optional[Union[int, List[int]]] = None,
verbose: bool = False,
consider_fleet_count: bool = True,
) | return sorted_design_list | Try to find the optimum designs for the ship class for each planet and add it as game object.
Only designs with a positive rating (i.e. matching the minimum requirements) will be returned.
Return list of (rating, planet_id, design_id, cost, design_stats) tuples, i.e. best available design for each planet
:param additional_parts: additional unavailable parts to consider in the design process
:param additional_hulls: additional unavailable hulls to consider in the design process
:param loc: planet ids where the designs are to be built. Default: All planets.
:param verbose: Toggles detailed logging for debugging.
:param consider_fleet_count: Toggles whether fleet upkeep should be reflected in the rating. | Try to find the optimum designs for the ship class for each planet and add it as game object. | [
"Try",
"to",
"find",
"the",
"optimum",
"designs",
"for",
"the",
"ship",
"class",
"for",
"each",
"planet",
"and",
"add",
"it",
"as",
"game",
"object",
"."
] | def optimize_design(
self,
additional_parts=(),
additional_hulls: Sequence = (),
loc: Optional[Union[int, List[int]]] = None,
verbose: bool = False,
consider_fleet_count: bool = True,
) -> List[Tuple[float, int, int, float, DesignStats]]:
"""Try to find the optimum designs for the ship class for each planet and add it as game object.
Only designs with a positive rating (i.e. matching the minimum requirements) will be returned.
Return list of (rating, planet_id, design_id, cost, design_stats) tuples, i.e. best available design for each planet
:param additional_parts: additional unavailable parts to consider in the design process
:param additional_hulls: additional unavailable hulls to consider in the design process
:param loc: planet ids where the designs are to be built. Default: All planets.
:param verbose: Toggles detailed logging for debugging.
:param consider_fleet_count: Toggles whether fleet upkeep should be reflected in the rating.
"""
if loc is None:
planets = get_inhabited_planets()
elif isinstance(loc, int):
planets = [loc]
elif isinstance(loc, list):
planets = loc
else:
error("Invalid loc parameter for optimize_design(). Expected int or list but got %s" % loc)
return []
self.consider_fleet_count = consider_fleet_count
Cache.update_cost_cache(partnames=additional_parts, hullnames=additional_hulls)
additional_part_dict = {}
for partname in additional_parts:
for slot in get_ship_part(partname).mountableSlotTypes:
additional_part_dict.setdefault(slot, []).append(partname)
# TODO: Rework caching to only cache raw stats of designs, then evaluate them
design_cache_class = Cache.best_designs.setdefault(self.__class__.__name__, {})
design_cache_fleet_upkeep = design_cache_class.setdefault(
WITH_UPKEEP if consider_fleet_count else WITHOUT_UPKEEP, {}
)
req_tuple = self.additional_specifications.convert_to_tuple()
design_cache_reqs = design_cache_fleet_upkeep.setdefault(req_tuple, {})
universe = fo.getUniverse()
best_design_list = []
if verbose:
debug("Trying to find optimum designs for shiptype class %s" % self.__class__.__name__)
relevant_techs = []
def extend_completed_techs(techs: Iterable):
relevant_techs.extend(_tech for _tech in techs if tech_is_complete(_tech))
if WEAPONS & self.useful_part_classes:
extend_completed_techs(AIDependencies.WEAPON_UPGRADE_TECHS)
if FIGHTER_HANGAR & self.useful_part_classes:
extend_completed_techs(AIDependencies.FIGHTER_UPGRADE_TECHS)
if FUEL & self.useful_part_classes:
extend_completed_techs(AIDependencies.FUEL_UPGRADE_TECHS)
extend_completed_techs(AIDependencies.TECH_EFFECTS)
relevant_techs = tuple(set(relevant_techs))
design_cache_tech = design_cache_reqs.setdefault(relevant_techs, {})
for pid in planets:
planet = universe.getPlanet(pid)
self.pid = pid
self.update_species(planet.speciesName)
# The piloting species is only important if its modifiers are of any use to the design
# Therefore, consider only those treats that are actually useful. Note that the
# canColonize trait is covered by the parts we can build, so no need to consider it here.
# The same is true for the canProduceShips trait which simply means no hull can be built.
relevant_grades = []
if WEAPONS & self.useful_part_classes:
weapons_grade = get_species_tag_grade(self.species, Tags.WEAPONS)
relevant_grades.append("WEAPON: %s" % weapons_grade)
if SHIELDS & self.useful_part_classes:
shields_grade = get_species_tag_grade(self.species, Tags.SHIELDS)
relevant_grades.append("SHIELDS: %s" % shields_grade)
if TROOPS & self.useful_part_classes:
troops_grade = get_species_tag_grade(self.species, Tags.ATTACKTROOPS)
relevant_grades.append("TROOPS: %s" % troops_grade)
species_tuple = tuple(relevant_grades)
design_cache_species = design_cache_tech.setdefault(species_tuple, {})
available_hulls = list(Cache.hulls_for_planets[pid]) + list(additional_hulls)
if verbose:
debug("Evaluating planet %s" % planet.name)
debug("Species: %s" % planet.speciesName)
debug("Available Ship Hulls: %s" % available_hulls)
available_parts = copy.copy(Cache.parts_for_planets[pid]) # this is a dict! {slottype:(partnames)}
available_slots = set(available_parts.keys()) | set(additional_part_dict.keys())
for slot in available_slots:
available_parts[slot] = list(available_parts.get(slot, [])) + additional_part_dict.get(slot, [])
self._filter_parts(available_parts, verbose=verbose)
all_parts = []
for partlist in available_parts.values():
all_parts += partlist
design_cache_parts = design_cache_species.setdefault(frozenset(all_parts), {})
best_rating_for_planet = 0
best_hull = None
best_parts = None
for hullname in available_hulls:
# TODO: Expose FOCS Exclusions and replace manually maintained AIDependencies dict
hull_excluded_part_classes = AIDependencies.HULL_EXCLUDED_SHIP_PART_CLASSES.get(hullname, [])
available_parts_in_hull = {
slot: [
part_name
for part_name in available_parts[slot]
if get_ship_part(part_name).partClass not in hull_excluded_part_classes
]
for slot in available_parts
}
if hullname in design_cache_parts:
cache = design_cache_parts[hullname]
best_hull_rating = cache[0]
current_parts = cache[1]
if verbose:
debug(
"Best rating for hull %s: %f (read from Cache) %s"
% (hullname, best_hull_rating, current_parts)
)
else:
self.update_hull(hullname)
best_hull_rating, current_parts = self._filling_algorithm(available_parts_in_hull)
design_cache_parts.update({hullname: (best_hull_rating, current_parts)})
if verbose:
debug("Best rating for hull %s: %f %s" % (hullname, best_hull_rating, current_parts))
if best_hull_rating > best_rating_for_planet:
best_rating_for_planet = best_hull_rating
best_hull = hullname
best_parts = current_parts
if verbose:
debug(
"Best overall rating for this planet: %f (%s with %s)"
% (best_rating_for_planet, best_hull, best_parts)
)
if best_hull:
self.update_hull(best_hull)
self.update_parts(best_parts)
design_id = self.add_design(verbose=verbose)
if verbose:
debug("For best design got got design id %s" % design_id)
if design_id is not None:
best_design_list.append(
(best_rating_for_planet, pid, design_id, self.production_cost, copy.deepcopy(self.design_stats))
)
else:
error("The best design for %s on planet %d could not be added." % (self.__class__.__name__, pid))
elif verbose:
debug("Could not find a suitable design of type %s for planet %s." % (self.__class__.__name__, planet))
sorted_design_list = sorted(best_design_list, key=lambda x: x[0], reverse=True)
return sorted_design_list | [
"def",
"optimize_design",
"(",
"self",
",",
"additional_parts",
"=",
"(",
")",
",",
"additional_hulls",
":",
"Sequence",
"=",
"(",
")",
",",
"loc",
":",
"Optional",
"[",
"Union",
"[",
"int",
",",
"List",
"[",
"int",
"]",
"]",
"]",
"=",
"None",
",",
... | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/ShipDesignAI.py#L957-L1114 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/mesa/MesaLib/src/mapi/glapi/gen/glX_proto_common.py | python | glx_print_proto.size_call | (self, func, outputs_also = 0) | return None | Create C code to calculate 'compsize'.
Creates code to calculate 'compsize'. If the function does
not need 'compsize' to be calculated, None will be
returned. | Create C code to calculate 'compsize'. | [
"Create",
"C",
"code",
"to",
"calculate",
"compsize",
"."
] | def size_call(self, func, outputs_also = 0):
"""Create C code to calculate 'compsize'.
Creates code to calculate 'compsize'. If the function does
not need 'compsize' to be calculated, None will be
returned."""
compsize = None
for param in func.parameterIterator():
if outputs_also or not param.is_output:
if param.is_image():
[dim, w, h, d, junk] = param.get_dimensions()
compsize = '__glImageSize(%s, %s, %s, %s, %s, %s)' % (w, h, d, param.img_format, param.img_type, param.img_target)
if not param.img_send_null:
compsize = '(%s != NULL) ? %s : 0' % (param.name, compsize)
return compsize
elif len(param.count_parameter_list):
parameters = string.join( param.count_parameter_list, "," )
compsize = "__gl%s_size(%s)" % (func.name, parameters)
return compsize
return None | [
"def",
"size_call",
"(",
"self",
",",
"func",
",",
"outputs_also",
"=",
"0",
")",
":",
"compsize",
"=",
"None",
"for",
"param",
"in",
"func",
".",
"parameterIterator",
"(",
")",
":",
"if",
"outputs_also",
"or",
"not",
"param",
".",
"is_output",
":",
"i... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/mesa/MesaLib/src/mapi/glapi/gen/glX_proto_common.py#L51-L77 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/constraints/constraint.py | python | Constraint.size | (self) | return self.args[0].size | int : The size of the constrained expression. | int : The size of the constrained expression. | [
"int",
":",
"The",
"size",
"of",
"the",
"constrained",
"expression",
"."
] | def size(self):
"""int : The size of the constrained expression."""
return self.args[0].size | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"self",
".",
"args",
"[",
"0",
"]",
".",
"size"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/constraints/constraint.py#L74-L76 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py | python | HashedCategoricalColumn._from_config | (cls, config, custom_objects=None, columns_by_name=None) | return cls(**kwargs) | See 'FeatureColumn` base class. | See 'FeatureColumn` base class. | [
"See",
"FeatureColumn",
"base",
"class",
"."
] | def _from_config(cls, config, custom_objects=None, columns_by_name=None):
"""See 'FeatureColumn` base class."""
_check_config_keys(config, cls._fields)
kwargs = _standardize_and_copy_config(config)
kwargs['dtype'] = dtypes.as_dtype(config['dtype'])
return cls(**kwargs) | [
"def",
"_from_config",
"(",
"cls",
",",
"config",
",",
"custom_objects",
"=",
"None",
",",
"columns_by_name",
"=",
"None",
")",
":",
"_check_config_keys",
"(",
"config",
",",
"cls",
".",
"_fields",
")",
"kwargs",
"=",
"_standardize_and_copy_config",
"(",
"conf... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L3555-L3560 | |
google/or-tools | 2cb85b4eead4c38e1c54b48044f92087cf165bce | ortools/sat/samples/simple_sat_program.py | python | SimpleSatProgram | () | Minimal CP-SAT example to showcase calling the solver. | Minimal CP-SAT example to showcase calling the solver. | [
"Minimal",
"CP",
"-",
"SAT",
"example",
"to",
"showcase",
"calling",
"the",
"solver",
"."
] | def SimpleSatProgram():
"""Minimal CP-SAT example to showcase calling the solver."""
# Creates the model.
# [START model]
model = cp_model.CpModel()
# [END model]
# Creates the variables.
# [START variables]
num_vals = 3
x = model.NewIntVar(0, num_vals - 1, 'x')
y = model.NewIntVar(0, num_vals - 1, 'y')
z = model.NewIntVar(0, num_vals - 1, 'z')
# [END variables]
# Creates the constraints.
# [START constraints]
model.Add(x != y)
# [END constraints]
# Creates a solver and solves the model.
# [START solve]
solver = cp_model.CpSolver()
status = solver.Solve(model)
# [END solve]
# [START print_solution]
if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
print('x = %i' % solver.Value(x))
print('y = %i' % solver.Value(y))
print('z = %i' % solver.Value(z))
else:
print('No solution found.') | [
"def",
"SimpleSatProgram",
"(",
")",
":",
"# Creates the model.",
"# [START model]",
"model",
"=",
"cp_model",
".",
"CpModel",
"(",
")",
"# [END model]",
"# Creates the variables.",
"# [START variables]",
"num_vals",
"=",
"3",
"x",
"=",
"model",
".",
"NewIntVar",
"(... | https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/samples/simple_sat_program.py#L21-L53 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/multiclass.py | python | _check_estimator | (estimator) | Make sure that an estimator implements the necessary methods. | Make sure that an estimator implements the necessary methods. | [
"Make",
"sure",
"that",
"an",
"estimator",
"implements",
"the",
"necessary",
"methods",
"."
] | def _check_estimator(estimator):
"""Make sure that an estimator implements the necessary methods."""
if (not hasattr(estimator, "decision_function") and
not hasattr(estimator, "predict_proba")):
raise ValueError("The base estimator should implement "
"decision_function or predict_proba!") | [
"def",
"_check_estimator",
"(",
"estimator",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"estimator",
",",
"\"decision_function\"",
")",
"and",
"not",
"hasattr",
"(",
"estimator",
",",
"\"predict_proba\"",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"The base... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/multiclass.py#L102-L107 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.