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
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/pydoc.py
python
Helper._gettopic
(self, topic, more_xrefs='')
return doc, xrefs
Return unbuffered tuple of (topic, xrefs). If an error occurs here, the exception is caught and displayed by the url handler. This function duplicates the showtopic method but returns its result directly so it can be formatted for display in an html page.
Return unbuffered tuple of (topic, xrefs).
[ "Return", "unbuffered", "tuple", "of", "(", "topic", "xrefs", ")", "." ]
def _gettopic(self, topic, more_xrefs=''): """Return unbuffered tuple of (topic, xrefs). If an error occurs here, the exception is caught and displayed by the url handler. This function duplicates the showtopic method but returns its result directly so it can be formatted for display in an html page. """ try: import pydoc_data.topics except ImportError: return(''' Sorry, topic and keyword documentation is not available because the module "pydoc_data.topics" could not be found. ''' , '') target = self.topics.get(topic, self.keywords.get(topic)) if not target: raise ValueError('could not find topic') if isinstance(target, str): return self._gettopic(target, more_xrefs) label, xrefs = target doc = pydoc_data.topics.topics[label] if more_xrefs: xrefs = (xrefs or '') + ' ' + more_xrefs return doc, xrefs
[ "def", "_gettopic", "(", "self", ",", "topic", ",", "more_xrefs", "=", "''", ")", ":", "try", ":", "import", "pydoc_data", ".", "topics", "except", "ImportError", ":", "return", "(", "'''\nSorry, topic and keyword documentation is not available because the\nmodule \"pyd...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/pydoc.py#L2041-L2066
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/html5lib/treebuilders/base.py
python
TreeBuilder.createElement
(self, token)
return element
Create an element but don't insert it anywhere
Create an element but don't insert it anywhere
[ "Create", "an", "element", "but", "don", "t", "insert", "it", "anywhere" ]
def createElement(self, token): """Create an element but don't insert it anywhere""" name = token["name"] namespace = token.get("namespace", self.defaultNamespace) element = self.elementClass(name, namespace) element.attributes = token["data"] return element
[ "def", "createElement", "(", "self", ",", "token", ")", ":", "name", "=", "token", "[", "\"name\"", "]", "namespace", "=", "token", ".", "get", "(", "\"namespace\"", ",", "self", ".", "defaultNamespace", ")", "element", "=", "self", ".", "elementClass", ...
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/html5lib/treebuilders/base.py#L301-L307
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/xml/dom/minidom.py
python
Node.removeChild
(self, oldChild)
return oldChild
[]
def removeChild(self, oldChild): try: self.childNodes.remove(oldChild) except ValueError: raise xml.dom.NotFoundErr() if oldChild.nextSibling is not None: oldChild.nextSibling.previousSibling = oldChild.previousSibling if oldChild.previousSibling is not None: oldChild.previousSibling.nextSibling = oldChild.nextSibling oldChild.nextSibling = oldChild.previousSibling = None if oldChild.nodeType in _nodeTypes_with_children: _clear_id_cache(self) oldChild.parentNode = None return oldChild
[ "def", "removeChild", "(", "self", ",", "oldChild", ")", ":", "try", ":", "self", ".", "childNodes", ".", "remove", "(", "oldChild", ")", "except", "ValueError", ":", "raise", "xml", ".", "dom", ".", "NotFoundErr", "(", ")", "if", "oldChild", ".", "nex...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/xml/dom/minidom.py#L162-L176
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/words/protocols/irc.py
python
ServerSupportedFeatures.isupport_TARGMAX
(self, params)
return dict(self._splitParamArgs(params, _intOrDefault))
Maximum number of targets allowable for commands that accept multiple targets.
Maximum number of targets allowable for commands that accept multiple targets.
[ "Maximum", "number", "of", "targets", "allowable", "for", "commands", "that", "accept", "multiple", "targets", "." ]
def isupport_TARGMAX(self, params): """ Maximum number of targets allowable for commands that accept multiple targets. """ return dict(self._splitParamArgs(params, _intOrDefault))
[ "def", "isupport_TARGMAX", "(", "self", ",", "params", ")", ":", "return", "dict", "(", "self", ".", "_splitParamArgs", "(", "params", ",", "_intOrDefault", ")", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/words/protocols/irc.py#L954-L959
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/html5lib/inputstream.py
python
HTMLUnicodeInputStream.char
(self)
return char
Read one character from the stream or queue if available. Return EOF when EOF is reached.
Read one character from the stream or queue if available. Return EOF when EOF is reached.
[ "Read", "one", "character", "from", "the", "stream", "or", "queue", "if", "available", ".", "Return", "EOF", "when", "EOF", "is", "reached", "." ]
def char(self): """ Read one character from the stream or queue if available. Return EOF when EOF is reached. """ # Read a new chunk from the input stream if necessary if self.chunkOffset >= self.chunkSize: if not self.readChunk(): return EOF chunkOffset = self.chunkOffset char = self.chunk[chunkOffset] self.chunkOffset = chunkOffset + 1 return char
[ "def", "char", "(", "self", ")", ":", "# Read a new chunk from the input stream if necessary", "if", "self", ".", "chunkOffset", ">=", "self", ".", "chunkSize", ":", "if", "not", "self", ".", "readChunk", "(", ")", ":", "return", "EOF", "chunkOffset", "=", "se...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/html5lib/inputstream.py#L243-L256
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/billiard-3.5.0.5/billiard/context.py
python
BaseContext.Barrier
(self, parties, action=None, timeout=None)
return Barrier(parties, action, timeout, ctx=self.get_context())
Returns a barrier object
Returns a barrier object
[ "Returns", "a", "barrier", "object" ]
def Barrier(self, parties, action=None, timeout=None): '''Returns a barrier object''' from .synchronize import Barrier return Barrier(parties, action, timeout, ctx=self.get_context())
[ "def", "Barrier", "(", "self", ",", "parties", ",", "action", "=", "None", ",", "timeout", "=", "None", ")", ":", "from", ".", "synchronize", "import", "Barrier", "return", "Barrier", "(", "parties", ",", "action", ",", "timeout", ",", "ctx", "=", "sel...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/billiard-3.5.0.5/billiard/context.py#L132-L135
jimmysong/pb-exercises
c5e64075c47503a40063aa836c06a452af14246d
session7/script.py
python
Script.is_p2sh_script_pubkey
(self)
return len(self.commands) == 3 and self.commands[0] == 0xa9 \ and type(self.commands[1]) == bytes and len(self.commands[1]) == 20 \ and self.commands[2] == 0x87
Returns whether this follows the OP_HASH160 <20 byte hash> OP_EQUAL pattern.
Returns whether this follows the OP_HASH160 <20 byte hash> OP_EQUAL pattern.
[ "Returns", "whether", "this", "follows", "the", "OP_HASH160", "<20", "byte", "hash", ">", "OP_EQUAL", "pattern", "." ]
def is_p2sh_script_pubkey(self): '''Returns whether this follows the OP_HASH160 <20 byte hash> OP_EQUAL pattern.''' # there should be exactly 3 commands # OP_HASH160 (0xa9), 20-byte hash, OP_EQUAL (0x87) return len(self.commands) == 3 and self.commands[0] == 0xa9 \ and type(self.commands[1]) == bytes and len(self.commands[1]) == 20 \ and self.commands[2] == 0x87
[ "def", "is_p2sh_script_pubkey", "(", "self", ")", ":", "# there should be exactly 3 commands", "# OP_HASH160 (0xa9), 20-byte hash, OP_EQUAL (0x87)", "return", "len", "(", "self", ".", "commands", ")", "==", "3", "and", "self", ".", "commands", "[", "0", "]", "==", "...
https://github.com/jimmysong/pb-exercises/blob/c5e64075c47503a40063aa836c06a452af14246d/session7/script.py#L210-L217
geopython/pycsw
43a5c92fa819a3a3fdc8a8e3ef075d784dff73fc
pycsw/core/admin.py
python
cli_optimize_db
(ctx, config, verbosity)
Optimize repository database
Optimize repository database
[ "Optimize", "repository", "database" ]
def cli_optimize_db(ctx, config, verbosity): """Optimize repository database""" cfg = parse_ini_config(config) context = pconfig.StaticContext() optimize_db( context, cfg['repository']['database'], cfg['repository']['table'] )
[ "def", "cli_optimize_db", "(", "ctx", ",", "config", ",", "verbosity", ")", ":", "cfg", "=", "parse_ini_config", "(", "config", ")", "context", "=", "pconfig", ".", "StaticContext", "(", ")", "optimize_db", "(", "context", ",", "cfg", "[", "'repository'", ...
https://github.com/geopython/pycsw/blob/43a5c92fa819a3a3fdc8a8e3ef075d784dff73fc/pycsw/core/admin.py#L789-L798
RealHacker/leetcode-solutions
50b21ea270dd095bef0b21e4e8bd79c1f279a85a
240_search_2d_matrix/search_2d_matrix_ii_take2.py
python
Solution.searchMatrix
(self, matrix, target)
:type matrix: List[List[int]] :type target: int :rtype: bool
:type matrix: List[List[int]] :type target: int :rtype: bool
[ ":", "type", "matrix", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "target", ":", "int", ":", "rtype", ":", "bool" ]
def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ x = 0 y = 0 xx = len(matrix)-1 yy = len(matrix[0])-1 rows = xx+1 cols = yy+1 while True: row = matrix[x][y:yy+1] py = bisect.bisect_left(row, target) if py<len(row) and row[py]==target: return True if py==0: return False col = [matrix[r][y] for r in range(x, xx+1)] px = bisect.bisect_left(col, target) if px<len(col) and col[px]==target: return True if px==0: return False xx = x+px-1 yy = y+py-1 x = x+1 y = y+1 if x>xx or y>yy: return False
[ "def", "searchMatrix", "(", "self", ",", "matrix", ",", "target", ")", ":", "x", "=", "0", "y", "=", "0", "xx", "=", "len", "(", "matrix", ")", "-", "1", "yy", "=", "len", "(", "matrix", "[", "0", "]", ")", "-", "1", "rows", "=", "xx", "+",...
https://github.com/RealHacker/leetcode-solutions/blob/50b21ea270dd095bef0b21e4e8bd79c1f279a85a/240_search_2d_matrix/search_2d_matrix_ii_take2.py#L2-L33
inspurer/WorkAttendanceSystem
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
V1.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/requests/packages/urllib3/packages/six.py
python
python_2_unicode_compatible
(klass)
return klass
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing.
[ "A", "decorator", "that", "defines", "__unicode__", "and", "__str__", "methods", "under", "Python", "2", ".", "Under", "Python", "3", "it", "does", "nothing", "." ]
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if '__str__' not in klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass
[ "def", "python_2_unicode_compatible", "(", "klass", ")", ":", "if", "PY2", ":", "if", "'__str__'", "not", "in", "klass", ".", "__dict__", ":", "raise", "ValueError", "(", "\"@python_2_unicode_compatible cannot be applied \"", "\"to %s because it doesn't define __str__().\""...
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V1.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/requests/packages/urllib3/packages/six.py#L828-L843
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/setuptools/depends.py
python
Require.version_ok
(self, version)
return self.attribute is None or self.format is None or \ str(version) != "unknown" and version >= self.requested_version
Is 'version' sufficiently up-to-date?
Is 'version' sufficiently up-to-date?
[ "Is", "version", "sufficiently", "up", "-", "to", "-", "date?" ]
def version_ok(self, version): """Is 'version' sufficiently up-to-date?""" return self.attribute is None or self.format is None or \ str(version) != "unknown" and version >= self.requested_version
[ "def", "version_ok", "(", "self", ",", "version", ")", ":", "return", "self", ".", "attribute", "is", "None", "or", "self", ".", "format", "is", "None", "or", "str", "(", "version", ")", "!=", "\"unknown\"", "and", "version", ">=", "self", ".", "reques...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/setuptools/depends.py#L38-L41
wakatime/legacy-python-cli
9b64548b16ab5ef16603d9a6c2620a16d0df8d46
wakatime/packages/py26/pygments/token.py
python
is_token_subtype
(ttype, other)
return ttype in other
Return True if ``ttype`` is a subtype of ``other``. exists for backwards compatibility. use ``ttype in other`` now.
Return True if ``ttype`` is a subtype of ``other``.
[ "Return", "True", "if", "ttype", "is", "a", "subtype", "of", "other", "." ]
def is_token_subtype(ttype, other): """ Return True if ``ttype`` is a subtype of ``other``. exists for backwards compatibility. use ``ttype in other`` now. """ return ttype in other
[ "def", "is_token_subtype", "(", "ttype", ",", "other", ")", ":", "return", "ttype", "in", "other" ]
https://github.com/wakatime/legacy-python-cli/blob/9b64548b16ab5ef16603d9a6c2620a16d0df8d46/wakatime/packages/py26/pygments/token.py#L86-L92
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/inspect.py
python
getmodulename
(path)
Return the module name for a given file, or None.
Return the module name for a given file, or None.
[ "Return", "the", "module", "name", "for", "a", "given", "file", "or", "None", "." ]
def getmodulename(path): """Return the module name for a given file, or None.""" info = getmoduleinfo(path) if info: return info[0]
[ "def", "getmodulename", "(", "path", ")", ":", "info", "=", "getmoduleinfo", "(", "path", ")", "if", "info", ":", "return", "info", "[", "0", "]" ]
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/inspect.py#L434-L437
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/graphicsItems/ViewBox/ViewBox.py
python
ViewBox.childrenBounds
(self, frac=None, orthoRange=(None,None), items=None)
return range
Return the bounding range of all children. [[xmin, xmax], [ymin, ymax]] Values may be None if there are no specific bounds for an axis.
Return the bounding range of all children. [[xmin, xmax], [ymin, ymax]] Values may be None if there are no specific bounds for an axis.
[ "Return", "the", "bounding", "range", "of", "all", "children", ".", "[[", "xmin", "xmax", "]", "[", "ymin", "ymax", "]]", "Values", "may", "be", "None", "if", "there", "are", "no", "specific", "bounds", "for", "an", "axis", "." ]
def childrenBounds(self, frac=None, orthoRange=(None,None), items=None): """Return the bounding range of all children. [[xmin, xmax], [ymin, ymax]] Values may be None if there are no specific bounds for an axis. """ profiler = debug.Profiler() if items is None: items = self.addedItems ## measure pixel dimensions in view box px, py = [v.length() if v is not None else 0 for v in self.childGroup.pixelVectors()] ## First collect all boundary information itemBounds = [] for item in items: if not item.isVisible() or not item.scene() is self.scene(): continue useX = True useY = True if hasattr(item, 'dataBounds'): if frac is None: frac = (1.0, 1.0) xr = item.dataBounds(0, frac=frac[0], orthoRange=orthoRange[0]) yr = item.dataBounds(1, frac=frac[1], orthoRange=orthoRange[1]) pxPad = 0 if not hasattr(item, 'pixelPadding') else item.pixelPadding() if xr is None or (xr[0] is None and xr[1] is None) or np.isnan(xr).any() or np.isinf(xr).any(): useX = False xr = (0,0) if yr is None or (yr[0] is None and yr[1] is None) or np.isnan(yr).any() or np.isinf(yr).any(): useY = False yr = (0,0) bounds = QtCore.QRectF(xr[0], yr[0], xr[1]-xr[0], yr[1]-yr[0]) bounds = self.mapFromItemToView(item, bounds).boundingRect() if not any([useX, useY]): continue ## If we are ignoring only one axis, we need to check for rotations if useX != useY: ## != means xor ang = round(item.transformAngle()) if ang == 0 or ang == 180: pass elif ang == 90 or ang == 270: useX, useY = useY, useX else: ## Item is rotated at non-orthogonal angle, ignore bounds entirely. ## Not really sure what is the expected behavior in this case. continue ## need to check for item rotations and decide how best to apply this boundary. itemBounds.append((bounds, useX, useY, pxPad)) else: if int(item.flags() & item.ItemHasNoContents) > 0: continue else: bounds = item.boundingRect() bounds = self.mapFromItemToView(item, bounds).boundingRect() itemBounds.append((bounds, True, True, 0)) ## determine tentative new range range = [None, None] for bounds, useX, useY, px in itemBounds: if useY: if range[1] is not None: range[1] = [min(bounds.top(), range[1][0]), max(bounds.bottom(), range[1][1])] else: range[1] = [bounds.top(), bounds.bottom()] if useX: if range[0] is not None: range[0] = [min(bounds.left(), range[0][0]), max(bounds.right(), range[0][1])] else: range[0] = [bounds.left(), bounds.right()] profiler() ## Now expand any bounds that have a pixel margin ## This must be done _after_ we have a good estimate of the new range ## to ensure that the pixel size is roughly accurate. w = self.width() h = self.height() if w > 0 and range[0] is not None: pxSize = (range[0][1] - range[0][0]) / w for bounds, useX, useY, px in itemBounds: if px == 0 or not useX: continue range[0][0] = min(range[0][0], bounds.left() - px*pxSize) range[0][1] = max(range[0][1], bounds.right() + px*pxSize) if h > 0 and range[1] is not None: pxSize = (range[1][1] - range[1][0]) / h for bounds, useX, useY, px in itemBounds: if px == 0 or not useY: continue range[1][0] = min(range[1][0], bounds.top() - px*pxSize) range[1][1] = max(range[1][1], bounds.bottom() + px*pxSize) return range
[ "def", "childrenBounds", "(", "self", ",", "frac", "=", "None", ",", "orthoRange", "=", "(", "None", ",", "None", ")", ",", "items", "=", "None", ")", ":", "profiler", "=", "debug", ".", "Profiler", "(", ")", "if", "items", "is", "None", ":", "item...
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/graphicsItems/ViewBox/ViewBox.py#L1268-L1365
tenable/pyTenable
1ccab9fc6f6e4c9f1cfe5128f694388ea112719d
tenable/io/tags.py
python
TagsAPI.unassign
(self, assets, tags)
return self._api.post('tags/assets/assignments', json={ 'action': 'remove', 'assets': [self._check('asset', a, 'uuid') for a in assets], 'tags': [self._check('tag', t, 'uuid') for t in tags], }).json()['job_uuid']
Un-assigns the tag category/value pairs defined to the assets defined. :devportal:`tags: assign tags <tags-assign-asset-tags>` Args: assets (list): A list of Asset UUIDs. tags (list): A list of tag category/value pair UUIDs. Returns: :obj:`str`: Job UUID of the un-assignment job. Examples: >>> tio.tags.unassign( ... assets=['00000000-0000-0000-0000-000000000000'], ... tags=['00000000-0000-0000-0000-000000000000'])
Un-assigns the tag category/value pairs defined to the assets defined.
[ "Un", "-", "assigns", "the", "tag", "category", "/", "value", "pairs", "defined", "to", "the", "assets", "defined", "." ]
def unassign(self, assets, tags): ''' Un-assigns the tag category/value pairs defined to the assets defined. :devportal:`tags: assign tags <tags-assign-asset-tags>` Args: assets (list): A list of Asset UUIDs. tags (list): A list of tag category/value pair UUIDs. Returns: :obj:`str`: Job UUID of the un-assignment job. Examples: >>> tio.tags.unassign( ... assets=['00000000-0000-0000-0000-000000000000'], ... tags=['00000000-0000-0000-0000-000000000000']) ''' self._check('assets', assets, list) self._check('tags', tags, list) return self._api.post('tags/assets/assignments', json={ 'action': 'remove', 'assets': [self._check('asset', a, 'uuid') for a in assets], 'tags': [self._check('tag', t, 'uuid') for t in tags], }).json()['job_uuid']
[ "def", "unassign", "(", "self", ",", "assets", ",", "tags", ")", ":", "self", ".", "_check", "(", "'assets'", ",", "assets", ",", "list", ")", "self", ".", "_check", "(", "'tags'", ",", "tags", ",", "list", ")", "return", "self", ".", "_api", ".", ...
https://github.com/tenable/pyTenable/blob/1ccab9fc6f6e4c9f1cfe5128f694388ea112719d/tenable/io/tags.py#L674-L701
awesto/django-shop
13d9a77aff7eede74a5f363c1d540e005d88dbcd
shop/admin/delivery.py
python
DeliveryInline.fulfilled
(self, obj)
return _("Pending")
[]
def fulfilled(self, obj): if obj.fulfilled_at: return timezone.localtime(obj.fulfilled_at).ctime() # TODO: find the correct time format return _("Pending")
[ "def", "fulfilled", "(", "self", ",", "obj", ")", ":", "if", "obj", ".", "fulfilled_at", ":", "return", "timezone", ".", "localtime", "(", "obj", ".", "fulfilled_at", ")", ".", "ctime", "(", ")", "# TODO: find the correct time format", "return", "_", "(", ...
https://github.com/awesto/django-shop/blob/13d9a77aff7eede74a5f363c1d540e005d88dbcd/shop/admin/delivery.py#L181-L184
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/idlelib/configSectionNameDialog.py
python
GetCfgSectionNameDialog.__init__
(self, parent, title, message, used_names, _htest=False)
message - string, informational message to display used_names - string collection, names already in use for validity check _htest - bool, change box location when running htest
message - string, informational message to display used_names - string collection, names already in use for validity check _htest - bool, change box location when running htest
[ "message", "-", "string", "informational", "message", "to", "display", "used_names", "-", "string", "collection", "names", "already", "in", "use", "for", "validity", "check", "_htest", "-", "bool", "change", "box", "location", "when", "running", "htest" ]
def __init__(self, parent, title, message, used_names, _htest=False): """ message - string, informational message to display used_names - string collection, names already in use for validity check _htest - bool, change box location when running htest """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.Cancel) self.parent = parent self.message = message self.used_names = used_names self.create_widgets() self.withdraw() #hide while setting geometry self.update_idletasks() #needs to be done here so that the winfo_reqwidth is valid self.messageInfo.config(width=self.frameMain.winfo_reqwidth()) self.geometry( "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 100) ) ) #centre dialog over parent (or below htest box) self.deiconify() #geometry set, unhide self.wait_window()
[ "def", "__init__", "(", "self", ",", "parent", ",", "title", ",", "message", ",", "used_names", ",", "_htest", "=", "False", ")", ":", "Toplevel", ".", "__init__", "(", "self", ",", "parent", ")", "self", ".", "configure", "(", "borderwidth", "=", "5",...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/idlelib/configSectionNameDialog.py#L11-L41
zzzeek/sqlalchemy
fc5c54fcd4d868c2a4c7ac19668d72f506fe821e
lib/sqlalchemy/sql/schema.py
python
Index.drop
(self, bind=None, checkfirst=False)
Issue a ``DROP`` statement for this :class:`.Index`, using the given :class:`.Connectable` for connectivity. .. note:: the "bind" argument will be required in SQLAlchemy 2.0. .. seealso:: :meth:`_schema.MetaData.drop_all`.
Issue a ``DROP`` statement for this :class:`.Index`, using the given :class:`.Connectable` for connectivity.
[ "Issue", "a", "DROP", "statement", "for", "this", ":", "class", ":", ".", "Index", "using", "the", "given", ":", "class", ":", ".", "Connectable", "for", "connectivity", "." ]
def drop(self, bind=None, checkfirst=False): """Issue a ``DROP`` statement for this :class:`.Index`, using the given :class:`.Connectable` for connectivity. .. note:: the "bind" argument will be required in SQLAlchemy 2.0. .. seealso:: :meth:`_schema.MetaData.drop_all`. """ if bind is None: bind = _bind_or_error(self) bind._run_ddl_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
[ "def", "drop", "(", "self", ",", "bind", "=", "None", ",", "checkfirst", "=", "False", ")", ":", "if", "bind", "is", "None", ":", "bind", "=", "_bind_or_error", "(", "self", ")", "bind", ".", "_run_ddl_visitor", "(", "ddl", ".", "SchemaDropper", ",", ...
https://github.com/zzzeek/sqlalchemy/blob/fc5c54fcd4d868c2a4c7ac19668d72f506fe821e/lib/sqlalchemy/sql/schema.py#L4198-L4213
delira-dev/delira
cd3ad277d6fad5f837d6c5147e6eee2ada648596
delira/models/backends/chainer/data_parallel.py
python
DataParallelChainerNetwork.__init__
(self, module: AbstractChainerNetwork, devices: list, output_device=None, batch_dim=0)
Parameters ---------- module : :class:`AbstractChainerNetwork` the module to wrap (will be replicated on all devices) devices : list a list containing the devices to use (either as strings or as :class:`chainer.backend.Device`). output_device : str or :class:`chainer.backend.Device` The output device Make sure, your labels are also on this device for loss calculation! If not specified, the second device of ``devices`` will be used for output gathering. batch_dim : int the index of the batchdimension (usually 0, but can become e.g. 1 in NLP tasks)
[]
def __init__(self, module: AbstractChainerNetwork, devices: list, output_device=None, batch_dim=0): """ Parameters ---------- module : :class:`AbstractChainerNetwork` the module to wrap (will be replicated on all devices) devices : list a list containing the devices to use (either as strings or as :class:`chainer.backend.Device`). output_device : str or :class:`chainer.backend.Device` The output device Make sure, your labels are also on this device for loss calculation! If not specified, the second device of ``devices`` will be used for output gathering. batch_dim : int the index of the batchdimension (usually 0, but can become e.g. 1 in NLP tasks) """ super().__init__() modules = [module.copy() for _ in devices] for _module, _device in zip(modules, devices): _module.to_device(_device) with self.init_scope(): self.modules = chainer.ChainList(*modules) self.devices = devices if output_device is None: output_device = devices[1] self._output_device = output_device assert self._output_device in self.devices self._output_device_idx = self.devices.index(self._output_device) self.dim = batch_dim
[ "def", "__init__", "(", "self", ",", "module", ":", "AbstractChainerNetwork", ",", "devices", ":", "list", ",", "output_device", "=", "None", ",", "batch_dim", "=", "0", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "modules", "=", "[", "modu...
https://github.com/delira-dev/delira/blob/cd3ad277d6fad5f837d6c5147e6eee2ada648596/delira/models/backends/chainer/data_parallel.py#L205-L246
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/src/oscar/snac/family_x01.py
python
x01_x05
(o, sock, data)
return id, addr, cookie
SNAC (x1, x5): Service redirect The server is telling is to go to another server. This happens initially at signon and any time a service is successfully requested reference: U{http://iserverd.khstu.ru/oscar/snac_01_05.html}
SNAC (x1, x5): Service redirect
[ "SNAC", "(", "x1", "x5", ")", ":", "Service", "redirect" ]
def x01_x05(o, sock, data): ''' SNAC (x1, x5): Service redirect The server is telling is to go to another server. This happens initially at signon and any time a service is successfully requested reference: U{http://iserverd.khstu.ru/oscar/snac_01_05.html} ''' format = (('tlvs', 'named_tlvs', -1, tlv_types),) tlvs, data = oscar.unpack(format, data) id, addr, cookie = tlvs.service_id, tlvs.server_addr, tlvs.cookie (id,) = struct.unpack('!H', id) assert all([id, addr, cookie]) return id, addr, cookie
[ "def", "x01_x05", "(", "o", ",", "sock", ",", "data", ")", ":", "format", "=", "(", "(", "'tlvs'", ",", "'named_tlvs'", ",", "-", "1", ",", "tlv_types", ")", ",", ")", "tlvs", ",", "data", "=", "oscar", ".", "unpack", "(", "format", ",", "data", ...
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/oscar/snac/family_x01.py#L117-L132
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3cfg.py
python
S3Config.get_base_cdn
(self)
return self.base.get("cdn", False)
Should we use CDNs (Content Distribution Networks) to serve some common CSS/JS?
Should we use CDNs (Content Distribution Networks) to serve some common CSS/JS?
[ "Should", "we", "use", "CDNs", "(", "Content", "Distribution", "Networks", ")", "to", "serve", "some", "common", "CSS", "/", "JS?" ]
def get_base_cdn(self): """ Should we use CDNs (Content Distribution Networks) to serve some common CSS/JS? """ return self.base.get("cdn", False)
[ "def", "get_base_cdn", "(", "self", ")", ":", "return", "self", ".", "base", ".", "get", "(", "\"cdn\"", ",", "False", ")" ]
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3cfg.py#L1116-L1120
facebookresearch/Detectron
1809dd41c1ffc881c0d6b1c16ea38d08894f8b6d
detectron/datasets/json_dataset.py
python
JsonDataset._get_gt_keypoints
(self, obj)
return gt_kps
Return ground truth keypoints.
Return ground truth keypoints.
[ "Return", "ground", "truth", "keypoints", "." ]
def _get_gt_keypoints(self, obj): """Return ground truth keypoints.""" if 'keypoints' not in obj: return None kp = np.array(obj['keypoints']) x = kp[0::3] # 0-indexed x coordinates y = kp[1::3] # 0-indexed y coordinates # 0: not labeled; 1: labeled, not inside mask; # 2: labeled and inside mask v = kp[2::3] num_keypoints = len(obj['keypoints']) / 3 assert num_keypoints == self.num_keypoints gt_kps = np.ones((3, self.num_keypoints), dtype=np.int32) for i in range(self.num_keypoints): gt_kps[0, i] = x[i] gt_kps[1, i] = y[i] gt_kps[2, i] = v[i] return gt_kps
[ "def", "_get_gt_keypoints", "(", "self", ",", "obj", ")", ":", "if", "'keypoints'", "not", "in", "obj", ":", "return", "None", "kp", "=", "np", ".", "array", "(", "obj", "[", "'keypoints'", "]", ")", "x", "=", "kp", "[", "0", ":", ":", "3", "]", ...
https://github.com/facebookresearch/Detectron/blob/1809dd41c1ffc881c0d6b1c16ea38d08894f8b6d/detectron/datasets/json_dataset.py#L311-L328
ahmetcemturan/SFACT
7576e29ba72b33e5058049b77b7b558875542747
fabmetheus_utilities/geometry/solids/triangle_mesh.py
python
getIsPathEntirelyOutsideTriangle
(begin, center, end, vector3Path)
return True
Determine if a path is entirely outside another loop.
Determine if a path is entirely outside another loop.
[ "Determine", "if", "a", "path", "is", "entirely", "outside", "another", "loop", "." ]
def getIsPathEntirelyOutsideTriangle(begin, center, end, vector3Path): 'Determine if a path is entirely outside another loop.' loop = [begin.dropAxis(), center.dropAxis(), end.dropAxis()] for vector3 in vector3Path: point = vector3.dropAxis() if euclidean.isPointInsideLoop(loop, point): return False return True
[ "def", "getIsPathEntirelyOutsideTriangle", "(", "begin", ",", "center", ",", "end", ",", "vector3Path", ")", ":", "loop", "=", "[", "begin", ".", "dropAxis", "(", ")", ",", "center", ".", "dropAxis", "(", ")", ",", "end", ".", "dropAxis", "(", ")", "]"...
https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/fabmetheus_utilities/geometry/solids/triangle_mesh.py#L405-L412
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/Jinja2/jinja2/filters.py
python
do_forceescape
(value)
return escape(text_type(value))
Enforce HTML escaping. This will probably double escape variables.
Enforce HTML escaping. This will probably double escape variables.
[ "Enforce", "HTML", "escaping", ".", "This", "will", "probably", "double", "escape", "variables", "." ]
def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(text_type(value))
[ "def", "do_forceescape", "(", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'__html__'", ")", ":", "value", "=", "value", ".", "__html__", "(", ")", "return", "escape", "(", "text_type", "(", "value", ")", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/Jinja2/jinja2/filters.py#L73-L77
hangoutsbot/hangoutsbot
aabe1059d5873f53691e28c19273277817fb34ba
hangupsbot/plugins/_example/example_memory.py
python
forgetchat
(bot, event, *args)
forget stored value for current conversation
forget stored value for current conversation
[ "forget", "stored", "value", "for", "current", "conversation" ]
def forgetchat(bot, event, *args): """forget stored value for current conversation""" text = bot.conversation_memory_get(event.conv_id, 'test_memory') if text is None: yield from bot.coro_send_message( event.conv, _("<b>{}</b>, nothing to forget for this conversation!").format( event.user.full_name)) else: bot.conversation_memory_set(event.conv_id, 'test_memory', None) yield from bot.coro_send_message( event.conv, _("<b>{}</b>, forgotten for this conversation!").format( event.user.full_name))
[ "def", "forgetchat", "(", "bot", ",", "event", ",", "*", "args", ")", ":", "text", "=", "bot", ".", "conversation_memory_get", "(", "event", ".", "conv_id", ",", "'test_memory'", ")", "if", "text", "is", "None", ":", "yield", "from", "bot", ".", "coro_...
https://github.com/hangoutsbot/hangoutsbot/blob/aabe1059d5873f53691e28c19273277817fb34ba/hangupsbot/plugins/_example/example_memory.py#L101-L115
PyMVPA/PyMVPA
76c476b3de8264b0bb849bf226da5674d659564e
mvpa2/generators/partition.py
python
Partitioner._set_selection_strategy
(self, strategy)
Set strategy to select splits out from available
Set strategy to select splits out from available
[ "Set", "strategy", "to", "select", "splits", "out", "from", "available" ]
def _set_selection_strategy(self, strategy): """Set strategy to select splits out from available """ strategy = strategy.lower() if not strategy in self._STRATEGIES: raise ValueError( "selection_strategy is not known. Known are %s" % str(self._STRATEGIES) ) self.__selection_strategy = strategy
[ "def", "_set_selection_strategy", "(", "self", ",", "strategy", ")", ":", "strategy", "=", "strategy", ".", "lower", "(", ")", "if", "not", "strategy", "in", "self", ".", "_STRATEGIES", ":", "raise", "ValueError", "(", "\"selection_strategy is not known. Known are...
https://github.com/PyMVPA/PyMVPA/blob/76c476b3de8264b0bb849bf226da5674d659564e/mvpa2/generators/partition.py#L97-L106
matthewwithanm/django-imagekit
2106b2e159f0d4a538532caca9654d4b0d8d8700
imagekit/templatetags/imagekit.py
python
parse_dimensions
(dimensions)
return {'width': width, 'height': height}
Parse the width and height values from a dimension string. Valid values are '1x1', '1x', and 'x1'. If one of the dimensions is omitted, the parse result will be None for that value.
Parse the width and height values from a dimension string. Valid values are '1x1', '1x', and 'x1'. If one of the dimensions is omitted, the parse result will be None for that value.
[ "Parse", "the", "width", "and", "height", "values", "from", "a", "dimension", "string", ".", "Valid", "values", "are", "1x1", "1x", "and", "x1", ".", "If", "one", "of", "the", "dimensions", "is", "omitted", "the", "parse", "result", "will", "be", "None",...
def parse_dimensions(dimensions): """ Parse the width and height values from a dimension string. Valid values are '1x1', '1x', and 'x1'. If one of the dimensions is omitted, the parse result will be None for that value. """ width, height = [d.strip() and int(d) or None for d in dimensions.split('x')] return {'width': width, 'height': height}
[ "def", "parse_dimensions", "(", "dimensions", ")", ":", "width", ",", "height", "=", "[", "d", ".", "strip", "(", ")", "and", "int", "(", "d", ")", "or", "None", "for", "d", "in", "dimensions", ".", "split", "(", "'x'", ")", "]", "return", "{", "...
https://github.com/matthewwithanm/django-imagekit/blob/2106b2e159f0d4a538532caca9654d4b0d8d8700/imagekit/templatetags/imagekit.py#L25-L33
mlrun/mlrun
4c120719d64327a34b7ee1ab08fb5e01b258b00a
mlrun/frameworks/pytorch/callbacks_handler.py
python
CallbacksHandler.on_validation_metrics_begin
(self, callbacks: List[str] = None)
return self._run_callbacks( method_name=_CallbackInterface.ON_VALIDATION_METRICS_BEGIN, callbacks=self._parse_names(names=callbacks), )
Call the 'on_validation_metrics_begin' method of every callback in the callbacks list. If the list is 'None' (not given), all callbacks will be called. :param callbacks: The callbacks names to use. If 'None', all of the callbacks will be used. :return: True if all of the callbacks called returned True and False if not.
Call the 'on_validation_metrics_begin' method of every callback in the callbacks list. If the list is 'None' (not given), all callbacks will be called.
[ "Call", "the", "on_validation_metrics_begin", "method", "of", "every", "callback", "in", "the", "callbacks", "list", ".", "If", "the", "list", "is", "None", "(", "not", "given", ")", "all", "callbacks", "will", "be", "called", "." ]
def on_validation_metrics_begin(self, callbacks: List[str] = None) -> bool: """ Call the 'on_validation_metrics_begin' method of every callback in the callbacks list. If the list is 'None' (not given), all callbacks will be called. :param callbacks: The callbacks names to use. If 'None', all of the callbacks will be used. :return: True if all of the callbacks called returned True and False if not. """ return self._run_callbacks( method_name=_CallbackInterface.ON_VALIDATION_METRICS_BEGIN, callbacks=self._parse_names(names=callbacks), )
[ "def", "on_validation_metrics_begin", "(", "self", ",", "callbacks", ":", "List", "[", "str", "]", "=", "None", ")", "->", "bool", ":", "return", "self", ".", "_run_callbacks", "(", "method_name", "=", "_CallbackInterface", ".", "ON_VALIDATION_METRICS_BEGIN", ",...
https://github.com/mlrun/mlrun/blob/4c120719d64327a34b7ee1ab08fb5e01b258b00a/mlrun/frameworks/pytorch/callbacks_handler.py#L492-L504
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/gdb/libpython.py
python
PyObjectPtr.proxyval
(self, visited)
return FakeRepr(self.safe_tp_name(), long(self._gdbval))
Scrape a value from the inferior process, and try to represent it within the gdb process, whilst (hopefully) avoiding crashes when the remote data is corrupt. Derived classes will override this. For example, a PyIntObject* with ob_ival 42 in the inferior process should result in an int(42) in this process. visited: a set of all gdb.Value pyobject pointers already visited whilst generating this value (to guard against infinite recursion when visiting object graphs with loops). Analogous to Py_ReprEnter and Py_ReprLeave
Scrape a value from the inferior process, and try to represent it within the gdb process, whilst (hopefully) avoiding crashes when the remote data is corrupt.
[ "Scrape", "a", "value", "from", "the", "inferior", "process", "and", "try", "to", "represent", "it", "within", "the", "gdb", "process", "whilst", "(", "hopefully", ")", "avoiding", "crashes", "when", "the", "remote", "data", "is", "corrupt", "." ]
def proxyval(self, visited): ''' Scrape a value from the inferior process, and try to represent it within the gdb process, whilst (hopefully) avoiding crashes when the remote data is corrupt. Derived classes will override this. For example, a PyIntObject* with ob_ival 42 in the inferior process should result in an int(42) in this process. visited: a set of all gdb.Value pyobject pointers already visited whilst generating this value (to guard against infinite recursion when visiting object graphs with loops). Analogous to Py_ReprEnter and Py_ReprLeave ''' class FakeRepr(object): """ Class representing a non-descript PyObject* value in the inferior process for when we don't have a custom scraper, intended to have a sane repr(). """ def __init__(self, tp_name, address): self.tp_name = tp_name self.address = address def __repr__(self): # For the NULL pointer, we have no way of knowing a type, so # special-case it as per # http://bugs.python.org/issue8032#msg100882 if self.address == 0: return '0x0' return '<%s at remote 0x%x>' % (self.tp_name, self.address) return FakeRepr(self.safe_tp_name(), long(self._gdbval))
[ "def", "proxyval", "(", "self", ",", "visited", ")", ":", "class", "FakeRepr", "(", "object", ")", ":", "\"\"\"\n Class representing a non-descript PyObject* value in the inferior\n process for when we don't have a custom scraper, intended to have\n a san...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/gdb/libpython.py#L229-L266
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/markdown/blockparser.py
python
State.isstate
(self, state)
Test that top (current) level is of given state.
Test that top (current) level is of given state.
[ "Test", "that", "top", "(", "current", ")", "level", "is", "of", "given", "state", "." ]
def isstate(self, state): """ Test that top (current) level is of given state. """ if len(self): return self[-1] == state else: return False
[ "def", "isstate", "(", "self", ",", "state", ")", ":", "if", "len", "(", "self", ")", ":", "return", "self", "[", "-", "1", "]", "==", "state", "else", ":", "return", "False" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/markdown/blockparser.py#L31-L36
johntruckenbrodt/pyroSAR
efac51134ba42d20120b259f968afe5a4ddcc46a
pyroSAR/gamma/parser_demo.py
python
az_integrate
(data, width, azi, cflg, scale='-', lz='-', logpath=None, outdir=None, shellscript=None)
| Calculate azimuth integral of float data (unwrapped phase or azimuth offsets) | Copyright 2012, Gamma Remote Sensing, v1.2 6-Feb-2012 Parameters ---------- data: (input) input data (example: SBI dtrapped phase) (float) width: (input) number of range samples/line azi: (output) input data integrated along azimuth (float) cflg: integration constant flag: * 0: set azimuth integral value to 0.0 at specified line * 1: set average of the azimuth integral to 0.0 scale: scale factor to apply to the data (enter - for default, default: 1.0) lz: line offset where the azimuth integral is set to 0.0 (cflg = 0, enter - for default, default: 0) logpath: str or None a directory to write command logfiles to outdir: str or None the directory to execute the command in shellscript: str or None a file to write the Gamma commands to in shell format
| Calculate azimuth integral of float data (unwrapped phase or azimuth offsets) | Copyright 2012, Gamma Remote Sensing, v1.2 6-Feb-2012
[ "|", "Calculate", "azimuth", "integral", "of", "float", "data", "(", "unwrapped", "phase", "or", "azimuth", "offsets", ")", "|", "Copyright", "2012", "Gamma", "Remote", "Sensing", "v1", ".", "2", "6", "-", "Feb", "-", "2012" ]
def az_integrate(data, width, azi, cflg, scale='-', lz='-', logpath=None, outdir=None, shellscript=None): """ | Calculate azimuth integral of float data (unwrapped phase or azimuth offsets) | Copyright 2012, Gamma Remote Sensing, v1.2 6-Feb-2012 Parameters ---------- data: (input) input data (example: SBI dtrapped phase) (float) width: (input) number of range samples/line azi: (output) input data integrated along azimuth (float) cflg: integration constant flag: * 0: set azimuth integral value to 0.0 at specified line * 1: set average of the azimuth integral to 0.0 scale: scale factor to apply to the data (enter - for default, default: 1.0) lz: line offset where the azimuth integral is set to 0.0 (cflg = 0, enter - for default, default: 0) logpath: str or None a directory to write command logfiles to outdir: str or None the directory to execute the command in shellscript: str or None a file to write the Gamma commands to in shell format """ process(['/usr/local/GAMMA_SOFTWARE-20180703/ISP/bin/az_integrate', data, width, azi, cflg, scale, lz], logpath=logpath, outdir=outdir, shellscript=shellscript)
[ "def", "az_integrate", "(", "data", ",", "width", ",", "azi", ",", "cflg", ",", "scale", "=", "'-'", ",", "lz", "=", "'-'", ",", "logpath", "=", "None", ",", "outdir", "=", "None", ",", "shellscript", "=", "None", ")", ":", "process", "(", "[", "...
https://github.com/johntruckenbrodt/pyroSAR/blob/efac51134ba42d20120b259f968afe5a4ddcc46a/pyroSAR/gamma/parser_demo.py#L229-L259
python-trio/trio
4edfd41bd5519a2e626e87f6c6ca9fb32b90a6f4
trio/_subprocess_platform/__init__.py
python
wait_child_exiting
(process: "_subprocess.Process")
Block until the child process managed by ``process`` is exiting. It is invalid to call this function if the process has already been waited on; that is, ``process.returncode`` must be None. When this function returns, it indicates that a call to :meth:`subprocess.Popen.wait` will immediately be able to return the process's exit status. The actual exit status is not consumed by this call, since :class:`~subprocess.Popen` wants to be able to do that itself.
Block until the child process managed by ``process`` is exiting.
[ "Block", "until", "the", "child", "process", "managed", "by", "process", "is", "exiting", "." ]
async def wait_child_exiting(process: "_subprocess.Process") -> None: """Block until the child process managed by ``process`` is exiting. It is invalid to call this function if the process has already been waited on; that is, ``process.returncode`` must be None. When this function returns, it indicates that a call to :meth:`subprocess.Popen.wait` will immediately be able to return the process's exit status. The actual exit status is not consumed by this call, since :class:`~subprocess.Popen` wants to be able to do that itself. """ raise NotImplementedError from _wait_child_exiting_error
[ "async", "def", "wait_child_exiting", "(", "process", ":", "\"_subprocess.Process\"", ")", "->", "None", ":", "raise", "NotImplementedError", "from", "_wait_child_exiting_error" ]
https://github.com/python-trio/trio/blob/4edfd41bd5519a2e626e87f6c6ca9fb32b90a6f4/trio/_subprocess_platform/__init__.py#L29-L41
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/analytics/tasks.py
python
update_hubspot_properties
(webuser, properties)
[]
def update_hubspot_properties(webuser, properties): vid = _get_user_hubspot_id(webuser) if vid: _track_on_hubspot(webuser, properties)
[ "def", "update_hubspot_properties", "(", "webuser", ",", "properties", ")", ":", "vid", "=", "_get_user_hubspot_id", "(", "webuser", ")", "if", "vid", ":", "_track_on_hubspot", "(", "webuser", ",", "properties", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/analytics/tasks.py#L288-L291
aws/serverless-application-model
ab6943a340a3f489af62b8c70c1366242b2887fe
samtranslator/plugins/globals/globals.py
python
Globals.del_section
(cls, template)
Helper method to delete the Globals section altogether from the template :param dict template: SAM template :return: Modified SAM template with Globals section
Helper method to delete the Globals section altogether from the template
[ "Helper", "method", "to", "delete", "the", "Globals", "section", "altogether", "from", "the", "template" ]
def del_section(cls, template): """ Helper method to delete the Globals section altogether from the template :param dict template: SAM template :return: Modified SAM template with Globals section """ if cls._KEYWORD in template: del template[cls._KEYWORD]
[ "def", "del_section", "(", "cls", ",", "template", ")", ":", "if", "cls", ".", "_KEYWORD", "in", "template", ":", "del", "template", "[", "cls", ".", "_KEYWORD", "]" ]
https://github.com/aws/serverless-application-model/blob/ab6943a340a3f489af62b8c70c1366242b2887fe/samtranslator/plugins/globals/globals.py#L120-L129
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/_abcoll.py
python
Mapping.itervalues
(self)
D.itervalues() -> an iterator over the values of D
D.itervalues() -> an iterator over the values of D
[ "D", ".", "itervalues", "()", "-", ">", "an", "iterator", "over", "the", "values", "of", "D" ]
def itervalues(self): 'D.itervalues() -> an iterator over the values of D' for key in self: yield self[key]
[ "def", "itervalues", "(", "self", ")", ":", "for", "key", "in", "self", ":", "yield", "self", "[", "key", "]" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/_abcoll.py#L398-L401
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/fabmetheus_utilities/svg_writer.py
python
SVGWriter.getRounded
(self, number)
return euclidean.getRoundedToPlacesString(self.decimalPlacesCarried, number)
Get number rounded to the number of carried decimal places as a string.
Get number rounded to the number of carried decimal places as a string.
[ "Get", "number", "rounded", "to", "the", "number", "of", "carried", "decimal", "places", "as", "a", "string", "." ]
def getRounded(self, number): 'Get number rounded to the number of carried decimal places as a string.' return euclidean.getRoundedToPlacesString(self.decimalPlacesCarried, number)
[ "def", "getRounded", "(", "self", ",", "number", ")", ":", "return", "euclidean", ".", "getRoundedToPlacesString", "(", "self", ".", "decimalPlacesCarried", ",", "number", ")" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/svg_writer.py#L228-L230
Epistimio/orion
732e739d99561020dbe620760acf062ade746006
src/orion/core/io/interactive_commands/branching_prompt.py
python
BranchingPrompt.complete_rename
(self, text, line, begidx, endidx)
return self._get_completions(names, text)
Auto-complete rename based on non-resolved missing dimensions and new dimensions conflicts
Auto-complete rename based on non-resolved missing dimensions and new dimensions conflicts
[ "Auto", "-", "complete", "rename", "based", "on", "non", "-", "resolved", "missing", "dimensions", "and", "new", "dimensions", "conflicts" ]
def complete_rename(self, text, line, begidx, endidx): """Auto-complete rename based on non-resolved missing dimensions and new dimensions conflicts """ if len(line.split(" ")) < 3: potential_conflicts = self.branch_builder.conflicts.get_remaining( [conflicts.MissingDimensionConflict] ) elif len(line.split(" ")) == 3: potential_conflicts = self.branch_builder.conflicts.get_remaining( [conflicts.NewDimensionConflict] ) else: potential_conflicts = [] names = [ conflict.dimension.name.lstrip("/") for conflict in potential_conflicts ] return self._get_completions(names, text)
[ "def", "complete_rename", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "if", "len", "(", "line", ".", "split", "(", "\" \"", ")", ")", "<", "3", ":", "potential_conflicts", "=", "self", ".", "branch_builder", ".", "c...
https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/core/io/interactive_commands/branching_prompt.py#L487-L506
dask/dask-searchcv
57c82ec138c16ad0c3a6b05372a08819cffbe0d2
dask_searchcv/methods.py
python
feature_union_concat
(Xs, nsamples, weights)
return np.hstack(Xs)
Apply weights and concatenate outputs from a FeatureUnion
Apply weights and concatenate outputs from a FeatureUnion
[ "Apply", "weights", "and", "concatenate", "outputs", "from", "a", "FeatureUnion" ]
def feature_union_concat(Xs, nsamples, weights): """Apply weights and concatenate outputs from a FeatureUnion""" if any(x is FIT_FAILURE for x in Xs): return FIT_FAILURE Xs = [X if w is None else X * w for X, w in zip(Xs, weights) if X is not None] if not Xs: return np.zeros((nsamples, 0)) if any(sparse.issparse(f) for f in Xs): return sparse.hstack(Xs).tocsr() return np.hstack(Xs)
[ "def", "feature_union_concat", "(", "Xs", ",", "nsamples", ",", "weights", ")", ":", "if", "any", "(", "x", "is", "FIT_FAILURE", "for", "x", "in", "Xs", ")", ":", "return", "FIT_FAILURE", "Xs", "=", "[", "X", "if", "w", "is", "None", "else", "X", "...
https://github.com/dask/dask-searchcv/blob/57c82ec138c16ad0c3a6b05372a08819cffbe0d2/dask_searchcv/methods.py#L177-L187
dagster-io/dagster
b27d569d5fcf1072543533a0c763815d96f90b8f
python_modules/dagster/dagster/serdes/serdes.py
python
deserialize_value
(val: str, whitelist_map: WhitelistMap = _WHITELIST_MAP)
return unpack_inner_value( seven.json.loads(check.str_param(val, "val")), whitelist_map=whitelist_map, descent_path="", )
Deserialize a json encoded string in to its original value
Deserialize a json encoded string in to its original value
[ "Deserialize", "a", "json", "encoded", "string", "in", "to", "its", "original", "value" ]
def deserialize_value(val: str, whitelist_map: WhitelistMap = _WHITELIST_MAP) -> Any: """Deserialize a json encoded string in to its original value""" return unpack_inner_value( seven.json.loads(check.str_param(val, "val")), whitelist_map=whitelist_map, descent_path="", )
[ "def", "deserialize_value", "(", "val", ":", "str", ",", "whitelist_map", ":", "WhitelistMap", "=", "_WHITELIST_MAP", ")", "->", "Any", ":", "return", "unpack_inner_value", "(", "seven", ".", "json", ".", "loads", "(", "check", ".", "str_param", "(", "val", ...
https://github.com/dagster-io/dagster/blob/b27d569d5fcf1072543533a0c763815d96f90b8f/python_modules/dagster/dagster/serdes/serdes.py#L407-L413
mandiant/flashmingo
bb905ff757805a5a832977d44991152c8aa8771a
flashmingo/Flashmingo.py
python
Flashmingo._init_core
(self)
Initializes the core functionality - Logging (rotating file) - Configuration (read from cfg.yml) - Plugin system
Initializes the core functionality
[ "Initializes", "the", "core", "functionality" ]
def _init_core(self): """Initializes the core functionality - Logging (rotating file) - Configuration (read from cfg.yml) - Plugin system """ if not self.ml: # No external logging facility # Flashmingo will use its own self.ml = self._init_logging() if not self.ml: print("Failed to initialize logging. Exiting...") sys.exit(1) self.cfg = self._read_config() if not self.cfg: self.ml.error('Failed to open the configuration file. Exiting...') sys.exit(1) self._register_plugins()
[ "def", "_init_core", "(", "self", ")", ":", "if", "not", "self", ".", "ml", ":", "# No external logging facility", "# Flashmingo will use its own", "self", ".", "ml", "=", "self", ".", "_init_logging", "(", ")", "if", "not", "self", ".", "ml", ":", "print", ...
https://github.com/mandiant/flashmingo/blob/bb905ff757805a5a832977d44991152c8aa8771a/flashmingo/Flashmingo.py#L37-L59
ctxis/CAPE
dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82
modules/machinery/vmwarerest.py
python
VMwareREST._initialize_check
(self)
Check for configuration file and vmware setup. @raise CuckooMachineError: if configuration is missing or wrong.
Check for configuration file and vmware setup.
[ "Check", "for", "configuration", "file", "and", "vmware", "setup", "." ]
def _initialize_check(self): """Check for configuration file and vmware setup. @raise CuckooMachineError: if configuration is missing or wrong. """ if not self.options.vmwarerest.host: raise CuckooMachineError("VMwareREST hostname/IP address missing, " "please add it to vmwarerest.conf") self.host = self.options.vmwarerest.host if not self.options.vmwarerest.port: raise CuckooMachineError("VMwareREST server port address missing, " "please add it to vmwarerest.conf") self.port = str(self.options.vmwarerest.port) if not self.options.vmwarerest.username: raise CuckooMachineError("VMwareREST username missing, " "please add it to vmwarerest.conf") self.username = self.options.vmwarerest.username if not self.options.vmwarerest.password: raise CuckooMachineError("VMwareREST password missing, " "please add it to vmwarerest.conf") self.password = self.options.vmwarerest.password super(VMwareREST, self)._initialize_check() log.info("VMwareREST machinery module initialised (%s:%s).", self.host, self.port)
[ "def", "_initialize_check", "(", "self", ")", ":", "if", "not", "self", ".", "options", ".", "vmwarerest", ".", "host", ":", "raise", "CuckooMachineError", "(", "\"VMwareREST hostname/IP address missing, \"", "\"please add it to vmwarerest.conf\"", ")", "self", ".", "...
https://github.com/ctxis/CAPE/blob/dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82/modules/machinery/vmwarerest.py#L20-L43
pytorch/audio
7b6b2d000023e2aa3365b769866c5f375e0d5fda
torchaudio/transforms.py
python
SpectralCentroid.forward
(self, waveform: Tensor)
return F.spectral_centroid( waveform, self.sample_rate, self.pad, self.window, self.n_fft, self.hop_length, self.win_length )
r""" Args: waveform (Tensor): Tensor of audio of dimension `(..., time)`. Returns: Tensor: Spectral Centroid of size `(..., time)`.
r""" Args: waveform (Tensor): Tensor of audio of dimension `(..., time)`.
[ "r", "Args", ":", "waveform", "(", "Tensor", ")", ":", "Tensor", "of", "audio", "of", "dimension", "(", "...", "time", ")", "." ]
def forward(self, waveform: Tensor) -> Tensor: r""" Args: waveform (Tensor): Tensor of audio of dimension `(..., time)`. Returns: Tensor: Spectral Centroid of size `(..., time)`. """ return F.spectral_centroid( waveform, self.sample_rate, self.pad, self.window, self.n_fft, self.hop_length, self.win_length )
[ "def", "forward", "(", "self", ",", "waveform", ":", "Tensor", ")", "->", "Tensor", ":", "return", "F", ".", "spectral_centroid", "(", "waveform", ",", "self", ".", "sample_rate", ",", "self", ".", "pad", ",", "self", ".", "window", ",", "self", ".", ...
https://github.com/pytorch/audio/blob/7b6b2d000023e2aa3365b769866c5f375e0d5fda/torchaudio/transforms.py#L1442-L1453
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/codeintel/play/core.py
python
GridBagSizer.CheckForIntersection
(*args)
return _core.GridBagSizer_CheckForIntersection(*args)
CheckForIntersection(GBSizerItem item, GBSizerItem excludeItem=None) -> bool CheckForIntersection(GBPosition pos, GBSpan span, GBSizerItem excludeItem=None) -> bool
CheckForIntersection(GBSizerItem item, GBSizerItem excludeItem=None) -> bool CheckForIntersection(GBPosition pos, GBSpan span, GBSizerItem excludeItem=None) -> bool
[ "CheckForIntersection", "(", "GBSizerItem", "item", "GBSizerItem", "excludeItem", "=", "None", ")", "-", ">", "bool", "CheckForIntersection", "(", "GBPosition", "pos", "GBSpan", "span", "GBSizerItem", "excludeItem", "=", "None", ")", "-", ">", "bool" ]
def CheckForIntersection(*args): """ CheckForIntersection(GBSizerItem item, GBSizerItem excludeItem=None) -> bool CheckForIntersection(GBPosition pos, GBSpan span, GBSizerItem excludeItem=None) -> bool """ return _core.GridBagSizer_CheckForIntersection(*args)
[ "def", "CheckForIntersection", "(", "*", "args", ")", ":", "return", "_core", ".", "GridBagSizer_CheckForIntersection", "(", "*", "args", ")" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/play/core.py#L8984-L8989
GoSecure/pyrdp
abd8b8762b6d7fd0e49d4a927b529f892b412743
pyrdp/parser/x224.py
python
X224Parser.writeError
(self, stream: BytesIO, pdu: X224ErrorPDU)
Write an error PDU onto the provided stream
Write an error PDU onto the provided stream
[ "Write", "an", "error", "PDU", "onto", "the", "provided", "stream" ]
def writeError(self, stream: BytesIO, pdu: X224ErrorPDU): """ Write an error PDU onto the provided stream """ stream.write(Uint8.pack(pdu.header)) stream.write(Uint16LE.pack(pdu.destination)) stream.write(Uint8.pack(pdu.cause))
[ "def", "writeError", "(", "self", ",", "stream", ":", "BytesIO", ",", "pdu", ":", "X224ErrorPDU", ")", ":", "stream", ".", "write", "(", "Uint8", ".", "pack", "(", "pdu", ".", "header", ")", ")", "stream", ".", "write", "(", "Uint16LE", ".", "pack", ...
https://github.com/GoSecure/pyrdp/blob/abd8b8762b6d7fd0e49d4a927b529f892b412743/pyrdp/parser/x224.py#L207-L213
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/nltk/sem/util.py
python
root_semrep
(syntree, semkey="SEM")
Find the semantic representation at the root of a tree. :param syntree: a parse ``Tree`` :param semkey: the feature label to use for the root semantics in the tree :return: the semantic representation at the root of a ``Tree`` :rtype: sem.Expression
Find the semantic representation at the root of a tree.
[ "Find", "the", "semantic", "representation", "at", "the", "root", "of", "a", "tree", "." ]
def root_semrep(syntree, semkey="SEM"): """ Find the semantic representation at the root of a tree. :param syntree: a parse ``Tree`` :param semkey: the feature label to use for the root semantics in the tree :return: the semantic representation at the root of a ``Tree`` :rtype: sem.Expression """ from nltk.grammar import FeatStructNonterminal node = syntree.label() assert isinstance(node, FeatStructNonterminal) try: return node[semkey] except KeyError: print(node, end=" ") print("has no specification for the feature %s" % semkey) raise
[ "def", "root_semrep", "(", "syntree", ",", "semkey", "=", "\"SEM\"", ")", ":", "from", "nltk", ".", "grammar", "import", "FeatStructNonterminal", "node", "=", "syntree", ".", "label", "(", ")", "assert", "isinstance", "(", "node", ",", "FeatStructNonterminal",...
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/sem/util.py#L52-L70
dbt-labs/dbt-core
e943b9fc842535e958ef4fd0b8703adc91556bc6
core/dbt/parser/schemas.py
python
ParserRef.from_target
( cls, target: Union[HasColumnDocs, HasColumnTests] )
return refs
[]
def from_target( cls, target: Union[HasColumnDocs, HasColumnTests] ) -> 'ParserRef': refs = cls() for column in target.columns: description = column.description data_type = column.data_type meta = column.meta refs.add(column, description, data_type, meta) return refs
[ "def", "from_target", "(", "cls", ",", "target", ":", "Union", "[", "HasColumnDocs", ",", "HasColumnTests", "]", ")", "->", "'ParserRef'", ":", "refs", "=", "cls", "(", ")", "for", "column", "in", "target", ".", "columns", ":", "description", "=", "colum...
https://github.com/dbt-labs/dbt-core/blob/e943b9fc842535e958ef4fd0b8703adc91556bc6/core/dbt/parser/schemas.py#L150-L159
magenta/magenta
be6558f1a06984faff6d6949234f5fe9ad0ffdb5
magenta/models/coconet/lib_evaluation.py
python
_statstr
(x)
return ("mean/sem: {mean:8.5f}+-{sem:8.5f} {min:.5f} < {q1:.5f} < {q2:.5f} < " "{q3:.5f} < {max:.5g}").format(**_stats(x))
[]
def _statstr(x): return ("mean/sem: {mean:8.5f}+-{sem:8.5f} {min:.5f} < {q1:.5f} < {q2:.5f} < " "{q3:.5f} < {max:.5g}").format(**_stats(x))
[ "def", "_statstr", "(", "x", ")", ":", "return", "(", "\"mean/sem: {mean:8.5f}+-{sem:8.5f} {min:.5f} < {q1:.5f} < {q2:.5f} < \"", "\"{q3:.5f} < {max:.5g}\"", ")", ".", "format", "(", "*", "*", "_stats", "(", "x", ")", ")" ]
https://github.com/magenta/magenta/blob/be6558f1a06984faff6d6949234f5fe9ad0ffdb5/magenta/models/coconet/lib_evaluation.py#L87-L89
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.py
python
_IndividualSpecifier.operator
(self)
return self._spec[0]
[]
def operator(self): return self._spec[0]
[ "def", "operator", "(", "self", ")", ":", "return", "self", ".", "_spec", "[", "0", "]" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.py#L145-L146
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/pyasn1/type/constraint.py
python
ComponentPresentConstraint._setValues
(self, values)
[]
def _setValues(self, values): self._values = ('<must be present>',) if values: raise error.PyAsn1Error('No arguments expected')
[ "def", "_setValues", "(", "self", ",", "values", ")", ":", "self", ".", "_values", "=", "(", "'<must be present>'", ",", ")", "if", "values", ":", "raise", "error", ".", "PyAsn1Error", "(", "'No arguments expected'", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/pyasn1/type/constraint.py#L428-L432
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
kube_apiserver_metrics/datadog_checks/kube_apiserver_metrics/config_models/defaults.py
python
instance_ntlm_domain
(field, value)
return get_default_field_value(field, value)
[]
def instance_ntlm_domain(field, value): return get_default_field_value(field, value)
[ "def", "instance_ntlm_domain", "(", "field", ",", "value", ")", ":", "return", "get_default_field_value", "(", "field", ",", "value", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/kube_apiserver_metrics/datadog_checks/kube_apiserver_metrics/config_models/defaults.py#L161-L162
egtwobits/mesh_mesh_align_plus
c6b39f4e163ed897de177c08d2c5f4ac205f9fa9
mesh_mesh_align_plus/align_planes.py
python
MAPLUS_PT_QuickAlignPlanesGUI.draw
(self, context)
[]
def draw(self, context): layout = self.layout maplus_data_ptr = bpy.types.AnyType(bpy.context.scene.maplus_data) addon_data = bpy.context.scene.maplus_data prims = addon_data.prim_list apl_top = layout.row() apl_gui = layout.box() apl_top.label( text="Align Planes", icon="MOD_ARRAY" ) apl_grab_col = apl_gui.column() apl_grab_col.prop( addon_data, 'quick_align_planes_auto_grab_src', text='Auto Grab Source from Selected Vertices' ) apl_src_geom_top = apl_grab_col.row(align=True) if not addon_data.quick_align_planes_auto_grab_src: if not addon_data.quick_apl_show_src_geom: apl_src_geom_top.operator( "maplus.showhidequickaplsrcgeom", icon='TRIA_RIGHT', text="", emboss=False ) preserve_button_roundedge = apl_src_geom_top.row() preserve_button_roundedge.operator( "maplus.quickalignplanesgrabsrc", icon='OUTLINER_OB_MESH', text="Grab Source" ) else: apl_src_geom_top.operator( "maplus.showhidequickaplsrcgeom", icon='TRIA_DOWN', text="", emboss=False ) apl_src_geom_top.label( text="Source Coordinates", icon="OUTLINER_OB_MESH" ) apl_src_geom_editor = apl_grab_col.box() plane_grab_all = apl_src_geom_editor.row(align=True) plane_grab_all.operator( "maplus.quickalignplanesgrabsrcloc", icon='VERTEXSEL', text="Grab All Local" ) plane_grab_all.operator( "maplus.quickalignplanesgrabsrc", icon='WORLD', text="Grab All Global" ) special_grabs = apl_src_geom_editor.row(align=True) special_grabs.operator( "maplus.copyfromaplsrc", icon='COPYDOWN', text="Copy (To Clipboard)" ) special_grabs.operator( "maplus.pasteintoaplsrc", icon='PASTEDOWN', text="Paste (From Clipboard)" ) maplus_guitools.layout_coordvec( parent_layout=apl_src_geom_editor, coordvec_label="Pt. A:", op_id_cursor_grab=( "maplus.quickaplsrcgrabplaneafromcursor" ), op_id_avg_grab=( "maplus.quickaplgrabavgsrcplanea" ), op_id_local_grab=( "maplus.quickaplsrcgrabplaneafromactivelocal" ), op_id_global_grab=( "maplus.quickaplsrcgrabplaneafromactiveglobal" ), coord_container=addon_data.quick_align_planes_src, coord_attribute="plane_pt_a", op_id_cursor_send=( "maplus.quickaplsrcsendplaneatocursor" ), op_id_text_tuple_swap_first=( "maplus.quickaplsrcswapplaneaplaneb", "B" ), op_id_text_tuple_swap_second=( "maplus.quickaplsrcswapplaneaplanec", "C" ) ) maplus_guitools.layout_coordvec( parent_layout=apl_src_geom_editor, coordvec_label="Pt. B:", op_id_cursor_grab=( "maplus.quickaplsrcgrabplanebfromcursor" ), op_id_avg_grab=( "maplus.quickaplgrabavgsrcplaneb" ), op_id_local_grab=( "maplus.quickaplsrcgrabplanebfromactivelocal" ), op_id_global_grab=( "maplus.quickaplsrcgrabplanebfromactiveglobal" ), coord_container=addon_data.quick_align_planes_src, coord_attribute="plane_pt_b", op_id_cursor_send=( "maplus.quickaplsrcsendplanebtocursor" ), op_id_text_tuple_swap_first=( "maplus.quickaplsrcswapplaneaplaneb", "A" ), op_id_text_tuple_swap_second=( "maplus.quickaplsrcswapplanebplanec", "C" ) ) maplus_guitools.layout_coordvec( parent_layout=apl_src_geom_editor, coordvec_label="Pt. C:", op_id_cursor_grab=( "maplus.quickaplsrcgrabplanecfromcursor" ), op_id_avg_grab=( "maplus.quickaplgrabavgsrcplanec" ), op_id_local_grab=( "maplus.quickaplsrcgrabplanecfromactivelocal" ), op_id_global_grab=( "maplus.quickaplsrcgrabplanecfromactiveglobal" ), coord_container=addon_data.quick_align_planes_src, coord_attribute="plane_pt_c", op_id_cursor_send=( "maplus.quickaplsrcsendplanectocursor" ), op_id_text_tuple_swap_first=( "maplus.quickaplsrcswapplaneaplanec", "A" ), op_id_text_tuple_swap_second=( "maplus.quickaplsrcswapplanebplanec", "B" ) ) if addon_data.quick_apl_show_src_geom: apl_grab_col.separator() apl_dest_geom_top = apl_grab_col.row(align=True) if not addon_data.quick_apl_show_dest_geom: apl_dest_geom_top.operator( "maplus.showhidequickapldestgeom", icon='TRIA_RIGHT', text="", emboss=False ) preserve_button_roundedge = apl_dest_geom_top.row() preserve_button_roundedge.operator( "maplus.quickalignplanesgrabdest", icon='OUTLINER_OB_MESH', text="Grab Destination" ) else: apl_dest_geom_top.operator( "maplus.showhidequickapldestgeom", icon='TRIA_DOWN', text="", emboss=False ) apl_dest_geom_top.label( text="Destination Coordinates", icon="OUTLINER_OB_MESH" ) apl_dest_geom_editor = apl_grab_col.box() plane_grab_all = apl_dest_geom_editor.row(align=True) plane_grab_all.operator( "maplus.quickalignplanesgrabdestloc", icon='VERTEXSEL', text="Grab All Local" ) plane_grab_all.operator( "maplus.quickalignplanesgrabdest", icon='WORLD', text="Grab All Global" ) special_grabs = apl_dest_geom_editor.row(align=True) special_grabs.operator( "maplus.copyfromapldest", icon='COPYDOWN', text="Copy (To Clipboard)" ) special_grabs.operator( "maplus.pasteintoapldest", icon='PASTEDOWN', text="Paste (From Clipboard)" ) maplus_guitools.layout_coordvec( parent_layout=apl_dest_geom_editor, coordvec_label="Pt. A:", op_id_cursor_grab=( "maplus.quickapldestgrabplaneafromcursor" ), op_id_avg_grab=( "maplus.quickaplgrabavgdestplanea" ), op_id_local_grab=( "maplus.quickapldestgrabplaneafromactivelocal" ), op_id_global_grab=( "maplus.quickapldestgrabplaneafromactiveglobal" ), coord_container=addon_data.quick_align_planes_dest, coord_attribute="plane_pt_a", op_id_cursor_send=( "maplus.quickapldestsendplaneatocursor" ), op_id_text_tuple_swap_first=( "maplus.quickapldestswapplaneaplaneb", "B" ), op_id_text_tuple_swap_second=( "maplus.quickapldestswapplaneaplanec", "C" ) ) maplus_guitools.layout_coordvec( parent_layout=apl_dest_geom_editor, coordvec_label="Pt. B:", op_id_cursor_grab=( "maplus.quickapldestgrabplanebfromcursor" ), op_id_avg_grab=( "maplus.quickaplgrabavgdestplaneb" ), op_id_local_grab=( "maplus.quickapldestgrabplanebfromactivelocal" ), op_id_global_grab=( "maplus.quickapldestgrabplanebfromactiveglobal" ), coord_container=addon_data.quick_align_planes_dest, coord_attribute="plane_pt_b", op_id_cursor_send=( "maplus.quickapldestsendplanebtocursor" ), op_id_text_tuple_swap_first=( "maplus.quickapldestswapplaneaplaneb", "A" ), op_id_text_tuple_swap_second=( "maplus.quickapldestswapplanebplanec", "C" ) ) maplus_guitools.layout_coordvec( parent_layout=apl_dest_geom_editor, coordvec_label="Pt. C:", op_id_cursor_grab=( "maplus.quickapldestgrabplanecfromcursor" ), op_id_avg_grab=( "maplus.quickaplgrabavgdestplanec" ), op_id_local_grab=( "maplus.quickapldestgrabplanecfromactivelocal" ), op_id_global_grab=( "maplus.quickapldestgrabplanecfromactiveglobal" ), coord_container=addon_data.quick_align_planes_dest, coord_attribute="plane_pt_c", op_id_cursor_send=( "maplus.quickapldestsendplanectocursor" ), op_id_text_tuple_swap_first=( "maplus.quickapldestswapplaneaplanec", "A" ), op_id_text_tuple_swap_second=( "maplus.quickapldestswapplanebplanec", "B" ) ) apl_gui.label(text="Operator settings:", icon="PREFERENCES") apl_mods = apl_gui.box() apl_mods_row1 = apl_mods.row() apl_mods_row1.prop( addon_data.quick_align_planes_transf, 'apl_flip_normal', text='Flip Normal' ) apl_mods_row1.prop( addon_data.quick_align_planes_transf, 'apl_use_custom_orientation', text='Use Transf. Orientation' ) apl_mods_row2 = apl_mods.row() apl_mods_row2.prop( addon_data.quick_align_planes_transf, 'apl_alternate_pivot', text='Pivot is A' ) apl_gui.prop( addon_data, 'quick_align_planes_set_origin_mode', text='Align origin mode' ) if addon_data.quick_align_planes_set_origin_mode: apl_set_origin_mode_dest_geom_top = apl_gui.row(align=True) if not addon_data.quick_apl_show_set_origin_mode_dest_geom: apl_set_origin_mode_dest_geom_top.operator( "maplus.showhidequickaplsetoriginmodedestgeom", icon='TRIA_RIGHT', text="", emboss=False ) preserve_button_roundedge = apl_set_origin_mode_dest_geom_top.row() preserve_button_roundedge.operator( "maplus.quickalignplanessetoriginmodegrabdest", icon='OUTLINER_OB_MESH', text="Grab Origin" ) else: apl_set_origin_mode_dest_geom_top.operator( "maplus.showhidequickaplsetoriginmodedestgeom", icon='TRIA_DOWN', text="", emboss=False ) apl_set_origin_mode_dest_geom_top.label( text="Origin Coordinates", icon="OUTLINER_OB_MESH" ) apl_set_origin_mode_dest_geom_editor = apl_gui.box() plane_grab_all = apl_set_origin_mode_dest_geom_editor.row(align=True) plane_grab_all.operator( "maplus.quickalignplanessetoriginmodegrabdestloc", icon='VERTEXSEL', text="Grab All Local" ) plane_grab_all.operator( "maplus.quickalignplanessetoriginmodegrabdest", icon='WORLD', text="Grab All Global" ) special_grabs = apl_set_origin_mode_dest_geom_editor.row(align=True) special_grabs.operator( "maplus.copyfromaplsetoriginmodedest", icon='COPYDOWN', text="Copy (To Clipboard)" ) special_grabs.operator( "maplus.pasteintoaplsetoriginmodedest", icon='PASTEDOWN', text="Paste (From Clipboard)" ) maplus_guitools.layout_coordvec( parent_layout=apl_set_origin_mode_dest_geom_editor, coordvec_label="Pt. A:", op_id_cursor_grab=( "maplus.quickaplsetoriginmodedestgrabplaneafromcursor" ), op_id_avg_grab=( "maplus.quickaplsetoriginmodegrabavgdestplanea" ), op_id_local_grab=( "maplus.quickaplsetoriginmodedestgrabplaneafromactivelocal" ), op_id_global_grab=( "maplus.quickaplsetoriginmodedestgrabplaneafromactiveglobal" ), coord_container=addon_data.quick_align_planes_set_origin_mode_dest, coord_attribute="plane_pt_a", op_id_cursor_send=( "maplus.quickaplsetoriginmodedestsendplaneatocursor" ), op_id_text_tuple_swap_first=( "maplus.quickaplsetoriginmodedestswapplaneaplaneb", "B" ), op_id_text_tuple_swap_second=( "maplus.quickaplsetoriginmodedestswapplaneaplanec", "C" ) ) maplus_guitools.layout_coordvec( parent_layout=apl_set_origin_mode_dest_geom_editor, coordvec_label="Pt. B:", op_id_cursor_grab=( "maplus.quickaplsetoriginmodedestgrabplanebfromcursor" ), op_id_avg_grab=( "maplus.quickaplgrabavgsetoriginmodedestplaneb" ), op_id_local_grab=( "maplus.quickaplsetoriginmodedestgrabplanebfromactivelocal" ), op_id_global_grab=( "maplus.quickaplsetoriginmodedestgrabplanebfromactiveglobal" ), coord_container=addon_data.quick_align_planes_set_origin_mode_dest, coord_attribute="plane_pt_b", op_id_cursor_send=( "maplus.quickaplsetoriginmodedestsendplanebtocursor" ), op_id_text_tuple_swap_first=( "maplus.quickaplsetoriginmodedestswapplaneaplaneb", "A" ), op_id_text_tuple_swap_second=( "maplus.quickaplsetoriginmodedestswapplanebplanec", "C" ) ) maplus_guitools.layout_coordvec( parent_layout=apl_set_origin_mode_dest_geom_editor, coordvec_label="Pt. C:", op_id_cursor_grab=( "maplus.quickaplsetoriginmodedestgrabplanecfromcursor" ), op_id_avg_grab=( "maplus.quickaplsetoriginmodegrabavgdestplanec" ), op_id_local_grab=( "maplus.quickaplsetoriginmodedestgrabplanecfromactivelocal" ), op_id_global_grab=( "maplus.quickaplsetoriginmodedestgrabplanecfromactiveglobal" ), coord_container=addon_data.quick_align_planes_set_origin_mode_dest, coord_attribute="plane_pt_c", op_id_cursor_send=( "maplus.quickaplsetoriginmodedestsendplanectocursor" ), op_id_text_tuple_swap_first=( "maplus.quickaplsetoriginmodedestswapplaneaplanec", "A" ), op_id_text_tuple_swap_second=( "maplus.quickaplsetoriginmodedestswapplanebplanec", "B" ) ) apl_set_origin_mode_settings = apl_gui.box() apl_set_origin_sett_row1 = apl_set_origin_mode_settings.row() apl_set_origin_sett_row1.prop( addon_data, 'quick_align_planes_set_origin_mode_alt_pivot', text='Pivot is A' ) apl_apply_header = apl_gui.row() apl_apply_header.label(text="Apply to:") apl_apply_header.prop( addon_data, 'use_experimental', text='Enable Experimental Mesh Ops.' ) apl_apply_items = apl_gui.row() apl_to_object_and_origin = apl_apply_items.column() apl_to_object_and_origin.operator( "maplus.quickalignplanesobject", text="Object" ) apl_to_object_and_origin.operator( "maplus.jjjquickalignplanesobjectorigin", text="Obj. Origin" ) apl_mesh_apply_items = apl_apply_items.column(align=True) apl_mesh_apply_items.operator( "maplus.quickalignplanesmeshselected", text="Mesh Piece" ) apl_mesh_apply_items.operator( "maplus.quickalignplaneswholemesh", text="Whole Mesh" ) # Disable relevant items depending on whether set origin mode # is enabled or not if addon_data.quick_align_planes_set_origin_mode: apl_grab_col.enabled = False apl_mods.enabled = False
[ "def", "draw", "(", "self", ",", "context", ")", ":", "layout", "=", "self", ".", "layout", "maplus_data_ptr", "=", "bpy", ".", "types", ".", "AnyType", "(", "bpy", ".", "context", ".", "scene", ".", "maplus_data", ")", "addon_data", "=", "bpy", ".", ...
https://github.com/egtwobits/mesh_mesh_align_plus/blob/c6b39f4e163ed897de177c08d2c5f4ac205f9fa9/mesh_mesh_align_plus/align_planes.py#L696-L1204
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/mixture.py
python
Mixture.Cpsms
(self)
return [i.Cpsm for i in self.Chemicals]
r'''Solid-phase pure component heat capacity of the chemicals in the mixture at its current temperature, in units of [J/mol/K]. Examples -------- >>> Mixture(['benzene', 'toluene'], ws=[0.5, 0.5], T=320).Cpsms [109.77384365511931, 135.22614707678474]
r'''Solid-phase pure component heat capacity of the chemicals in the mixture at its current temperature, in units of [J/mol/K].
[ "r", "Solid", "-", "phase", "pure", "component", "heat", "capacity", "of", "the", "chemicals", "in", "the", "mixture", "at", "its", "current", "temperature", "in", "units", "of", "[", "J", "/", "mol", "/", "K", "]", "." ]
def Cpsms(self): r'''Solid-phase pure component heat capacity of the chemicals in the mixture at its current temperature, in units of [J/mol/K]. Examples -------- >>> Mixture(['benzene', 'toluene'], ws=[0.5, 0.5], T=320).Cpsms [109.77384365511931, 135.22614707678474] ''' return [i.Cpsm for i in self.Chemicals]
[ "def", "Cpsms", "(", "self", ")", ":", "return", "[", "i", ".", "Cpsm", "for", "i", "in", "self", ".", "Chemicals", "]" ]
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/mixture.py#L1639-L1648
bungnoid/glTools
8ff0899de43784a18bd4543285655e68e28fb5e5
rig/mocapOverride.py
python
getOverrideConstraint
(control)
return list(set(overrideConstraint))
Return the mocap override constraint(s) for the specified control. @param control: The control to get the mocap override constraint for. @type control: list
Return the mocap override constraint(s) for the specified control.
[ "Return", "the", "mocap", "override", "constraint", "(", "s", ")", "for", "the", "specified", "control", "." ]
def getOverrideConstraint(control): ''' Return the mocap override constraint(s) for the specified control. @param control: The control to get the mocap override constraint for. @type control: list ''' # Check Control if not mc.objExists(control): raise Exception('Rig control transform "'+control+'" does not exist!') # Override Enable Attribute overrideAttr = overrideAttribute() if not mc.objExists(control+'.'+overrideAttr): raise Exception('OverrideEnable attribute "'+control+'.'+overrideAttr+'" does not exist!') # Override Constraint overrideConstraint = mc.listConnections(control+'.'+overrideAttr,s=False,d=True) if not overrideConstraint: raise Exception('Override constraint could not be determined from overrideEnabled attribute "'+control+'.'+overrideAttr+'"!') overrideConstraint = mc.ls(overrideConstraint,type='constraint') if not overrideConstraint: raise Exception('Override constraint could not be determined from overrideEnabled attribute "'+control+'.'+overrideAttr+'"!') # Return Result return list(set(overrideConstraint))
[ "def", "getOverrideConstraint", "(", "control", ")", ":", "# Check Control", "if", "not", "mc", ".", "objExists", "(", "control", ")", ":", "raise", "Exception", "(", "'Rig control transform \"'", "+", "control", "+", "'\" does not exist!'", ")", "# Override Enable ...
https://github.com/bungnoid/glTools/blob/8ff0899de43784a18bd4543285655e68e28fb5e5/rig/mocapOverride.py#L67-L91
gunnery/gunnery
733a261cae6243a11883a40e18b14f57cf6e47b2
gunnery/backend/tasks.py
python
generate_private_key
(environment_id)
Generate public and private key pair for environment
Generate public and private key pair for environment
[ "Generate", "public", "and", "private", "key", "pair", "for", "environment" ]
def generate_private_key(environment_id): """ Generate public and private key pair for environment """ environment = Environment.objects.get(pk=environment_id) PrivateKey(environment_id).generate('Gunnery-' + environment.application.name + '-' + environment.name) open(KnownHosts(environment_id).get_file_name(), 'w').close()
[ "def", "generate_private_key", "(", "environment_id", ")", ":", "environment", "=", "Environment", ".", "objects", ".", "get", "(", "pk", "=", "environment_id", ")", "PrivateKey", "(", "environment_id", ")", ".", "generate", "(", "'Gunnery-'", "+", "environment"...
https://github.com/gunnery/gunnery/blob/733a261cae6243a11883a40e18b14f57cf6e47b2/gunnery/backend/tasks.py#L30-L34
FSecureLABS/drozer
df11e6e63fbaefa9b58ed1e42533ddf76241d7e1
src/pydiesel/reflection/types/reflected_type.py
python
ReflectedType.fromArgument
(cls, argument, reflector)
Creates a new ReflectedType, given an Argument message as defined in the drozer protocol.
Creates a new ReflectedType, given an Argument message as defined in the drozer protocol.
[ "Creates", "a", "new", "ReflectedType", "given", "an", "Argument", "message", "as", "defined", "in", "the", "drozer", "protocol", "." ]
def fromArgument(cls, argument, reflector): """ Creates a new ReflectedType, given an Argument message as defined in the drozer protocol. """ if isinstance(argument, ReflectedType): return argument elif argument.type == Message.Argument.ARRAY: return cls.reflected_array.fromArgument(argument, reflector=reflector) elif argument.type == Message.Argument.DATA: return cls.reflected_binary(argument.data, reflector=reflector) elif argument.type == Message.Argument.NULL: return cls.reflected_null(reflector=reflector) elif argument.type == Message.Argument.OBJECT: return cls.reflected_object(argument.object.reference, reflector=reflector) elif argument.type == Message.Argument.PRIMITIVE: return cls.reflected_primitive.fromArgument(argument, reflector) elif argument.type == Message.Argument.STRING: return cls.reflected_string(argument.string, reflector=reflector) else: return None
[ "def", "fromArgument", "(", "cls", ",", "argument", ",", "reflector", ")", ":", "if", "isinstance", "(", "argument", ",", "ReflectedType", ")", ":", "return", "argument", "elif", "argument", ".", "type", "==", "Message", ".", "Argument", ".", "ARRAY", ":",...
https://github.com/FSecureLABS/drozer/blob/df11e6e63fbaefa9b58ed1e42533ddf76241d7e1/src/pydiesel/reflection/types/reflected_type.py#L29-L50
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/customer_extension_setting_service/client.py
python
CustomerExtensionSettingServiceClient.mutate_customer_extension_settings
( self, request: customer_extension_setting_service.MutateCustomerExtensionSettingsRequest = None, *, customer_id: str = None, operations: Sequence[ customer_extension_setting_service.CustomerExtensionSettingOperation ] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), )
return response
r"""Creates, updates, or removes customer extension settings. Operation statuses are returned. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `CollectionSizeError <>`__ `CriterionError <>`__ `DatabaseError <>`__ `DateError <>`__ `DistinctError <>`__ `ExtensionSettingError <>`__ `FieldError <>`__ `HeaderError <>`__ `IdError <>`__ `InternalError <>`__ `ListOperationError <>`__ `MutateError <>`__ `NewResourceCreationError <>`__ `NotEmptyError <>`__ `NullError <>`__ `OperatorError <>`__ `QuotaError <>`__ `RangeError <>`__ `RequestError <>`__ `SizeLimitError <>`__ `StringFormatError <>`__ `StringLengthError <>`__ `UrlFieldError <>`__ Args: request (:class:`google.ads.googleads.v8.services.types.MutateCustomerExtensionSettingsRequest`): The request object. Request message for [CustomerExtensionSettingService.MutateCustomerExtensionSettings][google.ads.googleads.v8.services.CustomerExtensionSettingService.MutateCustomerExtensionSettings]. customer_id (:class:`str`): Required. The ID of the customer whose customer extension settings are being modified. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. operations (:class:`Sequence[google.ads.googleads.v8.services.types.CustomerExtensionSettingOperation]`): Required. The list of operations to perform on individual customer extension settings. This corresponds to the ``operations`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v8.services.types.MutateCustomerExtensionSettingsResponse: Response message for a customer extension setting mutate.
r"""Creates, updates, or removes customer extension settings. Operation statuses are returned.
[ "r", "Creates", "updates", "or", "removes", "customer", "extension", "settings", ".", "Operation", "statuses", "are", "returned", "." ]
def mutate_customer_extension_settings( self, request: customer_extension_setting_service.MutateCustomerExtensionSettingsRequest = None, *, customer_id: str = None, operations: Sequence[ customer_extension_setting_service.CustomerExtensionSettingOperation ] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> customer_extension_setting_service.MutateCustomerExtensionSettingsResponse: r"""Creates, updates, or removes customer extension settings. Operation statuses are returned. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `CollectionSizeError <>`__ `CriterionError <>`__ `DatabaseError <>`__ `DateError <>`__ `DistinctError <>`__ `ExtensionSettingError <>`__ `FieldError <>`__ `HeaderError <>`__ `IdError <>`__ `InternalError <>`__ `ListOperationError <>`__ `MutateError <>`__ `NewResourceCreationError <>`__ `NotEmptyError <>`__ `NullError <>`__ `OperatorError <>`__ `QuotaError <>`__ `RangeError <>`__ `RequestError <>`__ `SizeLimitError <>`__ `StringFormatError <>`__ `StringLengthError <>`__ `UrlFieldError <>`__ Args: request (:class:`google.ads.googleads.v8.services.types.MutateCustomerExtensionSettingsRequest`): The request object. Request message for [CustomerExtensionSettingService.MutateCustomerExtensionSettings][google.ads.googleads.v8.services.CustomerExtensionSettingService.MutateCustomerExtensionSettings]. customer_id (:class:`str`): Required. The ID of the customer whose customer extension settings are being modified. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. operations (:class:`Sequence[google.ads.googleads.v8.services.types.CustomerExtensionSettingOperation]`): Required. The list of operations to perform on individual customer extension settings. This corresponds to the ``operations`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v8.services.types.MutateCustomerExtensionSettingsResponse: Response message for a customer extension setting mutate. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([customer_id, operations]): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a customer_extension_setting_service.MutateCustomerExtensionSettingsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance( request, customer_extension_setting_service.MutateCustomerExtensionSettingsRequest, ): request = customer_extension_setting_service.MutateCustomerExtensionSettingsRequest( request ) # If we have keyword arguments corresponding to fields on the # request, apply these. if customer_id is not None: request.customer_id = customer_id if operations is not None: request.operations = operations # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ self._transport.mutate_customer_extension_settings ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( (("customer_id", request.customer_id),) ), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response
[ "def", "mutate_customer_extension_settings", "(", "self", ",", "request", ":", "customer_extension_setting_service", ".", "MutateCustomerExtensionSettingsRequest", "=", "None", ",", "*", ",", "customer_id", ":", "str", "=", "None", ",", "operations", ":", "Sequence", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/customer_extension_setting_service/client.py#L463-L569
billpmurphy/hask
4609cc8d9d975f51b6ecdbd33640cdffdc28f953
hask/Data/String.py
python
unlines
(strings)
return "\n".join(strings)
lines :: [String] -> String unlines is an inverse operation to lines. It joins lines, after appending a terminating newline to each.
lines :: [String] -> String
[ "lines", "::", "[", "String", "]", "-", ">", "String" ]
def unlines(strings): """ lines :: [String] -> String unlines is an inverse operation to lines. It joins lines, after appending a terminating newline to each. """ return "\n".join(strings)
[ "def", "unlines", "(", "strings", ")", ":", "return", "\"\\n\"", ".", "join", "(", "strings", ")" ]
https://github.com/billpmurphy/hask/blob/4609cc8d9d975f51b6ecdbd33640cdffdc28f953/hask/Data/String.py#L29-L36
hasanirtiza/Pedestron
3bdcf8476edc0741f28a80dd4cb161ac532507ee
mmdet/ops/dcn/modules/deform_conv.py
python
DeformConvPack.forward
(self, x)
return deform_conv(x, offset, self.weight, self.stride, self.padding, self.dilation, self.groups, self.deformable_groups)
[]
def forward(self, x): offset = self.conv_offset(x) return deform_conv(x, offset, self.weight, self.stride, self.padding, self.dilation, self.groups, self.deformable_groups)
[ "def", "forward", "(", "self", ",", "x", ")", ":", "offset", "=", "self", ".", "conv_offset", "(", "x", ")", "return", "deform_conv", "(", "x", ",", "offset", ",", "self", ".", "weight", ",", "self", ".", "stride", ",", "self", ".", "padding", ",",...
https://github.com/hasanirtiza/Pedestron/blob/3bdcf8476edc0741f28a80dd4cb161ac532507ee/mmdet/ops/dcn/modules/deform_conv.py#L78-L81
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/plexapi/server.py
python
PlexServer.refreshContent
(self)
return self.query('/sync/refreshContent', self._session.put)
Force PMS to refresh content for known SyncLists.
Force PMS to refresh content for known SyncLists.
[ "Force", "PMS", "to", "refresh", "content", "for", "known", "SyncLists", "." ]
def refreshContent(self): """ Force PMS to refresh content for known SyncLists. """ return self.query('/sync/refreshContent', self._session.put)
[ "def", "refreshContent", "(", "self", ")", ":", "return", "self", ".", "query", "(", "'/sync/refreshContent'", ",", "self", ".", "_session", ".", "put", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/plexapi/server.py#L791-L793
VLSIDA/OpenRAM
f66aac3264598eeae31225c62b6a4af52412d407
compiler/modules/bank.py
python
bank.add_modules
(self)
Add all the modules using the class loader
Add all the modules using the class loader
[ "Add", "all", "the", "modules", "using", "the", "class", "loader" ]
def add_modules(self): """ Add all the modules using the class loader """ local_array_size = OPTS.local_array_size if local_array_size > 0: # Find the even multiple that satisfies the fanout with equal sized local arrays total_cols = self.num_cols + self.num_spare_cols num_lb = floor(total_cols / local_array_size) final_size = total_cols - num_lb * local_array_size cols = [local_array_size] * (num_lb - 1) # Add the odd bits to the last local array cols.append(local_array_size + final_size) self.bitcell_array = factory.create(module_type="global_bitcell_array", cols=cols, rows=self.num_rows) else: self.bitcell_array = factory.create(module_type="replica_bitcell_array", cols=self.num_cols + self.num_spare_cols, rows=self.num_rows) self.add_mod(self.bitcell_array) self.port_address = [] for port in self.all_ports: self.port_address.append(factory.create(module_type="port_address", cols=self.num_cols + self.num_spare_cols, rows=self.num_rows, port=port)) self.add_mod(self.port_address[port]) self.port_data = [] self.bit_offsets = self.get_column_offsets() for port in self.all_ports: temp_pre = factory.create(module_type="port_data", sram_config=self.sram_config, port=port, bit_offsets=self.bit_offsets) self.port_data.append(temp_pre) self.add_mod(self.port_data[port]) if(self.num_banks > 1): self.bank_select = factory.create(module_type="bank_select") self.add_mod(self.bank_select)
[ "def", "add_modules", "(", "self", ")", ":", "local_array_size", "=", "OPTS", ".", "local_array_size", "if", "local_array_size", ">", "0", ":", "# Find the even multiple that satisfies the fanout with equal sized local arrays", "total_cols", "=", "self", ".", "num_cols", ...
https://github.com/VLSIDA/OpenRAM/blob/f66aac3264598eeae31225c62b6a4af52412d407/compiler/modules/bank.py#L372-L414
santi-pdp/pase
2a41e63e54fa8673efd12c16cdcdd5ad4f0f125e
ASR/data_io.py
python
read_vec_int_ark
(file_or_fd,output_folder)
generator(key,vec) = read_vec_int_ark(file_or_fd) Create generator of (key,vector<int>) tuples, which reads from the ark file/stream. file_or_fd : ark, gzipped ark, pipe or opened file descriptor. Read ark to a 'dictionary': d = { u:d for u,d in kaldi_io.read_vec_int_ark(file) }
generator(key,vec) = read_vec_int_ark(file_or_fd) Create generator of (key,vector<int>) tuples, which reads from the ark file/stream. file_or_fd : ark, gzipped ark, pipe or opened file descriptor.
[ "generator", "(", "key", "vec", ")", "=", "read_vec_int_ark", "(", "file_or_fd", ")", "Create", "generator", "of", "(", "key", "vector<int", ">", ")", "tuples", "which", "reads", "from", "the", "ark", "file", "/", "stream", ".", "file_or_fd", ":", "ark", ...
def read_vec_int_ark(file_or_fd,output_folder): """ generator(key,vec) = read_vec_int_ark(file_or_fd) Create generator of (key,vector<int>) tuples, which reads from the ark file/stream. file_or_fd : ark, gzipped ark, pipe or opened file descriptor. Read ark to a 'dictionary': d = { u:d for u,d in kaldi_io.read_vec_int_ark(file) } """ fd = open_or_fd(file_or_fd,output_folder) try: key = read_key(fd) while key: ali = read_vec_int(fd,output_folder) yield key, ali key = read_key(fd) finally: if fd is not file_or_fd: fd.close()
[ "def", "read_vec_int_ark", "(", "file_or_fd", ",", "output_folder", ")", ":", "fd", "=", "open_or_fd", "(", "file_or_fd", ",", "output_folder", ")", "try", ":", "key", "=", "read_key", "(", "fd", ")", "while", "key", ":", "ali", "=", "read_vec_int", "(", ...
https://github.com/santi-pdp/pase/blob/2a41e63e54fa8673efd12c16cdcdd5ad4f0f125e/ASR/data_io.py#L656-L672
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppDB/appscale/datastore/fdb/sdk.py
python
BaseCursor._AcquireCursorID
(cls)
return cursor_id
Acquires the next cursor id in a thread safe manner.
Acquires the next cursor id in a thread safe manner.
[ "Acquires", "the", "next", "cursor", "id", "in", "a", "thread", "safe", "manner", "." ]
def _AcquireCursorID(cls): """Acquires the next cursor id in a thread safe manner.""" cls._next_cursor_lock.acquire() try: cursor_id = cls._next_cursor cls._next_cursor += 1 finally: cls._next_cursor_lock.release() return cursor_id
[ "def", "_AcquireCursorID", "(", "cls", ")", ":", "cls", ".", "_next_cursor_lock", ".", "acquire", "(", ")", "try", ":", "cursor_id", "=", "cls", ".", "_next_cursor", "cls", ".", "_next_cursor", "+=", "1", "finally", ":", "cls", ".", "_next_cursor_lock", "....
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppDB/appscale/datastore/fdb/sdk.py#L105-L113
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/aui/framemanager.py
python
AuiManager.ProcessMgrEvent
(self, event)
Process the AUI events sent to the manager. :param `event`: the event to process, an instance of :class:`AuiManagerEvent`.
Process the AUI events sent to the manager.
[ "Process", "the", "AUI", "events", "sent", "to", "the", "manager", "." ]
def ProcessMgrEvent(self, event): """ Process the AUI events sent to the manager. :param `event`: the event to process, an instance of :class:`AuiManagerEvent`. """ # first, give the owner frame a chance to override if self._frame: if self._frame.GetEventHandler().ProcessEvent(event): return self.ProcessEvent(event)
[ "def", "ProcessMgrEvent", "(", "self", ",", "event", ")", ":", "# first, give the owner frame a chance to override", "if", "self", ".", "_frame", ":", "if", "self", ".", "_frame", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "event", ")", ":", "...
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/aui/framemanager.py#L4627-L4639
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/importlib/_bootstrap.py
python
_requires_builtin
(fxn)
return _requires_builtin_wrapper
Decorator to verify the named module is built-in.
Decorator to verify the named module is built-in.
[ "Decorator", "to", "verify", "the", "named", "module", "is", "built", "-", "in", "." ]
def _requires_builtin(fxn): """Decorator to verify the named module is built-in.""" def _requires_builtin_wrapper(self, fullname): if fullname not in sys.builtin_module_names: raise ImportError('{!r} is not a built-in module'.format(fullname), name=fullname) return fxn(self, fullname) _wrap(_requires_builtin_wrapper, fxn) return _requires_builtin_wrapper
[ "def", "_requires_builtin", "(", "fxn", ")", ":", "def", "_requires_builtin_wrapper", "(", "self", ",", "fullname", ")", ":", "if", "fullname", "not", "in", "sys", ".", "builtin_module_names", ":", "raise", "ImportError", "(", "'{!r} is not a built-in module'", "....
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/importlib/_bootstrap.py#L252-L260
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/alexa/capabilities.py
python
AlexaEqualizerController.name
(self)
return "Alexa.EqualizerController"
Return the Alexa API name of this interface.
Return the Alexa API name of this interface.
[ "Return", "the", "Alexa", "API", "name", "of", "this", "interface", "." ]
def name(self): """Return the Alexa API name of this interface.""" return "Alexa.EqualizerController"
[ "def", "name", "(", "self", ")", ":", "return", "\"Alexa.EqualizerController\"" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/alexa/capabilities.py#L1939-L1941
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_internal/commands/wheel.py
python
WheelCommand.run
(self, options, args)
return SUCCESS
[]
def run(self, options, args): # type: (Values, List[str]) -> int cmdoptions.check_install_build_global(options) session = self.get_default_session(options) finder = self._build_package_finder(options, session) wheel_cache = WheelCache(options.cache_dir, options.format_control) options.wheel_dir = normalize_path(options.wheel_dir) ensure_dir(options.wheel_dir) req_tracker = self.enter_context(get_requirement_tracker()) directory = TempDirectory( delete=not options.no_clean, kind="wheel", globally_managed=True, ) reqs = self.get_requirements(args, options, finder, session) preparer = self.make_requirement_preparer( temp_build_dir=directory, options=options, req_tracker=req_tracker, session=session, finder=finder, download_dir=options.wheel_dir, use_user_site=False, ) resolver = self.make_resolver( preparer=preparer, finder=finder, options=options, wheel_cache=wheel_cache, ignore_requires_python=options.ignore_requires_python, use_pep517=options.use_pep517, ) self.trace_basic_info(finder) requirement_set = resolver.resolve( reqs, check_supported_wheels=True ) reqs_to_build = [] # type: List[InstallRequirement] for req in requirement_set.requirements.values(): if req.is_wheel: preparer.save_linked_requirement(req) elif should_build_for_wheel_command(req): reqs_to_build.append(req) # build wheels build_successes, build_failures = build( reqs_to_build, wheel_cache=wheel_cache, verify=(not options.no_verify), build_options=options.build_options or [], global_options=options.global_options or [], ) for req in build_successes: assert req.link and req.link.is_wheel assert req.local_file_path # copy from cache to target directory try: shutil.copy(req.local_file_path, options.wheel_dir) except OSError as e: logger.warning( "Building wheel for %s failed: %s", req.name, e, ) build_failures.append(req) if len(build_failures) != 0: raise CommandError( "Failed to build one or more wheels" ) return SUCCESS
[ "def", "run", "(", "self", ",", "options", ",", "args", ")", ":", "# type: (Values, List[str]) -> int", "cmdoptions", ".", "check_install_build_global", "(", "options", ")", "session", "=", "self", ".", "get_default_session", "(", "options", ")", "finder", "=", ...
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_internal/commands/wheel.py#L119-L198
amietn/vcsi
b55262f1fe1d5423a6614366f181827208d3901a
vcsi/vcsi.py
python
max_line_length
( media_info, metadata_font, header_margin, width=Config.contact_sheet_width, text=None)
return max_length
Find the number of characters that fit in width with given font.
Find the number of characters that fit in width with given font.
[ "Find", "the", "number", "of", "characters", "that", "fit", "in", "width", "with", "given", "font", "." ]
def max_line_length( media_info, metadata_font, header_margin, width=Config.contact_sheet_width, text=None): """Find the number of characters that fit in width with given font. """ if text is None: text = media_info.filename max_width = width - 2 * header_margin max_length = 0 for i in range(len(text) + 1): text_chunk = text[:i] text_width = 0 if len(text_chunk) == 0 else metadata_font.getsize(text_chunk)[0] max_length = i if text_width > max_width: break return max_length
[ "def", "max_line_length", "(", "media_info", ",", "metadata_font", ",", "header_margin", ",", "width", "=", "Config", ".", "contact_sheet_width", ",", "text", "=", "None", ")", ":", "if", "text", "is", "None", ":", "text", "=", "media_info", ".", "filename",...
https://github.com/amietn/vcsi/blob/b55262f1fe1d5423a6614366f181827208d3901a/vcsi/vcsi.py#L832-L854
martius-lab/blackbox-backprop
0152a6df8c819580d800b052ef17f39bdb82eb98
blackbox_backprop/mAP.py
python
MapLoss.raw_map_computation
(self, scores, targets)
return 1.0 - precisions_per_class[present_class_mask].mean()
:param scores: [batch_size, num_classes] predicted relevance scores :param targets: [batch_size, num_classes] ground truth relevances
:param scores: [batch_size, num_classes] predicted relevance scores :param targets: [batch_size, num_classes] ground truth relevances
[ ":", "param", "scores", ":", "[", "batch_size", "num_classes", "]", "predicted", "relevance", "scores", ":", "param", "targets", ":", "[", "batch_size", "num_classes", "]", "ground", "truth", "relevances" ]
def raw_map_computation(self, scores, targets): """ :param scores: [batch_size, num_classes] predicted relevance scores :param targets: [batch_size, num_classes] ground truth relevances """ # Compute map HIGH_CONSTANT = 2.0 epsilon = 1e-5 transposed_scores = scores.transpose(0, 1) transposed_targets = targets.transpose(0, 1) deviations = torch.abs(torch.randn_like(transposed_targets)) * (transposed_targets - 0.5) transposed_scores = transposed_scores - self.margin * deviations ranks_of_positive = TrueRanker.apply(transposed_scores, self.lambda_val) scores_for_ranking_positives = -ranks_of_positive + HIGH_CONSTANT * transposed_targets ranks_within_positive = rank_normalised(scores_for_ranking_positives) ranks_within_positive.requires_grad = False assert torch.all(ranks_within_positive * transposed_targets < ranks_of_positive * transposed_targets + epsilon) sum_of_precisions_at_j_per_class = ((ranks_within_positive / ranks_of_positive) * transposed_targets).sum(dim=1) precisions_per_class = sum_of_precisions_at_j_per_class / (transposed_targets.sum(dim=1) + epsilon) present_class_mask = targets.sum(axis=0) != 0 return 1.0 - precisions_per_class[present_class_mask].mean()
[ "def", "raw_map_computation", "(", "self", ",", "scores", ",", "targets", ")", ":", "# Compute map", "HIGH_CONSTANT", "=", "2.0", "epsilon", "=", "1e-5", "transposed_scores", "=", "scores", ".", "transpose", "(", "0", ",", "1", ")", "transposed_targets", "=", ...
https://github.com/martius-lab/blackbox-backprop/blob/0152a6df8c819580d800b052ef17f39bdb82eb98/blackbox_backprop/mAP.py#L30-L53
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/storage/stores/nosql/mongo/engine.py
python
MongoStorageEngine.rdf_store
(self)
return MongoRDFsStore(self)
[]
def rdf_store(self): return MongoRDFsStore(self)
[ "def", "rdf_store", "(", "self", ")", ":", "return", "MongoRDFsStore", "(", "self", ")" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/storage/stores/nosql/mongo/engine.py#L94-L95
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/spack/compiler.py
python
tokenize_flags
(flags_str)
return flags
Given a compiler flag specification as a string, this returns a list where the entries are the flags. For compiler options which set values using the syntax "-flag value", this function groups flags and their values together. Any token not preceded by a "-" is considered the value of a prior flag.
Given a compiler flag specification as a string, this returns a list where the entries are the flags. For compiler options which set values using the syntax "-flag value", this function groups flags and their values together. Any token not preceded by a "-" is considered the value of a prior flag.
[ "Given", "a", "compiler", "flag", "specification", "as", "a", "string", "this", "returns", "a", "list", "where", "the", "entries", "are", "the", "flags", ".", "For", "compiler", "options", "which", "set", "values", "using", "the", "syntax", "-", "flag", "v...
def tokenize_flags(flags_str): """Given a compiler flag specification as a string, this returns a list where the entries are the flags. For compiler options which set values using the syntax "-flag value", this function groups flags and their values together. Any token not preceded by a "-" is considered the value of a prior flag.""" tokens = flags_str.split() if not tokens: return [] flag = tokens[0] flags = [] for token in tokens[1:]: if not token.startswith('-'): flag += ' ' + token else: flags.append(flag) flag = token flags.append(flag) return flags
[ "def", "tokenize_flags", "(", "flags_str", ")", ":", "tokens", "=", "flags_str", ".", "split", "(", ")", "if", "not", "tokens", ":", "return", "[", "]", "flag", "=", "tokens", "[", "0", "]", "flags", "=", "[", "]", "for", "token", "in", "tokens", "...
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/spack/compiler.py#L57-L75
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
plugins/updatenotifier/updatenotifier/libs/jinja2/environment.py
python
Environment.call_test
(self, name, value, args=None, kwargs=None)
return func(value, *(args or ()), **(kwargs or {}))
Invokes a test on a value the same way the compiler does it. .. versionadded:: 2.7
Invokes a test on a value the same way the compiler does it.
[ "Invokes", "a", "test", "on", "a", "value", "the", "same", "way", "the", "compiler", "does", "it", "." ]
def call_test(self, name, value, args=None, kwargs=None): """Invokes a test on a value the same way the compiler does it. .. versionadded:: 2.7 """ func = self.tests.get(name) if func is None: fail_for_missing_callable('no test named %r', name) return func(value, *(args or ()), **(kwargs or {}))
[ "def", "call_test", "(", "self", ",", "name", ",", "value", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "func", "=", "self", ".", "tests", ".", "get", "(", "name", ")", "if", "func", "is", "None", ":", "fail_for_missing_callable",...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/plugins/updatenotifier/updatenotifier/libs/jinja2/environment.py#L469-L477
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/knots/knot.py
python
Knot.arf_invariant
(self)
return 1
Return the Arf invariant. EXAMPLES:: sage: B = BraidGroup(4) sage: K = Knot(B([-1, 2, 1, 2])) sage: K.arf_invariant() 0 sage: B = BraidGroup(8) sage: K = Knot(B([-2, 3, 1, 2, 1, 4])) sage: K.arf_invariant() 0 sage: K = Knot(B([1, 2, 1, 2])) sage: K.arf_invariant() 1
Return the Arf invariant.
[ "Return", "the", "Arf", "invariant", "." ]
def arf_invariant(self): """ Return the Arf invariant. EXAMPLES:: sage: B = BraidGroup(4) sage: K = Knot(B([-1, 2, 1, 2])) sage: K.arf_invariant() 0 sage: B = BraidGroup(8) sage: K = Knot(B([-2, 3, 1, 2, 1, 4])) sage: K.arf_invariant() 0 sage: K = Knot(B([1, 2, 1, 2])) sage: K.arf_invariant() 1 """ a = self.alexander_polynomial()(-1) if (a % 8) == 1 or (a % 8) == 7: return 0 return 1
[ "def", "arf_invariant", "(", "self", ")", ":", "a", "=", "self", ".", "alexander_polynomial", "(", ")", "(", "-", "1", ")", "if", "(", "a", "%", "8", ")", "==", "1", "or", "(", "a", "%", "8", ")", "==", "7", ":", "return", "0", "return", "1" ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/knots/knot.py#L331-L352
hangoutsbot/hangoutsbot
aabe1059d5873f53691e28c19273277817fb34ba
hangupsbot/handlers.py
python
EventHandler.handle_command
(self, event)
Handle command messages
Handle command messages
[ "Handle", "command", "messages" ]
def handle_command(self, event): """Handle command messages""" # is commands_enabled? config_commands_enabled = self.bot.get_config_suboption(event.conv_id, 'commands_enabled') tagged_ignore = "ignore" in self.bot.tags.useractive(event.user_id.chat_id, event.conv_id) if not config_commands_enabled or tagged_ignore: admins_list = self.bot.get_config_suboption(event.conv_id, 'admins') or [] # admins always have commands enabled if event.user_id.chat_id not in admins_list: return # ensure bot alias is always a list if not isinstance(self.bot_command, list): self.bot_command = [self.bot_command] # check that a bot alias is used e.g. /bot if not event.text.split()[0].lower() in self.bot_command: if self.bot.conversations.catalog[event.conv_id]["type"] == "ONE_TO_ONE" and self.bot.get_config_option('auto_alias_one_to_one'): event.text = u" ".join((self.bot_command[0], event.text)) # Insert default alias if not already present else: return # Parse message event.text = event.text.replace(u'\xa0', u' ') # convert non-breaking space in Latin1 (ISO 8859-1) try: line_args = shlex.split(event.text, posix=False) except Exception as e: logger.exception(e) yield from self.bot.coro_send_message(event.conv, _("{}: {}").format( event.user.full_name, str(e))) return # Test if command length is sufficient if len(line_args) < 2: config_silent = self.bot.get_config_suboption(event.conv.id_, 'silentmode') tagged_silent = "silent" in self.bot.tags.useractive(event.user_id.chat_id, event.conv.id_) if not (config_silent or tagged_silent): yield from self.bot.coro_send_message(event.conv, _('{}: Missing parameter(s)').format( event.user.full_name)) return commands = command.get_available_commands(self.bot, event.user.id_.chat_id, event.conv_id) supplied_command = line_args[1].lower() if supplied_command in commands["user"]: pass elif supplied_command in commands["admin"]: pass elif supplied_command in command.commands: yield from command.blocked_command(self.bot, event, *line_args[1:]) return else: yield from command.unknown_command(self.bot, event, *line_args[1:]) return # Run command results = yield from command.run(self.bot, event, *line_args[1:]) if "acknowledge" in dir(event): for id in event.acknowledge: yield from self.run_reprocessor(id, event, results)
[ "def", "handle_command", "(", "self", ",", "event", ")", ":", "# is commands_enabled?", "config_commands_enabled", "=", "self", ".", "bot", ".", "get_config_suboption", "(", "event", ".", "conv_id", ",", "'commands_enabled'", ")", "tagged_ignore", "=", "\"ignore\"",...
https://github.com/hangoutsbot/hangoutsbot/blob/aabe1059d5873f53691e28c19273277817fb34ba/hangupsbot/handlers.py#L296-L359
bonfy/leetcode
aae6fbb9198aa866937ca66e6212b090e6f5e8c6
solutions/0079-word-search/word-search.py
python
Solution.exist
(self, board, word)
return False
:type board: List[List[str]] :type word: str :rtype: bool
:type board: List[List[str]] :type word: str :rtype: bool
[ ":", "type", "board", ":", "List", "[", "List", "[", "str", "]]", ":", "type", "word", ":", "str", ":", "rtype", ":", "bool" ]
def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ if not board: return False for i in xrange(len(board)): for j in xrange(len(board[0])): if self.dfs(board, i, j, word): return True return False
[ "def", "exist", "(", "self", ",", "board", ",", "word", ")", ":", "if", "not", "board", ":", "return", "False", "for", "i", "in", "xrange", "(", "len", "(", "board", ")", ")", ":", "for", "j", "in", "xrange", "(", "len", "(", "board", "[", "0",...
https://github.com/bonfy/leetcode/blob/aae6fbb9198aa866937ca66e6212b090e6f5e8c6/solutions/0079-word-search/word-search.py#L26-L38
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/repackage/setuptools/setuptools/command/easy_install.py
python
easy_install.write_script
(self, script_name, contents, mode="t", blockers=())
Write an executable file to the scripts directory
Write an executable file to the scripts directory
[ "Write", "an", "executable", "file", "to", "the", "scripts", "directory" ]
def write_script(self, script_name, contents, mode="t", blockers=()): """Write an executable file to the scripts directory""" self.delete_blockers( # clean up old .py/.pyw w/o a script [os.path.join(self.script_dir, x) for x in blockers] ) log.info("Installing %s script to %s", script_name, self.script_dir) target = os.path.join(self.script_dir, script_name) self.add_output(target) if self.dry_run: return mask = current_umask() ensure_directory(target) if os.path.exists(target): os.unlink(target) with open(target, "w" + mode) as f: f.write(contents) chmod(target, 0o777 - mask)
[ "def", "write_script", "(", "self", ",", "script_name", ",", "contents", ",", "mode", "=", "\"t\"", ",", "blockers", "=", "(", ")", ")", ":", "self", ".", "delete_blockers", "(", "# clean up old .py/.pyw w/o a script", "[", "os", ".", "path", ".", "join", ...
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/repackage/setuptools/setuptools/command/easy_install.py#L828-L846
pubs/pubs
59be47ca9107364db452f8138206ab9895438e33
pubs/filebroker.py
python
FileBroker.push
(self, citekey, metadata, bibdata)
Put content to disk. Will gladly override anything standing in its way.
Put content to disk. Will gladly override anything standing in its way.
[ "Put", "content", "to", "disk", ".", "Will", "gladly", "override", "anything", "standing", "in", "its", "way", "." ]
def push(self, citekey, metadata, bibdata): """Put content to disk. Will gladly override anything standing in its way.""" self.push_metafile(citekey, metadata) self.push_bibfile(citekey, bibdata)
[ "def", "push", "(", "self", ",", "citekey", ",", "metadata", ",", "bibdata", ")", ":", "self", ".", "push_metafile", "(", "citekey", ",", "metadata", ")", "self", ".", "push_bibfile", "(", "citekey", ",", "bibdata", ")" ]
https://github.com/pubs/pubs/blob/59be47ca9107364db452f8138206ab9895438e33/pubs/filebroker.py#L96-L99
niosus/EasyClangComplete
3b16eb17735aaa3f56bb295fc5481b269ee9f2ef
plugin/clang/cindex38.py
python
Cursor.result_type
(self)
return self._result_type
Retrieve the Type of the result for this Cursor.
Retrieve the Type of the result for this Cursor.
[ "Retrieve", "the", "Type", "of", "the", "result", "for", "this", "Cursor", "." ]
def result_type(self): """Retrieve the Type of the result for this Cursor.""" if not hasattr(self, '_result_type'): self._result_type = conf.lib.clang_getCursorResultType(self) return self._result_type
[ "def", "result_type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_result_type'", ")", ":", "self", ".", "_result_type", "=", "conf", ".", "lib", ".", "clang_getCursorResultType", "(", "self", ")", "return", "self", ".", "_result_typ...
https://github.com/niosus/EasyClangComplete/blob/3b16eb17735aaa3f56bb295fc5481b269ee9f2ef/plugin/clang/cindex38.py#L1336-L1341
eBay/accelerator
218d9a5e4451ac72b9e65df6c5b32e37d25136c8
accelerator/standard_methods/a_dataset_sort.py
python
analysis
(sliceno, params, prepare_res)
[]
def analysis(sliceno, params, prepare_res): dw, ds_list, sort_idx = prepare_res if options.sort_across_slices: sort_idx = sort_idx[sliceno] columniter = partial(ds_list.iterate, None, copy_mode=True) else: sort_idx, _ = sort(partial(ds_list.iterate, sliceno)) columniter = partial(ds_list.iterate, sliceno, copy_mode=True) for ix, column in enumerate(datasets.source.columns, 1): colstat = '%r (%d/%d)' % (column, ix, len(datasets.source.columns),) with status('Reading ' + colstat): lst = list(columniter(column)) with status('Writing ' + colstat): w = dw.writers[column].write for idx in sort_idx: w(lst[idx]) # Delete the list before making a new one, so we use less memory. del lst
[ "def", "analysis", "(", "sliceno", ",", "params", ",", "prepare_res", ")", ":", "dw", ",", "ds_list", ",", "sort_idx", "=", "prepare_res", "if", "options", ".", "sort_across_slices", ":", "sort_idx", "=", "sort_idx", "[", "sliceno", "]", "columniter", "=", ...
https://github.com/eBay/accelerator/blob/218d9a5e4451ac72b9e65df6c5b32e37d25136c8/accelerator/standard_methods/a_dataset_sort.py#L205-L222
standardebooks/tools
f57af3c5938a9aeed9e97e82b2c130424f6033e5
se/formatting.py
python
namespace_to_class
(selector: str)
return selector.replace(":", "-").replace("|", "-").replace("~=", "-").replace("[", ".").replace("]", "").replace("\"", "")
Helper function to remove namespace selectors from a single selector, and replace them with class names. INPUTS selector: A single CSS selector OUTPUTS A string representing the selector with namespaces replaced by classes
Helper function to remove namespace selectors from a single selector, and replace them with class names.
[ "Helper", "function", "to", "remove", "namespace", "selectors", "from", "a", "single", "selector", "and", "replace", "them", "with", "class", "names", "." ]
def namespace_to_class(selector: str) -> str: """ Helper function to remove namespace selectors from a single selector, and replace them with class names. INPUTS selector: A single CSS selector OUTPUTS A string representing the selector with namespaces replaced by classes """ # First, remove periods from epub:type. We can't remove periods in the entire selector because there might be class selectors involved epub_type = regex.search(r"\"[^\"]+?\"", selector) if epub_type: selector = selector.replace(epub_type.group(), epub_type.group().replace(".", "-")) # Now clean things up return selector.replace(":", "-").replace("|", "-").replace("~=", "-").replace("[", ".").replace("]", "").replace("\"", "")
[ "def", "namespace_to_class", "(", "selector", ":", "str", ")", "->", "str", ":", "# First, remove periods from epub:type.\t We can't remove periods in the entire selector because there might be class selectors involved", "epub_type", "=", "regex", ".", "search", "(", "r\"\\\"[^\\\"...
https://github.com/standardebooks/tools/blob/f57af3c5938a9aeed9e97e82b2c130424f6033e5/se/formatting.py#L1221-L1238
david-abel/simple_rl
d8fe6007efb4840377f085a4e35ba89aaa2cdf6d
simple_rl/abstraction/features/RBFCodingClass.py
python
RBFCoding.get_features
(self, state)
return new_features
Args: state (simple_rl.State) Returns: (list): contains the radial basis function features.
Args: state (simple_rl.State)
[ "Args", ":", "state", "(", "simple_rl", ".", "State", ")" ]
def get_features(self, state): ''' Args: state (simple_rl.State) Returns: (list): contains the radial basis function features. ''' state_feats = state.features() # Perform feature bucketing. new_features = [] for i, feat in enumerate(state_feats): new_feat = math.exp(-(feat)**2) new_features.append(new_feat) return new_features
[ "def", "get_features", "(", "self", ",", "state", ")", ":", "state_feats", "=", "state", ".", "features", "(", ")", "# Perform feature bucketing. ", "new_features", "=", "[", "]", "for", "i", ",", "feat", "in", "enumerate", "(", "state_feats", ")", ":...
https://github.com/david-abel/simple_rl/blob/d8fe6007efb4840377f085a4e35ba89aaa2cdf6d/simple_rl/abstraction/features/RBFCodingClass.py#L14-L30
jcmgray/quimb
a54b22c61534be8acbc9efe4da97fb5c7f12057d
quimb/tensor/tensor_1d.py
python
__iadd__
(self, other)
return self.add_MPS(other, inplace=True)
In-place MPS addition.
In-place MPS addition.
[ "In", "-", "place", "MPS", "addition", "." ]
def __iadd__(self, other): """In-place MPS addition. """ return self.add_MPS(other, inplace=True)
[ "def", "__iadd__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "add_MPS", "(", "other", ",", "inplace", "=", "True", ")" ]
https://github.com/jcmgray/quimb/blob/a54b22c61534be8acbc9efe4da97fb5c7f12057d/quimb/tensor/tensor_1d.py#L1749-L1752
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/visual/textbox/fontmanager.py
python
FontManager.getFontStylesForFamily
(self, family_name)
For the given family_name, a list of style names supported is returned.
For the given family_name, a list of style names supported is returned.
[ "For", "the", "given", "family_name", "a", "list", "of", "style", "names", "supported", "is", "returned", "." ]
def getFontStylesForFamily(self, family_name): """For the given family_name, a list of style names supported is returned. """ style_dict = self._available_font_info.get(family_name) if style_dict: return list(style_dict.keys())
[ "def", "getFontStylesForFamily", "(", "self", ",", "family_name", ")", ":", "style_dict", "=", "self", ".", "_available_font_info", ".", "get", "(", "family_name", ")", "if", "style_dict", ":", "return", "list", "(", "style_dict", ".", "keys", "(", ")", ")" ...
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/visual/textbox/fontmanager.py#L117-L123
cylc/cylc-flow
5ec221143476c7c616c156b74158edfbcd83794a
cylc/flow/main_loop/log_data_store.py
python
_iter_data_store
(data_store)
[]
def _iter_data_store(data_store): for item in data_store.values(): for key, value in item.items(): if key != 'workflow': yield (key, value) # there should only be one workflow in the data store break
[ "def", "_iter_data_store", "(", "data_store", ")", ":", "for", "item", "in", "data_store", ".", "values", "(", ")", ":", "for", "key", ",", "value", "in", "item", ".", "items", "(", ")", ":", "if", "key", "!=", "'workflow'", ":", "yield", "(", "key",...
https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/main_loop/log_data_store.py#L75-L81
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/shelve.py
python
Shelf.__getitem__
(self, key)
return value
[]
def __getitem__(self, key): try: value = self.cache[key] except KeyError: f = StringIO(self.dict[key]) value = Unpickler(f).load() if self.writeback: self.cache[key] = value return value
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "try", ":", "value", "=", "self", ".", "cache", "[", "key", "]", "except", "KeyError", ":", "f", "=", "StringIO", "(", "self", ".", "dict", "[", "key", "]", ")", "value", "=", "Unpickler", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/shelve.py#L117-L125
bsmali4/xssfork
515b45dfb0edb9263da544ad91fc1cb5f410bfd1
thirdparty/requests/packages/urllib3/util/retry.py
python
Retry._is_connection_error
(self, err)
return isinstance(err, ConnectTimeoutError)
Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry.
Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry.
[ "Errors", "when", "we", "re", "fairly", "sure", "that", "the", "server", "did", "not", "receive", "the", "request", "so", "it", "should", "be", "safe", "to", "retry", "." ]
def _is_connection_error(self, err): """ Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry. """ return isinstance(err, ConnectTimeoutError)
[ "def", "_is_connection_error", "(", "self", ",", "err", ")", ":", "return", "isinstance", "(", "err", ",", "ConnectTimeoutError", ")" ]
https://github.com/bsmali4/xssfork/blob/515b45dfb0edb9263da544ad91fc1cb5f410bfd1/thirdparty/requests/packages/urllib3/util/retry.py#L180-L184
klen/pylama
227ddc94eb73638d423833075b1af2ac6bb308f7
pylama/context.py
python
RunContext.source
(self)
return self._source
Get the current source code.
Get the current source code.
[ "Get", "the", "current", "source", "code", "." ]
def source(self): """Get the current source code.""" if self._source is None: self._source = read(self.filename) return self._source
[ "def", "source", "(", "self", ")", ":", "if", "self", ".", "_source", "is", "None", ":", "self", ".", "_source", "=", "read", "(", "self", ".", "filename", ")", "return", "self", ".", "_source" ]
https://github.com/klen/pylama/blob/227ddc94eb73638d423833075b1af2ac6bb308f7/pylama/context.py#L113-L117
balakg/posewarp-cvpr2018
5e62e0419968adeb5291eed7012e62d52af14c7f
code/transformations.py
python
bilinear_transform
(coords, params, inverse=False)
return out
Apply bilinear transformation. :param coords: :class:`numpy.array` Nx2 coordinate matrix of source coordinate system :param params: :class:`numpy.array` parameters returned by `make_tform` :param inverse: bool apply inverse transformation, default is False :returns: :class:`numpy.array` transformed coordinates
Apply bilinear transformation.
[ "Apply", "bilinear", "transformation", "." ]
def bilinear_transform(coords, params, inverse=False): ''' Apply bilinear transformation. :param coords: :class:`numpy.array` Nx2 coordinate matrix of source coordinate system :param params: :class:`numpy.array` parameters returned by `make_tform` :param inverse: bool apply inverse transformation, default is False :returns: :class:`numpy.array` transformed coordinates ''' a0, a1, a2, a3, b0, b1, b2, b3 = params x = coords[:,0] y = coords[:,1] out = np.zeros(coords.shape) if inverse: raise NotImplemented('There is no explicit way to do the inverse ' 'transformation. Determine the inverse transformation parameters ' 'and use the fwd transformation instead.') else: out[:,0] = a0+a1*x+a2*y+a3*x*y out[:,1] = b0+b1*x+b2*y+b3*x*y return out
[ "def", "bilinear_transform", "(", "coords", ",", "params", ",", "inverse", "=", "False", ")", ":", "a0", ",", "a1", ",", "a2", ",", "a3", ",", "b0", ",", "b1", ",", "b2", ",", "b3", "=", "params", "x", "=", "coords", "[", ":", ",", "0", "]", ...
https://github.com/balakg/posewarp-cvpr2018/blob/5e62e0419968adeb5291eed7012e62d52af14c7f/code/transformations.py#L199-L225
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/zope.interface-4.5.0/src/zope/interface/common/mapping.py
python
IExtendedWriteMapping.setdefault
(key, default=None)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
[ "D", ".", "setdefault", "(", "k", "[", "d", "]", ")", "-", ">", "D", ".", "get", "(", "k", "d", ")", "also", "set", "D", "[", "k", "]", "=", "d", "if", "k", "not", "in", "D" ]
def setdefault(key, default=None): "D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D"
[ "def", "setdefault", "(", "key", ",", "default", "=", "None", ")", ":" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/zope.interface-4.5.0/src/zope/interface/common/mapping.py#L109-L110
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/monitor/v20180724/models.py
python
AlarmEvent.__init__
(self)
r""" :param EventName: 事件名 :type EventName: str :param Description: 展示的事件名 :type Description: str :param Namespace: 告警策略类型 :type Namespace: str
r""" :param EventName: 事件名 :type EventName: str :param Description: 展示的事件名 :type Description: str :param Namespace: 告警策略类型 :type Namespace: str
[ "r", ":", "param", "EventName", ":", "事件名", ":", "type", "EventName", ":", "str", ":", "param", "Description", ":", "展示的事件名", ":", "type", "Description", ":", "str", ":", "param", "Namespace", ":", "告警策略类型", ":", "type", "Namespace", ":", "str" ]
def __init__(self): r""" :param EventName: 事件名 :type EventName: str :param Description: 展示的事件名 :type Description: str :param Namespace: 告警策略类型 :type Namespace: str """ self.EventName = None self.Description = None self.Namespace = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "EventName", "=", "None", "self", ".", "Description", "=", "None", "self", ".", "Namespace", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/monitor/v20180724/models.py#L26-L37
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/files.py
python
UploadSessionFinishError.get_properties_error
(self)
return self._value
The supplied property group is invalid. The file has uploaded without property groups. Only call this if :meth:`is_properties_error` is true. :rtype: file_properties.InvalidPropertyGroupError
The supplied property group is invalid. The file has uploaded without property groups.
[ "The", "supplied", "property", "group", "is", "invalid", ".", "The", "file", "has", "uploaded", "without", "property", "groups", "." ]
def get_properties_error(self): """ The supplied property group is invalid. The file has uploaded without property groups. Only call this if :meth:`is_properties_error` is true. :rtype: file_properties.InvalidPropertyGroupError """ if not self.is_properties_error(): raise AttributeError("tag 'properties_error' not set") return self._value
[ "def", "get_properties_error", "(", "self", ")", ":", "if", "not", "self", ".", "is_properties_error", "(", ")", ":", "raise", "AttributeError", "(", "\"tag 'properties_error' not set\"", ")", "return", "self", ".", "_value" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/files.py#L9769-L9780
nilboy/pixel-recursive-super-resolution
925d04afb44c035c10f604a7eca02e8f3bc5eb96
solver.py
python
Solver.sample
(self, sess, mu=1.1, step=None)
[]
def sample(self, sess, mu=1.1, step=None): c_logits = self.net.conditioning_logits p_logits = self.net.prior_logits lr_imgs = self.dataset.lr_images hr_imgs = self.dataset.hr_images np_hr_imgs, np_lr_imgs = sess.run([hr_imgs, lr_imgs]) gen_hr_imgs = np.zeros((self.batch_size, 32, 32, 3), dtype=np.float32) #gen_hr_imgs = np_hr_imgs #gen_hr_imgs[:,16:,16:,:] = 0.0 np_c_logits = sess.run(c_logits, feed_dict={lr_imgs: np_lr_imgs, self.net.train:False}) print('iters %d: ' % step) for i in range(32): for j in range(32): for c in range(3): np_p_logits = sess.run(p_logits, feed_dict={hr_imgs: gen_hr_imgs}) new_pixel = logits_2_pixel_value(np_c_logits[:, i, j, c*256:(c+1)*256] + np_p_logits[:, i, j, c*256:(c+1)*256], mu=mu) gen_hr_imgs[:, i, j, c] = new_pixel # save_samples(np_lr_imgs, self.samples_dir + '/lr_' + str(mu*10) + '_' + str(step) + '.jpg') save_samples(np_hr_imgs, self.samples_dir + '/hr_' + str(mu*10) + '_' + str(step) + '.jpg') save_samples(gen_hr_imgs, self.samples_dir + '/generate_' + str(mu*10) + '_' + str(step) + '.jpg')
[ "def", "sample", "(", "self", ",", "sess", ",", "mu", "=", "1.1", ",", "step", "=", "None", ")", ":", "c_logits", "=", "self", ".", "net", ".", "conditioning_logits", "p_logits", "=", "self", ".", "net", ".", "prior_logits", "lr_imgs", "=", "self", "...
https://github.com/nilboy/pixel-recursive-super-resolution/blob/925d04afb44c035c10f604a7eca02e8f3bc5eb96/solver.py#L90-L111
hirofumi0810/neural_sp
b91877c6d2a11f06026480ab422176274d88cbf2
neural_sp/evaluators/accuracy.py
python
eval_accuracy
(models, dataloader, batch_size=1, progressbar=False)
return accuracy
Evaluate a Seq2seq by teacher-forcing accuracy. Args: models (List): models to evaluate dataloader (torch.utils.data.DataLoader): evaluation dataloader batch_size (int): batch size progressbar (bool): if True, visualize progressbar Returns: accuracy (float): Average accuracy
Evaluate a Seq2seq by teacher-forcing accuracy.
[ "Evaluate", "a", "Seq2seq", "by", "teacher", "-", "forcing", "accuracy", "." ]
def eval_accuracy(models, dataloader, batch_size=1, progressbar=False): """Evaluate a Seq2seq by teacher-forcing accuracy. Args: models (List): models to evaluate dataloader (torch.utils.data.DataLoader): evaluation dataloader batch_size (int): batch size progressbar (bool): if True, visualize progressbar Returns: accuracy (float): Average accuracy """ total_acc = 0 n_tokens = 0 # Reset data counter dataloader.reset() if progressbar: pbar = tqdm(total=len(dataloader)) for batch in dataloader: _, observation = models[0](batch, task='all', is_eval=True) n_tokens_b = sum([len(y) for y in batch['ys']]) _acc = observation.get('acc.att', observation.get('acc.att-sub1', 0)) total_acc += _acc * n_tokens_b n_tokens += n_tokens_b if progressbar: pbar.update(len(batch['ys'])) if progressbar: pbar.close() # Reset data counters dataloader.reset(is_new_epoch=True) accuracy = total_acc / n_tokens logger.debug('Accuracy (%s): %.2f %%' % (dataloader.set, accuracy)) return accuracy
[ "def", "eval_accuracy", "(", "models", ",", "dataloader", ",", "batch_size", "=", "1", ",", "progressbar", "=", "False", ")", ":", "total_acc", "=", "0", "n_tokens", "=", "0", "# Reset data counter", "dataloader", ".", "reset", "(", ")", "if", "progressbar",...
https://github.com/hirofumi0810/neural_sp/blob/b91877c6d2a11f06026480ab422176274d88cbf2/neural_sp/evaluators/accuracy.py#L13-L54
secdev/scapy
65089071da1acf54622df0b4fa7fc7673d47d3cd
scapy/layers/tls/cert.py
python
Cert.isSelfSigned
(self)
return False
Return True if the certificate is self-signed: - issuer and subject are the same - the signature of the certificate is valid.
Return True if the certificate is self-signed: - issuer and subject are the same - the signature of the certificate is valid.
[ "Return", "True", "if", "the", "certificate", "is", "self", "-", "signed", ":", "-", "issuer", "and", "subject", "are", "the", "same", "-", "the", "signature", "of", "the", "certificate", "is", "valid", "." ]
def isSelfSigned(self): """ Return True if the certificate is self-signed: - issuer and subject are the same - the signature of the certificate is valid. """ if self.issuer_hash == self.subject_hash: return self.isIssuerCert(self) return False
[ "def", "isSelfSigned", "(", "self", ")", ":", "if", "self", ".", "issuer_hash", "==", "self", ".", "subject_hash", ":", "return", "self", ".", "isIssuerCert", "(", "self", ")", "return", "False" ]
https://github.com/secdev/scapy/blob/65089071da1acf54622df0b4fa7fc7673d47d3cd/scapy/layers/tls/cert.py#L643-L651
samuelclay/NewsBlur
2c45209df01a1566ea105e04d499367f32ac9ad2
vendor/readability/readability.py
python
clean
(text)
return text.strip()
[]
def clean(text): # Many spaces make the following regexes run forever text = re.sub(r"\s{255,}", " " * 255, text) text = re.sub(r"\s*\n\s*", "\n", text) text = re.sub(r"\t|[ \t]{2,}", " ", text) return text.strip()
[ "def", "clean", "(", "text", ")", ":", "# Many spaces make the following regexes run forever", "text", "=", "re", ".", "sub", "(", "r\"\\s{255,}\"", ",", "\" \"", "*", "255", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r\"\\s*\\n\\s*\"", ",", "\"\...
https://github.com/samuelclay/NewsBlur/blob/2c45209df01a1566ea105e04d499367f32ac9ad2/vendor/readability/readability.py#L65-L70
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/mako/parsetree.py
python
Comment.__repr__
(self)
return "Comment(%r, %r)" % (self.text, (self.lineno, self.pos))
[]
def __repr__(self): return "Comment(%r, %r)" % (self.text, (self.lineno, self.pos))
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"Comment(%r, %r)\"", "%", "(", "self", ".", "text", ",", "(", "self", ".", "lineno", ",", "self", ".", "pos", ")", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/mako/parsetree.py#L187-L188
hakril/PythonForWindows
61e027a678d5b87aa64fcf8a37a6661a86236589
windows/winproxy/apis/kernel32.py
python
WriteProcessMemory
(hProcess, lpBaseAddress, lpBuffer, nSize=None, lpNumberOfBytesWritten=None)
return WriteProcessMemory.ctypes_function(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten)
Computer nSize with len(lpBuffer) if not given
Computer nSize with len(lpBuffer) if not given
[ "Computer", "nSize", "with", "len", "(", "lpBuffer", ")", "if", "not", "given" ]
def WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize=None, lpNumberOfBytesWritten=None): """Computer nSize with len(lpBuffer) if not given""" if nSize is None: nSize = len(lpBuffer) return WriteProcessMemory.ctypes_function(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten)
[ "def", "WriteProcessMemory", "(", "hProcess", ",", "lpBaseAddress", ",", "lpBuffer", ",", "nSize", "=", "None", ",", "lpNumberOfBytesWritten", "=", "None", ")", ":", "if", "nSize", "is", "None", ":", "nSize", "=", "len", "(", "lpBuffer", ")", "return", "Wr...
https://github.com/hakril/PythonForWindows/blob/61e027a678d5b87aa64fcf8a37a6661a86236589/windows/winproxy/apis/kernel32.py#L278-L282
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/lib/werkzeug/routing.py
python
MapAdapter.make_redirect_url
(self, path_info, query_args=None, domain_part=None)
return str('%s://%s/%s%s' % ( self.url_scheme or 'http', self.get_host(domain_part), posixpath.join(self.script_name[:-1].lstrip('/'), path_info.lstrip('/')), suffix ))
Creates a redirect URL. :internal:
Creates a redirect URL.
[ "Creates", "a", "redirect", "URL", "." ]
def make_redirect_url(self, path_info, query_args=None, domain_part=None): """Creates a redirect URL. :internal: """ suffix = '' if query_args: suffix = '?' + self.encode_query_args(query_args) return str('%s://%s/%s%s' % ( self.url_scheme or 'http', self.get_host(domain_part), posixpath.join(self.script_name[:-1].lstrip('/'), path_info.lstrip('/')), suffix ))
[ "def", "make_redirect_url", "(", "self", ",", "path_info", ",", "query_args", "=", "None", ",", "domain_part", "=", "None", ")", ":", "suffix", "=", "''", "if", "query_args", ":", "suffix", "=", "'?'", "+", "self", ".", "encode_query_args", "(", "query_arg...
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/werkzeug/routing.py#L1646-L1660
geometalab/Vector-Tiles-Reader-QGIS-Plugin
a31ae86959c8f3b7d6f332f84191cd7ca4683e1d
ext-libs/google/protobuf/internal/well_known_types.py
python
Timestamp.ToSeconds
(self)
return self.seconds
Converts Timestamp to seconds since epoch.
Converts Timestamp to seconds since epoch.
[ "Converts", "Timestamp", "to", "seconds", "since", "epoch", "." ]
def ToSeconds(self): """Converts Timestamp to seconds since epoch.""" return self.seconds
[ "def", "ToSeconds", "(", "self", ")", ":", "return", "self", ".", "seconds" ]
https://github.com/geometalab/Vector-Tiles-Reader-QGIS-Plugin/blob/a31ae86959c8f3b7d6f332f84191cd7ca4683e1d/ext-libs/google/protobuf/internal/well_known_types.py#L203-L205
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Centos_5.9/pyasn1/type/namedtype.py
python
NamedTypes.getTagMapNearPosition
(self, idx)
[]
def getTagMapNearPosition(self, idx): if not self.__ambigiousTypes: self.__buildAmbigiousTagMap() try: return self.__ambigiousTypes[idx].getTagMap() except KeyError: raise error.PyAsn1Error('Type position out of range')
[ "def", "getTagMapNearPosition", "(", "self", ",", "idx", ")", ":", "if", "not", "self", ".", "__ambigiousTypes", ":", "self", ".", "__buildAmbigiousTagMap", "(", ")", "try", ":", "return", "self", ".", "__ambigiousTypes", "[", "idx", "]", ".", "getTagMap", ...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_5.9/pyasn1/type/namedtype.py#L101-L106
prompt-toolkit/python-prompt-toolkit
e9eac2eb59ec385e81742fa2ac623d4b8de00925
examples/prompts/colored-prompt.py
python
example_2
()
Using HTML for the formatting.
Using HTML for the formatting.
[ "Using", "HTML", "for", "the", "formatting", "." ]
def example_2(): """ Using HTML for the formatting. """ answer = prompt( HTML( "<username>john</username><at>@</at>" "<host>localhost</host>" "<colon>:</colon>" "<path>/user/john</path>" '<style bg="#00aa00" fg="#ffffff">#</style> ' ), style=style, ) print("You said: %s" % answer)
[ "def", "example_2", "(", ")", ":", "answer", "=", "prompt", "(", "HTML", "(", "\"<username>john</username><at>@</at>\"", "\"<host>localhost</host>\"", "\"<colon>:</colon>\"", "\"<path>/user/john</path>\"", "'<style bg=\"#00aa00\" fg=\"#ffffff\">#</style> '", ")", ",", "style", ...
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/e9eac2eb59ec385e81742fa2ac623d4b8de00925/examples/prompts/colored-prompt.py#L46-L60