nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hasanirtiza/Pedestron | 3bdcf8476edc0741f28a80dd4cb161ac532507ee | mmdet/models/backbones/mobilenet.py | python | InvertedResidual.forward | (self, x) | [] | def forward(self, x):
if self.use_res_connect:
return x + self.conv(x)
else:
return self.conv(x) | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"use_res_connect",
":",
"return",
"x",
"+",
"self",
".",
"conv",
"(",
"x",
")",
"else",
":",
"return",
"self",
".",
"conv",
"(",
"x",
")"
] | https://github.com/hasanirtiza/Pedestron/blob/3bdcf8476edc0741f28a80dd4cb161ac532507ee/mmdet/models/backbones/mobilenet.py#L67-L71 | ||||
soravux/scoop | 3c0357c32cec3169a19c822a3857c968a48775c5 | scoop/_debug.py | python | createDirectory | (path_suffix="") | Create a directory in a way that multiple concurrent requests won't
be problematic. | Create a directory in a way that multiple concurrent requests won't
be problematic. | [
"Create",
"a",
"directory",
"in",
"a",
"way",
"that",
"multiple",
"concurrent",
"requests",
"won",
"t",
"be",
"problematic",
"."
] | def createDirectory(path_suffix=""):
"""Create a directory in a way that multiple concurrent requests won't
be problematic."""
try:
os.makedirs(os.path.join(getDebugDirectory(), path_suffix))
except:
pass | [
"def",
"createDirectory",
"(",
"path_suffix",
"=",
"\"\"",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"getDebugDirectory",
"(",
")",
",",
"path_suffix",
")",
")",
"except",
":",
"pass"
] | https://github.com/soravux/scoop/blob/3c0357c32cec3169a19c822a3857c968a48775c5/scoop/_debug.py#L37-L43 | ||
maas/maas | db2f89970c640758a51247c59bf1ec6f60cf4ab5 | src/provisioningserver/utils/services.py | python | set_ipv4_multicast_source_address | (sock, source_address) | Sets the given socket up to send multicast from the specified source.
Ensures the multicast TTL is set to 1, so that packets are not forwarded
beyond the local link.
:param sock: An opened IP socket.
:param source_address: A string representing an IPv4 source address. | Sets the given socket up to send multicast from the specified source. | [
"Sets",
"the",
"given",
"socket",
"up",
"to",
"send",
"multicast",
"from",
"the",
"specified",
"source",
"."
] | def set_ipv4_multicast_source_address(sock, source_address):
"""Sets the given socket up to send multicast from the specified source.
Ensures the multicast TTL is set to 1, so that packets are not forwarded
beyond the local link.
:param sock: An opened IP socket.
:param source_address: A string representing an IPv4 source address.
"""
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)
sock.setsockopt(
socket.IPPROTO_IP,
socket.IP_MULTICAST_IF,
socket.inet_aton(source_address),
) | [
"def",
"set_ipv4_multicast_source_address",
"(",
"sock",
",",
"source_address",
")",
":",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
"IPPROTO_IP",
",",
"socket",
".",
"IP_MULTICAST_TTL",
",",
"1",
")",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
"IPPROT... | https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/provisioningserver/utils/services.py#L356-L370 | ||
grow/grow | 97fc21730b6a674d5d33948d94968e79447ce433 | grow/documents/document_format.py | python | DocumentFormat.__init__ | (self, doc) | [] | def __init__(self, doc):
self._doc = doc
self._content = None
self._raw_content = None | [
"def",
"__init__",
"(",
"self",
",",
"doc",
")",
":",
"self",
".",
"_doc",
"=",
"doc",
"self",
".",
"_content",
"=",
"None",
"self",
".",
"_raw_content",
"=",
"None"
] | https://github.com/grow/grow/blob/97fc21730b6a674d5d33948d94968e79447ce433/grow/documents/document_format.py#L38-L41 | ||||
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/html5lib/treebuilders/dom.py | python | getDomBuilder | (DomImplementation) | return locals() | [] | def getDomBuilder(DomImplementation):
Dom = DomImplementation
class AttrList(MutableMapping):
def __init__(self, element):
self.element = element
def __iter__(self):
return iter(self.element.attributes.keys())
def __setitem__(self, name, value):
if isinstance(name, tuple):
raise NotImplementedError
else:
attr = self.element.ownerDocument.createAttribute(name)
attr.value = value
self.element.attributes[name] = attr
def __len__(self):
return len(self.element.attributes)
def items(self):
return list(self.element.attributes.items())
def values(self):
return list(self.element.attributes.values())
def __getitem__(self, name):
if isinstance(name, tuple):
raise NotImplementedError
else:
return self.element.attributes[name].value
def __delitem__(self, name):
if isinstance(name, tuple):
raise NotImplementedError
else:
del self.element.attributes[name]
class NodeBuilder(base.Node):
def __init__(self, element):
base.Node.__init__(self, element.nodeName)
self.element = element
namespace = property(lambda self: hasattr(self.element, "namespaceURI") and
self.element.namespaceURI or None)
def appendChild(self, node):
node.parent = self
self.element.appendChild(node.element)
def insertText(self, data, insertBefore=None):
text = self.element.ownerDocument.createTextNode(data)
if insertBefore:
self.element.insertBefore(text, insertBefore.element)
else:
self.element.appendChild(text)
def insertBefore(self, node, refNode):
self.element.insertBefore(node.element, refNode.element)
node.parent = self
def removeChild(self, node):
if node.element.parentNode == self.element:
self.element.removeChild(node.element)
node.parent = None
def reparentChildren(self, newParent):
while self.element.hasChildNodes():
child = self.element.firstChild
self.element.removeChild(child)
newParent.element.appendChild(child)
self.childNodes = []
def getAttributes(self):
return AttrList(self.element)
def setAttributes(self, attributes):
if attributes:
for name, value in list(attributes.items()):
if isinstance(name, tuple):
if name[0] is not None:
qualifiedName = (name[0] + ":" + name[1])
else:
qualifiedName = name[1]
self.element.setAttributeNS(name[2], qualifiedName,
value)
else:
self.element.setAttribute(
name, value)
attributes = property(getAttributes, setAttributes)
def cloneNode(self):
return NodeBuilder(self.element.cloneNode(False))
def hasContent(self):
return self.element.hasChildNodes()
def getNameTuple(self):
if self.namespace is None:
return namespaces["html"], self.name
else:
return self.namespace, self.name
nameTuple = property(getNameTuple)
class TreeBuilder(base.TreeBuilder): # pylint:disable=unused-variable
def documentClass(self):
self.dom = Dom.getDOMImplementation().createDocument(None, None, None)
return weakref.proxy(self)
def insertDoctype(self, token):
name = token["name"]
publicId = token["publicId"]
systemId = token["systemId"]
domimpl = Dom.getDOMImplementation()
doctype = domimpl.createDocumentType(name, publicId, systemId)
self.document.appendChild(NodeBuilder(doctype))
if Dom == minidom:
doctype.ownerDocument = self.dom
def elementClass(self, name, namespace=None):
if namespace is None and self.defaultNamespace is None:
node = self.dom.createElement(name)
else:
node = self.dom.createElementNS(namespace, name)
return NodeBuilder(node)
def commentClass(self, data):
return NodeBuilder(self.dom.createComment(data))
def fragmentClass(self):
return NodeBuilder(self.dom.createDocumentFragment())
def appendChild(self, node):
self.dom.appendChild(node.element)
def testSerializer(self, element):
return testSerializer(element)
def getDocument(self):
return self.dom
def getFragment(self):
return base.TreeBuilder.getFragment(self).element
def insertText(self, data, parent=None):
data = data
if parent != self:
base.TreeBuilder.insertText(self, data, parent)
else:
# HACK: allow text nodes as children of the document node
if hasattr(self.dom, '_child_node_types'):
# pylint:disable=protected-access
if Node.TEXT_NODE not in self.dom._child_node_types:
self.dom._child_node_types = list(self.dom._child_node_types)
self.dom._child_node_types.append(Node.TEXT_NODE)
self.dom.appendChild(self.dom.createTextNode(data))
implementation = DomImplementation
name = None
def testSerializer(element):
element.normalize()
rv = []
def serializeElement(element, indent=0):
if element.nodeType == Node.DOCUMENT_TYPE_NODE:
if element.name:
if element.publicId or element.systemId:
publicId = element.publicId or ""
systemId = element.systemId or ""
rv.append("""|%s<!DOCTYPE %s "%s" "%s">""" %
(' ' * indent, element.name, publicId, systemId))
else:
rv.append("|%s<!DOCTYPE %s>" % (' ' * indent, element.name))
else:
rv.append("|%s<!DOCTYPE >" % (' ' * indent,))
elif element.nodeType == Node.DOCUMENT_NODE:
rv.append("#document")
elif element.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
rv.append("#document-fragment")
elif element.nodeType == Node.COMMENT_NODE:
rv.append("|%s<!-- %s -->" % (' ' * indent, element.nodeValue))
elif element.nodeType == Node.TEXT_NODE:
rv.append("|%s\"%s\"" % (' ' * indent, element.nodeValue))
else:
if (hasattr(element, "namespaceURI") and
element.namespaceURI is not None):
name = "%s %s" % (constants.prefixes[element.namespaceURI],
element.nodeName)
else:
name = element.nodeName
rv.append("|%s<%s>" % (' ' * indent, name))
if element.hasAttributes():
attributes = []
for i in range(len(element.attributes)):
attr = element.attributes.item(i)
name = attr.nodeName
value = attr.value
ns = attr.namespaceURI
if ns:
name = "%s %s" % (constants.prefixes[ns], attr.localName)
else:
name = attr.nodeName
attributes.append((name, value))
for name, value in sorted(attributes):
rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value))
indent += 2
for child in element.childNodes:
serializeElement(child, indent)
serializeElement(element, 0)
return "\n".join(rv)
return locals() | [
"def",
"getDomBuilder",
"(",
"DomImplementation",
")",
":",
"Dom",
"=",
"DomImplementation",
"class",
"AttrList",
"(",
"MutableMapping",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"element",
")",
":",
"self",
".",
"element",
"=",
"element",
"def",
"__ite... | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/html5lib/treebuilders/dom.py#L14-L232 | |||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-1.3/django/contrib/gis/gdal/envelope.py | python | Envelope.tuple | (self) | return (self.min_x, self.min_y, self.max_x, self.max_y) | Returns a tuple representing the envelope. | Returns a tuple representing the envelope. | [
"Returns",
"a",
"tuple",
"representing",
"the",
"envelope",
"."
] | def tuple(self):
"Returns a tuple representing the envelope."
return (self.min_x, self.min_y, self.max_x, self.max_y) | [
"def",
"tuple",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"min_x",
",",
"self",
".",
"min_y",
",",
"self",
".",
"max_x",
",",
"self",
".",
"max_y",
")"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/contrib/gis/gdal/envelope.py#L164-L166 | |
Davidham3/ASTGCN | d5d40645fa45471f2b473fc49a29ec3f0a993c6d | model/mstgcn.py | python | cheb_conv.forward | (self, x) | return nd.relu(nd.concat(*outputs, dim=-1)) | Chebyshev graph convolution operation
Parameters
----------
x: mx.ndarray, graph signal matrix,
shape is (batch_size, N, F, T_{r-1}), F is the num of features
Returns
----------
mx.ndarray, shape is (batch_size, N, self.num_of_filters, T_{r-1}) | Chebyshev graph convolution operation | [
"Chebyshev",
"graph",
"convolution",
"operation"
] | def forward(self, x):
'''
Chebyshev graph convolution operation
Parameters
----------
x: mx.ndarray, graph signal matrix,
shape is (batch_size, N, F, T_{r-1}), F is the num of features
Returns
----------
mx.ndarray, shape is (batch_size, N, self.num_of_filters, T_{r-1})
'''
(batch_size, num_of_vertices,
num_of_features, num_of_timesteps) = x.shape
self.Theta.shape = (self.K, num_of_features, self.num_of_filters)
self.Theta._finish_deferred_init()
outputs = []
for time_step in range(num_of_timesteps):
graph_signal = x[:, :, :, time_step]
output = nd.zeros(shape=(batch_size, num_of_vertices,
self.num_of_filters), ctx=x.context)
for k in range(self.K):
T_k = self.cheb_polynomials[k]
theta_k = self.Theta.data()[k]
rhs = nd.dot(graph_signal.transpose((0, 2, 1)),
T_k).transpose((0, 2, 1))
output = output + nd.dot(rhs, theta_k)
outputs.append(output.expand_dims(-1))
return nd.relu(nd.concat(*outputs, dim=-1)) | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"(",
"batch_size",
",",
"num_of_vertices",
",",
"num_of_features",
",",
"num_of_timesteps",
")",
"=",
"x",
".",
"shape",
"self",
".",
"Theta",
".",
"shape",
"=",
"(",
"self",
".",
"K",
",",
"num_of_fea... | https://github.com/Davidham3/ASTGCN/blob/d5d40645fa45471f2b473fc49a29ec3f0a993c6d/model/mstgcn.py#L31-L65 | |
openstack/cinder | 23494a6d6c51451688191e1847a458f1d3cdcaa5 | cinder/db/api.py | python | project_default_volume_type_unset | (context, project_id) | return IMPL.project_default_volume_type_unset(context, project_id) | Unset default volume type for a project (hard delete) | Unset default volume type for a project (hard delete) | [
"Unset",
"default",
"volume",
"type",
"for",
"a",
"project",
"(",
"hard",
"delete",
")"
] | def project_default_volume_type_unset(context, project_id):
"""Unset default volume type for a project (hard delete)"""
return IMPL.project_default_volume_type_unset(context, project_id) | [
"def",
"project_default_volume_type_unset",
"(",
"context",
",",
"project_id",
")",
":",
"return",
"IMPL",
".",
"project_default_volume_type_unset",
"(",
"context",
",",
"project_id",
")"
] | https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/db/api.py#L725-L727 | |
FSecureLABS/Jandroid | e31d0dab58a2bfd6ed8e0a387172b8bd7c893436 | libs/platform-tools/platform-tools_darwin/systrace/catapult/third_party/pyserial/serial/urlhandler/protocol_loop.py | python | LoopbackSerial.read | (self, size=1) | return bytes(data) | Read size bytes from the serial port. If a timeout is set it may
return less characters as requested. With no timeout it will block
until the requested number of bytes is read. | Read size bytes from the serial port. If a timeout is set it may
return less characters as requested. With no timeout it will block
until the requested number of bytes is read. | [
"Read",
"size",
"bytes",
"from",
"the",
"serial",
"port",
".",
"If",
"a",
"timeout",
"is",
"set",
"it",
"may",
"return",
"less",
"characters",
"as",
"requested",
".",
"With",
"no",
"timeout",
"it",
"will",
"block",
"until",
"the",
"requested",
"number",
... | def read(self, size=1):
"""Read size bytes from the serial port. If a timeout is set it may
return less characters as requested. With no timeout it will block
until the requested number of bytes is read."""
if not self._isOpen: raise portNotOpenError
if self._timeout is not None:
timeout = time.time() + self._timeout
else:
timeout = None
data = bytearray()
while size > 0:
self.buffer_lock.acquire()
try:
block = to_bytes(self.loop_buffer[:size])
del self.loop_buffer[:size]
finally:
self.buffer_lock.release()
data += block
size -= len(block)
# check for timeout now, after data has been read.
# useful for timeout = 0 (non blocking) read
if timeout and time.time() > timeout:
break
return bytes(data) | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"portNotOpenError",
"if",
"self",
".",
"_timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"time",
".",
"time",
"(",
")",
"+",
"self",... | https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_darwin/systrace/catapult/third_party/pyserial/serial/urlhandler/protocol_loop.py#L117-L140 | |
jiangxinyang227/NLP-Project | b11f67d8962f40e17990b4fc4551b0ea5496881c | retrieval_QA/lstm_siamese/train.py | python | Trainer.load_data | (self) | return data_obj | 创建数据对象
:return: | 创建数据对象
:return: | [
"创建数据对象",
":",
"return",
":"
] | def load_data(self):
"""
创建数据对象
:return:
"""
# 生成训练集对象并生成训练数据
data_obj = SiameseLstmData(self.config)
return data_obj | [
"def",
"load_data",
"(",
"self",
")",
":",
"# 生成训练集对象并生成训练数据",
"data_obj",
"=",
"SiameseLstmData",
"(",
"self",
".",
"config",
")",
"return",
"data_obj"
] | https://github.com/jiangxinyang227/NLP-Project/blob/b11f67d8962f40e17990b4fc4551b0ea5496881c/retrieval_QA/lstm_siamese/train.py#L27-L35 | |
scipy/scipy | e0a749f01e79046642ccfdc419edbf9e7ca141ad | scipy/optimize/_shgo.py | python | SHGO.g_topograph | (self, x_min, X_min) | return self.Ss | Returns the topographical vector stemming from the specified value
``x_min`` for the current feasible set ``X_min`` with True boolean
values indicating positive entries and False values indicating
negative entries. | Returns the topographical vector stemming from the specified value
``x_min`` for the current feasible set ``X_min`` with True boolean
values indicating positive entries and False values indicating
negative entries. | [
"Returns",
"the",
"topographical",
"vector",
"stemming",
"from",
"the",
"specified",
"value",
"x_min",
"for",
"the",
"current",
"feasible",
"set",
"X_min",
"with",
"True",
"boolean",
"values",
"indicating",
"positive",
"entries",
"and",
"False",
"values",
"indicat... | def g_topograph(self, x_min, X_min):
"""
Returns the topographical vector stemming from the specified value
``x_min`` for the current feasible set ``X_min`` with True boolean
values indicating positive entries and False values indicating
negative entries.
"""
x_min = np.array([x_min])
self.Y = spatial.distance.cdist(x_min, X_min, 'euclidean')
# Find sorted indexes of spatial distances:
self.Z = np.argsort(self.Y, axis=-1)
self.Ss = X_min[self.Z][0]
self.minimizer_pool = self.minimizer_pool[self.Z]
self.minimizer_pool = self.minimizer_pool[0]
return self.Ss | [
"def",
"g_topograph",
"(",
"self",
",",
"x_min",
",",
"X_min",
")",
":",
"x_min",
"=",
"np",
".",
"array",
"(",
"[",
"x_min",
"]",
")",
"self",
".",
"Y",
"=",
"spatial",
".",
"distance",
".",
"cdist",
"(",
"x_min",
",",
"X_min",
",",
"'euclidean'",... | https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/optimize/_shgo.py#L1040-L1056 | |
dmlc/dgl | 8d14a739bc9e446d6c92ef83eafe5782398118de | python/dgl/_deprecate/graph.py | python | DGLGraph.pull | (self,
v,
message_func="default",
reduce_func="default",
apply_node_func="default",
inplace=False) | Pull messages from the node(s)' predecessors and then update their features.
Optionally, apply a function to update the node features after receive.
* `reduce_func` will be skipped for nodes with no incoming message.
* If all ``v`` have no incoming message, this will downgrade to an :func:`apply_nodes`.
* If some ``v`` have no incoming message, their new feature value will be calculated
by the column initializer (see :func:`set_n_initializer`). The feature shapes and
dtypes will be inferred.
Parameters
----------
v : int, iterable of int, or tensor
The node(s) to be updated.
message_func : callable, optional
Message function on the edges. The function should be
an :mod:`Edge UDF <dgl.udf>`.
reduce_func : callable, optional
Reduce function on the node. The function should be
a :mod:`Node UDF <dgl.udf>`.
apply_node_func : callable, optional
Apply function on the nodes. The function should be
a :mod:`Node UDF <dgl.udf>`.
inplace: bool, optional
If True, update will be done in place, but autograd will break.
Examples
--------
Create a graph for demo.
.. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``).
>>> import torch as th
>>> g = dgl.DGLGraph()
>>> g.add_nodes(3)
>>> g.ndata['x'] = th.tensor([[0.], [1.], [2.]])
Use the built-in message function :func:`~dgl.function.copy_src` for copying
node features as the message.
>>> m_func = dgl.function.copy_src('x', 'm')
>>> g.register_message_func(m_func)
Use the built-int message reducing function :func:`~dgl.function.sum`, which
sums the messages received and replace the old node features with it.
>>> m_reduce_func = dgl.function.sum('m', 'x')
>>> g.register_reduce_func(m_reduce_func)
As no edges exist, nothing happens.
>>> g.pull(g.nodes())
>>> g.ndata['x']
tensor([[0.],
[1.],
[2.]])
Add edges ``0 -> 1, 1 -> 2``. Pull messages for the node :math:`2`.
>>> g.add_edges([0, 1], [1, 2])
>>> g.pull(2)
>>> g.ndata['x']
tensor([[0.],
[1.],
[1.]])
The feature of node :math:`2` changes but the feature of node :math:`1`
remains the same as we did not :func:`pull` (and reduce) messages for it.
See Also
--------
push | Pull messages from the node(s)' predecessors and then update their features. | [
"Pull",
"messages",
"from",
"the",
"node",
"(",
"s",
")",
"predecessors",
"and",
"then",
"update",
"their",
"features",
"."
] | def pull(self,
v,
message_func="default",
reduce_func="default",
apply_node_func="default",
inplace=False):
"""Pull messages from the node(s)' predecessors and then update their features.
Optionally, apply a function to update the node features after receive.
* `reduce_func` will be skipped for nodes with no incoming message.
* If all ``v`` have no incoming message, this will downgrade to an :func:`apply_nodes`.
* If some ``v`` have no incoming message, their new feature value will be calculated
by the column initializer (see :func:`set_n_initializer`). The feature shapes and
dtypes will be inferred.
Parameters
----------
v : int, iterable of int, or tensor
The node(s) to be updated.
message_func : callable, optional
Message function on the edges. The function should be
an :mod:`Edge UDF <dgl.udf>`.
reduce_func : callable, optional
Reduce function on the node. The function should be
a :mod:`Node UDF <dgl.udf>`.
apply_node_func : callable, optional
Apply function on the nodes. The function should be
a :mod:`Node UDF <dgl.udf>`.
inplace: bool, optional
If True, update will be done in place, but autograd will break.
Examples
--------
Create a graph for demo.
.. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``).
>>> import torch as th
>>> g = dgl.DGLGraph()
>>> g.add_nodes(3)
>>> g.ndata['x'] = th.tensor([[0.], [1.], [2.]])
Use the built-in message function :func:`~dgl.function.copy_src` for copying
node features as the message.
>>> m_func = dgl.function.copy_src('x', 'm')
>>> g.register_message_func(m_func)
Use the built-int message reducing function :func:`~dgl.function.sum`, which
sums the messages received and replace the old node features with it.
>>> m_reduce_func = dgl.function.sum('m', 'x')
>>> g.register_reduce_func(m_reduce_func)
As no edges exist, nothing happens.
>>> g.pull(g.nodes())
>>> g.ndata['x']
tensor([[0.],
[1.],
[2.]])
Add edges ``0 -> 1, 1 -> 2``. Pull messages for the node :math:`2`.
>>> g.add_edges([0, 1], [1, 2])
>>> g.pull(2)
>>> g.ndata['x']
tensor([[0.],
[1.],
[1.]])
The feature of node :math:`2` changes but the feature of node :math:`1`
remains the same as we did not :func:`pull` (and reduce) messages for it.
See Also
--------
push
"""
if message_func == "default":
message_func = self._message_func
if reduce_func == "default":
reduce_func = self._reduce_func
if apply_node_func == "default":
apply_node_func = self._apply_node_func
assert message_func is not None
assert reduce_func is not None
v = utils.toindex(v)
if len(v) == 0:
return
with ir.prog() as prog:
scheduler.schedule_pull(graph=AdaptedDGLGraph(self),
pull_nodes=v,
message_func=message_func,
reduce_func=reduce_func,
apply_func=apply_node_func,
inplace=inplace)
Runtime.run(prog) | [
"def",
"pull",
"(",
"self",
",",
"v",
",",
"message_func",
"=",
"\"default\"",
",",
"reduce_func",
"=",
"\"default\"",
",",
"apply_node_func",
"=",
"\"default\"",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"message_func",
"==",
"\"default\"",
":",
"messag... | https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/python/dgl/_deprecate/graph.py#L3041-L3142 | ||
Blockstream/satellite | ceb46a00e176c43a6b4170359f6948663a0616bb | blocksatcli/monitoring_api.py | python | BsMonitoring._save_credentials | (self, uuid, fingerprint) | Record the successful registration locally on the JSON config | Record the successful registration locally on the JSON config | [
"Record",
"the",
"successful",
"registration",
"locally",
"on",
"the",
"JSON",
"config"
] | def _save_credentials(self, uuid, fingerprint):
"""Record the successful registration locally on the JSON config"""
self.user_info['monitoring'] = {
'registered': True,
'uuid': uuid,
'fingerprint': fingerprint
}
config.write_cfg_file(self.cfg, self.cfg_dir, self.user_info)
self.registered = True | [
"def",
"_save_credentials",
"(",
"self",
",",
"uuid",
",",
"fingerprint",
")",
":",
"self",
".",
"user_info",
"[",
"'monitoring'",
"]",
"=",
"{",
"'registered'",
":",
"True",
",",
"'uuid'",
":",
"uuid",
",",
"'fingerprint'",
":",
"fingerprint",
"}",
"confi... | https://github.com/Blockstream/satellite/blob/ceb46a00e176c43a6b4170359f6948663a0616bb/blocksatcli/monitoring_api.py#L168-L176 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/m2r.py | python | RestInlineLexer.output_eol_literal_marker | (self, m) | return self.renderer.eol_literal_marker(marker) | Pass through rest link. | Pass through rest link. | [
"Pass",
"through",
"rest",
"link",
"."
] | def output_eol_literal_marker(self, m):
"""Pass through rest link."""
marker = ':' if m.group(1) is None else ''
return self.renderer.eol_literal_marker(marker) | [
"def",
"output_eol_literal_marker",
"(",
"self",
",",
"m",
")",
":",
"marker",
"=",
"':'",
"if",
"m",
".",
"group",
"(",
"1",
")",
"is",
"None",
"else",
"''",
"return",
"self",
".",
"renderer",
".",
"eol_literal_marker",
"(",
"marker",
")"
] | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/m2r.py#L172-L175 | |
demisto/content | 5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07 | Packs/QRadar/Integrations/QRadar_v2/QRadar_v2.py | python | get_entry_for_assets | (title, obj, contents, human_readable_obj, headers=None) | return {
"Type": entryTypes["note"],
"Contents": contents,
"ContentsFormat": formats["json"],
"ReadableContentsFormat": formats["markdown"],
"HumanReadable": "### {0}\n{1}".format(title, human_readable_md),
"EntryContext": obj,
} | Specific implementation for assets commands, that turns asset result to entryObject | Specific implementation for assets commands, that turns asset result to entryObject | [
"Specific",
"implementation",
"for",
"assets",
"commands",
"that",
"turns",
"asset",
"result",
"to",
"entryObject"
] | def get_entry_for_assets(title, obj, contents, human_readable_obj, headers=None):
"""
Specific implementation for assets commands, that turns asset result to entryObject
"""
if len(obj) == 0:
return "There is no output result"
obj = filter_dict_null(obj)
human_readable_obj = filter_dict_null(human_readable_obj)
if headers:
if isinstance(headers, str):
headers = headers.split(",")
headers = list(
[x for x in list_entry if x in headers] for list_entry in human_readable_obj
)
human_readable_md = ""
for k, h_obj in human_readable_obj.items():
human_readable_md = human_readable_md + tableToMarkdown(k, h_obj, headers)
return {
"Type": entryTypes["note"],
"Contents": contents,
"ContentsFormat": formats["json"],
"ReadableContentsFormat": formats["markdown"],
"HumanReadable": "### {0}\n{1}".format(title, human_readable_md),
"EntryContext": obj,
} | [
"def",
"get_entry_for_assets",
"(",
"title",
",",
"obj",
",",
"contents",
",",
"human_readable_obj",
",",
"headers",
"=",
"None",
")",
":",
"if",
"len",
"(",
"obj",
")",
"==",
"0",
":",
"return",
"\"There is no output result\"",
"obj",
"=",
"filter_dict_null",... | https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/QRadar/Integrations/QRadar_v2/QRadar_v2.py#L1537-L1561 | |
ahmetcemturan/SFACT | 7576e29ba72b33e5058049b77b7b558875542747 | fabmetheus_utilities/geometry/geometry_utilities/matrix.py | python | getTetragridM | (elementNode, prefix, tetragrid) | return tetragrid | Get the tetragrid from the elementNode letter m values. | Get the tetragrid from the elementNode letter m values. | [
"Get",
"the",
"tetragrid",
"from",
"the",
"elementNode",
"letter",
"m",
"values",
"."
] | def getTetragridM(elementNode, prefix, tetragrid):
'Get the tetragrid from the elementNode letter m values.'
keysM = getKeysM(prefix)
evaluatedDictionary = evaluate.getEvaluatedDictionaryByEvaluationKeys(elementNode, keysM)
if len(evaluatedDictionary.keys()) < 1:
return tetragrid
for row in xrange(4):
for column in xrange(4):
key = getKeyM(row, column, prefix)
if key in evaluatedDictionary:
value = evaluatedDictionary[key]
if value == None or value == 'None':
print('Warning, value in getTetragridM in matrix is None for key for dictionary:')
print(key)
print(evaluatedDictionary)
else:
tetragrid = getIdentityTetragrid(tetragrid)
tetragrid[row][column] = float(value)
euclidean.removeElementsFromDictionary(elementNode.attributes, keysM)
return tetragrid | [
"def",
"getTetragridM",
"(",
"elementNode",
",",
"prefix",
",",
"tetragrid",
")",
":",
"keysM",
"=",
"getKeysM",
"(",
"prefix",
")",
"evaluatedDictionary",
"=",
"evaluate",
".",
"getEvaluatedDictionaryByEvaluationKeys",
"(",
"elementNode",
",",
"keysM",
")",
"if",... | https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/fabmetheus_utilities/geometry/geometry_utilities/matrix.py#L268-L287 | |
yongxuUSTC/dcase2017_task4_cvssp | 97ab1e29709bc87c9c1f9459929fb3853e7fa664 | evaluation/evaluation_qk/evaluation.py | python | recall | (pred, gt, thres) | [] | def recall(pred, gt, thres):
(tp, fn, fp, tn) = tp_fn_fp_tn(pred, gt, thres)
if (tp + fn) == 0:
return 0
else:
return float(tp) / (tp + fn) | [
"def",
"recall",
"(",
"pred",
",",
"gt",
",",
"thres",
")",
":",
"(",
"tp",
",",
"fn",
",",
"fp",
",",
"tn",
")",
"=",
"tp_fn_fp_tn",
"(",
"pred",
",",
"gt",
",",
"thres",
")",
"if",
"(",
"tp",
"+",
"fn",
")",
"==",
"0",
":",
"return",
"0",... | https://github.com/yongxuUSTC/dcase2017_task4_cvssp/blob/97ab1e29709bc87c9c1f9459929fb3853e7fa664/evaluation/evaluation_qk/evaluation.py#L46-L51 | ||||
brettcannon/gidgethub | 7f05154182fb5ff8194e42bcc357497251aa554b | gidgethub/sansio.py | python | validate_event | (payload: bytes, *, signature: str, secret: str) | Validate the signature of a webhook event. | Validate the signature of a webhook event. | [
"Validate",
"the",
"signature",
"of",
"a",
"webhook",
"event",
"."
] | def validate_event(payload: bytes, *, signature: str, secret: str) -> None:
"""Validate the signature of a webhook event."""
# https://docs.github.com/en/developers/webhooks-and-events/securing-your-webhooks#validating-payloads-from-github
sha256_signature_prefix = "sha256="
sha1_signature_prefix = "sha1="
if signature.startswith(sha256_signature_prefix):
hmac_sig = hmac.new(
secret.encode("UTF-8"), msg=payload, digestmod="sha256"
).hexdigest()
calculated_sig = sha256_signature_prefix + hmac_sig
elif signature.startswith(sha1_signature_prefix):
hmac_sig = hmac.new(
secret.encode("UTF-8"), msg=payload, digestmod="sha1"
).hexdigest()
calculated_sig = sha1_signature_prefix + hmac_sig
else:
raise ValidationFailure(
f"signature does not start with {repr(sha256_signature_prefix)} or {repr(sha1_signature_prefix)}"
)
if not hmac.compare_digest(signature, calculated_sig):
raise ValidationFailure("payload's signature does not align with the secret") | [
"def",
"validate_event",
"(",
"payload",
":",
"bytes",
",",
"*",
",",
"signature",
":",
"str",
",",
"secret",
":",
"str",
")",
"->",
"None",
":",
"# https://docs.github.com/en/developers/webhooks-and-events/securing-your-webhooks#validating-payloads-from-github",
"sha256_si... | https://github.com/brettcannon/gidgethub/blob/7f05154182fb5ff8194e42bcc357497251aa554b/gidgethub/sansio.py#L70-L90 | ||
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | python3.8.2/Lib/mailbox.py | python | _mboxMMDF.get_message | (self, key) | return msg | Return a Message representation or raise a KeyError. | Return a Message representation or raise a KeyError. | [
"Return",
"a",
"Message",
"representation",
"or",
"raise",
"a",
"KeyError",
"."
] | def get_message(self, key):
"""Return a Message representation or raise a KeyError."""
start, stop = self._lookup(key)
self._file.seek(start)
from_line = self._file.readline().replace(linesep, b'')
string = self._file.read(stop - self._file.tell())
msg = self._message_factory(string.replace(linesep, b'\n'))
msg.set_from(from_line[5:].decode('ascii'))
return msg | [
"def",
"get_message",
"(",
"self",
",",
"key",
")",
":",
"start",
",",
"stop",
"=",
"self",
".",
"_lookup",
"(",
"key",
")",
"self",
".",
"_file",
".",
"seek",
"(",
"start",
")",
"from_line",
"=",
"self",
".",
"_file",
".",
"readline",
"(",
")",
... | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/mailbox.py#L774-L782 | |
out0fmemory/GoAgent-Always-Available | c4254984fea633ce3d1893fe5901debd9f22c2a9 | server/lib/google/appengine/_internal/antlr3/tokens.py | python | Token.setTokenIndex | (self, index) | @brief Set the index in the input stream.
Using setter/getter methods is deprecated. Use o.index instead. | @brief Set the index in the input stream. | [
"@brief",
"Set",
"the",
"index",
"in",
"the",
"input",
"stream",
"."
] | def setTokenIndex(self, index):
"""@brief Set the index in the input stream.
Using setter/getter methods is deprecated. Use o.index instead."""
raise NotImplementedError | [
"def",
"setTokenIndex",
"(",
"self",
",",
"index",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/_internal/antlr3/tokens.py#L133-L138 | ||
athena-team/athena | e704884ec6a3a947769d892aa267578038e49ecb | athena/models/stargan_vc.py | python | StarganModel.get_loss | (self, outputs, samples, training=None, stage="classifier") | get stargan loss of different stage | get stargan loss of different stage | [
"get",
"stargan",
"loss",
"of",
"different",
"stage"
] | def get_loss(self, outputs, samples, training=None, stage="classifier"):
""" get stargan loss of different stage
"""
if stage == "classifier":
loss = self.loss_function(outputs, samples, stage=stage)
self.metric_c.update_state(loss)
metrics_c = self.metric_c.result()
return loss, metrics_c
elif stage == "generator":
loss = self.loss_function(outputs, samples, stage=stage)
self.metric_g.update_state(loss)
metrics_g = self.metric_g.result()
return loss, metrics_g
else:
loss = self.loss_function(outputs, samples, stage=stage)
self.metric_d.update_state(loss)
metrics_d = self.metric_d.result()
return loss, metrics_d | [
"def",
"get_loss",
"(",
"self",
",",
"outputs",
",",
"samples",
",",
"training",
"=",
"None",
",",
"stage",
"=",
"\"classifier\"",
")",
":",
"if",
"stage",
"==",
"\"classifier\"",
":",
"loss",
"=",
"self",
".",
"loss_function",
"(",
"outputs",
",",
"samp... | https://github.com/athena-team/athena/blob/e704884ec6a3a947769d892aa267578038e49ecb/athena/models/stargan_vc.py#L275-L292 | ||
ustayready/CredKing | 68b612e4cdf01d2b65b14ab2869bb8a5531056ee | plugins/gmail/urllib3/util/selectors.py | python | _fileobj_to_fd | (fileobj) | return fd | Return a file descriptor from a file object. If
given an integer will simply return that integer back. | Return a file descriptor from a file object. If
given an integer will simply return that integer back. | [
"Return",
"a",
"file",
"descriptor",
"from",
"a",
"file",
"object",
".",
"If",
"given",
"an",
"integer",
"will",
"simply",
"return",
"that",
"integer",
"back",
"."
] | def _fileobj_to_fd(fileobj):
""" Return a file descriptor from a file object. If
given an integer will simply return that integer back. """
if isinstance(fileobj, int):
fd = fileobj
else:
try:
fd = int(fileobj.fileno())
except (AttributeError, TypeError, ValueError):
raise ValueError("Invalid file object: {0!r}".format(fileobj))
if fd < 0:
raise ValueError("Invalid file descriptor: {0}".format(fd))
return fd | [
"def",
"_fileobj_to_fd",
"(",
"fileobj",
")",
":",
"if",
"isinstance",
"(",
"fileobj",
",",
"int",
")",
":",
"fd",
"=",
"fileobj",
"else",
":",
"try",
":",
"fd",
"=",
"int",
"(",
"fileobj",
".",
"fileno",
"(",
")",
")",
"except",
"(",
"AttributeError... | https://github.com/ustayready/CredKing/blob/68b612e4cdf01d2b65b14ab2869bb8a5531056ee/plugins/gmail/urllib3/util/selectors.py#L41-L53 | |
tctianchi/pyvenn | 24d6e1ddf9fb7c9881268dbad28a979da63815fa | venn.py | python | venn4 | (labels, names=['A', 'B', 'C', 'D'], **options) | return fig, ax | plots a 4-set Venn diagram
@type labels: dict[str, str]
@type names: list[str]
@rtype: (Figure, AxesSubplot)
input
labels: a label dict where keys are identified via binary codes ('0001', '0010', '0100', ...),
hence a valid set could look like: {'0001': 'text 1', '0010': 'text 2', '0100': 'text 3', ...}.
unmentioned codes are considered as ''.
names: group names
more: colors, figsize, dpi, fontsize
return
pyplot Figure and AxesSubplot object | plots a 4-set Venn diagram | [
"plots",
"a",
"4",
"-",
"set",
"Venn",
"diagram"
] | def venn4(labels, names=['A', 'B', 'C', 'D'], **options):
"""
plots a 4-set Venn diagram
@type labels: dict[str, str]
@type names: list[str]
@rtype: (Figure, AxesSubplot)
input
labels: a label dict where keys are identified via binary codes ('0001', '0010', '0100', ...),
hence a valid set could look like: {'0001': 'text 1', '0010': 'text 2', '0100': 'text 3', ...}.
unmentioned codes are considered as ''.
names: group names
more: colors, figsize, dpi, fontsize
return
pyplot Figure and AxesSubplot object
"""
colors = options.get('colors', [default_colors[i] for i in range(4)])
figsize = options.get('figsize', (12, 12))
dpi = options.get('dpi', 96)
fontsize = options.get('fontsize', 14)
fig = plt.figure(0, figsize=figsize, dpi=dpi)
ax = fig.add_subplot(111, aspect='equal')
ax.set_axis_off()
ax.set_ylim(bottom=0.0, top=1.0)
ax.set_xlim(left=0.0, right=1.0)
# body
draw_ellipse(fig, ax, 0.350, 0.400, 0.72, 0.45, 140.0, colors[0])
draw_ellipse(fig, ax, 0.450, 0.500, 0.72, 0.45, 140.0, colors[1])
draw_ellipse(fig, ax, 0.544, 0.500, 0.72, 0.45, 40.0, colors[2])
draw_ellipse(fig, ax, 0.644, 0.400, 0.72, 0.45, 40.0, colors[3])
draw_text(fig, ax, 0.85, 0.42, labels.get('0001', ''), fontsize=fontsize)
draw_text(fig, ax, 0.68, 0.72, labels.get('0010', ''), fontsize=fontsize)
draw_text(fig, ax, 0.77, 0.59, labels.get('0011', ''), fontsize=fontsize)
draw_text(fig, ax, 0.32, 0.72, labels.get('0100', ''), fontsize=fontsize)
draw_text(fig, ax, 0.71, 0.30, labels.get('0101', ''), fontsize=fontsize)
draw_text(fig, ax, 0.50, 0.66, labels.get('0110', ''), fontsize=fontsize)
draw_text(fig, ax, 0.65, 0.50, labels.get('0111', ''), fontsize=fontsize)
draw_text(fig, ax, 0.14, 0.42, labels.get('1000', ''), fontsize=fontsize)
draw_text(fig, ax, 0.50, 0.17, labels.get('1001', ''), fontsize=fontsize)
draw_text(fig, ax, 0.29, 0.30, labels.get('1010', ''), fontsize=fontsize)
draw_text(fig, ax, 0.39, 0.24, labels.get('1011', ''), fontsize=fontsize)
draw_text(fig, ax, 0.23, 0.59, labels.get('1100', ''), fontsize=fontsize)
draw_text(fig, ax, 0.61, 0.24, labels.get('1101', ''), fontsize=fontsize)
draw_text(fig, ax, 0.35, 0.50, labels.get('1110', ''), fontsize=fontsize)
draw_text(fig, ax, 0.50, 0.38, labels.get('1111', ''), fontsize=fontsize)
# legend
draw_text(fig, ax, 0.13, 0.18, names[0], colors[0], fontsize=fontsize, ha="right")
draw_text(fig, ax, 0.18, 0.83, names[1], colors[1], fontsize=fontsize, ha="right", va="bottom")
draw_text(fig, ax, 0.82, 0.83, names[2], colors[2], fontsize=fontsize, ha="left", va="bottom")
draw_text(fig, ax, 0.87, 0.18, names[3], colors[3], fontsize=fontsize, ha="left", va="top")
leg = ax.legend(names, loc='center left', bbox_to_anchor=(1.0, 0.5), fancybox=True)
leg.get_frame().set_alpha(0.5)
return fig, ax | [
"def",
"venn4",
"(",
"labels",
",",
"names",
"=",
"[",
"'A'",
",",
"'B'",
",",
"'C'",
",",
"'D'",
"]",
",",
"*",
"*",
"options",
")",
":",
"colors",
"=",
"options",
".",
"get",
"(",
"'colors'",
",",
"[",
"default_colors",
"[",
"i",
"]",
"for",
... | https://github.com/tctianchi/pyvenn/blob/24d6e1ddf9fb7c9881268dbad28a979da63815fa/venn.py#L218-L276 | |
gee-community/gee_tools | d7b35174933739f3aeee439d622e5fab57b6dd2d | geetools/algorithms.py | python | sumDistance | (image, collection, bands=None, discard_zeros=False,
name='sumdist') | return ee.Image(collection.iterate(over_rest, accum)) | Compute de sum of all distances between the given image and the
collection passed
:param image:
:param collection:
:return: | Compute de sum of all distances between the given image and the
collection passed
:param image:
:param collection:
:return: | [
"Compute",
"de",
"sum",
"of",
"all",
"distances",
"between",
"the",
"given",
"image",
"and",
"the",
"collection",
"passed",
":",
"param",
"image",
":",
":",
"param",
"collection",
":",
":",
"return",
":"
] | def sumDistance(image, collection, bands=None, discard_zeros=False,
name='sumdist'):
""" Compute de sum of all distances between the given image and the
collection passed
:param image:
:param collection:
:return:
"""
condition = isinstance(collection, ee.ImageCollection)
if condition:
collection = collection.toList(collection.size())
accum = ee.Image(0).rename(name)
def over_rest(im, ini):
ini = ee.Image(ini)
im = ee.Image(im)
dist = ee.Image(euclideanDistance(image, im, bands, discard_zeros))\
.rename(name)
return ini.add(dist)
return ee.Image(collection.iterate(over_rest, accum)) | [
"def",
"sumDistance",
"(",
"image",
",",
"collection",
",",
"bands",
"=",
"None",
",",
"discard_zeros",
"=",
"False",
",",
"name",
"=",
"'sumdist'",
")",
":",
"condition",
"=",
"isinstance",
"(",
"collection",
",",
"ee",
".",
"ImageCollection",
")",
"if",
... | https://github.com/gee-community/gee_tools/blob/d7b35174933739f3aeee439d622e5fab57b6dd2d/geetools/algorithms.py#L207-L230 | |
proycon/pynlpl | 7707f69a91caaa6cde037f0d0379f1d42500a68b | pynlpl/formats/folia.py | python | AllowTokenAnnotation.alternatives | (self, Class=None, set=None) | Generator over alternatives, either all or only of a specific annotation type, and possibly restrained also by set.
Arguments:
Class (class): The python Class you want to retrieve (e.g. PosAnnotation). Or set to ``None`` to select all alternatives regardless of what type they are.
set (str): The set you want to retrieve (defaults to ``None``, which selects irregardless of set)
Yields:
:class:`Alternative` elements | Generator over alternatives, either all or only of a specific annotation type, and possibly restrained also by set. | [
"Generator",
"over",
"alternatives",
"either",
"all",
"or",
"only",
"of",
"a",
"specific",
"annotation",
"type",
"and",
"possibly",
"restrained",
"also",
"by",
"set",
"."
] | def alternatives(self, Class=None, set=None):
"""Generator over alternatives, either all or only of a specific annotation type, and possibly restrained also by set.
Arguments:
Class (class): The python Class you want to retrieve (e.g. PosAnnotation). Or set to ``None`` to select all alternatives regardless of what type they are.
set (str): The set you want to retrieve (defaults to ``None``, which selects irregardless of set)
Yields:
:class:`Alternative` elements
"""
for e in self.select(Alternative,None, True, []): #pylint: disable=too-many-nested-blocks
if Class is None:
yield e
elif len(e) >= 1: #child elements?
for e2 in e:
try:
if isinstance(e2, Class):
try:
if set is None or e2.set == set:
yield e #not e2
break #yield an alternative only once (in case there are multiple matches)
except AttributeError:
continue
except AttributeError:
continue | [
"def",
"alternatives",
"(",
"self",
",",
"Class",
"=",
"None",
",",
"set",
"=",
"None",
")",
":",
"for",
"e",
"in",
"self",
".",
"select",
"(",
"Alternative",
",",
"None",
",",
"True",
",",
"[",
"]",
")",
":",
"#pylint: disable=too-many-nested-blocks",
... | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L3080-L3105 | ||
CvvT/dumpDex | 92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1 | python/idaapi.py | python | OutMnem | (*args) | return _idaapi.OutMnem(*args) | OutMnem(width=8, postfix=None) -> int | OutMnem(width=8, postfix=None) -> int | [
"OutMnem",
"(",
"width",
"=",
"8",
"postfix",
"=",
"None",
")",
"-",
">",
"int"
] | def OutMnem(*args):
"""
OutMnem(width=8, postfix=None) -> int
"""
return _idaapi.OutMnem(*args) | [
"def",
"OutMnem",
"(",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"OutMnem",
"(",
"*",
"args",
")"
] | https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L49165-L49169 | |
hydroshare/hydroshare | 7ba563b55412f283047fb3ef6da367d41dec58c6 | hs_file_types/models/model_instance.py | python | ModelInstanceFileMetaData.get_rdf_graph | (self) | return graph | [] | def get_rdf_graph(self):
graph = super(ModelInstanceFileMetaData, self).get_rdf_graph()
subject = self.rdf_subject()
graph.add((subject, HSTERMS.includesModelOutput, Literal(self.has_model_output)))
if self.executed_by:
resource = self.logical_file.resource
hs_res_url = os.path.join(current_site_url(), 'resource', resource.file_path)
aggr_url = os.path.join(hs_res_url, self.executed_by.map_short_file_path) + '#aggregation'
graph.add((subject, HSTERMS.executedByModelProgram, URIRef(aggr_url)))
if self.logical_file.metadata_schema_json:
graph.add((subject, HSTERMS.modelProgramSchema, URIRef(self.logical_file.schema_file_url)))
if self.metadata_json:
graph.add((subject, HSTERMS.modelProgramSchemaValues, URIRef(self.logical_file.schema_values_file_url)))
return graph | [
"def",
"get_rdf_graph",
"(",
"self",
")",
":",
"graph",
"=",
"super",
"(",
"ModelInstanceFileMetaData",
",",
"self",
")",
".",
"get_rdf_graph",
"(",
")",
"subject",
"=",
"self",
".",
"rdf_subject",
"(",
")",
"graph",
".",
"add",
"(",
"(",
"subject",
",",... | https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_file_types/models/model_instance.py#L281-L299 | |||
wequant-org/liveStrategyEngine | 6e799e33cfa83b4496dd694e1d2bf30ea104e2c1 | exchangeConnection/huobi/huobiServiceETH.py | python | get_withdraw_address | (currency) | return api_key_get(params, url) | :param currency:
:return: | :param currency:
:return: | [
":",
"param",
"currency",
":",
":",
"return",
":"
] | def get_withdraw_address(currency):
"""
:param currency:
:return:
"""
params = {'currency': currency}
url = '/v1/dw/withdraw-virtual/addresses'
return api_key_get(params, url) | [
"def",
"get_withdraw_address",
"(",
"currency",
")",
":",
"params",
"=",
"{",
"'currency'",
":",
"currency",
"}",
"url",
"=",
"'/v1/dw/withdraw-virtual/addresses'",
"return",
"api_key_get",
"(",
"params",
",",
"url",
")"
] | https://github.com/wequant-org/liveStrategyEngine/blob/6e799e33cfa83b4496dd694e1d2bf30ea104e2c1/exchangeConnection/huobi/huobiServiceETH.py#L245-L253 | |
Inboxen/Inboxen | ea41f9e235f2eacd76ea3df0f892b92c31b23605 | inboxen/_version.py | python | render_git_describe_long | (pieces) | return rendered | TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix) | TAG-DISTANCE-gHEX[-dirty]. | [
"TAG",
"-",
"DISTANCE",
"-",
"gHEX",
"[",
"-",
"dirty",
"]",
"."
] | def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
else:
# exception #1
rendered = pieces["short"]
if pieces["dirty"]:
rendered += "-dirty"
return rendered | [
"def",
"render_git_describe_long",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"rendered",
"+=",
"\"-%d-g%s\"",
"%",
"(",
"pieces",
"[",
"\"distance\"",
"]",
",",
"pieces",
... | https://github.com/Inboxen/Inboxen/blob/ea41f9e235f2eacd76ea3df0f892b92c31b23605/inboxen/_version.py#L425-L442 | |
rsms/inter | 0dac20662c34efc40dbf154b6366310cd4dfa551 | misc/tools/svg.py | python | valueToString | (v) | return v | >>> valueToString(0)
'0'
>>> valueToString(10)
'10'
>>> valueToString(-10)
'-10'
>>> valueToString(0.1)
'0.1'
>>> valueToString(0.0001)
'0.0001'
>>> valueToString(0.00001)
'0'
>>> valueToString(10.0001)
'10.0001'
>>> valueToString(10.00001)
'10' | >>> valueToString(0)
'0'
>>> valueToString(10)
'10'
>>> valueToString(-10)
'-10'
>>> valueToString(0.1)
'0.1'
>>> valueToString(0.0001)
'0.0001'
>>> valueToString(0.00001)
'0'
>>> valueToString(10.0001)
'10.0001'
>>> valueToString(10.00001)
'10' | [
">>>",
"valueToString",
"(",
"0",
")",
"0",
">>>",
"valueToString",
"(",
"10",
")",
"10",
">>>",
"valueToString",
"(",
"-",
"10",
")",
"-",
"10",
">>>",
"valueToString",
"(",
"0",
".",
"1",
")",
"0",
".",
"1",
">>>",
"valueToString",
"(",
"0",
".",... | def valueToString(v):
"""
>>> valueToString(0)
'0'
>>> valueToString(10)
'10'
>>> valueToString(-10)
'-10'
>>> valueToString(0.1)
'0.1'
>>> valueToString(0.0001)
'0.0001'
>>> valueToString(0.00001)
'0'
>>> valueToString(10.0001)
'10.0001'
>>> valueToString(10.00001)
'10'
"""
if int(v) == v:
v = "%d" % (int(v))
else:
v = "%.4f" % v
# strip unnecessary zeros
# there is probably an easier way to do this
compiled = []
for c in reversed(v):
if not compiled and c == "0":
continue
compiled.append(c)
v = "".join(reversed(compiled))
if v.endswith("."):
v = v[:-1]
if not v:
v = "0"
return v | [
"def",
"valueToString",
"(",
"v",
")",
":",
"if",
"int",
"(",
"v",
")",
"==",
"v",
":",
"v",
"=",
"\"%d\"",
"%",
"(",
"int",
"(",
"v",
")",
")",
"else",
":",
"v",
"=",
"\"%.4f\"",
"%",
"v",
"# strip unnecessary zeros",
"# there is probably an easier wa... | https://github.com/rsms/inter/blob/0dac20662c34efc40dbf154b6366310cd4dfa551/misc/tools/svg.py#L31-L66 | |
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pkg_resources/_vendor/packaging/version.py | python | Version.is_postrelease | (self) | return bool(self._version.post) | [] | def is_postrelease(self):
return bool(self._version.post) | [
"def",
"is_postrelease",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"_version",
".",
"post",
")"
] | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pkg_resources/_vendor/packaging/version.py#L294-L295 | |||
averagesecurityguy/scripts | 54660525f36e3e97d23fbd259ceb9b10823f2ee2 | webapp/dirb.py | python | save | (resources) | Save the resources to a file. | Save the resources to a file. | [
"Save",
"the",
"resources",
"to",
"a",
"file",
"."
] | def save(resources):
"""
Save the resources to a file.
"""
with open('dirb_resources.txt', 'w') as f:
for resource in resources:
f.write('{0}\n'.format(resource)) | [
"def",
"save",
"(",
"resources",
")",
":",
"with",
"open",
"(",
"'dirb_resources.txt'",
",",
"'w'",
")",
"as",
"f",
":",
"for",
"resource",
"in",
"resources",
":",
"f",
".",
"write",
"(",
"'{0}\\n'",
".",
"format",
"(",
"resource",
")",
")"
] | https://github.com/averagesecurityguy/scripts/blob/54660525f36e3e97d23fbd259ceb9b10823f2ee2/webapp/dirb.py#L140-L146 | ||
cobbler/cobbler | eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc | cobbler/validate.py | python | validate_obj_type | (object_type: str) | return object_type in ["distro", "profile", "system", "repo", "image", "mgmtclass", "package", "file", "menu"] | :param object_type:
:return: | [] | def validate_obj_type(object_type: str) -> bool:
"""
:param object_type:
:return:
"""
if not isinstance(object_type, str):
return False
return object_type in ["distro", "profile", "system", "repo", "image", "mgmtclass", "package", "file", "menu"] | [
"def",
"validate_obj_type",
"(",
"object_type",
":",
"str",
")",
"->",
"bool",
":",
"if",
"not",
"isinstance",
"(",
"object_type",
",",
"str",
")",
":",
"return",
"False",
"return",
"object_type",
"in",
"[",
"\"distro\"",
",",
"\"profile\"",
",",
"\"system\"... | https://github.com/cobbler/cobbler/blob/eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc/cobbler/validate.py#L646-L654 | ||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-0.96/django/db/transaction.py | python | rollback_unless_managed | () | Rolls back changes if the system is not in managed transaction mode. | Rolls back changes if the system is not in managed transaction mode. | [
"Rolls",
"back",
"changes",
"if",
"the",
"system",
"is",
"not",
"in",
"managed",
"transaction",
"mode",
"."
] | def rollback_unless_managed():
"""
Rolls back changes if the system is not in managed transaction mode.
"""
if not is_managed():
connection._rollback()
else:
set_dirty() | [
"def",
"rollback_unless_managed",
"(",
")",
":",
"if",
"not",
"is_managed",
"(",
")",
":",
"connection",
".",
"_rollback",
"(",
")",
"else",
":",
"set_dirty",
"(",
")"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-0.96/django/db/transaction.py#L140-L147 | ||
quantopian/zipline | 014f1fc339dc8b7671d29be2d85ce57d3daec343 | zipline/pipeline/pipeline.py | python | Pipeline.set_screen | (self, screen, overwrite=False) | Set a screen on this Pipeline.
Parameters
----------
filter : zipline.pipeline.Filter
The filter to apply as a screen.
overwrite : bool
Whether to overwrite any existing screen. If overwrite is False
and self.screen is not None, we raise an error. | Set a screen on this Pipeline. | [
"Set",
"a",
"screen",
"on",
"this",
"Pipeline",
"."
] | def set_screen(self, screen, overwrite=False):
"""Set a screen on this Pipeline.
Parameters
----------
filter : zipline.pipeline.Filter
The filter to apply as a screen.
overwrite : bool
Whether to overwrite any existing screen. If overwrite is False
and self.screen is not None, we raise an error.
"""
if self._screen is not None and not overwrite:
raise ValueError(
"set_screen() called with overwrite=False and screen already "
"set.\n"
"If you want to apply multiple filters as a screen use "
"set_screen(filter1 & filter2 & ...).\n"
"If you want to replace the previous screen with a new one, "
"use set_screen(new_filter, overwrite=True)."
)
self._screen = screen | [
"def",
"set_screen",
"(",
"self",
",",
"screen",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"self",
".",
"_screen",
"is",
"not",
"None",
"and",
"not",
"overwrite",
":",
"raise",
"ValueError",
"(",
"\"set_screen() called with overwrite=False and screen already... | https://github.com/quantopian/zipline/blob/014f1fc339dc8b7671d29be2d85ce57d3daec343/zipline/pipeline/pipeline.py#L155-L175 | ||
cylc/cylc-flow | 5ec221143476c7c616c156b74158edfbcd83794a | cylc/flow/workflow_files.py | python | get_contact_file | (reg) | return os.path.join(
get_workflow_srv_dir(reg), WorkflowFiles.Service.CONTACT) | Return name of contact file. | Return name of contact file. | [
"Return",
"name",
"of",
"contact",
"file",
"."
] | def get_contact_file(reg):
"""Return name of contact file."""
return os.path.join(
get_workflow_srv_dir(reg), WorkflowFiles.Service.CONTACT) | [
"def",
"get_contact_file",
"(",
"reg",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"get_workflow_srv_dir",
"(",
"reg",
")",
",",
"WorkflowFiles",
".",
"Service",
".",
"CONTACT",
")"
] | https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/workflow_files.py#L539-L542 | |
phantomcyber/playbooks | 9e850ecc44cb98c5dde53784744213a1ed5799bd | endace_splunk_search_download_pcap.py | python | PCAP_Links | (action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs) | return | [] | def PCAP_Links(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug('PCAP_Links() called')
template = """{0}"""
# parameter list for template variable replacement
parameters = [
"filtered-data:Extract_PCAP_Links:condition_1:Get_PCAP_Status:action_result.data.*.datamine.links.2.href",
]
phantom.format(container=container, template=template, parameters=parameters, name="PCAP_Links", separator=", ")
Add_Links_to_note(container=container)
return | [
"def",
"PCAP_Links",
"(",
"action",
"=",
"None",
",",
"success",
"=",
"None",
",",
"container",
"=",
"None",
",",
"results",
"=",
"None",
",",
"handle",
"=",
"None",
",",
"filtered_artifacts",
"=",
"None",
",",
"filtered_results",
"=",
"None",
",",
"cust... | https://github.com/phantomcyber/playbooks/blob/9e850ecc44cb98c5dde53784744213a1ed5799bd/endace_splunk_search_download_pcap.py#L176-L190 | |||
adulau/Forban | 4b06c8a2e2f18ff872ca20a534587a5f15a692fa | lib/ext/cherrypy/wsgiserver/wsgiserver2.py | python | HTTPServer.stop | (self) | Gracefully shutdown a server that is serving forever. | Gracefully shutdown a server that is serving forever. | [
"Gracefully",
"shutdown",
"a",
"server",
"that",
"is",
"serving",
"forever",
"."
] | def stop(self):
"""Gracefully shutdown a server that is serving forever."""
self.ready = False
if self._start_time is not None:
self._run_time += (time.time() - self._start_time)
self._start_time = None
sock = getattr(self, "socket", None)
if sock:
if not isinstance(self.bind_addr, basestring):
# Touch our own socket to make accept() return immediately.
try:
host, port = sock.getsockname()[:2]
except socket.error:
x = sys.exc_info()[1]
if x.args[0] not in socket_errors_to_ignore:
# Changed to use error code and not message
# See http://www.cherrypy.org/ticket/860.
raise
else:
# Note that we're explicitly NOT using AI_PASSIVE,
# here, because we want an actual IP to touch.
# localhost won't work if we've bound to a public IP,
# but it will if we bound to '0.0.0.0' (INADDR_ANY).
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
s = None
try:
s = socket.socket(af, socktype, proto)
# See http://groups.google.com/group/cherrypy-users/
# browse_frm/thread/bbfe5eb39c904fe0
s.settimeout(1.0)
s.connect((host, port))
s.close()
except socket.error:
if s:
s.close()
if hasattr(sock, "close"):
sock.close()
self.socket = None
self.requests.stop(self.shutdown_timeout) | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"ready",
"=",
"False",
"if",
"self",
".",
"_start_time",
"is",
"not",
"None",
":",
"self",
".",
"_run_time",
"+=",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_start_time",
")",
"self",
... | https://github.com/adulau/Forban/blob/4b06c8a2e2f18ff872ca20a534587a5f15a692fa/lib/ext/cherrypy/wsgiserver/wsgiserver2.py#L1980-L2022 | ||
opensourcesec/CIRTKit | 58b8793ada69320ffdbdd4ecdc04a3bb2fa83c37 | modules/reversing/viper/peepdf/PDFCore.py | python | PDFDictionary.getDictType | (self) | return self.dictType | Gets the type of dictionary
@return: The dictionary type (string) | Gets the type of dictionary | [
"Gets",
"the",
"type",
"of",
"dictionary"
] | def getDictType(self):
'''
Gets the type of dictionary
@return: The dictionary type (string)
'''
return self.dictType | [
"def",
"getDictType",
"(",
"self",
")",
":",
"return",
"self",
".",
"dictType"
] | https://github.com/opensourcesec/CIRTKit/blob/58b8793ada69320ffdbdd4ecdc04a3bb2fa83c37/modules/reversing/viper/peepdf/PDFCore.py#L1336-L1342 | |
pydata/xarray | 9226c7ac87b3eb246f7a7e49f8f0f23d68951624 | xarray/coding/cftimeindex.py | python | CFTimeIndex.get_loc | (self, key, method=None, tolerance=None) | Adapted from pandas.tseries.index.DatetimeIndex.get_loc | Adapted from pandas.tseries.index.DatetimeIndex.get_loc | [
"Adapted",
"from",
"pandas",
".",
"tseries",
".",
"index",
".",
"DatetimeIndex",
".",
"get_loc"
] | def get_loc(self, key, method=None, tolerance=None):
"""Adapted from pandas.tseries.index.DatetimeIndex.get_loc"""
if isinstance(key, str):
return self._get_string_slice(key)
else:
return pd.Index.get_loc(self, key, method=method, tolerance=tolerance) | [
"def",
"get_loc",
"(",
"self",
",",
"key",
",",
"method",
"=",
"None",
",",
"tolerance",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"str",
")",
":",
"return",
"self",
".",
"_get_string_slice",
"(",
"key",
")",
"else",
":",
"return",
... | https://github.com/pydata/xarray/blob/9226c7ac87b3eb246f7a7e49f8f0f23d68951624/xarray/coding/cftimeindex.py#L462-L467 | ||
superfell/Beatbox | 14f35e83d2bca254406f003a5a8559d6cc42f56b | beatbox/_beatbox.py | python | GetDeletedRequest.__init__ | (self, serverUrl, sessionId, headers, sObjectType, start, end) | [] | def __init__(self, serverUrl, sessionId, headers, sObjectType, start, end):
GetUpdatedRequest.__init__(self, serverUrl, sessionId, headers, sObjectType, start, end, "getDeleted") | [
"def",
"__init__",
"(",
"self",
",",
"serverUrl",
",",
"sessionId",
",",
"headers",
",",
"sObjectType",
",",
"start",
",",
"end",
")",
":",
"GetUpdatedRequest",
".",
"__init__",
"(",
"self",
",",
"serverUrl",
",",
"sessionId",
",",
"headers",
",",
"sObject... | https://github.com/superfell/Beatbox/blob/14f35e83d2bca254406f003a5a8559d6cc42f56b/beatbox/_beatbox.py#L625-L626 | ||||
postgres/pgadmin4 | 374c5e952fa594d749fadf1f88076c1cba8c5f64 | web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/__init__.py | python | CompoundTriggerView.enable_disable_trigger | (self, gid, sid, did, scid, tid, trid) | This function will enable OR disable the current
compound trigger object
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
trid: Trigger ID | This function will enable OR disable the current
compound trigger object | [
"This",
"function",
"will",
"enable",
"OR",
"disable",
"the",
"current",
"compound",
"trigger",
"object"
] | def enable_disable_trigger(self, gid, sid, did, scid, tid, trid):
"""
This function will enable OR disable the current
compound trigger object
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
trid: Trigger ID
"""
data = request.form if request.form else json.loads(
request.data, encoding='utf-8'
)
# Convert str 'true' to boolean type
is_enable_trigger = data['is_enable_trigger']
try:
SQL = render_template("/".join([self.template_path,
self._PROPERTIES_SQL]),
tid=tid, trid=trid,
datlastsysoid=self.datlastsysoid)
status, res = self.conn.execute_dict(SQL)
if not status:
return internal_server_error(errormsg=res)
if len(res['rows']) == 0:
return gone(self.not_found_error_msg())
o_data = dict(res['rows'][0])
# If enable is set to true means we need SQL to enable
# current compound trigger which is disabled already so we need to
# alter the 'is_enable_trigger' flag so that we can render
# correct SQL for operation
o_data['is_enable_trigger'] = is_enable_trigger
# Adding parent into data dict, will be using it while creating sql
o_data['schema'] = self.schema
o_data['table'] = self.table
SQL = render_template("/".join([self.template_path,
'enable_disable_trigger.sql']),
data=o_data, conn=self.conn)
status, res = self.conn.execute_scalar(SQL)
if not status:
return internal_server_error(errormsg=res)
return make_json_response(
success=1,
info="Compound Trigger updated",
data={
'id': trid,
'tid': tid,
'scid': scid
}
)
except Exception as e:
return internal_server_error(errormsg=str(e)) | [
"def",
"enable_disable_trigger",
"(",
"self",
",",
"gid",
",",
"sid",
",",
"did",
",",
"scid",
",",
"tid",
",",
"trid",
")",
":",
"data",
"=",
"request",
".",
"form",
"if",
"request",
".",
"form",
"else",
"json",
".",
"loads",
"(",
"request",
".",
... | https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/compound_triggers/__init__.py#L757-L821 | ||
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/mps/v20190612/models.py | python | ModifyContentReviewTemplateResponse.__init__ | (self) | r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | [
"r",
":",
"param",
"RequestId",
":",
"唯一请求",
"ID,每次请求都会返回。定位问题时需要提供该次请求的",
"RequestId。",
":",
"type",
"RequestId",
":",
"str"
] | def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"RequestId",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/mps/v20190612/models.py#L10180-L10185 | ||
alteryx/featuretools | d59e11082962f163540fd6e185901f65c506326a | featuretools/primitives/standard/cum_transform_feature.py | python | CumMin.get_function | (self) | return cum_min | [] | def get_function(self):
def cum_min(values):
return values.cummin()
return cum_min | [
"def",
"get_function",
"(",
"self",
")",
":",
"def",
"cum_min",
"(",
"values",
")",
":",
"return",
"values",
".",
"cummin",
"(",
")",
"return",
"cum_min"
] | https://github.com/alteryx/featuretools/blob/d59e11082962f163540fd6e185901f65c506326a/featuretools/primitives/standard/cum_transform_feature.py#L112-L116 | |||
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/setuptools/dist.py | python | check_extras | (dist, attr, value) | Verify that extras_require mapping is valid | Verify that extras_require mapping is valid | [
"Verify",
"that",
"extras_require",
"mapping",
"is",
"valid"
] | def check_extras(dist, attr, value):
"""Verify that extras_require mapping is valid"""
try:
list(itertools.starmap(_check_extra, value.items()))
except (TypeError, ValueError, AttributeError):
raise DistutilsSetupError(
"'extras_require' must be a dictionary whose values are "
"strings or lists of strings containing valid project/version "
"requirement specifiers."
) | [
"def",
"check_extras",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"list",
"(",
"itertools",
".",
"starmap",
"(",
"_check_extra",
",",
"value",
".",
"items",
"(",
")",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
",",
"A... | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/setuptools/dist.py#L139-L148 | ||
oduwsdl/ipwb | 2ff7b87f45cd263d765368a3cde557755ee23b06 | ipwb/util.py | python | pad_digits14 | (dtstr, validate=False) | return dtstr | Pad datetime to make a 14-digit string and optionally validate it | Pad datetime to make a 14-digit string and optionally validate it | [
"Pad",
"datetime",
"to",
"make",
"a",
"14",
"-",
"digit",
"string",
"and",
"optionally",
"validate",
"it"
] | def pad_digits14(dtstr, validate=False):
'''Pad datetime to make a 14-digit string and optionally validate it'''
match = dt_pattern.match(dtstr)
if match:
Y = match.group(1)
m = match.group(2) or '01'
d = match.group(3) or '01'
H = match.group(4) or '00'
M = match.group(5) or '00'
S = match.group(6) or '00'
dtstr = f'{Y}{m}{d}{H}{M}{S}'
if validate:
datetime.datetime.strptime(dtstr, '%Y%m%d%H%M%S')
return dtstr | [
"def",
"pad_digits14",
"(",
"dtstr",
",",
"validate",
"=",
"False",
")",
":",
"match",
"=",
"dt_pattern",
".",
"match",
"(",
"dtstr",
")",
"if",
"match",
":",
"Y",
"=",
"match",
".",
"group",
"(",
"1",
")",
"m",
"=",
"match",
".",
"group",
"(",
"... | https://github.com/oduwsdl/ipwb/blob/2ff7b87f45cd263d765368a3cde557755ee23b06/ipwb/util.py#L192-L205 | |
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/dev/bdf_vectorized/cards/dynamic.py | python | TSTEP.add_card | (cls, card, comment='') | return TSTEP(sid, N, DT, NO, comment=comment) | Adds a TSTEP card from ``BDF.add_card(...)``
Parameters
----------
card : BDFCard()
a BDFCard object
comment : str; default=''
a comment for the card | Adds a TSTEP card from ``BDF.add_card(...)`` | [
"Adds",
"a",
"TSTEP",
"card",
"from",
"BDF",
".",
"add_card",
"(",
"...",
")"
] | def add_card(cls, card, comment=''):
"""
Adds a TSTEP card from ``BDF.add_card(...)``
Parameters
----------
card : BDFCard()
a BDFCard object
comment : str; default=''
a comment for the card
"""
sid = integer(card, 1, 'sid')
N = []
DT = []
NO = []
nrows = int(ceil((len(card) - 1.) / 8.))
for i in range(nrows):
n = 8 * i + 1
ni = integer_or_blank(card, n + 1, 'N' + str(i), 1)
dt = double_or_blank(card, n + 2, 'dt' + str(i), 0.)
no = integer_or_blank(card, n + 3, 'NO' + str(i), 1)
N.append(ni)
DT.append(dt)
NO.append(no)
return TSTEP(sid, N, DT, NO, comment=comment) | [
"def",
"add_card",
"(",
"cls",
",",
"card",
",",
"comment",
"=",
"''",
")",
":",
"sid",
"=",
"integer",
"(",
"card",
",",
"1",
",",
"'sid'",
")",
"N",
"=",
"[",
"]",
"DT",
"=",
"[",
"]",
"NO",
"=",
"[",
"]",
"nrows",
"=",
"int",
"(",
"ceil"... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/dev/bdf_vectorized/cards/dynamic.py#L963-L988 | |
taomujian/linbing | fe772a58f41e3b046b51a866bdb7e4655abaf51a | python/app/thirdparty/oneforall/modules/wildcard.py | python | to_detect_wildcard | (domain) | return any_similar_html(all_request_resp) | Detect use wildcard dns record or not
:param str domain: domain
:return bool use wildcard dns record or not | Detect use wildcard dns record or not | [
"Detect",
"use",
"wildcard",
"dns",
"record",
"or",
"not"
] | def to_detect_wildcard(domain):
"""
Detect use wildcard dns record or not
:param str domain: domain
:return bool use wildcard dns record or not
"""
logger.log('INFOR', f'Detecting {domain} use wildcard dns record or not')
random_subdomains = gen_random_subdomains(domain, 3)
if not all_resolve_success(random_subdomains):
return False
is_all_success, all_request_resp = all_request_success(random_subdomains)
if not is_all_success:
return True
return any_similar_html(all_request_resp) | [
"def",
"to_detect_wildcard",
"(",
"domain",
")",
":",
"logger",
".",
"log",
"(",
"'INFOR'",
",",
"f'Detecting {domain} use wildcard dns record or not'",
")",
"random_subdomains",
"=",
"gen_random_subdomains",
"(",
"domain",
",",
"3",
")",
"if",
"not",
"all_resolve_suc... | https://github.com/taomujian/linbing/blob/fe772a58f41e3b046b51a866bdb7e4655abaf51a/python/app/thirdparty/oneforall/modules/wildcard.py#L101-L115 | |
gbeced/pyalgotrade | ad2bcc6b25c06c66eee4a8d522ce844504d8ec62 | pyalgotrade/bitstamp/wsclient.py | python | Trade.getId | (self) | return self.getData()["id"] | Returns the trade id. | Returns the trade id. | [
"Returns",
"the",
"trade",
"id",
"."
] | def getId(self):
"""Returns the trade id."""
return self.getData()["id"] | [
"def",
"getId",
"(",
"self",
")",
":",
"return",
"self",
".",
"getData",
"(",
")",
"[",
"\"id\"",
"]"
] | https://github.com/gbeced/pyalgotrade/blob/ad2bcc6b25c06c66eee4a8d522ce844504d8ec62/pyalgotrade/bitstamp/wsclient.py#L47-L49 | |
metapensiero/metapensiero.pj | 0e243d70bfb8aabfa8fe45bd1338e2959fc667c3 | src/metapensiero/pj/processor/util.py | python | rfilter | (r, it, invert=False) | >>> list(rfilter(r'^.o+$', ['foo', 'bar']))
['foo']
>>> list(rfilter(r'^.o+$', ['foo', 'bar'], invert=True))
['bar'] | >>> list(rfilter(r'^.o+$', ['foo', 'bar']))
['foo'] | [
">>>",
"list",
"(",
"rfilter",
"(",
"r",
"^",
".",
"o",
"+",
"$",
"[",
"foo",
"bar",
"]",
"))",
"[",
"foo",
"]"
] | def rfilter(r, it, invert=False):
"""
>>> list(rfilter(r'^.o+$', ['foo', 'bar']))
['foo']
>>> list(rfilter(r'^.o+$', ['foo', 'bar'], invert=True))
['bar']
"""
# Supports Python 2 and 3
if isinstance(r, str):
r = re.compile(r)
try:
if isinstance(r, unicode):
r = re.compile
except NameError:
pass
for x in it:
m = r.search(x)
ok = False
if m:
ok = True
if invert:
if not ok:
yield x
else:
if ok:
yield x | [
"def",
"rfilter",
"(",
"r",
",",
"it",
",",
"invert",
"=",
"False",
")",
":",
"# Supports Python 2 and 3",
"if",
"isinstance",
"(",
"r",
",",
"str",
")",
":",
"r",
"=",
"re",
".",
"compile",
"(",
"r",
")",
"try",
":",
"if",
"isinstance",
"(",
"r",
... | https://github.com/metapensiero/metapensiero.pj/blob/0e243d70bfb8aabfa8fe45bd1338e2959fc667c3/src/metapensiero/pj/processor/util.py#L153-L181 | ||
guildai/guildai | 1665985a3d4d788efc1a3180ca51cc417f71ca78 | guild/external/pkg_resources/extern/__init__.py | python | VendorImporter.install | (self) | Install this importer into sys.meta_path if not already present. | Install this importer into sys.meta_path if not already present. | [
"Install",
"this",
"importer",
"into",
"sys",
".",
"meta_path",
"if",
"not",
"already",
"present",
"."
] | def install(self):
"""
Install this importer into sys.meta_path if not already present.
"""
if self not in sys.meta_path:
sys.meta_path.append(self) | [
"def",
"install",
"(",
"self",
")",
":",
"if",
"self",
"not",
"in",
"sys",
".",
"meta_path",
":",
"sys",
".",
"meta_path",
".",
"append",
"(",
"self",
")"
] | https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pkg_resources/extern/__init__.py#L64-L69 | ||
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/numpy/lib/nanfunctions.py | python | _nanpercentile | (a, q, axis=None, out=None, overwrite_input=False,
interpolation='linear') | return result | Private function that doesn't support extended axis or keepdims.
These methods are extended to this function using _ureduce
See nanpercentile for parameter usage | Private function that doesn't support extended axis or keepdims.
These methods are extended to this function using _ureduce
See nanpercentile for parameter usage | [
"Private",
"function",
"that",
"doesn",
"t",
"support",
"extended",
"axis",
"or",
"keepdims",
".",
"These",
"methods",
"are",
"extended",
"to",
"this",
"function",
"using",
"_ureduce",
"See",
"nanpercentile",
"for",
"parameter",
"usage"
] | def _nanpercentile(a, q, axis=None, out=None, overwrite_input=False,
interpolation='linear'):
"""
Private function that doesn't support extended axis or keepdims.
These methods are extended to this function using _ureduce
See nanpercentile for parameter usage
"""
if axis is None:
part = a.ravel()
result = _nanpercentile1d(part, q, overwrite_input, interpolation)
else:
result = np.apply_along_axis(_nanpercentile1d, axis, a, q,
overwrite_input, interpolation)
# apply_along_axis fills in collapsed axis with results.
# Move that axis to the beginning to match percentile's
# convention.
if q.ndim != 0:
result = np.rollaxis(result, axis)
if out is not None:
out[...] = result
return result | [
"def",
"_nanpercentile",
"(",
"a",
",",
"q",
",",
"axis",
"=",
"None",
",",
"out",
"=",
"None",
",",
"overwrite_input",
"=",
"False",
",",
"interpolation",
"=",
"'linear'",
")",
":",
"if",
"axis",
"is",
"None",
":",
"part",
"=",
"a",
".",
"ravel",
... | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/numpy/lib/nanfunctions.py#L1008-L1030 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/numpy-1.16.0-py3.7-macosx-10.9-x86_64.egg/numpy/distutils/ccompiler.py | python | simple_version_match | (pat=r'[-.\d]+', ignore='', start='') | return matcher | Simple matching of version numbers, for use in CCompiler and FCompiler.
Parameters
----------
pat : str, optional
A regular expression matching version numbers.
Default is ``r'[-.\\d]+'``.
ignore : str, optional
A regular expression matching patterns to skip.
Default is ``''``, in which case nothing is skipped.
start : str, optional
A regular expression matching the start of where to start looking
for version numbers.
Default is ``''``, in which case searching is started at the
beginning of the version string given to `matcher`.
Returns
-------
matcher : callable
A function that is appropriate to use as the ``.version_match``
attribute of a `CCompiler` class. `matcher` takes a single parameter,
a version string. | Simple matching of version numbers, for use in CCompiler and FCompiler. | [
"Simple",
"matching",
"of",
"version",
"numbers",
"for",
"use",
"in",
"CCompiler",
"and",
"FCompiler",
"."
] | def simple_version_match(pat=r'[-.\d]+', ignore='', start=''):
"""
Simple matching of version numbers, for use in CCompiler and FCompiler.
Parameters
----------
pat : str, optional
A regular expression matching version numbers.
Default is ``r'[-.\\d]+'``.
ignore : str, optional
A regular expression matching patterns to skip.
Default is ``''``, in which case nothing is skipped.
start : str, optional
A regular expression matching the start of where to start looking
for version numbers.
Default is ``''``, in which case searching is started at the
beginning of the version string given to `matcher`.
Returns
-------
matcher : callable
A function that is appropriate to use as the ``.version_match``
attribute of a `CCompiler` class. `matcher` takes a single parameter,
a version string.
"""
def matcher(self, version_string):
# version string may appear in the second line, so getting rid
# of new lines:
version_string = version_string.replace('\n', ' ')
pos = 0
if start:
m = re.match(start, version_string)
if not m:
return None
pos = m.end()
while True:
m = re.search(pat, version_string[pos:])
if not m:
return None
if ignore and re.match(ignore, m.group(0)):
pos = m.end()
continue
break
return m.group(0)
return matcher | [
"def",
"simple_version_match",
"(",
"pat",
"=",
"r'[-.\\d]+'",
",",
"ignore",
"=",
"''",
",",
"start",
"=",
"''",
")",
":",
"def",
"matcher",
"(",
"self",
",",
"version_string",
")",
":",
"# version string may appear in the second line, so getting rid",
"# of new li... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/numpy-1.16.0-py3.7-macosx-10.9-x86_64.egg/numpy/distutils/ccompiler.py#L572-L617 | |
oracle/oci-python-sdk | 3c1604e4e212008fb6718e2f68cdb5ef71fd5793 | src/oci/load_balancer/load_balancer_client.py | python | LoadBalancerClient.update_hostname | (self, update_hostname_details, load_balancer_id, name, **kwargs) | Overwrites an existing hostname resource on the specified load balancer. Use this operation to change a
virtual hostname.
:param oci.load_balancer.models.UpdateHostnameDetails update_hostname_details: (required)
The configuration details to update a virtual hostname.
:param str load_balancer_id: (required)
The `OCID`__ of the load balancer associated with the virtual hostname
to update.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:param str name: (required)
The name of the hostname resource to update.
Example: `example_hostname_001`
:param str opc_request_id: (optional)
The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a
particular request, please provide the request ID.
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
:return: A :class:`~oci.response.Response` object with data of type None
:rtype: :class:`~oci.response.Response`
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/loadbalancer/update_hostname.py.html>`__ to see an example of how to use update_hostname API. | Overwrites an existing hostname resource on the specified load balancer. Use this operation to change a
virtual hostname. | [
"Overwrites",
"an",
"existing",
"hostname",
"resource",
"on",
"the",
"specified",
"load",
"balancer",
".",
"Use",
"this",
"operation",
"to",
"change",
"a",
"virtual",
"hostname",
"."
] | def update_hostname(self, update_hostname_details, load_balancer_id, name, **kwargs):
"""
Overwrites an existing hostname resource on the specified load balancer. Use this operation to change a
virtual hostname.
:param oci.load_balancer.models.UpdateHostnameDetails update_hostname_details: (required)
The configuration details to update a virtual hostname.
:param str load_balancer_id: (required)
The `OCID`__ of the load balancer associated with the virtual hostname
to update.
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:param str name: (required)
The name of the hostname resource to update.
Example: `example_hostname_001`
:param str opc_request_id: (optional)
The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a
particular request, please provide the request ID.
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
:return: A :class:`~oci.response.Response` object with data of type None
:rtype: :class:`~oci.response.Response`
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/loadbalancer/update_hostname.py.html>`__ to see an example of how to use update_hostname API.
"""
resource_path = "/loadBalancers/{loadBalancerId}/hostnames/{name}"
method = "PUT"
# Don't accept unknown kwargs
expected_kwargs = [
"retry_strategy",
"opc_request_id"
]
extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs]
if extra_kwargs:
raise ValueError(
"update_hostname got unknown kwargs: {!r}".format(extra_kwargs))
path_params = {
"loadBalancerId": load_balancer_id,
"name": name
}
path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing}
for (k, v) in six.iteritems(path_params):
if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0):
raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k))
header_params = {
"accept": "application/json",
"content-type": "application/json",
"opc-request-id": kwargs.get("opc_request_id", missing)
}
header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None}
retry_strategy = self.base_client.get_preferred_retry_strategy(
operation_retry_strategy=kwargs.get('retry_strategy'),
client_retry_strategy=self.retry_strategy
)
if retry_strategy:
if not isinstance(retry_strategy, retry.NoneRetryStrategy):
self.base_client.add_opc_client_retries_header(header_params)
retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback)
return retry_strategy.make_retrying_call(
self.base_client.call_api,
resource_path=resource_path,
method=method,
path_params=path_params,
header_params=header_params,
body=update_hostname_details)
else:
return self.base_client.call_api(
resource_path=resource_path,
method=method,
path_params=path_params,
header_params=header_params,
body=update_hostname_details) | [
"def",
"update_hostname",
"(",
"self",
",",
"update_hostname_details",
",",
"load_balancer_id",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"resource_path",
"=",
"\"/loadBalancers/{loadBalancerId}/hostnames/{name}\"",
"method",
"=",
"\"PUT\"",
"# Don't accept unknown ... | https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/load_balancer/load_balancer_client.py#L4935-L5026 | ||
marinho/geraldo | 868ebdce67176d9b6205cddc92476f642c783fff | site/newsite/site-geraldo/django/utils/simplejson/__init__.py | python | read | (s) | return loads(s) | jsonlib, JsonUtils, python-json, json-py API compatibility hook.
Use loads(s) instead. | jsonlib, JsonUtils, python-json, json-py API compatibility hook.
Use loads(s) instead. | [
"jsonlib",
"JsonUtils",
"python",
"-",
"json",
"json",
"-",
"py",
"API",
"compatibility",
"hook",
".",
"Use",
"loads",
"(",
"s",
")",
"instead",
"."
] | def read(s):
"""
jsonlib, JsonUtils, python-json, json-py API compatibility hook.
Use loads(s) instead.
"""
import warnings
warnings.warn("simplejson.loads(s) should be used instead of read(s)",
DeprecationWarning)
return loads(s) | [
"def",
"read",
"(",
"s",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"simplejson.loads(s) should be used instead of read(s)\"",
",",
"DeprecationWarning",
")",
"return",
"loads",
"(",
"s",
")"
] | https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/site/newsite/site-geraldo/django/utils/simplejson/__init__.py#L352-L360 | |
pymedusa/Medusa | 1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38 | medusa/black_and_white_list.py | python | BlackAndWhiteList.set_white_keywords | (self, values) | Set whitelist to new values.
:param values: Complete list of keywords to be set as whitelist | Set whitelist to new values. | [
"Set",
"whitelist",
"to",
"new",
"values",
"."
] | def set_white_keywords(self, values):
"""Set whitelist to new values.
:param values: Complete list of keywords to be set as whitelist
"""
self._del_all_keywords('whitelist')
self._add_keywords('whitelist', values)
self.whitelist = values
logger.debug('Whitelist set to: {whitelist}', whitelist=self.whitelist) | [
"def",
"set_white_keywords",
"(",
"self",
",",
"values",
")",
":",
"self",
".",
"_del_all_keywords",
"(",
"'whitelist'",
")",
"self",
".",
"_add_keywords",
"(",
"'whitelist'",
",",
"values",
")",
"self",
".",
"whitelist",
"=",
"values",
"logger",
".",
"debug... | https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/medusa/black_and_white_list.py#L79-L87 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_group.py | python | OpenShiftCLI._evacuate | (self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False) | return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') | perform oadm manage-node evacuate | perform oadm manage-node evacuate | [
"perform",
"oadm",
"manage",
"-",
"node",
"evacuate"
] | def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
''' perform oadm manage-node evacuate '''
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if dry_run:
cmd.append('--dry-run')
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
if grace_period:
cmd.append('--grace-period={}'.format(int(grace_period)))
if force:
cmd.append('--force')
cmd.append('--evacuate')
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') | [
"def",
"_evacuate",
"(",
"self",
",",
"node",
"=",
"None",
",",
"selector",
"=",
"None",
",",
"pod_selector",
"=",
"None",
",",
"dry_run",
"=",
"False",
",",
"grace_period",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"'manage... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_group.py#L1035-L1057 | |
qiucheng025/zao- | 3a5edf3607b3a523f95746bc69b688090c76d89a | tools/preview.py | python | FacesDisplay.crop_destination_faces | (self) | Update the main faces dict with new destination faces based on source matrices | Update the main faces dict with new destination faces based on source matrices | [
"Update",
"the",
"main",
"faces",
"dict",
"with",
"new",
"destination",
"faces",
"based",
"on",
"source",
"matrices"
] | def crop_destination_faces(self):
""" Update the main faces dict with new destination faces based on source matrices """
logger.debug("Updating destination faces")
self.faces["dst"] = list()
destination = self.destination if self.destination else [np.ones_like(src["image"])
for src in self.source]
for idx, image in enumerate(destination):
self.faces["dst"].append(AlignerExtract().transform(
image,
self.faces["matrix"][idx],
self.size,
self.padding))
logger.debug("Updated destination faces") | [
"def",
"crop_destination_faces",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Updating destination faces\"",
")",
"self",
".",
"faces",
"[",
"\"dst\"",
"]",
"=",
"list",
"(",
")",
"destination",
"=",
"self",
".",
"destination",
"if",
"self",
".",
... | https://github.com/qiucheng025/zao-/blob/3a5edf3607b3a523f95746bc69b688090c76d89a/tools/preview.py#L473-L485 | ||
clinton-hall/nzbToMedia | 27669389216902d1085660167e7bda0bd8527ecf | libs/common/click/types.py | python | ParamType.convert | (self, value, param, ctx) | return value | Converts the value. This is not invoked for values that are
`None` (the missing value). | Converts the value. This is not invoked for values that are
`None` (the missing value). | [
"Converts",
"the",
"value",
".",
"This",
"is",
"not",
"invoked",
"for",
"values",
"that",
"are",
"None",
"(",
"the",
"missing",
"value",
")",
"."
] | def convert(self, value, param, ctx):
"""Converts the value. This is not invoked for values that are
`None` (the missing value).
"""
return value | [
"def",
"convert",
"(",
"self",
",",
"value",
",",
"param",
",",
"ctx",
")",
":",
"return",
"value"
] | https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/click/types.py#L51-L55 | |
clips/pattern | d25511f9ca7ed9356b801d8663b8b5168464e68f | pattern/vector/stemmer.py | python | R2 | (w) | return R1(R1(w)) | R2 is the region after the first non-vowel following a vowel in R1,
or the end of the word if there is no such non-vowel. | R2 is the region after the first non-vowel following a vowel in R1,
or the end of the word if there is no such non-vowel. | [
"R2",
"is",
"the",
"region",
"after",
"the",
"first",
"non",
"-",
"vowel",
"following",
"a",
"vowel",
"in",
"R1",
"or",
"the",
"end",
"of",
"the",
"word",
"if",
"there",
"is",
"no",
"such",
"non",
"-",
"vowel",
"."
] | def R2(w):
""" R2 is the region after the first non-vowel following a vowel in R1,
or the end of the word if there is no such non-vowel.
"""
if w.startswith(tuple(overstemmed)):
return R1(R1(R1(w)))
return R1(R1(w)) | [
"def",
"R2",
"(",
"w",
")",
":",
"if",
"w",
".",
"startswith",
"(",
"tuple",
"(",
"overstemmed",
")",
")",
":",
"return",
"R1",
"(",
"R1",
"(",
"R1",
"(",
"w",
")",
")",
")",
"return",
"R1",
"(",
"R1",
"(",
"w",
")",
")"
] | https://github.com/clips/pattern/blob/d25511f9ca7ed9356b801d8663b8b5168464e68f/pattern/vector/stemmer.py#L93-L99 | |
yandex/yandex-tank | b41bcc04396c4ed46fc8b28a261197320854fd33 | yandextank/plugins/InfluxUploader/decoder.py | python | Decoder.__init__ | (self, tank_tag, uuid, parent_tags, labeled, histograms) | [] | def __init__(self, tank_tag, uuid, parent_tags, labeled, histograms):
self.labeled = labeled
initial_tags = {
"tank": tank_tag,
"uuid": uuid
}
initial_tags.update(parent_tags)
self.tags = initial_tags
self.histograms = histograms | [
"def",
"__init__",
"(",
"self",
",",
"tank_tag",
",",
"uuid",
",",
"parent_tags",
",",
"labeled",
",",
"histograms",
")",
":",
"self",
".",
"labeled",
"=",
"labeled",
"initial_tags",
"=",
"{",
"\"tank\"",
":",
"tank_tag",
",",
"\"uuid\"",
":",
"uuid",
"}... | https://github.com/yandex/yandex-tank/blob/b41bcc04396c4ed46fc8b28a261197320854fd33/yandextank/plugins/InfluxUploader/decoder.py#L25-L33 | ||||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/microsoft_face/__init__.py | python | MicrosoftFaceGroupEntity.state | (self) | return len(self._api.store[self._id]) | Return the state of the entity. | Return the state of the entity. | [
"Return",
"the",
"state",
"of",
"the",
"entity",
"."
] | def state(self):
"""Return the state of the entity."""
return len(self._api.store[self._id]) | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"_api",
".",
"store",
"[",
"self",
".",
"_id",
"]",
")"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/microsoft_face/__init__.py#L228-L230 | |
fossasia/x-mario-center | fe67afe28d995dcf4e2498e305825a4859566172 | softwarecenter/db/pkginfo_impl/aptcache.py | python | AptCache.get_origin | (self, pkgname) | return origin_str.lower() | return a uniqe origin for the given package name. currently
this will use | return a uniqe origin for the given package name. currently
this will use | [
"return",
"a",
"uniqe",
"origin",
"for",
"the",
"given",
"package",
"name",
".",
"currently",
"this",
"will",
"use"
] | def get_origin(self, pkgname):
"""
return a uniqe origin for the given package name. currently
this will use
"""
if not pkgname in self._cache or not self._cache[pkgname].candidate:
return None
origins = set([origin.origin for origin in self.get_origins(pkgname)])
if len(origins) > 1:
LOG.warn("more than one origin '%s'" % origins)
return None
if not origins:
return None
# we support only a single origin (but its fine if that is available
# on multiple mirrors). lowercase as the server excepts it this way
origin_str = origins.pop()
return origin_str.lower() | [
"def",
"get_origin",
"(",
"self",
",",
"pkgname",
")",
":",
"if",
"not",
"pkgname",
"in",
"self",
".",
"_cache",
"or",
"not",
"self",
".",
"_cache",
"[",
"pkgname",
"]",
".",
"candidate",
":",
"return",
"None",
"origins",
"=",
"set",
"(",
"[",
"origi... | https://github.com/fossasia/x-mario-center/blob/fe67afe28d995dcf4e2498e305825a4859566172/softwarecenter/db/pkginfo_impl/aptcache.py#L362-L378 | |
spyder-ide/spyder | 55da47c032dfcf519600f67f8b30eab467f965e7 | spyder/api/editorextension.py | python | EditorExtension.enabled | (self) | return self._enabled | Tells if the editor extension is enabled.
:meth:`spyder.api.EditorExtension.on_state_changed` will be called as
soon as the editor extension state changed.
:type: bool | Tells if the editor extension is enabled. | [
"Tells",
"if",
"the",
"editor",
"extension",
"is",
"enabled",
"."
] | def enabled(self):
"""
Tells if the editor extension is enabled.
:meth:`spyder.api.EditorExtension.on_state_changed` will be called as
soon as the editor extension state changed.
:type: bool
"""
return self._enabled | [
"def",
"enabled",
"(",
"self",
")",
":",
"return",
"self",
".",
"_enabled"
] | https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/api/editorextension.py#L60-L69 | |
pytorch/opacus | 5c83d59fc169e93667946204f7a6859827a38ace | opacus/accountants/analysis/rdp.py | python | _compute_log_a | (q: float, sigma: float, alpha: float) | r"""Computes :math:`log(A_\alpha)` for any positive finite ``alpha``.
Notes:
Note that
:math:`A_\alpha` is real valued function of ``alpha`` and ``q``,
and that 0 < ``q`` < 1.
Refer to Section 3.3 of https://arxiv.org/pdf/1908.10530.pdf
for details.
Args:
q: Sampling rate of SGM.
sigma: The standard deviation of the additive Gaussian noise.
alpha: The order at which RDP is computed.
Returns:
:math:`log(A_\alpha)` as defined in the paper mentioned above. | r"""Computes :math:`log(A_\alpha)` for any positive finite ``alpha``. | [
"r",
"Computes",
":",
"math",
":",
"log",
"(",
"A_",
"\\",
"alpha",
")",
"for",
"any",
"positive",
"finite",
"alpha",
"."
] | def _compute_log_a(q: float, sigma: float, alpha: float) -> float:
r"""Computes :math:`log(A_\alpha)` for any positive finite ``alpha``.
Notes:
Note that
:math:`A_\alpha` is real valued function of ``alpha`` and ``q``,
and that 0 < ``q`` < 1.
Refer to Section 3.3 of https://arxiv.org/pdf/1908.10530.pdf
for details.
Args:
q: Sampling rate of SGM.
sigma: The standard deviation of the additive Gaussian noise.
alpha: The order at which RDP is computed.
Returns:
:math:`log(A_\alpha)` as defined in the paper mentioned above.
"""
if float(alpha).is_integer():
return _compute_log_a_for_int_alpha(q, sigma, int(alpha))
else:
return _compute_log_a_for_frac_alpha(q, sigma, alpha) | [
"def",
"_compute_log_a",
"(",
"q",
":",
"float",
",",
"sigma",
":",
"float",
",",
"alpha",
":",
"float",
")",
"->",
"float",
":",
"if",
"float",
"(",
"alpha",
")",
".",
"is_integer",
"(",
")",
":",
"return",
"_compute_log_a_for_int_alpha",
"(",
"q",
",... | https://github.com/pytorch/opacus/blob/5c83d59fc169e93667946204f7a6859827a38ace/opacus/accountants/analysis/rdp.py#L183-L205 | ||
caktux/pytrader | b45b216dab3db78d6028d85e9a6f80419c22cea0 | strategy.py | python | Strategy.slot_tick | (self, instance, (bid, ask)) | a tick message has been received from the streaming API | a tick message has been received from the streaming API | [
"a",
"tick",
"message",
"has",
"been",
"received",
"from",
"the",
"streaming",
"API"
] | def slot_tick(self, instance, (bid, ask)):
"""a tick message has been received from the streaming API"""
pass | [
"def",
"slot_tick",
"(",
"self",
",",
"instance",
",",
"(",
"bid",
",",
"ask",
")",
")",
":",
"pass"
] | https://github.com/caktux/pytrader/blob/b45b216dab3db78d6028d85e9a6f80419c22cea0/strategy.py#L47-L49 | ||
limodou/uliweb | 8bc827fa6bf7bf58aa8136b6c920fe2650c52422 | uliweb/lib/werkzeug/wrappers.py | python | BaseRequest._get_file_stream | (self, total_content_length, content_type, filename=None,
content_length=None) | return default_stream_factory(total_content_length, content_type,
filename, content_length) | Called to get a stream for the file upload.
This must provide a file-like class with `read()`, `readline()`
and `seek()` methods that is both writeable and readable.
The default implementation returns a temporary file if the total
content length is higher than 500KB. Because many browsers do not
provide a content length for the files only the total content
length matters.
:param total_content_length: the total content length of all the
data in the request combined. This value
is guaranteed to be there.
:param content_type: the mimetype of the uploaded file.
:param filename: the filename of the uploaded file. May be `None`.
:param content_length: the length of this file. This value is usually
not provided because webbrowsers do not provide
this value. | Called to get a stream for the file upload. | [
"Called",
"to",
"get",
"a",
"stream",
"for",
"the",
"file",
"upload",
"."
] | def _get_file_stream(self, total_content_length, content_type, filename=None,
content_length=None):
"""Called to get a stream for the file upload.
This must provide a file-like class with `read()`, `readline()`
and `seek()` methods that is both writeable and readable.
The default implementation returns a temporary file if the total
content length is higher than 500KB. Because many browsers do not
provide a content length for the files only the total content
length matters.
:param total_content_length: the total content length of all the
data in the request combined. This value
is guaranteed to be there.
:param content_type: the mimetype of the uploaded file.
:param filename: the filename of the uploaded file. May be `None`.
:param content_length: the length of this file. This value is usually
not provided because webbrowsers do not provide
this value.
"""
return default_stream_factory(total_content_length, content_type,
filename, content_length) | [
"def",
"_get_file_stream",
"(",
"self",
",",
"total_content_length",
",",
"content_type",
",",
"filename",
"=",
"None",
",",
"content_length",
"=",
"None",
")",
":",
"return",
"default_stream_factory",
"(",
"total_content_length",
",",
"content_type",
",",
"filename... | https://github.com/limodou/uliweb/blob/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/lib/werkzeug/wrappers.py#L288-L310 | |
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | vsphere/datadog_checks/vsphere/legacy/mor_cache.py | python | MorCache.mors | (self, key) | Generator returning all the mors in the cache for the given instance key. | Generator returning all the mors in the cache for the given instance key. | [
"Generator",
"returning",
"all",
"the",
"mors",
"in",
"the",
"cache",
"for",
"the",
"given",
"instance",
"key",
"."
] | def mors(self, key):
"""
Generator returning all the mors in the cache for the given instance key.
"""
with self._mor_lock:
for k, v in iteritems(self._mor.get(key, {})):
yield k, v | [
"def",
"mors",
"(",
"self",
",",
"key",
")",
":",
"with",
"self",
".",
"_mor_lock",
":",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"self",
".",
"_mor",
".",
"get",
"(",
"key",
",",
"{",
"}",
")",
")",
":",
"yield",
"k",
",",
"v"
] | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/vsphere/datadog_checks/vsphere/legacy/mor_cache.py#L86-L92 | ||
compas-dev/compas | 0b33f8786481f710115fb1ae5fe79abc2a9a5175 | src/compas/files/las.py | python | LASReader.read | (self) | Read the contents of the file. | Read the contents of the file. | [
"Read",
"the",
"contents",
"of",
"the",
"file",
"."
] | def read(self):
"""Read the contents of the file."""
pass | [
"def",
"read",
"(",
"self",
")",
":",
"pass"
] | https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas/files/las.py#L68-L70 | ||
bbfamily/abu | 2de85ae57923a720dac99a545b4f856f6b87304b | python/c11.py | python | sample_1123 | () | 11.2.3 跳空主裁
:return: | 11.2.3 跳空主裁
:return: | [
"11",
".",
"2",
".",
"3",
"跳空主裁",
":",
"return",
":"
] | def sample_1123():
"""
11.2.3 跳空主裁
:return:
"""
abu_result_tuple_train, abu_result_tuple_test, metrics_train, metrics_test = load_abu_result_tuple()
orders_pd_train = abu_result_tuple_train.orders_pd
ump_jump = AbuUmpMainJump.ump_main_clf_dump(orders_pd_train, save_order=False)
print(ump_jump.fiter.df.head())
print('失败概率最大的分类簇{0}'.format(ump_jump.cprs.lrs.argmax()))
# 拿出跳空失败概率最大的分类簇
max_failed_cluster_orders = ump_jump.nts[ump_jump.cprs.lrs.argmax()]
# 显示失败概率最大的分类簇,表11-6所示
print('max_failed_cluster_orders:\n', max_failed_cluster_orders)
ml.show_orders_hist(max_failed_cluster_orders, feature_columns=['buy_diff_up_days', 'buy_jump_up_power',
'buy_diff_down_days', 'buy_jump_down_power'])
print('分类簇中jump_up_power平均值为{0:.2f}, 向上跳空平均天数{1:.2f}'.format(
max_failed_cluster_orders.buy_jump_up_power.mean(), max_failed_cluster_orders.buy_diff_up_days.mean()))
print('分类簇中jump_down_power平均值为{0:.2f}, 向下跳空平均天数{1:.2f}'.format(
max_failed_cluster_orders.buy_jump_down_power.mean(), max_failed_cluster_orders.buy_diff_down_days.mean()))
print('训练数据集中jump_up_power平均值为{0:.2f},向上跳空平均天数{1:.2f}'.format(
orders_pd_train.buy_jump_up_power.mean(), orders_pd_train.buy_diff_up_days.mean()))
print('训练数据集中jump_down_power平均值为{0:.2f}, 向下跳空平均天数{1:.2f}'.format(
orders_pd_train.buy_jump_down_power.mean(), orders_pd_train.buy_diff_down_days.mean())) | [
"def",
"sample_1123",
"(",
")",
":",
"abu_result_tuple_train",
",",
"abu_result_tuple_test",
",",
"metrics_train",
",",
"metrics_test",
"=",
"load_abu_result_tuple",
"(",
")",
"orders_pd_train",
"=",
"abu_result_tuple_train",
".",
"orders_pd",
"ump_jump",
"=",
"AbuUmpMa... | https://github.com/bbfamily/abu/blob/2de85ae57923a720dac99a545b4f856f6b87304b/python/c11.py#L174-L203 | ||
meraki/dashboard-api-python | aef5e6fe5d23a40d435d5c64ff30580a28af07f1 | meraki/aio/api/organizations.py | python | AsyncOrganizations.getOrganizationWebhooksAlertTypes | (self, organizationId: str) | return self._session.get(metadata, resource) | **Return a list of alert types to be used with managing webhook alerts**
https://developer.cisco.com/meraki/api-v1/#!get-organization-webhooks-alert-types
- organizationId (string): (required) | **Return a list of alert types to be used with managing webhook alerts**
https://developer.cisco.com/meraki/api-v1/#!get-organization-webhooks-alert-types | [
"**",
"Return",
"a",
"list",
"of",
"alert",
"types",
"to",
"be",
"used",
"with",
"managing",
"webhook",
"alerts",
"**",
"https",
":",
"//",
"developer",
".",
"cisco",
".",
"com",
"/",
"meraki",
"/",
"api",
"-",
"v1",
"/",
"#!get",
"-",
"organization",
... | def getOrganizationWebhooksAlertTypes(self, organizationId: str):
"""
**Return a list of alert types to be used with managing webhook alerts**
https://developer.cisco.com/meraki/api-v1/#!get-organization-webhooks-alert-types
- organizationId (string): (required)
"""
metadata = {
'tags': ['organizations', 'monitor', 'webhooks', 'alertTypes'],
'operation': 'getOrganizationWebhooksAlertTypes'
}
resource = f'/organizations/{organizationId}/webhooks/alertTypes'
return self._session.get(metadata, resource) | [
"def",
"getOrganizationWebhooksAlertTypes",
"(",
"self",
",",
"organizationId",
":",
"str",
")",
":",
"metadata",
"=",
"{",
"'tags'",
":",
"[",
"'organizations'",
",",
"'monitor'",
",",
"'webhooks'",
",",
"'alertTypes'",
"]",
",",
"'operation'",
":",
"'getOrgani... | https://github.com/meraki/dashboard-api-python/blob/aef5e6fe5d23a40d435d5c64ff30580a28af07f1/meraki/aio/api/organizations.py#L2229-L2243 | |
openai/iaf | ad33fe4872bf6e4b4f387e709a625376bb8b0d9d | graphy/nodes/conv.py | python | resnetv3_layer_a | (name, n_feats, nl='softplus', alpha=.1, w={}) | return G.Struct(__call__=f, w=w, postup=postup) | [] | def resnetv3_layer_a(name, n_feats, nl='softplus', alpha=.1, w={}):
f_nl1 = N.nonlinearity(name+"_nl1", nl)
f_nl2 = N.nonlinearity(name+"_nl2", nl)
# either no change in shape, or subsampling
conv1 = conv2d(name+'_conv1', n_feats, n_feats, (3,3), w=w)
conv2 = conv2d(name+'_conv2', n_feats, n_feats, (3,3), w=w)
def f(_input, w):
h = f_nl1(_input)
h = f_nl2(conv1(h, w))
h = conv2(h, w)
return _input + alpha * h
def postup(updates, w):
updates = conv1.postup(updates, w)
updates = conv2.postup(updates, w)
return updates
return G.Struct(__call__=f, w=w, postup=postup) | [
"def",
"resnetv3_layer_a",
"(",
"name",
",",
"n_feats",
",",
"nl",
"=",
"'softplus'",
",",
"alpha",
"=",
".1",
",",
"w",
"=",
"{",
"}",
")",
":",
"f_nl1",
"=",
"N",
".",
"nonlinearity",
"(",
"name",
"+",
"\"_nl1\"",
",",
"nl",
")",
"f_nl2",
"=",
... | https://github.com/openai/iaf/blob/ad33fe4872bf6e4b4f387e709a625376bb8b0d9d/graphy/nodes/conv.py#L424-L444 | |||
mahmoud/boltons | 270e974975984f662f998c8f6eb0ebebd964de82 | boltons/tableutils.py | python | Table.__getitem__ | (self, idx) | return self._data[idx] | [] | def __getitem__(self, idx):
return self._data[idx] | [
"def",
"__getitem__",
"(",
"self",
",",
"idx",
")",
":",
"return",
"self",
".",
"_data",
"[",
"idx",
"]"
] | https://github.com/mahmoud/boltons/blob/270e974975984f662f998c8f6eb0ebebd964de82/boltons/tableutils.py#L434-L435 | |||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/modules/network.py | python | active_tcp | () | Return a dict containing information on all of the running TCP connections (currently linux and solaris only)
.. versionchanged:: 2015.8.4
Added support for SunOS
CLI Example:
.. code-block:: bash
salt '*' network.active_tcp | Return a dict containing information on all of the running TCP connections (currently linux and solaris only) | [
"Return",
"a",
"dict",
"containing",
"information",
"on",
"all",
"of",
"the",
"running",
"TCP",
"connections",
"(",
"currently",
"linux",
"and",
"solaris",
"only",
")"
] | def active_tcp():
"""
Return a dict containing information on all of the running TCP connections (currently linux and solaris only)
.. versionchanged:: 2015.8.4
Added support for SunOS
CLI Example:
.. code-block:: bash
salt '*' network.active_tcp
"""
if __grains__["kernel"] == "Linux":
return __utils__["network.active_tcp"]()
elif __grains__["kernel"] == "SunOS":
# lets use netstat to mimic linux as close as possible
ret = {}
for connection in _netstat_sunos():
if not connection["proto"].startswith("tcp"):
continue
if connection["state"] != "ESTABLISHED":
continue
ret[len(ret) + 1] = {
"local_addr": ".".join(connection["local-address"].split(".")[:-1]),
"local_port": ".".join(connection["local-address"].split(".")[-1:]),
"remote_addr": ".".join(connection["remote-address"].split(".")[:-1]),
"remote_port": ".".join(connection["remote-address"].split(".")[-1:]),
}
return ret
elif __grains__["kernel"] == "AIX":
# lets use netstat to mimic linux as close as possible
ret = {}
for connection in _netstat_aix():
if not connection["proto"].startswith("tcp"):
continue
if connection["state"] != "ESTABLISHED":
continue
ret[len(ret) + 1] = {
"local_addr": ".".join(connection["local-address"].split(".")[:-1]),
"local_port": ".".join(connection["local-address"].split(".")[-1:]),
"remote_addr": ".".join(connection["remote-address"].split(".")[:-1]),
"remote_port": ".".join(connection["remote-address"].split(".")[-1:]),
}
return ret
else:
return {} | [
"def",
"active_tcp",
"(",
")",
":",
"if",
"__grains__",
"[",
"\"kernel\"",
"]",
"==",
"\"Linux\"",
":",
"return",
"__utils__",
"[",
"\"network.active_tcp\"",
"]",
"(",
")",
"elif",
"__grains__",
"[",
"\"kernel\"",
"]",
"==",
"\"SunOS\"",
":",
"# lets use netst... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/network.py#L870-L917 | ||
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/lib2to3/fixer_util.py | python | find_root | (node) | return node | Find the top level namespace. | Find the top level namespace. | [
"Find",
"the",
"top",
"level",
"namespace",
"."
] | def find_root(node):
"""Find the top level namespace."""
# Scamper up to the top level namespace
while node.type != syms.file_input:
node = node.parent
if not node:
raise ValueError("root found before file_input node was found.")
return node | [
"def",
"find_root",
"(",
"node",
")",
":",
"# Scamper up to the top level namespace",
"while",
"node",
".",
"type",
"!=",
"syms",
".",
"file_input",
":",
"node",
"=",
"node",
".",
"parent",
"if",
"not",
"node",
":",
"raise",
"ValueError",
"(",
"\"root found be... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/lib2to3/fixer_util.py#L273-L280 | |
deepmind/bsuite | f305972cf05042f6ce23d638477ea9b33918ba17 | bsuite/environments/umbrella_chain.py | python | UmbrellaChain.context | (self) | return self._context | [] | def context(self):
return self._context | [
"def",
"context",
"(",
"self",
")",
":",
"return",
"self",
".",
"_context"
] | https://github.com/deepmind/bsuite/blob/f305972cf05042f6ce23d638477ea9b33918ba17/bsuite/environments/umbrella_chain.py#L114-L115 | |||
jihunchoi/unsupervised-treelstm | 47623f56f9890f730ca05dce8cf8dd10c72ba9e0 | snli/build_vocab.py | python | collect_words | (path, lower) | return word_set | [] | def collect_words(path, lower):
word_set = set()
with jsonlines.open(path, 'r') as reader:
for obj in reader:
for key in ['sentence1', 'sentence2']:
sentence = obj[key]
if lower:
sentence = sentence.lower()
words = word_tokenize(sentence)
word_set.update(words)
return word_set | [
"def",
"collect_words",
"(",
"path",
",",
"lower",
")",
":",
"word_set",
"=",
"set",
"(",
")",
"with",
"jsonlines",
".",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"reader",
":",
"for",
"obj",
"in",
"reader",
":",
"for",
"key",
"in",
"[",
"'senten... | https://github.com/jihunchoi/unsupervised-treelstm/blob/47623f56f9890f730ca05dce8cf8dd10c72ba9e0/snli/build_vocab.py#L7-L17 | |||
Floobits/floobits-emacs | 93b3317fb6c842efe165e54c8a32bf51d436837d | floo/common/exc_fmt.py | python | pp_e | (e) | return str_e(e) | returns a str in all pythons everywher | returns a str in all pythons everywher | [
"returns",
"a",
"str",
"in",
"all",
"pythons",
"everywher"
] | def pp_e(e):
"""returns a str in all pythons everywher"""
# py3k has __traceback__
tb = getattr(e, "__traceback__", None)
if tb is not None:
return "\n".join(traceback.format_tb(tb)) + str_e(e)
# in case of sys.exc_clear()
_, _, tb = sys.exc_info()
if tb is not None:
return "\n".join(traceback.format_tb(tb)) + str_e(e)
return str_e(e) | [
"def",
"pp_e",
"(",
"e",
")",
":",
"# py3k has __traceback__",
"tb",
"=",
"getattr",
"(",
"e",
",",
"\"__traceback__\"",
",",
"None",
")",
"if",
"tb",
"is",
"not",
"None",
":",
"return",
"\"\\n\"",
".",
"join",
"(",
"traceback",
".",
"format_tb",
"(",
... | https://github.com/Floobits/floobits-emacs/blob/93b3317fb6c842efe165e54c8a32bf51d436837d/floo/common/exc_fmt.py#L25-L37 | |
zatosource/zato | 2a9d273f06f9d776fbfeb53e73855af6e40fa208 | code/zato-agent/src/zato/agent/load_balancer/server.py | python | BaseLoadBalancerAgent._lb_agent_get_work_config | (self) | return {'work_dir':self.work_dir, 'haproxy_command':self.haproxy_command, # noqa
'keyfile':self.keyfile, 'certfile':self.certfile, # noqa
'ca_certs':self.ca_certs, 'verify_fields':self.verify_fields} | Return the agent's basic configuration. | Return the agent's basic configuration. | [
"Return",
"the",
"agent",
"s",
"basic",
"configuration",
"."
] | def _lb_agent_get_work_config(self):
""" Return the agent's basic configuration.
"""
return {'work_dir':self.work_dir, 'haproxy_command':self.haproxy_command, # noqa
'keyfile':self.keyfile, 'certfile':self.certfile, # noqa
'ca_certs':self.ca_certs, 'verify_fields':self.verify_fields} | [
"def",
"_lb_agent_get_work_config",
"(",
"self",
")",
":",
"return",
"{",
"'work_dir'",
":",
"self",
".",
"work_dir",
",",
"'haproxy_command'",
":",
"self",
".",
"haproxy_command",
",",
"# noqa",
"'keyfile'",
":",
"self",
".",
"keyfile",
",",
"'certfile'",
":"... | https://github.com/zatosource/zato/blob/2a9d273f06f9d776fbfeb53e73855af6e40fa208/code/zato-agent/src/zato/agent/load_balancer/server.py#L459-L464 | |
frappe/frappe | b64cab6867dfd860f10ccaf41a4ec04bc890b583 | frappe/core/doctype/file/file.py | python | attach_files_to_document | (doc, event) | Runs on on_update hook of all documents.
Goes through every Attach and Attach Image field and attaches
the file url to the document if it is not already attached. | Runs on on_update hook of all documents.
Goes through every Attach and Attach Image field and attaches
the file url to the document if it is not already attached. | [
"Runs",
"on",
"on_update",
"hook",
"of",
"all",
"documents",
".",
"Goes",
"through",
"every",
"Attach",
"and",
"Attach",
"Image",
"field",
"and",
"attaches",
"the",
"file",
"url",
"to",
"the",
"document",
"if",
"it",
"is",
"not",
"already",
"attached",
"."... | def attach_files_to_document(doc, event):
""" Runs on on_update hook of all documents.
Goes through every Attach and Attach Image field and attaches
the file url to the document if it is not already attached.
"""
attach_fields = doc.meta.get(
"fields", {"fieldtype": ["in", ["Attach", "Attach Image"]]}
)
for df in attach_fields:
# this method runs in on_update hook of all documents
# we dont want the update to fail if file cannot be attached for some reason
try:
value = doc.get(df.fieldname)
if not (value or '').startswith(("/files", "/private/files")):
return
if frappe.db.exists("File", {
"file_url": value,
"attached_to_name": doc.name,
"attached_to_doctype": doc.doctype,
"attached_to_field": df.fieldname,
}):
return
frappe.get_doc(
doctype="File",
file_url=value,
attached_to_name=doc.name,
attached_to_doctype=doc.doctype,
attached_to_field=df.fieldname,
folder="Home/Attachments",
).insert()
except Exception:
frappe.log_error(title=_("Error Attaching File")) | [
"def",
"attach_files_to_document",
"(",
"doc",
",",
"event",
")",
":",
"attach_fields",
"=",
"doc",
".",
"meta",
".",
"get",
"(",
"\"fields\"",
",",
"{",
"\"fieldtype\"",
":",
"[",
"\"in\"",
",",
"[",
"\"Attach\"",
",",
"\"Attach Image\"",
"]",
"]",
"}",
... | https://github.com/frappe/frappe/blob/b64cab6867dfd860f10ccaf41a4ec04bc890b583/frappe/core/doctype/file/file.py#L981-L1016 | ||
edisonlz/fastor | 342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3 | base/site-packages/tencentcloud/batch/v20170312/models.py | python | ModifyComputeEnvResponse.__init__ | (self) | :param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。
:type RequestId: str | :param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。
:type RequestId: str | [
":",
"param",
"RequestId",
":",
"唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。",
":",
"type",
"RequestId",
":",
"str"
] | def __init__(self):
"""
:param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。
:type RequestId: str
"""
self.RequestId = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"RequestId",
"=",
"None"
] | https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/tencentcloud/batch/v20170312/models.py#L1901-L1906 | ||
cobbler/cobbler | eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc | cobbler/api.py | python | CobblerAPI.rename_menu | (self, ref, newname: str) | Rename a menu to a new name.
:param ref: The internal unique handle for the item.
:param newname: The new name for the item. | Rename a menu to a new name. | [
"Rename",
"a",
"menu",
"to",
"a",
"new",
"name",
"."
] | def rename_menu(self, ref, newname: str):
"""
Rename a menu to a new name.
:param ref: The internal unique handle for the item.
:param newname: The new name for the item.
"""
self.rename_item("menu", ref, newname) | [
"def",
"rename_menu",
"(",
"self",
",",
"ref",
",",
"newname",
":",
"str",
")",
":",
"self",
".",
"rename_item",
"(",
"\"menu\"",
",",
"ref",
",",
"newname",
")"
] | https://github.com/cobbler/cobbler/blob/eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc/cobbler/api.py#L649-L656 | ||
JacquesLucke/animation_nodes | b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1 | animation_nodes/nodes/subprogram/loop_generator_output.py | python | LoopGeneratorOutputNode.settingChanged | (self, context) | [] | def settingChanged(self, context):
self.refresh()
subprogramInterfaceChanged() | [
"def",
"settingChanged",
"(",
"self",
",",
"context",
")",
":",
"self",
".",
"refresh",
"(",
")",
"subprogramInterfaceChanged",
"(",
")"
] | https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/nodes/subprogram/loop_generator_output.py#L15-L17 | ||||
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/nose/ext/dtcompat.py | python | DocTestParser._check_prompt_blank | (self, lines, indent, name, lineno) | Given the lines of a source string (including prompts and
leading indentation), check to make sure that every prompt is
followed by a space character. If any line is not followed by
a space character, then raise ValueError. | Given the lines of a source string (including prompts and
leading indentation), check to make sure that every prompt is
followed by a space character. If any line is not followed by
a space character, then raise ValueError. | [
"Given",
"the",
"lines",
"of",
"a",
"source",
"string",
"(",
"including",
"prompts",
"and",
"leading",
"indentation",
")",
"check",
"to",
"make",
"sure",
"that",
"every",
"prompt",
"is",
"followed",
"by",
"a",
"space",
"character",
".",
"If",
"any",
"line"... | def _check_prompt_blank(self, lines, indent, name, lineno):
"""
Given the lines of a source string (including prompts and
leading indentation), check to make sure that every prompt is
followed by a space character. If any line is not followed by
a space character, then raise ValueError.
"""
for i, line in enumerate(lines):
if len(line) >= indent+4 and line[indent+3] != ' ':
raise ValueError('line %r of the docstring for %s '
'lacks blank after %s: %r' %
(lineno+i+1, name,
line[indent:indent+3], line)) | [
"def",
"_check_prompt_blank",
"(",
"self",
",",
"lines",
",",
"indent",
",",
"name",
",",
"lineno",
")",
":",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"len",
"(",
"line",
")",
">=",
"indent",
"+",
"4",
"and",
"line"... | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/nose/ext/dtcompat.py#L696-L708 | ||
WPO-Foundation/wptagent | 94470f007294213f900dcd9a207678b5b9fce5d3 | ws4py/client/threadedclient.py | python | WebSocketClient.run_forever | (self) | Simply blocks the thread until the
websocket has terminated. | Simply blocks the thread until the
websocket has terminated. | [
"Simply",
"blocks",
"the",
"thread",
"until",
"the",
"websocket",
"has",
"terminated",
"."
] | def run_forever(self):
"""
Simply blocks the thread until the
websocket has terminated.
"""
while not self.terminated:
self._th.join(timeout=0.1) | [
"def",
"run_forever",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"terminated",
":",
"self",
".",
"_th",
".",
"join",
"(",
"timeout",
"=",
"0.1",
")"
] | https://github.com/WPO-Foundation/wptagent/blob/94470f007294213f900dcd9a207678b5b9fce5d3/ws4py/client/threadedclient.py#L53-L59 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/util/compiler.py | python | _get_custom_models | (models) | return custom_models | Returns CustomModels for models with a custom `__implementation__` | Returns CustomModels for models with a custom `__implementation__` | [
"Returns",
"CustomModels",
"for",
"models",
"with",
"a",
"custom",
"__implementation__"
] | def _get_custom_models(models):
"""Returns CustomModels for models with a custom `__implementation__`"""
if models is None:
models = Model.model_class_reverse_map.values()
custom_models = OrderedDict()
for cls in models:
impl = getattr(cls, "__implementation__", None)
if impl is not None:
model = CustomModel(cls)
custom_models[model.full_name] = model
if not custom_models:
return None
return custom_models | [
"def",
"_get_custom_models",
"(",
"models",
")",
":",
"if",
"models",
"is",
"None",
":",
"models",
"=",
"Model",
".",
"model_class_reverse_map",
".",
"values",
"(",
")",
"custom_models",
"=",
"OrderedDict",
"(",
")",
"for",
"cls",
"in",
"models",
":",
"imp... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/util/compiler.py#L494-L509 | |
bnpy/bnpy | d5b311e8f58ccd98477f4a0c8a4d4982e3fca424 | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | python | calc_fgrid | (o_grid=None, o_pos=None,
r_grid=None, r_pos=None,
omega=None, rho=None, **kwargs) | return f_grid | Evaluate the objective across range of values for one entry | Evaluate the objective across range of values for one entry | [
"Evaluate",
"the",
"objective",
"across",
"range",
"of",
"values",
"for",
"one",
"entry"
] | def calc_fgrid(o_grid=None, o_pos=None,
r_grid=None, r_pos=None,
omega=None, rho=None, **kwargs):
''' Evaluate the objective across range of values for one entry
'''
K = omega.size
if o_grid is not None:
assert o_pos >= 0 and o_pos < K
f_grid = np.zeros_like(o_grid)
omega_n = omega.copy()
for n in range(o_grid.size):
omega_n[o_pos] = o_grid[n]
f_grid[n] = negL_omega(rho=rho, omega=omega_n,
approx_grad=1, **kwargs)
elif r_grid is not None:
assert r_pos >= 0 and r_pos < K
f_grid = np.zeros_like(r_grid)
rho_n = rho.copy()
for n in range(r_grid.size):
rho_n[o_pos] = r_grid[n]
f_grid[n] = negL_rho(rho=rho_n, omega=omega,
approx_grad=1, **kwargs)
else:
raise ValueError("Must specify either o_grid or r_grid")
return f_grid | [
"def",
"calc_fgrid",
"(",
"o_grid",
"=",
"None",
",",
"o_pos",
"=",
"None",
",",
"r_grid",
"=",
"None",
",",
"r_pos",
"=",
"None",
",",
"omega",
"=",
"None",
",",
"rho",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"K",
"=",
"omega",
".",
"s... | https://github.com/bnpy/bnpy/blob/d5b311e8f58ccd98477f4a0c8a4d4982e3fca424/bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py#L600-L625 | |
Esri/ArcREST | ab240fde2b0200f61d4a5f6df033516e53f2f416 | src/arcrest/hostedservice/service.py | python | AdminFeatureService.securityHandler | (self, value) | sets the security handler | sets the security handler | [
"sets",
"the",
"security",
"handler"
] | def securityHandler(self, value):
""" sets the security handler """
if isinstance(value, BaseSecurityHandler):
if isinstance(value, (security.AGOLTokenSecurityHandler,security.PortalTokenSecurityHandler,security.ArcGISTokenSecurityHandler)):
self._securityHandler = value
else:
raise AttributeError("Admin only supports security.AGOLTokenSecurityHandler") | [
"def",
"securityHandler",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"BaseSecurityHandler",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"security",
".",
"AGOLTokenSecurityHandler",
",",
"security",
".",
"PortalTokenSe... | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/hostedservice/service.py#L787-L794 | ||
dipy/dipy | be956a529465b28085f8fc435a756947ddee1c89 | dipy/data/fetcher.py | python | get_fnames | (name='small_64D') | Provide full paths to example or test datasets.
Parameters
----------
name : str
the filename/s of which dataset to return, one of:
- 'small_64D' small region of interest nifti,bvecs,bvals 64 directions
- 'small_101D' small region of interest nifti, bvecs, bvals
101 directions
- 'aniso_vox' volume with anisotropic voxel size as Nifti
- 'fornix' 300 tracks in Trackvis format (from Pittsburgh
Brain Competition)
- 'gqi_vectors' the scanner wave vectors needed for a GQI acquisitions
of 101 directions tested on Siemens 3T Trio
- 'small_25' small ROI (10x8x2) DTI data (b value 2000, 25 directions)
- 'test_piesno' slice of N=8, K=14 diffusion data
- 'reg_c' small 2D image used for validating registration
- 'reg_o' small 2D image used for validation registration
- 'cb_2' two vectorized cingulum bundles
Returns
-------
fnames : tuple
filenames for dataset
Examples
--------
>>> import numpy as np
>>> from dipy.io.image import load_nifti
>>> from dipy.data import get_fnames
>>> fimg, fbvals, fbvecs = get_fnames('small_101D')
>>> bvals=np.loadtxt(fbvals)
>>> bvecs=np.loadtxt(fbvecs).T
>>> data, affine = load_nifti(fimg)
>>> data.shape == (6, 10, 10, 102)
True
>>> bvals.shape == (102,)
True
>>> bvecs.shape == (102, 3)
True | Provide full paths to example or test datasets. | [
"Provide",
"full",
"paths",
"to",
"example",
"or",
"test",
"datasets",
"."
] | def get_fnames(name='small_64D'):
"""Provide full paths to example or test datasets.
Parameters
----------
name : str
the filename/s of which dataset to return, one of:
- 'small_64D' small region of interest nifti,bvecs,bvals 64 directions
- 'small_101D' small region of interest nifti, bvecs, bvals
101 directions
- 'aniso_vox' volume with anisotropic voxel size as Nifti
- 'fornix' 300 tracks in Trackvis format (from Pittsburgh
Brain Competition)
- 'gqi_vectors' the scanner wave vectors needed for a GQI acquisitions
of 101 directions tested on Siemens 3T Trio
- 'small_25' small ROI (10x8x2) DTI data (b value 2000, 25 directions)
- 'test_piesno' slice of N=8, K=14 diffusion data
- 'reg_c' small 2D image used for validating registration
- 'reg_o' small 2D image used for validation registration
- 'cb_2' two vectorized cingulum bundles
Returns
-------
fnames : tuple
filenames for dataset
Examples
--------
>>> import numpy as np
>>> from dipy.io.image import load_nifti
>>> from dipy.data import get_fnames
>>> fimg, fbvals, fbvecs = get_fnames('small_101D')
>>> bvals=np.loadtxt(fbvals)
>>> bvecs=np.loadtxt(fbvecs).T
>>> data, affine = load_nifti(fimg)
>>> data.shape == (6, 10, 10, 102)
True
>>> bvals.shape == (102,)
True
>>> bvecs.shape == (102, 3)
True
"""
DATA_DIR = pjoin(os.path.dirname(__file__), 'files')
if name == 'small_64D':
fbvals = pjoin(DATA_DIR, 'small_64D.bval')
fbvecs = pjoin(DATA_DIR, 'small_64D.bvec')
fimg = pjoin(DATA_DIR, 'small_64D.nii')
return fimg, fbvals, fbvecs
if name == '55dir_grad':
fbvals = pjoin(DATA_DIR, '55dir_grad.bval')
fbvecs = pjoin(DATA_DIR, '55dir_grad.bvec')
return fbvals, fbvecs
if name == 'small_101D':
fbvals = pjoin(DATA_DIR, 'small_101D.bval')
fbvecs = pjoin(DATA_DIR, 'small_101D.bvec')
fimg = pjoin(DATA_DIR, 'small_101D.nii.gz')
return fimg, fbvals, fbvecs
if name == 'aniso_vox':
return pjoin(DATA_DIR, 'aniso_vox.nii.gz')
if name == 'ascm_test':
return pjoin(DATA_DIR, 'ascm_out_test.nii.gz')
if name == 'fornix':
return pjoin(DATA_DIR, 'tracks300.trk')
if name == 'gqi_vectors':
return pjoin(DATA_DIR, 'ScannerVectors_GQI101.txt')
if name == 'dsi515btable':
return pjoin(DATA_DIR, 'dsi515_b_table.txt')
if name == 'dsi4169btable':
return pjoin(DATA_DIR, 'dsi4169_b_table.txt')
if name == 'grad514':
return pjoin(DATA_DIR, 'grad_514.txt')
if name == "small_25":
fbvals = pjoin(DATA_DIR, 'small_25.bval')
fbvecs = pjoin(DATA_DIR, 'small_25.bvec')
fimg = pjoin(DATA_DIR, 'small_25.nii.gz')
return fimg, fbvals, fbvecs
if name == 'small_25_streamlines':
fstreamlines = pjoin(DATA_DIR, 'EuDX_small_25.trk')
return fstreamlines
if name == "S0_10":
fimg = pjoin(DATA_DIR, 'S0_10slices.nii.gz')
return fimg
if name == "test_piesno":
fimg = pjoin(DATA_DIR, 'test_piesno.nii.gz')
return fimg
if name == "reg_c":
return pjoin(DATA_DIR, 'C.npy')
if name == "reg_o":
return pjoin(DATA_DIR, 'circle.npy')
if name == 'cb_2':
return pjoin(DATA_DIR, 'cb_2.npz')
if name == "t1_coronal_slice":
return pjoin(DATA_DIR, 't1_coronal_slice.npy')
if name == "t-design":
N = 45
return pjoin(DATA_DIR, 'tdesign' + str(N) + '.txt')
if name == 'scil_b0':
files, folder = fetch_scil_b0()
files = files['datasets_multi-site_all_companies.zip'][2]
files = [pjoin(folder, f) for f in files]
return [f for f in files if os.path.isfile(f)]
if name == 'stanford_hardi':
files, folder = fetch_stanford_hardi()
fraw = pjoin(folder, 'HARDI150.nii.gz')
fbval = pjoin(folder, 'HARDI150.bval')
fbvec = pjoin(folder, 'HARDI150.bvec')
return fraw, fbval, fbvec
if name == 'taiwan_ntu_dsi':
files, folder = fetch_taiwan_ntu_dsi()
fraw = pjoin(folder, 'DSI203.nii.gz')
fbval = pjoin(folder, 'DSI203.bval')
fbvec = pjoin(folder, 'DSI203.bvec')
return fraw, fbval, fbvec
if name == 'sherbrooke_3shell':
files, folder = fetch_sherbrooke_3shell()
fraw = pjoin(folder, 'HARDI193.nii.gz')
fbval = pjoin(folder, 'HARDI193.bval')
fbvec = pjoin(folder, 'HARDI193.bvec')
return fraw, fbval, fbvec
if name == 'isbi2013_2shell':
files, folder = fetch_isbi2013_2shell()
fraw = pjoin(folder, 'phantom64.nii.gz')
fbval = pjoin(folder, 'phantom64.bval')
fbvec = pjoin(folder, 'phantom64.bvec')
return fraw, fbval, fbvec
if name == 'stanford_labels':
files, folder = fetch_stanford_labels()
return pjoin(folder, "aparc-reduced.nii.gz")
if name == 'syn_data':
files, folder = fetch_syn_data()
t1_name = pjoin(folder, 't1.nii.gz')
b0_name = pjoin(folder, 'b0.nii.gz')
return t1_name, b0_name
if name == 'stanford_t1':
files, folder = fetch_stanford_t1()
return pjoin(folder, 't1.nii.gz')
if name == 'stanford_pve_maps':
files, folder = fetch_stanford_pve_maps()
f_pve_csf = pjoin(folder, 'pve_csf.nii.gz')
f_pve_gm = pjoin(folder, 'pve_gm.nii.gz')
f_pve_wm = pjoin(folder, 'pve_wm.nii.gz')
return f_pve_csf, f_pve_gm, f_pve_wm
if name == 'ivim':
files, folder = fetch_ivim()
fraw = pjoin(folder, 'ivim.nii.gz')
fbval = pjoin(folder, 'ivim.bval')
fbvec = pjoin(folder, 'ivim.bvec')
return fraw, fbval, fbvec
if name == 'tissue_data':
files, folder = fetch_tissue_data()
t1_name = pjoin(folder, 't1_brain.nii.gz')
t1d_name = pjoin(folder, 't1_brain_denoised.nii.gz')
ap_name = pjoin(folder, 'power_map.nii.gz')
return t1_name, t1d_name, ap_name
if name == 'cfin_multib':
files, folder = fetch_cfin_multib()
t1_name = pjoin(folder, 'T1.nii')
fraw = pjoin(folder, '__DTI_AX_ep2d_2_5_iso_33d_20141015095334_4.nii')
fbval = pjoin(folder,
'__DTI_AX_ep2d_2_5_iso_33d_20141015095334_4.bval')
fbvec = pjoin(folder,
'__DTI_AX_ep2d_2_5_iso_33d_20141015095334_4.bvec')
return fraw, fbval, fbvec, t1_name
if name == 'target_tractrogram_hcp':
files, folder = fetch_target_tractogram_hcp()
return pjoin(folder, 'target_tractogram_hcp', 'hcp_tractogram',
'streamlines.trk')
if name == 'bundle_atlas_hcp842':
files, folder = fetch_bundle_atlas_hcp842()
return get_bundle_atlas_hcp842()
if name == 'fury_surface':
files, folder = fetch_fury_surface()
surface_name = pjoin(folder, '100307_white_lh.vtk')
return surface_name | [
"def",
"get_fnames",
"(",
"name",
"=",
"'small_64D'",
")",
":",
"DATA_DIR",
"=",
"pjoin",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'files'",
")",
"if",
"name",
"==",
"'small_64D'",
":",
"fbvals",
"=",
"pjoin",
"(",
"DATA_DIR"... | https://github.com/dipy/dipy/blob/be956a529465b28085f8fc435a756947ddee1c89/dipy/data/fetcher.py#L509-L683 | ||
hyde/hyde | 7f415402cc3e007a746eb2b5bc102281fdb415bd | hyde/server.py | python | HydeRequestHandler.do_404 | (self) | Sends a 'not found' response. | Sends a 'not found' response. | [
"Sends",
"a",
"not",
"found",
"response",
"."
] | def do_404(self):
"""
Sends a 'not found' response.
"""
site = self.server.site
if self.path != site.config.not_found:
self.redirect(site.config.not_found)
else:
res = site.content.resource_from_relative_deploy_path(
site.config.not_found)
message = "Requested resource not found"
if not res:
logger.error(
"Cannot find the 404 template [%s]."
% site.config.not_found)
else:
f404 = File(self.translate_path(site.config.not_found))
if f404.exists:
message = f404.read_all()
self.send_response(200, message) | [
"def",
"do_404",
"(",
"self",
")",
":",
"site",
"=",
"self",
".",
"server",
".",
"site",
"if",
"self",
".",
"path",
"!=",
"site",
".",
"config",
".",
"not_found",
":",
"self",
".",
"redirect",
"(",
"site",
".",
"config",
".",
"not_found",
")",
"els... | https://github.com/hyde/hyde/blob/7f415402cc3e007a746eb2b5bc102281fdb415bd/hyde/server.py#L97-L117 | ||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/Django-1.11.29/django/views/debug.py | python | ExceptionReporter.format_exception | (self) | return list | Return the same data as from traceback.format_exception. | Return the same data as from traceback.format_exception. | [
"Return",
"the",
"same",
"data",
"as",
"from",
"traceback",
".",
"format_exception",
"."
] | def format_exception(self):
"""
Return the same data as from traceback.format_exception.
"""
import traceback
frames = self.get_traceback_frames()
tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames]
list = ['Traceback (most recent call last):\n']
list += traceback.format_list(tb)
list += traceback.format_exception_only(self.exc_type, self.exc_value)
return list | [
"def",
"format_exception",
"(",
"self",
")",
":",
"import",
"traceback",
"frames",
"=",
"self",
".",
"get_traceback_frames",
"(",
")",
"tb",
"=",
"[",
"(",
"f",
"[",
"'filename'",
"]",
",",
"f",
"[",
"'lineno'",
"]",
",",
"f",
"[",
"'function'",
"]",
... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/views/debug.py#L448-L458 | |
cocos2d/cocos2d-console | 0b55cf8a5ebafffc7977fe5c64a4dea9b2d58c34 | plugins/plugin_luacompile/__init__.py | python | CCPluginLuaCompile.init | (self, options, workingdir) | Arguments:
- `options`: | Arguments:
- `options`: | [
"Arguments",
":",
"-",
"options",
":"
] | def init(self, options, workingdir):
"""
Arguments:
- `options`:
"""
self._current_src_dir = None
self._src_dir_arr = self.normalize_path_in_list(options.src_dir_arr)
self._dst_dir = options.dst_dir
if not os.path.isabs(self._dst_dir):
self._dst_dir = os.path.abspath(self._dst_dir)
self._verbose = options.verbose
self._workingdir = workingdir
self._lua_files = {}
self._isEncrypt = options.encrypt
self._encryptkey = options.encryptkey
self._encryptsign = options.encryptsign
self._bytecode_64bit = options.bytecode_64bit
self._luajit_exe_path = self.get_luajit_path()
self._disable_compile = options.disable_compile
if self._luajit_exe_path is None:
raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_TOOL_NOT_FOUND'),
cocos.CCPluginError.ERROR_TOOLS_NOT_FOUND)
self._luajit_dir = os.path.dirname(self._luajit_exe_path) | [
"def",
"init",
"(",
"self",
",",
"options",
",",
"workingdir",
")",
":",
"self",
".",
"_current_src_dir",
"=",
"None",
"self",
".",
"_src_dir_arr",
"=",
"self",
".",
"normalize_path_in_list",
"(",
"options",
".",
"src_dir_arr",
")",
"self",
".",
"_dst_dir",
... | https://github.com/cocos2d/cocos2d-console/blob/0b55cf8a5ebafffc7977fe5c64a4dea9b2d58c34/plugins/plugin_luacompile/__init__.py#L111-L136 | ||
davidbau/ganseeing | 93cea2c8f391aef001ddf9dcb35c43990681a47c | seeing/proggan.py | python | PixelNormLayer.forward | (self, x) | return x / torch.sqrt(torch.mean(x**2, dim=1, keepdim=True) + 1e-8) | [] | def forward(self, x):
return x / torch.sqrt(torch.mean(x**2, dim=1, keepdim=True) + 1e-8) | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"return",
"x",
"/",
"torch",
".",
"sqrt",
"(",
"torch",
".",
"mean",
"(",
"x",
"**",
"2",
",",
"dim",
"=",
"1",
",",
"keepdim",
"=",
"True",
")",
"+",
"1e-8",
")"
] | https://github.com/davidbau/ganseeing/blob/93cea2c8f391aef001ddf9dcb35c43990681a47c/seeing/proggan.py#L105-L106 | |||
andresriancho/w3af | cd22e5252243a87aaa6d0ddea47cf58dacfe00a9 | w3af/plugins/attack/db/sqlmap/thirdparty/odict/odict.py | python | Values.__add__ | (self, other) | return self._main.values() + other | [] | def __add__(self, other): return self._main.values() + other | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"_main",
".",
"values",
"(",
")",
"+",
"other"
] | https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/thirdparty/odict/odict.py#L1156-L1156 | |||
nltk/nltk | 3f74ac55681667d7ef78b664557487145f51eb02 | nltk/corpus/reader/wordnet.py | python | WordNetCorpusReader.of2ss | (self, of) | return self.synset_from_pos_and_offset(of[-1], int(of[:8])) | take an id and return the synsets | take an id and return the synsets | [
"take",
"an",
"id",
"and",
"return",
"the",
"synsets"
] | def of2ss(self, of):
"""take an id and return the synsets"""
return self.synset_from_pos_and_offset(of[-1], int(of[:8])) | [
"def",
"of2ss",
"(",
"self",
",",
"of",
")",
":",
"return",
"self",
".",
"synset_from_pos_and_offset",
"(",
"of",
"[",
"-",
"1",
"]",
",",
"int",
"(",
"of",
"[",
":",
"8",
"]",
")",
")"
] | https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/corpus/reader/wordnet.py#L1254-L1256 | |
enthought/chaco | 0907d1dedd07a499202efbaf2fe2a4e51b4c8e5f | chaco/tools/toolbars/plot_toolbar.py | python | PlotToolbar.normal_mouse_move | (self, event) | handler for normal mouse move | handler for normal mouse move | [
"handler",
"for",
"normal",
"mouse",
"move"
] | def normal_mouse_move(self, event):
"""handler for normal mouse move"""
self.on_hover("")
if self.hiding:
self.hiding = False | [
"def",
"normal_mouse_move",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"on_hover",
"(",
"\"\"",
")",
"if",
"self",
".",
"hiding",
":",
"self",
".",
"hiding",
"=",
"False"
] | https://github.com/enthought/chaco/blob/0907d1dedd07a499202efbaf2fe2a4e51b4c8e5f/chaco/tools/toolbars/plot_toolbar.py#L122-L126 | ||
Qirky/Troop | 529c5eb14e456f683e6d23fd4adcddc8446aa115 | src/OSC.py | python | OSCRequestHandler.setup | (self) | Prepare RequestHandler.
Unpacks request as (packet, source socket address)
Creates an empty list for replies. | Prepare RequestHandler.
Unpacks request as (packet, source socket address)
Creates an empty list for replies. | [
"Prepare",
"RequestHandler",
".",
"Unpacks",
"request",
"as",
"(",
"packet",
"source",
"socket",
"address",
")",
"Creates",
"an",
"empty",
"list",
"for",
"replies",
"."
] | def setup(self):
"""Prepare RequestHandler.
Unpacks request as (packet, source socket address)
Creates an empty list for replies.
"""
(self.packet, self.socket) = self.request
self.replies = [] | [
"def",
"setup",
"(",
"self",
")",
":",
"(",
"self",
".",
"packet",
",",
"self",
".",
"socket",
")",
"=",
"self",
".",
"request",
"self",
".",
"replies",
"=",
"[",
"]"
] | https://github.com/Qirky/Troop/blob/529c5eb14e456f683e6d23fd4adcddc8446aa115/src/OSC.py#L1765-L1771 | ||
aws/aws-sam-cli | 2aa7bf01b2e0b0864ef63b1898a8b30577443acc | samcli/commands/local/lib/swagger/integration_uri.py | python | LambdaUri._get_function_name_from_arn | (function_arn) | return None | Given the integration ARN, extract the Lambda function name from the ARN. If there
are stage variables, or other unsupported formats, this function will return None.
Parameters
----------
function_arn : basestring or None
Function ARN from the swagger document
Returns
-------
basestring or None
Function name of this integration. None if the ARN is not parsable | Given the integration ARN, extract the Lambda function name from the ARN. If there
are stage variables, or other unsupported formats, this function will return None. | [
"Given",
"the",
"integration",
"ARN",
"extract",
"the",
"Lambda",
"function",
"name",
"from",
"the",
"ARN",
".",
"If",
"there",
"are",
"stage",
"variables",
"or",
"other",
"unsupported",
"formats",
"this",
"function",
"will",
"return",
"None",
"."
] | def _get_function_name_from_arn(function_arn) -> Optional[str]:
"""
Given the integration ARN, extract the Lambda function name from the ARN. If there
are stage variables, or other unsupported formats, this function will return None.
Parameters
----------
function_arn : basestring or None
Function ARN from the swagger document
Returns
-------
basestring or None
Function name of this integration. None if the ARN is not parsable
"""
if not function_arn:
return None
matches = re.match(LambdaUri._REGEX_GET_FUNCTION_NAME, function_arn)
if not matches or not matches.groups():
LOG.debug("No Lambda function ARN defined for integration containing ARN %s", function_arn)
return None
groups = matches.groups()
maybe_function_name: str = groups[0] # This regex has only one group match
# Function name could be a real name or a stage variable or some unknown format
if re.match(LambdaUri._REGEX_STAGE_VARIABLE, maybe_function_name):
# yes, this is a stage variable
LOG.debug("Stage variables are not supported. Ignoring integration with function ARN %s", function_arn)
return None
if re.match(LambdaUri._REGEX_VALID_FUNCTION_NAME, maybe_function_name):
# Yes, this is a real function name
return maybe_function_name
# Some unknown format
LOG.debug("Ignoring integration ARN. Unable to parse Function Name from function arn %s", function_arn)
return None | [
"def",
"_get_function_name_from_arn",
"(",
"function_arn",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"not",
"function_arn",
":",
"return",
"None",
"matches",
"=",
"re",
".",
"match",
"(",
"LambdaUri",
".",
"_REGEX_GET_FUNCTION_NAME",
",",
"function_arn"... | https://github.com/aws/aws-sam-cli/blob/2aa7bf01b2e0b0864ef63b1898a8b30577443acc/samcli/commands/local/lib/swagger/integration_uri.py#L141-L180 | |
mrJean1/PyGeodesy | 7da5ca71aa3edb7bc49e219e0b8190686e1a7965 | pygeodesy/cartesianBase.py | python | CartesianBase.isEllipsoidal | (self) | return self.datum.isEllipsoidal if self._datum else None | Check whether this cartesian is ellipsoidal (C{bool} or C{None} if unknown). | Check whether this cartesian is ellipsoidal (C{bool} or C{None} if unknown). | [
"Check",
"whether",
"this",
"cartesian",
"is",
"ellipsoidal",
"(",
"C",
"{",
"bool",
"}",
"or",
"C",
"{",
"None",
"}",
"if",
"unknown",
")",
"."
] | def isEllipsoidal(self):
'''Check whether this cartesian is ellipsoidal (C{bool} or C{None} if unknown).
'''
return self.datum.isEllipsoidal if self._datum else None | [
"def",
"isEllipsoidal",
"(",
"self",
")",
":",
"return",
"self",
".",
"datum",
".",
"isEllipsoidal",
"if",
"self",
".",
"_datum",
"else",
"None"
] | https://github.com/mrJean1/PyGeodesy/blob/7da5ca71aa3edb7bc49e219e0b8190686e1a7965/pygeodesy/cartesianBase.py#L284-L287 | |
LuxCoreRender/BlendLuxCore | bf31ca58501d54c02acd97001b6db7de81da7cbf | nodes/base.py | python | LuxCoreNodeVolume.add_common_inputs | (self) | Call from derived classes (in init method) | Call from derived classes (in init method) | [
"Call",
"from",
"derived",
"classes",
"(",
"in",
"init",
"method",
")"
] | def add_common_inputs(self):
""" Call from derived classes (in init method) """
self.add_input("LuxCoreSocketColor", "Absorption", (1, 1, 1))
self.add_input("LuxCoreSocketIOR", "IOR", 1.5)
self.add_input("LuxCoreSocketColor", "Emission", (0, 0, 0)) | [
"def",
"add_common_inputs",
"(",
"self",
")",
":",
"self",
".",
"add_input",
"(",
"\"LuxCoreSocketColor\"",
",",
"\"Absorption\"",
",",
"(",
"1",
",",
"1",
",",
"1",
")",
")",
"self",
".",
"add_input",
"(",
"\"LuxCoreSocketIOR\"",
",",
"\"IOR\"",
",",
"1.5... | https://github.com/LuxCoreRender/BlendLuxCore/blob/bf31ca58501d54c02acd97001b6db7de81da7cbf/nodes/base.py#L224-L228 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.