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
iclavera/learning_to_adapt
bd7d99ba402521c96631e7d09714128f549db0f1
learning_to_adapt/mujoco_py/mjtypes.py
python
MjvLightWrapper.castshadow
(self, value)
[]
def castshadow(self, value): self._wrapped.contents.castshadow = value
[ "def", "castshadow", "(", "self", ",", "value", ")", ":", "self", ".", "_wrapped", ".", "contents", ".", "castshadow", "=", "value" ]
https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/learning_to_adapt/mujoco_py/mjtypes.py#L1782-L1783
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_mutating_webhook_configuration.py
python
V1MutatingWebhookConfiguration.api_version
(self)
return self._api_version
Gets the api_version of this V1MutatingWebhookConfiguration. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1MutatingWebhookConfiguration. # noqa: E501 :rtype: str
Gets the api_version of this V1MutatingWebhookConfiguration. # noqa: E501
[ "Gets", "the", "api_version", "of", "this", "V1MutatingWebhookConfiguration", ".", "#", "noqa", ":", "E501" ]
def api_version(self): """Gets the api_version of this V1MutatingWebhookConfiguration. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1MutatingWebhookConfiguration. # noqa: E501 :rtype: str """ return self._api_version
[ "def", "api_version", "(", "self", ")", ":", "return", "self", ".", "_api_version" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_mutating_webhook_configuration.py#L71-L79
simonwagner/mergepbx
c88004aa278f94386a6182230b198bed79f93b35
src/plist/antlr/runtime/antlr3/debug.py
python
DebugEventListener.setTokenBoundaries
(self, t, tokenStartIndex, tokenStopIndex)
Set the token start/stop token index for a subtree root or node. If you are receiving this event over a socket via RemoteDebugEventSocketListener then only t.ID is set.
Set the token start/stop token index for a subtree root or node.
[ "Set", "the", "token", "start", "/", "stop", "token", "index", "for", "a", "subtree", "root", "or", "node", "." ]
def setTokenBoundaries(self, t, tokenStartIndex, tokenStopIndex): """Set the token start/stop token index for a subtree root or node. If you are receiving this event over a socket via RemoteDebugEventSocketListener then only t.ID is set. """ pass
[ "def", "setTokenBoundaries", "(", "self", ",", "t", ",", "tokenStartIndex", ",", "tokenStopIndex", ")", ":", "pass" ]
https://github.com/simonwagner/mergepbx/blob/c88004aa278f94386a6182230b198bed79f93b35/src/plist/antlr/runtime/antlr3/debug.py#L719-L725
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/proxy/proxybase.py
python
ProxyDbBase.find_initial_person
(self)
Find an initial person, given that they might not be available.
Find an initial person, given that they might not be available.
[ "Find", "an", "initial", "person", "given", "that", "they", "might", "not", "be", "available", "." ]
def find_initial_person(self): """ Find an initial person, given that they might not be available. """ person = self.basedb.find_initial_person() if person and self.has_person_handle(person.handle): return person else: return None
[ "def", "find_initial_person", "(", "self", ")", ":", "person", "=", "self", ".", "basedb", ".", "find_initial_person", "(", ")", "if", "person", "and", "self", ".", "has_person_handle", "(", "person", ".", "handle", ")", ":", "return", "person", "else", ":", "return", "None" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/proxy/proxybase.py#L981-L990
lisa-lab/pylearn2
af81e5c362f0df4df85c3e54e23b2adeec026055
pylearn2/monitor.py
python
Monitor.get_epochs_seen
(self)
return self._epochs_seen
.. todo:: WRITEME Returns ------- epochs_seen : int The number of epochs the model has been trained on. One "epoch" is one pass through Dataset.iterator.
.. todo::
[ "..", "todo", "::" ]
def get_epochs_seen(self): """ .. todo:: WRITEME Returns ------- epochs_seen : int The number of epochs the model has been trained on. One "epoch" is one pass through Dataset.iterator. """ return self._epochs_seen
[ "def", "get_epochs_seen", "(", "self", ")", ":", "return", "self", ".", "_epochs_seen" ]
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/monitor.py#L317-L329
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/requests/cookies.py
python
MockRequest.host
(self)
return self.get_host()
[]
def host(self): return self.get_host()
[ "def", "host", "(", "self", ")", ":", "return", "self", ".", "get_host", "(", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/requests/cookies.py#L93-L94
ev3dev/ev3dev-lang-python
f84152ca9b952a7a47a3f477542f878f3b69b824
ev3dev2/motor.py
python
MoveDifferential.on_arc_left
(self, speed, radius_mm, distance_mm, brake=True, block=True)
Drive counter-clockwise in a circle with 'radius_mm' for 'distance_mm'
Drive counter-clockwise in a circle with 'radius_mm' for 'distance_mm'
[ "Drive", "counter", "-", "clockwise", "in", "a", "circle", "with", "radius_mm", "for", "distance_mm" ]
def on_arc_left(self, speed, radius_mm, distance_mm, brake=True, block=True): """ Drive counter-clockwise in a circle with 'radius_mm' for 'distance_mm' """ self._on_arc(speed, radius_mm, distance_mm, brake, block, False)
[ "def", "on_arc_left", "(", "self", ",", "speed", ",", "radius_mm", ",", "distance_mm", ",", "brake", "=", "True", ",", "block", "=", "True", ")", ":", "self", ".", "_on_arc", "(", "speed", ",", "radius_mm", ",", "distance_mm", ",", "brake", ",", "block", ",", "False", ")" ]
https://github.com/ev3dev/ev3dev-lang-python/blob/f84152ca9b952a7a47a3f477542f878f3b69b824/ev3dev2/motor.py#L2558-L2562
nats-io/nats.py
49635bf58b1c888c66fa37569a9248b1a83a6c0a
nats/protocol/command.py
python
unsub_cmd
(sid, limit)
return f'{UNSUB_OP} {sid} {limit_s}{_CRLF_}'.encode()
[]
def unsub_cmd(sid, limit): limit_s = '' if limit == 0 else f'{limit}' return f'{UNSUB_OP} {sid} {limit_s}{_CRLF_}'.encode()
[ "def", "unsub_cmd", "(", "sid", ",", "limit", ")", ":", "limit_s", "=", "''", "if", "limit", "==", "0", "else", "f'{limit}'", "return", "f'{UNSUB_OP} {sid} {limit_s}{_CRLF_}'", ".", "encode", "(", ")" ]
https://github.com/nats-io/nats.py/blob/49635bf58b1c888c66fa37569a9248b1a83a6c0a/nats/protocol/command.py#L24-L26
albertz/music-player
d23586f5bf657cbaea8147223be7814d117ae73d
mac/pyobjc-framework-Quartz/Examples/Programming with Quartz/BasicDrawing/AppDrawing.py
python
doImageMaskedWithColor
(context)
[]
def doImageMaskedWithColor(context): url = GetURL(kOtherColorImage) if url is not None: ImageMasking.doMaskImageWithColorFromURL(context, url, RAW_IMAGE_WIDTH, RAW_IMAGE_HEIGHT, True)
[ "def", "doImageMaskedWithColor", "(", "context", ")", ":", "url", "=", "GetURL", "(", "kOtherColorImage", ")", "if", "url", "is", "not", "None", ":", "ImageMasking", ".", "doMaskImageWithColorFromURL", "(", "context", ",", "url", ",", "RAW_IMAGE_WIDTH", ",", "RAW_IMAGE_HEIGHT", ",", "True", ")" ]
https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/mac/pyobjc-framework-Quartz/Examples/Programming with Quartz/BasicDrawing/AppDrawing.py#L147-L153
python-mechanize/mechanize
3cd4d19ee701d9aa458fa23b7515c268d3f1cef0
mechanize/_useragent.py
python
UserAgentBase.set_cookiejar
(self, cookiejar)
Set a mechanize.CookieJar, or None.
Set a mechanize.CookieJar, or None.
[ "Set", "a", "mechanize", ".", "CookieJar", "or", "None", "." ]
def set_cookiejar(self, cookiejar): """Set a mechanize.CookieJar, or None.""" self._set_handler("_cookies", obj=cookiejar)
[ "def", "set_cookiejar", "(", "self", ",", "cookiejar", ")", ":", "self", ".", "_set_handler", "(", "\"_cookies\"", ",", "obj", "=", "cookiejar", ")" ]
https://github.com/python-mechanize/mechanize/blob/3cd4d19ee701d9aa458fa23b7515c268d3f1cef0/mechanize/_useragent.py#L170-L172
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/plat-mac/gensuitemodule.py
python
processfile
(fullname, output=None, basepkgname=None, edit_modnames=None, creatorsignature=None, dump=None, verbose=None)
Ask an application for its terminology and process that
Ask an application for its terminology and process that
[ "Ask", "an", "application", "for", "its", "terminology", "and", "process", "that" ]
def processfile(fullname, output=None, basepkgname=None, edit_modnames=None, creatorsignature=None, dump=None, verbose=None): """Ask an application for its terminology and process that""" if not is_scriptable(fullname) and verbose: print >>verbose, "Warning: app does not seem scriptable: %s" % fullname if verbose: print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname) try: aedescobj, launched = OSATerminology.GetAppTerminology(fullname) except MacOS.Error, arg: if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound if verbose: print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually" aedata, sig = getappterminology(fullname, verbose=verbose) if not creatorsignature: creatorsignature = sig else: raise else: if launched: if verbose: print >>verbose, "Launched", fullname raw = aetools.unpack(aedescobj) if not raw: if verbose: print >>verbose, 'Unpack returned empty value:', raw return if not raw[0].data: if verbose: print >>verbose, 'Unpack returned value without data:', raw return aedata = raw[0] aete = decode(aedata.data, verbose) if dump: dumpaetelist([aete], dump) return compileaete(aete, None, fullname, output=output, basepkgname=basepkgname, creatorsignature=creatorsignature, edit_modnames=edit_modnames, verbose=verbose)
[ "def", "processfile", "(", "fullname", ",", "output", "=", "None", ",", "basepkgname", "=", "None", ",", "edit_modnames", "=", "None", ",", "creatorsignature", "=", "None", ",", "dump", "=", "None", ",", "verbose", "=", "None", ")", ":", "if", "not", "is_scriptable", "(", "fullname", ")", "and", "verbose", ":", "print", ">>", "verbose", ",", "\"Warning: app does not seem scriptable: %s\"", "%", "fullname", "if", "verbose", ":", "print", ">>", "verbose", ",", "\"\\nASKING FOR aete DICTIONARY IN\"", ",", "repr", "(", "fullname", ")", "try", ":", "aedescobj", ",", "launched", "=", "OSATerminology", ".", "GetAppTerminology", "(", "fullname", ")", "except", "MacOS", ".", "Error", ",", "arg", ":", "if", "arg", "[", "0", "]", "in", "(", "-", "1701", ",", "-", "192", ")", ":", "# errAEDescNotFound, resNotFound", "if", "verbose", ":", "print", ">>", "verbose", ",", "\"GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually\"", "aedata", ",", "sig", "=", "getappterminology", "(", "fullname", ",", "verbose", "=", "verbose", ")", "if", "not", "creatorsignature", ":", "creatorsignature", "=", "sig", "else", ":", "raise", "else", ":", "if", "launched", ":", "if", "verbose", ":", "print", ">>", "verbose", ",", "\"Launched\"", ",", "fullname", "raw", "=", "aetools", ".", "unpack", "(", "aedescobj", ")", "if", "not", "raw", ":", "if", "verbose", ":", "print", ">>", "verbose", ",", "'Unpack returned empty value:'", ",", "raw", "return", "if", "not", "raw", "[", "0", "]", ".", "data", ":", "if", "verbose", ":", "print", ">>", "verbose", ",", "'Unpack returned value without data:'", ",", "raw", "return", "aedata", "=", "raw", "[", "0", "]", "aete", "=", "decode", "(", "aedata", ".", "data", ",", "verbose", ")", "if", "dump", ":", "dumpaetelist", "(", "[", "aete", "]", ",", "dump", ")", "return", "compileaete", "(", "aete", ",", "None", ",", "fullname", ",", "output", "=", "output", ",", "basepkgname", "=", "basepkgname", ",", "creatorsignature", "=", "creatorsignature", ",", "edit_modnames", "=", "edit_modnames", ",", "verbose", "=", "verbose", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/plat-mac/gensuitemodule.py#L186-L225
fossasia/open-event-server
5ce3b88c0bcf8685944e634701203944b2cf17dd
app/models/user.py
python
User.get_unread_notifs
(self)
return notifs
Get unread notifications with titles, humanized receiving time and Mark-as-read links.
Get unread notifications with titles, humanized receiving time and Mark-as-read links.
[ "Get", "unread", "notifications", "with", "titles", "humanized", "receiving", "time", "and", "Mark", "-", "as", "-", "read", "links", "." ]
def get_unread_notifs(self): """ Get unread notifications with titles, humanized receiving time and Mark-as-read links. """ notifs = [] unread_notifs = Notification.query.filter_by(user=self, is_read=False).order_by( desc(Notification.received_at) ) for notif in unread_notifs: notifs.append( { 'title': notif.title, 'received_at': humanize.naturaltime( datetime.now(pytz.utc) - notif.received_at ), 'mark_read': url_for( 'notifications.mark_as_read', notification_id=notif.id ), } ) return notifs
[ "def", "get_unread_notifs", "(", "self", ")", ":", "notifs", "=", "[", "]", "unread_notifs", "=", "Notification", ".", "query", ".", "filter_by", "(", "user", "=", "self", ",", "is_read", "=", "False", ")", ".", "order_by", "(", "desc", "(", "Notification", ".", "received_at", ")", ")", "for", "notif", "in", "unread_notifs", ":", "notifs", ".", "append", "(", "{", "'title'", ":", "notif", ".", "title", ",", "'received_at'", ":", "humanize", ".", "naturaltime", "(", "datetime", ".", "now", "(", "pytz", ".", "utc", ")", "-", "notif", ".", "received_at", ")", ",", "'mark_read'", ":", "url_for", "(", "'notifications.mark_as_read'", ",", "notification_id", "=", "notif", ".", "id", ")", ",", "}", ")", "return", "notifs" ]
https://github.com/fossasia/open-event-server/blob/5ce3b88c0bcf8685944e634701203944b2cf17dd/app/models/user.py#L395-L417
GoogleCloudPlatform/datastore-ndb-python
cf4cab3f1f69cd04e1a9229871be466b53729f3f
ndb/query.py
python
Parameter.__init__
(self, key)
Constructor. Args: key: The Parameter key, must be either an integer or a string.
Constructor.
[ "Constructor", "." ]
def __init__(self, key): """Constructor. Args: key: The Parameter key, must be either an integer or a string. """ if not isinstance(key, (int, long, basestring)): raise TypeError('Parameter key must be an integer or string, not %s' % (key,)) self.__key = key
[ "def", "__init__", "(", "self", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "(", "int", ",", "long", ",", "basestring", ")", ")", ":", "raise", "TypeError", "(", "'Parameter key must be an integer or string, not %s'", "%", "(", "key", ",", ")", ")", "self", ".", "__key", "=", "key" ]
https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/query.py#L288-L297
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/codecs.py
python
getincrementalencoder
(encoding)
return encoder
Lookup up the codec for the given encoding and return its IncrementalEncoder class or factory function. Raises a LookupError in case the encoding cannot be found or the codecs doesn't provide an incremental encoder.
Lookup up the codec for the given encoding and return its IncrementalEncoder class or factory function.
[ "Lookup", "up", "the", "codec", "for", "the", "given", "encoding", "and", "return", "its", "IncrementalEncoder", "class", "or", "factory", "function", "." ]
def getincrementalencoder(encoding): """ Lookup up the codec for the given encoding and return its IncrementalEncoder class or factory function. Raises a LookupError in case the encoding cannot be found or the codecs doesn't provide an incremental encoder. """ encoder = lookup(encoding).incrementalencoder if encoder is None: raise LookupError(encoding) return encoder
[ "def", "getincrementalencoder", "(", "encoding", ")", ":", "encoder", "=", "lookup", "(", "encoding", ")", ".", "incrementalencoder", "if", "encoder", "is", "None", ":", "raise", "LookupError", "(", "encoding", ")", "return", "encoder" ]
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/codecs.py#L962-L974
MontrealCorpusTools/Montreal-Forced-Aligner
63473f9a4fabd31eec14e1e5022882f85cfdaf31
montreal_forced_aligner/segmenter.py
python
Segmenter.segmentation_options
(self)
return { "max_segment_length": self.max_segment_length, "min_pause_duration": self.min_pause_duration, "snap_boundary_threshold": self.snap_boundary_threshold, "frame_shift": round(self.frame_shift / 1000, 2), }
Options for segmentation
Options for segmentation
[ "Options", "for", "segmentation" ]
def segmentation_options(self): """Options for segmentation""" return { "max_segment_length": self.max_segment_length, "min_pause_duration": self.min_pause_duration, "snap_boundary_threshold": self.snap_boundary_threshold, "frame_shift": round(self.frame_shift / 1000, 2), }
[ "def", "segmentation_options", "(", "self", ")", ":", "return", "{", "\"max_segment_length\"", ":", "self", ".", "max_segment_length", ",", "\"min_pause_duration\"", ":", "self", ".", "min_pause_duration", ",", "\"snap_boundary_threshold\"", ":", "self", ".", "snap_boundary_threshold", ",", "\"frame_shift\"", ":", "round", "(", "self", ".", "frame_shift", "/", "1000", ",", "2", ")", ",", "}" ]
https://github.com/MontrealCorpusTools/Montreal-Forced-Aligner/blob/63473f9a4fabd31eec14e1e5022882f85cfdaf31/montreal_forced_aligner/segmenter.py#L276-L283
criteo/biggraphite
1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30
biggraphite/metadata_cache.py
python
DiskCache.stats
(self)
return ret
Count number of cached entries.
Count number of cached entries.
[ "Count", "number", "of", "cached", "entries", "." ]
def stats(self): """Count number of cached entries.""" ret = super(DiskCache, self).stats() ret["root"] = (self.__env.stat(),) for name, database in self.__databases.items(): with self.__env.begin(database, write=False) as txn: ret[name] = txn.stat(database) return ret
[ "def", "stats", "(", "self", ")", ":", "ret", "=", "super", "(", "DiskCache", ",", "self", ")", ".", "stats", "(", ")", "ret", "[", "\"root\"", "]", "=", "(", "self", ".", "__env", ".", "stat", "(", ")", ",", ")", "for", "name", ",", "database", "in", "self", ".", "__databases", ".", "items", "(", ")", ":", "with", "self", ".", "__env", ".", "begin", "(", "database", ",", "write", "=", "False", ")", "as", "txn", ":", "ret", "[", "name", "]", "=", "txn", ".", "stat", "(", "database", ")", "return", "ret" ]
https://github.com/criteo/biggraphite/blob/1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30/biggraphite/metadata_cache.py#L542-L550
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/lib-tk/turtle.py
python
RawTurtle._clearstamp
(self, stampid)
does the work for clearstamp() and clearstamps()
does the work for clearstamp() and clearstamps()
[ "does", "the", "work", "for", "clearstamp", "()", "and", "clearstamps", "()" ]
def _clearstamp(self, stampid): """does the work for clearstamp() and clearstamps() """ if stampid in self.stampItems: if isinstance(stampid, tuple): for subitem in stampid: self.screen._delete(subitem) else: self.screen._delete(stampid) self.stampItems.remove(stampid) # Delete stampitem from undobuffer if necessary # if clearstamp is called directly. item = ("stamp", stampid) buf = self.undobuffer if item not in buf.buffer: return index = buf.buffer.index(item) buf.buffer.remove(item) if index <= buf.ptr: buf.ptr = (buf.ptr - 1) % buf.bufsize buf.buffer.insert((buf.ptr+1)%buf.bufsize, [None])
[ "def", "_clearstamp", "(", "self", ",", "stampid", ")", ":", "if", "stampid", "in", "self", ".", "stampItems", ":", "if", "isinstance", "(", "stampid", ",", "tuple", ")", ":", "for", "subitem", "in", "stampid", ":", "self", ".", "screen", ".", "_delete", "(", "subitem", ")", "else", ":", "self", ".", "screen", ".", "_delete", "(", "stampid", ")", "self", ".", "stampItems", ".", "remove", "(", "stampid", ")", "# Delete stampitem from undobuffer if necessary", "# if clearstamp is called directly.", "item", "=", "(", "\"stamp\"", ",", "stampid", ")", "buf", "=", "self", ".", "undobuffer", "if", "item", "not", "in", "buf", ".", "buffer", ":", "return", "index", "=", "buf", ".", "buffer", ".", "index", "(", "item", ")", "buf", ".", "buffer", ".", "remove", "(", "item", ")", "if", "index", "<=", "buf", ".", "ptr", ":", "buf", ".", "ptr", "=", "(", "buf", ".", "ptr", "-", "1", ")", "%", "buf", ".", "bufsize", "buf", ".", "buffer", ".", "insert", "(", "(", "buf", ".", "ptr", "+", "1", ")", "%", "buf", ".", "bufsize", ",", "[", "None", "]", ")" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/lib-tk/turtle.py#L2917-L2937
dabeaz/ply
559a7a1feabb0853be79d4f4dd9e9e9e5ea0d08c
example/ansic/cparse.py
python
p_statement
(t)
statement : labeled_statement | expression_statement | compound_statement | selection_statement | iteration_statement | jump_statement
statement : labeled_statement | expression_statement | compound_statement | selection_statement | iteration_statement | jump_statement
[ "statement", ":", "labeled_statement", "|", "expression_statement", "|", "compound_statement", "|", "selection_statement", "|", "iteration_statement", "|", "jump_statement" ]
def p_statement(t): ''' statement : labeled_statement | expression_statement | compound_statement | selection_statement | iteration_statement | jump_statement ''' pass
[ "def", "p_statement", "(", "t", ")", ":", "pass" ]
https://github.com/dabeaz/ply/blob/559a7a1feabb0853be79d4f4dd9e9e9e5ea0d08c/example/ansic/cparse.py#L553-L562
galaxyproject/galaxy
4c03520f05062e0f4a1b3655dc0b7452fda69943
lib/galaxy/datatypes/sequence.py
python
Alignment.split
(cls, input_datasets, subdir_generator_function, split_params)
Split a generic alignment file (not sensible or possible, see subclasses).
Split a generic alignment file (not sensible or possible, see subclasses).
[ "Split", "a", "generic", "alignment", "file", "(", "not", "sensible", "or", "possible", "see", "subclasses", ")", "." ]
def split(cls, input_datasets, subdir_generator_function, split_params): """Split a generic alignment file (not sensible or possible, see subclasses).""" if split_params is None: return None raise NotImplementedError("Can't split generic alignment files")
[ "def", "split", "(", "cls", ",", "input_datasets", ",", "subdir_generator_function", ",", "split_params", ")", ":", "if", "split_params", "is", "None", ":", "return", "None", "raise", "NotImplementedError", "(", "\"Can't split generic alignment files\"", ")" ]
https://github.com/galaxyproject/galaxy/blob/4c03520f05062e0f4a1b3655dc0b7452fda69943/lib/galaxy/datatypes/sequence.py#L303-L307
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/python-openid-2.2.5/openid/server/server.py
python
OpenIDResponse.toHTML
(self, form_tag_attrs=None)
return oidutil.autoSubmitHTML(self.toFormMarkup(form_tag_attrs))
Returns an HTML document that auto-submits the form markup for this response. @returntype: str @see: toFormMarkup @since: 2.1.?
Returns an HTML document that auto-submits the form markup for this response.
[ "Returns", "an", "HTML", "document", "that", "auto", "-", "submits", "the", "form", "markup", "for", "this", "response", "." ]
def toHTML(self, form_tag_attrs=None): """Returns an HTML document that auto-submits the form markup for this response. @returntype: str @see: toFormMarkup @since: 2.1.? """ return oidutil.autoSubmitHTML(self.toFormMarkup(form_tag_attrs))
[ "def", "toHTML", "(", "self", ",", "form_tag_attrs", "=", "None", ")", ":", "return", "oidutil", ".", "autoSubmitHTML", "(", "self", ".", "toFormMarkup", "(", "form_tag_attrs", ")", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/python-openid-2.2.5/openid/server/server.py#L1004-L1014
aleju/imgaug
0101108d4fed06bc5056c4a03e2bcb0216dac326
imgaug/augmenters/geometric.py
python
PiecewiseAffine._augment_maps_by_samples
(self, augmentables, arr_attr_name, samples, cval, mode, order)
return result
[]
def _augment_maps_by_samples(self, augmentables, arr_attr_name, samples, cval, mode, order): result = augmentables for i, augmentable in enumerate(augmentables): arr = getattr(augmentable, arr_attr_name) transformer = self._get_transformer( arr.shape, augmentable.shape, samples.nb_rows[i], samples.nb_cols[i], samples.jitter[i]) if transformer is not None: arr_warped = tf.warp( arr, transformer, order=order if order is not None else samples.order[i], mode=mode if mode is not None else samples.mode[i], cval=cval if cval is not None else samples.cval[i], preserve_range=True, output_shape=arr.shape ) # skimage converts to float64 arr_warped = arr_warped.astype(arr.dtype) # TODO not entirely clear whether this breaks the value # range -- Affine does # TODO add test for this # order=3 matches cubic interpolation and can cause values # to go outside of the range [0.0, 1.0] not clear whether # 4+ also do that # We don't modify segmaps here, because they don't have a # clear value range of [0, 1] if order >= 3 and isinstance(augmentable, ia.HeatmapsOnImage): arr_warped = np.clip(arr_warped, 0.0, 1.0, out=arr_warped) setattr(augmentable, arr_attr_name, arr_warped) return result
[ "def", "_augment_maps_by_samples", "(", "self", ",", "augmentables", ",", "arr_attr_name", ",", "samples", ",", "cval", ",", "mode", ",", "order", ")", ":", "result", "=", "augmentables", "for", "i", ",", "augmentable", "in", "enumerate", "(", "augmentables", ")", ":", "arr", "=", "getattr", "(", "augmentable", ",", "arr_attr_name", ")", "transformer", "=", "self", ".", "_get_transformer", "(", "arr", ".", "shape", ",", "augmentable", ".", "shape", ",", "samples", ".", "nb_rows", "[", "i", "]", ",", "samples", ".", "nb_cols", "[", "i", "]", ",", "samples", ".", "jitter", "[", "i", "]", ")", "if", "transformer", "is", "not", "None", ":", "arr_warped", "=", "tf", ".", "warp", "(", "arr", ",", "transformer", ",", "order", "=", "order", "if", "order", "is", "not", "None", "else", "samples", ".", "order", "[", "i", "]", ",", "mode", "=", "mode", "if", "mode", "is", "not", "None", "else", "samples", ".", "mode", "[", "i", "]", ",", "cval", "=", "cval", "if", "cval", "is", "not", "None", "else", "samples", ".", "cval", "[", "i", "]", ",", "preserve_range", "=", "True", ",", "output_shape", "=", "arr", ".", "shape", ")", "# skimage converts to float64", "arr_warped", "=", "arr_warped", ".", "astype", "(", "arr", ".", "dtype", ")", "# TODO not entirely clear whether this breaks the value", "# range -- Affine does", "# TODO add test for this", "# order=3 matches cubic interpolation and can cause values", "# to go outside of the range [0.0, 1.0] not clear whether", "# 4+ also do that", "# We don't modify segmaps here, because they don't have a", "# clear value range of [0, 1]", "if", "order", ">=", "3", "and", "isinstance", "(", "augmentable", ",", "ia", ".", "HeatmapsOnImage", ")", ":", "arr_warped", "=", "np", ".", "clip", "(", "arr_warped", ",", "0.0", ",", "1.0", ",", "out", "=", "arr_warped", ")", "setattr", "(", "augmentable", ",", "arr_attr_name", ",", "arr_warped", ")", "return", "result" ]
https://github.com/aleju/imgaug/blob/0101108d4fed06bc5056c4a03e2bcb0216dac326/imgaug/augmenters/geometric.py#L3230-L3268
softlayer/softlayer-python
cdef7d63c66413197a9a97b0414de9f95887a82a
SoftLayer/managers/image.py
python
ImageManager.edit
(self, image_id, name=None, note=None, tag=None)
return bool(name or note or tag)
Edit image related details. :param int image_id: The ID of the image :param string name: Name of the Image. :param string note: Note of the image. :param string tag: Tags of the image to be updated to.
Edit image related details.
[ "Edit", "image", "related", "details", "." ]
def edit(self, image_id, name=None, note=None, tag=None): """Edit image related details. :param int image_id: The ID of the image :param string name: Name of the Image. :param string note: Note of the image. :param string tag: Tags of the image to be updated to. """ obj = {} if name: obj['name'] = name if note: obj['note'] = note if obj: self.vgbdtg.editObject(obj, id=image_id) if tag: self.vgbdtg.setTags(str(tag), id=image_id) return bool(name or note or tag)
[ "def", "edit", "(", "self", ",", "image_id", ",", "name", "=", "None", ",", "note", "=", "None", ",", "tag", "=", "None", ")", ":", "obj", "=", "{", "}", "if", "name", ":", "obj", "[", "'name'", "]", "=", "name", "if", "note", ":", "obj", "[", "'note'", "]", "=", "note", "if", "obj", ":", "self", ".", "vgbdtg", ".", "editObject", "(", "obj", ",", "id", "=", "image_id", ")", "if", "tag", ":", "self", ".", "vgbdtg", ".", "setTags", "(", "str", "(", "tag", ")", ",", "id", "=", "image_id", ")", "return", "bool", "(", "name", "or", "note", "or", "tag", ")" ]
https://github.com/softlayer/softlayer-python/blob/cdef7d63c66413197a9a97b0414de9f95887a82a/SoftLayer/managers/image.py#L104-L122
google/glazier
8a7f3dacb8be8a73a15d988d02a3c14e306d8f6e
glazier/lib/beyondcorp.py
python
BeyondCorp._GetDisk
(self, label: str)
return drive_letter
Leverages the drive label to define the drive letter. The BeyondCorp USB device is not gaurenteed to be on a certain drive letter. Args: label: Drive label to use when querying for drive letter. Raises: BCError: Error executing WMI query. BCError: BeyondCorp drive letter was empty. Returns: Drive letter for the drive that contains the seed.
Leverages the drive label to define the drive letter.
[ "Leverages", "the", "drive", "label", "to", "define", "the", "drive", "letter", "." ]
def _GetDisk(self, label: str) -> str: """Leverages the drive label to define the drive letter. The BeyondCorp USB device is not gaurenteed to be on a certain drive letter. Args: label: Drive label to use when querying for drive letter. Raises: BCError: Error executing WMI query. BCError: BeyondCorp drive letter was empty. Returns: Drive letter for the drive that contains the seed. """ query = f'SELECT Name FROM win32_logicaldisk WHERE volumename="{label}"' try: drive_letter = wmi_query.WMIQuery().Query(query)[0].Name except wmi_query.WmiError as e: raise BCError(f'Failed to query WMI for BeyondCorp drive letter: {e}') if not drive_letter: raise BCError('BeyondCorp drive letter was empty.') logging.debug('BeyondCorp Drive letter = %s', drive_letter) return drive_letter
[ "def", "_GetDisk", "(", "self", ",", "label", ":", "str", ")", "->", "str", ":", "query", "=", "f'SELECT Name FROM win32_logicaldisk WHERE volumename=\"{label}\"'", "try", ":", "drive_letter", "=", "wmi_query", ".", "WMIQuery", "(", ")", ".", "Query", "(", "query", ")", "[", "0", "]", ".", "Name", "except", "wmi_query", ".", "WmiError", "as", "e", ":", "raise", "BCError", "(", "f'Failed to query WMI for BeyondCorp drive letter: {e}'", ")", "if", "not", "drive_letter", ":", "raise", "BCError", "(", "'BeyondCorp drive letter was empty.'", ")", "logging", ".", "debug", "(", "'BeyondCorp Drive letter = %s'", ",", "drive_letter", ")", "return", "drive_letter" ]
https://github.com/google/glazier/blob/8a7f3dacb8be8a73a15d988d02a3c14e306d8f6e/glazier/lib/beyondcorp.py#L115-L141
jupyterhub/jupyterhub
e58cf0670690d11631f9dc6e1ab702c60f7bfd13
jupyterhub/utils.py
python
hash_token
(token, salt=8, rounds=16384, algorithm='sha512')
return f"{algorithm}:{rounds}:{salt}:{digest}"
Hash a token, and return it as `algorithm:salt:hash`. If `salt` is an integer, a random salt of that many bytes will be used.
Hash a token, and return it as `algorithm:salt:hash`.
[ "Hash", "a", "token", "and", "return", "it", "as", "algorithm", ":", "salt", ":", "hash", "." ]
def hash_token(token, salt=8, rounds=16384, algorithm='sha512'): """Hash a token, and return it as `algorithm:salt:hash`. If `salt` is an integer, a random salt of that many bytes will be used. """ h = hashlib.new(algorithm) if isinstance(salt, int): salt = b2a_hex(secrets.token_bytes(salt)) if isinstance(salt, bytes): bsalt = salt salt = salt.decode('utf8') else: bsalt = salt.encode('utf8') btoken = token.encode('utf8', 'replace') h.update(bsalt) for i in range(rounds): h.update(btoken) digest = h.hexdigest() return f"{algorithm}:{rounds}:{salt}:{digest}"
[ "def", "hash_token", "(", "token", ",", "salt", "=", "8", ",", "rounds", "=", "16384", ",", "algorithm", "=", "'sha512'", ")", ":", "h", "=", "hashlib", ".", "new", "(", "algorithm", ")", "if", "isinstance", "(", "salt", ",", "int", ")", ":", "salt", "=", "b2a_hex", "(", "secrets", ".", "token_bytes", "(", "salt", ")", ")", "if", "isinstance", "(", "salt", ",", "bytes", ")", ":", "bsalt", "=", "salt", "salt", "=", "salt", ".", "decode", "(", "'utf8'", ")", "else", ":", "bsalt", "=", "salt", ".", "encode", "(", "'utf8'", ")", "btoken", "=", "token", ".", "encode", "(", "'utf8'", ",", "'replace'", ")", "h", ".", "update", "(", "bsalt", ")", "for", "i", "in", "range", "(", "rounds", ")", ":", "h", ".", "update", "(", "btoken", ")", "digest", "=", "h", ".", "hexdigest", "(", ")", "return", "f\"{algorithm}:{rounds}:{salt}:{digest}\"" ]
https://github.com/jupyterhub/jupyterhub/blob/e58cf0670690d11631f9dc6e1ab702c60f7bfd13/jupyterhub/utils.py#L339-L358
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/mailbox.py
python
BabylMessage.set_labels
(self, labels)
Set the list of labels on the message.
Set the list of labels on the message.
[ "Set", "the", "list", "of", "labels", "on", "the", "message", "." ]
def set_labels(self, labels): """Set the list of labels on the message.""" self._labels = list(labels)
[ "def", "set_labels", "(", "self", ",", "labels", ")", ":", "self", ".", "_labels", "=", "list", "(", "labels", ")" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/mailbox.py#L1836-L1838
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_13/paramiko/config.py
python
LazyFqdn.__str__
(self)
return self.fqdn
[]
def __str__(self): if self.fqdn is None: # # If the SSH config contains AddressFamily, use that when # determining the local host's FQDN. Using socket.getfqdn() from # the standard library is the most general solution, but can # result in noticeable delays on some platforms when IPv6 is # misconfigured or not available, as it calls getaddrinfo with no # address family specified, so both IPv4 and IPv6 are checked. # # Handle specific option fqdn = None address_family = self.config.get('addressfamily', 'any').lower() if address_family != 'any': try: family = socket.AF_INET if address_family == 'inet' \ else socket.AF_INET6 results = socket.getaddrinfo( self.host, None, family, socket.SOCK_DGRAM, socket.IPPROTO_IP, socket.AI_CANONNAME ) for res in results: af, socktype, proto, canonname, sa = res if canonname and '.' in canonname: fqdn = canonname break # giaerror -> socket.getaddrinfo() can't resolve self.host # (which is from socket.gethostname()). Fall back to the # getfqdn() call below. except socket.gaierror: pass # Handle 'any' / unspecified if fqdn is None: fqdn = socket.getfqdn() # Cache self.fqdn = fqdn return self.fqdn
[ "def", "__str__", "(", "self", ")", ":", "if", "self", ".", "fqdn", "is", "None", ":", "#", "# If the SSH config contains AddressFamily, use that when", "# determining the local host's FQDN. Using socket.getfqdn() from", "# the standard library is the most general solution, but can", "# result in noticeable delays on some platforms when IPv6 is", "# misconfigured or not available, as it calls getaddrinfo with no", "# address family specified, so both IPv4 and IPv6 are checked.", "#", "# Handle specific option", "fqdn", "=", "None", "address_family", "=", "self", ".", "config", ".", "get", "(", "'addressfamily'", ",", "'any'", ")", ".", "lower", "(", ")", "if", "address_family", "!=", "'any'", ":", "try", ":", "family", "=", "socket", ".", "AF_INET", "if", "address_family", "==", "'inet'", "else", "socket", ".", "AF_INET6", "results", "=", "socket", ".", "getaddrinfo", "(", "self", ".", "host", ",", "None", ",", "family", ",", "socket", ".", "SOCK_DGRAM", ",", "socket", ".", "IPPROTO_IP", ",", "socket", ".", "AI_CANONNAME", ")", "for", "res", "in", "results", ":", "af", ",", "socktype", ",", "proto", ",", "canonname", ",", "sa", "=", "res", "if", "canonname", "and", "'.'", "in", "canonname", ":", "fqdn", "=", "canonname", "break", "# giaerror -> socket.getaddrinfo() can't resolve self.host", "# (which is from socket.gethostname()). Fall back to the", "# getfqdn() call below.", "except", "socket", ".", "gaierror", ":", "pass", "# Handle 'any' / unspecified", "if", "fqdn", "is", "None", ":", "fqdn", "=", "socket", ".", "getfqdn", "(", ")", "# Cache", "self", ".", "fqdn", "=", "fqdn", "return", "self", ".", "fqdn" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_13/paramiko/config.py#L43-L84
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/data/storage.py
python
EdgeStorage.is_coalesced
(self)
return (edge_index.numel() == new_edge_index.numel() and bool( (edge_index == new_edge_index).all()))
[]
def is_coalesced(self) -> bool: for value in self.values('adj', 'adj_t'): return value.is_coalesced() edge_index = self.edge_index new_edge_index, _ = coalesce(edge_index, None, self.size(0), self.size(1)) return (edge_index.numel() == new_edge_index.numel() and bool( (edge_index == new_edge_index).all()))
[ "def", "is_coalesced", "(", "self", ")", "->", "bool", ":", "for", "value", "in", "self", ".", "values", "(", "'adj'", ",", "'adj_t'", ")", ":", "return", "value", ".", "is_coalesced", "(", ")", "edge_index", "=", "self", ".", "edge_index", "new_edge_index", ",", "_", "=", "coalesce", "(", "edge_index", ",", "None", ",", "self", ".", "size", "(", "0", ")", ",", "self", ".", "size", "(", "1", ")", ")", "return", "(", "edge_index", ".", "numel", "(", ")", "==", "new_edge_index", ".", "numel", "(", ")", "and", "bool", "(", "(", "edge_index", "==", "new_edge_index", ")", ".", "all", "(", ")", ")", ")" ]
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/data/storage.py#L380-L388
v1k45/django-notify-x
c8828c1c0c550b7b33acccb4db51fc612045afa3
notify/templatetags/notification_tags.py
python
RenderNotificationsNode.generate_html
(self, notifications)
return html_string
Generates rendered HTML content using supplied notifications. :param notifications: Notification QuerySet Object :return: Rendered HTML.
Generates rendered HTML content using supplied notifications. :param notifications: Notification QuerySet Object :return: Rendered HTML.
[ "Generates", "rendered", "HTML", "content", "using", "supplied", "notifications", ".", ":", "param", "notifications", ":", "Notification", "QuerySet", "Object", ":", "return", ":", "Rendered", "HTML", "." ]
def generate_html(self, notifications): """ Generates rendered HTML content using supplied notifications. :param notifications: Notification QuerySet Object :return: Rendered HTML. """ html_chunks = [] for nf in notifications: extra = nf.as_json() if self.target == 'box' else {} html = render_notification(nf, render_target=self.target, **extra) html_chunks.append(html) if not html_chunks: html_chunks.append(_("<b>No notifications yet.</b>")) html_string = '\n'.join(html_chunks) return html_string
[ "def", "generate_html", "(", "self", ",", "notifications", ")", ":", "html_chunks", "=", "[", "]", "for", "nf", "in", "notifications", ":", "extra", "=", "nf", ".", "as_json", "(", ")", "if", "self", ".", "target", "==", "'box'", "else", "{", "}", "html", "=", "render_notification", "(", "nf", ",", "render_target", "=", "self", ".", "target", ",", "*", "*", "extra", ")", "html_chunks", ".", "append", "(", "html", ")", "if", "not", "html_chunks", ":", "html_chunks", ".", "append", "(", "_", "(", "\"<b>No notifications yet.</b>\"", ")", ")", "html_string", "=", "'\\n'", ".", "join", "(", "html_chunks", ")", "return", "html_string" ]
https://github.com/v1k45/django-notify-x/blob/c8828c1c0c550b7b33acccb4db51fc612045afa3/notify/templatetags/notification_tags.py#L46-L60
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/apis/remote_process_groups_api.py
python
RemoteProcessGroupsApi.get_remote_process_group_with_http_info
(self, id, **kwargs)
return self.api_client.call_api('/remote-process-groups/{id}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='RemoteProcessGroupEntity', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
Gets a remote process group This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_remote_process_group_with_http_info(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: The remote process group id. (required) :return: RemoteProcessGroupEntity If the method is called asynchronously, returns the request thread.
Gets a remote process group
[ "Gets", "a", "remote", "process", "group" ]
def get_remote_process_group_with_http_info(self, id, **kwargs): """ Gets a remote process group This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_remote_process_group_with_http_info(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: The remote process group id. (required) :return: RemoteProcessGroupEntity If the method is called asynchronously, returns the request thread. """ all_params = ['id'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_remote_process_group" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params) or (params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_remote_process_group`") collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['tokenAuth'] return self.api_client.call_api('/remote-process-groups/{id}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='RemoteProcessGroupEntity', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
[ "def", "get_remote_process_group_with_http_info", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "all_params", "=", "[", "'id'", "]", "all_params", ".", "append", "(", "'callback'", ")", "all_params", ".", "append", "(", "'_return_http_data_only'", ")", "all_params", ".", "append", "(", "'_preload_content'", ")", "all_params", ".", "append", "(", "'_request_timeout'", ")", "params", "=", "locals", "(", ")", "for", "key", ",", "val", "in", "iteritems", "(", "params", "[", "'kwargs'", "]", ")", ":", "if", "key", "not", "in", "all_params", ":", "raise", "TypeError", "(", "\"Got an unexpected keyword argument '%s'\"", "\" to method get_remote_process_group\"", "%", "key", ")", "params", "[", "key", "]", "=", "val", "del", "params", "[", "'kwargs'", "]", "# verify the required parameter 'id' is set", "if", "(", "'id'", "not", "in", "params", ")", "or", "(", "params", "[", "'id'", "]", "is", "None", ")", ":", "raise", "ValueError", "(", "\"Missing the required parameter `id` when calling `get_remote_process_group`\"", ")", "collection_formats", "=", "{", "}", "path_params", "=", "{", "}", "if", "'id'", "in", "params", ":", "path_params", "[", "'id'", "]", "=", "params", "[", "'id'", "]", "query_params", "=", "[", "]", "header_params", "=", "{", "}", "form_params", "=", "[", "]", "local_var_files", "=", "{", "}", "body_params", "=", "None", "# HTTP header `Accept`", "header_params", "[", "'Accept'", "]", "=", "self", ".", "api_client", ".", "select_header_accept", "(", "[", "'application/json'", "]", ")", "# HTTP header `Content-Type`", "header_params", "[", "'Content-Type'", "]", "=", "self", ".", "api_client", ".", "select_header_content_type", "(", "[", "'*/*'", "]", ")", "# Authentication setting", "auth_settings", "=", "[", "'tokenAuth'", "]", "return", "self", ".", "api_client", ".", "call_api", "(", "'/remote-process-groups/{id}'", ",", "'GET'", ",", "path_params", ",", "query_params", ",", "header_params", ",", "body", "=", "body_params", ",", "post_params", "=", "form_params", ",", "files", "=", "local_var_files", ",", "response_type", "=", "'RemoteProcessGroupEntity'", ",", "auth_settings", "=", "auth_settings", ",", "callback", "=", "params", ".", "get", "(", "'callback'", ")", ",", "_return_http_data_only", "=", "params", ".", "get", "(", "'_return_http_data_only'", ")", ",", "_preload_content", "=", "params", ".", "get", "(", "'_preload_content'", ",", "True", ")", ",", "_request_timeout", "=", "params", ".", "get", "(", "'_request_timeout'", ")", ",", "collection_formats", "=", "collection_formats", ")" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/apis/remote_process_groups_api.py#L69-L147
poodarchu/Det3D
01258d8cb26656c5b950f8d41f9dcc1dd62a391e
det3d/ops/align_aggregation/correlation/modules/correlation.py
python
Correlation.forward
(self, input1, input2)
return correlation( input1, input2, self.kernel_size, self.patch_size, self.stride, self.padding, self.dilation_patch, )
[]
def forward(self, input1, input2): return correlation( input1, input2, self.kernel_size, self.patch_size, self.stride, self.padding, self.dilation_patch, )
[ "def", "forward", "(", "self", ",", "input1", ",", "input2", ")", ":", "return", "correlation", "(", "input1", ",", "input2", ",", "self", ".", "kernel_size", ",", "self", ".", "patch_size", ",", "self", ".", "stride", ",", "self", ".", "padding", ",", "self", ".", "dilation_patch", ",", ")" ]
https://github.com/poodarchu/Det3D/blob/01258d8cb26656c5b950f8d41f9dcc1dd62a391e/det3d/ops/align_aggregation/correlation/modules/correlation.py#L33-L42
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
tensorflow_dl_models/research/differential_privacy/dp_sgd/per_example_gradients/per_example_gradients.py
python
PXGRegistry.Register
(self, op_name, pxg_class)
Associates `op_name` key with `pxg_class` value. Registers `pxg_class` as the class that will be called to perform per-example differentiation through ops with `op_name`. Args: op_name: String op name. pxg_class: An instance of any class with the same signature as MatMulPXG.
Associates `op_name` key with `pxg_class` value.
[ "Associates", "op_name", "key", "with", "pxg_class", "value", "." ]
def Register(self, op_name, pxg_class): """Associates `op_name` key with `pxg_class` value. Registers `pxg_class` as the class that will be called to perform per-example differentiation through ops with `op_name`. Args: op_name: String op name. pxg_class: An instance of any class with the same signature as MatMulPXG. """ self.d[op_name] = pxg_class
[ "def", "Register", "(", "self", ",", "op_name", ",", "pxg_class", ")", ":", "self", ".", "d", "[", "op_name", "]", "=", "pxg_class" ]
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/tensorflow_dl_models/research/differential_privacy/dp_sgd/per_example_gradients/per_example_gradients.py#L132-L142
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/jinja2_35/jinja2/visitor.py
python
NodeVisitor.visit
(self, node, *args, **kwargs)
return self.generic_visit(node, *args, **kwargs)
Visit a node.
Visit a node.
[ "Visit", "a", "node", "." ]
def visit(self, node, *args, **kwargs): """Visit a node.""" f = self.get_visitor(node) if f is not None: return f(node, *args, **kwargs) return self.generic_visit(node, *args, **kwargs)
[ "def", "visit", "(", "self", ",", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "f", "=", "self", ".", "get_visitor", "(", "node", ")", "if", "f", "is", "not", "None", ":", "return", "f", "(", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "generic_visit", "(", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/jinja2_35/jinja2/visitor.py#L34-L39
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_image.py
python
Image.text
(self)
return self["text"]
Sets the text elements associated with each z value. The 'text' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray
Sets the text elements associated with each z value. The 'text' property is an array that may be specified as a tuple, list, numpy array, or pandas Series
[ "Sets", "the", "text", "elements", "associated", "with", "each", "z", "value", ".", "The", "text", "property", "is", "an", "array", "that", "may", "be", "specified", "as", "a", "tuple", "list", "numpy", "array", "or", "pandas", "Series" ]
def text(self): """ Sets the text elements associated with each z value. The 'text' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["text"]
[ "def", "text", "(", "self", ")", ":", "return", "self", "[", "\"text\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_image.py#L615-L626
cocos2d/cocos2d-x-samples
9f1472d9083a18853bb1fe97a337292f42abe44a
download-engine.py
python
CocosZipInstaller.unpack_zipfile
(self, extract_dir)
Unpack zip `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined by ``zipfile.is_zipfile()``).
Unpack zip `filename` to `extract_dir`
[ "Unpack", "zip", "filename", "to", "extract_dir" ]
def unpack_zipfile(self, extract_dir): """Unpack zip `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined by ``zipfile.is_zipfile()``). """ self.ensure_directory(self._extracted_folder_name); if not zipfile.is_zipfile(self._filename): raise UnrecognizedFormat("%s is not a zip file" % (self._filename)) print("==> Extracting files, please wait ...") z = zipfile.ZipFile(self._filename) try: for info in z.infolist(): name = info.filename # don't extract absolute paths or ones with .. in them if name.startswith('/') or '..' in name: continue target = os.path.join(extract_dir, *name.split('/')) if not target: continue dirname = os.path.dirname(target) if not os.path.exists(dirname): os.makedirs(dirname) if name.endswith('/'): # directory self.ensure_directory(target) else: # file data = z.read(info.filename) f = open(target, 'wb') try: f.write(data) finally: f.close() del data unix_attributes = info.external_attr >> 16 if unix_attributes: os.chmod(target, unix_attributes) finally: z.close() print("==> Extraction done!")
[ "def", "unpack_zipfile", "(", "self", ",", "extract_dir", ")", ":", "self", ".", "ensure_directory", "(", "self", ".", "_extracted_folder_name", ")", "if", "not", "zipfile", ".", "is_zipfile", "(", "self", ".", "_filename", ")", ":", "raise", "UnrecognizedFormat", "(", "\"%s is not a zip file\"", "%", "(", "self", ".", "_filename", ")", ")", "print", "(", "\"==> Extracting files, please wait ...\"", ")", "z", "=", "zipfile", ".", "ZipFile", "(", "self", ".", "_filename", ")", "try", ":", "for", "info", "in", "z", ".", "infolist", "(", ")", ":", "name", "=", "info", ".", "filename", "# don't extract absolute paths or ones with .. in them", "if", "name", ".", "startswith", "(", "'/'", ")", "or", "'..'", "in", "name", ":", "continue", "target", "=", "os", ".", "path", ".", "join", "(", "extract_dir", ",", "*", "name", ".", "split", "(", "'/'", ")", ")", "if", "not", "target", ":", "continue", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "target", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "if", "name", ".", "endswith", "(", "'/'", ")", ":", "# directory", "self", ".", "ensure_directory", "(", "target", ")", "else", ":", "# file", "data", "=", "z", ".", "read", "(", "info", ".", "filename", ")", "f", "=", "open", "(", "target", ",", "'wb'", ")", "try", ":", "f", ".", "write", "(", "data", ")", "finally", ":", "f", ".", "close", "(", ")", "del", "data", "unix_attributes", "=", "info", ".", "external_attr", ">>", "16", "if", "unix_attributes", ":", "os", ".", "chmod", "(", "target", ",", "unix_attributes", ")", "finally", ":", "z", ".", "close", "(", ")", "print", "(", "\"==> Extraction done!\"", ")" ]
https://github.com/cocos2d/cocos2d-x-samples/blob/9f1472d9083a18853bb1fe97a337292f42abe44a/download-engine.py#L148-L195
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/external/six.py
python
python_2_unicode_compatible
(klass)
return klass
A class 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 class decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing.
[ "A", "class", "decorator", "that", "defines", "__unicode__", "and", "__str__", "methods", "under", "Python", "2", ".", "Under", "Python", "3", "it", "does", "nothing", "." ]
def python_2_unicode_compatible(klass): """ A class 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__().\"", "%", "klass", ".", "__name__", ")", "klass", ".", "__unicode__", "=", "klass", ".", "__str__", "klass", ".", "__str__", "=", "lambda", "self", ":", "self", ".", "__unicode__", "(", ")", ".", "encode", "(", "'utf-8'", ")", "return", "klass" ]
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/external/six.py#L958-L973
tvaddonsco/script.module.urlresolver
ddeca574c133d51879624bf3059c6e73445d90bc
lib/urlresolver/plugins/lib/jscrypto/pyaes.py
python
AES.shift_rows
(self, b)
ShiftRows step. Shifts 2nd row to left by 1, 3rd row by 2, 4th row by 3 Since we're performing this on a transposed matrix, cells are numbered from top to bottom:: 0 4 8 12 -> 0 4 8 12 -- 1st row doesn't change 1 5 9 13 -> 5 9 13 1 -- row shifted to left by 1 (wraps around) 2 6 10 14 -> 10 14 2 6 -- shifted by 2 3 7 11 15 -> 15 3 7 11 -- shifted by 3
ShiftRows step. Shifts 2nd row to left by 1, 3rd row by 2, 4th row by 3
[ "ShiftRows", "step", ".", "Shifts", "2nd", "row", "to", "left", "by", "1", "3rd", "row", "by", "2", "4th", "row", "by", "3" ]
def shift_rows(self, b): """ShiftRows step. Shifts 2nd row to left by 1, 3rd row by 2, 4th row by 3 Since we're performing this on a transposed matrix, cells are numbered from top to bottom:: 0 4 8 12 -> 0 4 8 12 -- 1st row doesn't change 1 5 9 13 -> 5 9 13 1 -- row shifted to left by 1 (wraps around) 2 6 10 14 -> 10 14 2 6 -- shifted by 2 3 7 11 15 -> 15 3 7 11 -- shifted by 3 """ b[1], b[5], b[9], b[13] = b[5], b[9], b[13], b[1] b[2], b[6], b[10], b[14] = b[10], b[14], b[2], b[6] b[3], b[7], b[11], b[15] = b[15], b[3], b[7], b[11]
[ "def", "shift_rows", "(", "self", ",", "b", ")", ":", "b", "[", "1", "]", ",", "b", "[", "5", "]", ",", "b", "[", "9", "]", ",", "b", "[", "13", "]", "=", "b", "[", "5", "]", ",", "b", "[", "9", "]", ",", "b", "[", "13", "]", ",", "b", "[", "1", "]", "b", "[", "2", "]", ",", "b", "[", "6", "]", ",", "b", "[", "10", "]", ",", "b", "[", "14", "]", "=", "b", "[", "10", "]", ",", "b", "[", "14", "]", ",", "b", "[", "2", "]", ",", "b", "[", "6", "]", "b", "[", "3", "]", ",", "b", "[", "7", "]", ",", "b", "[", "11", "]", ",", "b", "[", "15", "]", "=", "b", "[", "15", "]", ",", "b", "[", "3", "]", ",", "b", "[", "7", "]", ",", "b", "[", "11", "]" ]
https://github.com/tvaddonsco/script.module.urlresolver/blob/ddeca574c133d51879624bf3059c6e73445d90bc/lib/urlresolver/plugins/lib/jscrypto/pyaes.py#L190-L204
cool-RR/python_toolbox
cb9ef64b48f1d03275484d707dc5079b6701ad0c
python_toolbox/zip_tools.py
python
zip_folder
(source_folder, zip_path, ignored_patterns=())
Zip `folder` into a zip file specified by `zip_path`. Note: Creates a folder inside the zip with the same name of the original folder, in contrast to other implementation which put all of the files on the root level of the zip. `ignored_patterns` are fnmatch-style patterns specifiying file-paths to ignore. Any empty sub-folders will be ignored.
Zip `folder` into a zip file specified by `zip_path`.
[ "Zip", "folder", "into", "a", "zip", "file", "specified", "by", "zip_path", "." ]
def zip_folder(source_folder, zip_path, ignored_patterns=()): ''' Zip `folder` into a zip file specified by `zip_path`. Note: Creates a folder inside the zip with the same name of the original folder, in contrast to other implementation which put all of the files on the root level of the zip. `ignored_patterns` are fnmatch-style patterns specifiying file-paths to ignore. Any empty sub-folders will be ignored. ''' zip_path = pathlib.Path(zip_path) source_folder = pathlib.Path(source_folder).absolute() assert source_folder.is_dir() ignored_re_patterns = [re.compile(fnmatch.translate(ignored_pattern)) for ignored_pattern in ignored_patterns] zip_name = zip_path.stem internal_pure_path = pathlib.PurePath(source_folder.name) with zip_module.ZipFile(str(zip_path), 'w', zip_module.ZIP_DEFLATED) \ as zip_file: for root, subfolders, files in os.walk(str(source_folder)): root = pathlib.Path(root) subfolders = map(pathlib.Path, subfolders) files = map(pathlib.Path, files) for file_path in files: if any(ignored_re_pattern.match(root / file_path) for ignored_re_pattern in ignored_re_patterns): continue absolute_file_path = root / file_path destination_file_path = internal_pure_path / \ absolute_file_path.name zip_file.write(str(absolute_file_path), str(destination_file_path))
[ "def", "zip_folder", "(", "source_folder", ",", "zip_path", ",", "ignored_patterns", "=", "(", ")", ")", ":", "zip_path", "=", "pathlib", ".", "Path", "(", "zip_path", ")", "source_folder", "=", "pathlib", ".", "Path", "(", "source_folder", ")", ".", "absolute", "(", ")", "assert", "source_folder", ".", "is_dir", "(", ")", "ignored_re_patterns", "=", "[", "re", ".", "compile", "(", "fnmatch", ".", "translate", "(", "ignored_pattern", ")", ")", "for", "ignored_pattern", "in", "ignored_patterns", "]", "zip_name", "=", "zip_path", ".", "stem", "internal_pure_path", "=", "pathlib", ".", "PurePath", "(", "source_folder", ".", "name", ")", "with", "zip_module", ".", "ZipFile", "(", "str", "(", "zip_path", ")", ",", "'w'", ",", "zip_module", ".", "ZIP_DEFLATED", ")", "as", "zip_file", ":", "for", "root", ",", "subfolders", ",", "files", "in", "os", ".", "walk", "(", "str", "(", "source_folder", ")", ")", ":", "root", "=", "pathlib", ".", "Path", "(", "root", ")", "subfolders", "=", "map", "(", "pathlib", ".", "Path", ",", "subfolders", ")", "files", "=", "map", "(", "pathlib", ".", "Path", ",", "files", ")", "for", "file_path", "in", "files", ":", "if", "any", "(", "ignored_re_pattern", ".", "match", "(", "root", "/", "file_path", ")", "for", "ignored_re_pattern", "in", "ignored_re_patterns", ")", ":", "continue", "absolute_file_path", "=", "root", "/", "file_path", "destination_file_path", "=", "internal_pure_path", "/", "absolute_file_path", ".", "name", "zip_file", ".", "write", "(", "str", "(", "absolute_file_path", ")", ",", "str", "(", "destination_file_path", ")", ")" ]
https://github.com/cool-RR/python_toolbox/blob/cb9ef64b48f1d03275484d707dc5079b6701ad0c/python_toolbox/zip_tools.py#L16-L60
JacquesLucke/animation_nodes
b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1
animation_nodes/problems.py
python
UndefinedNodeExists.__init__
(self, nodes)
[]
def __init__(self, nodes): self.nodeIDs = [node.toID() for node in nodes]
[ "def", "__init__", "(", "self", ",", "nodes", ")", ":", "self", ".", "nodeIDs", "=", "[", "node", ".", "toID", "(", ")", "for", "node", "in", "nodes", "]" ]
https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/problems.py#L140-L141
styxit/HTPC-Manager
490697460b4fa1797106aece27d873bc256b2ff1
libs/requests/packages/urllib3/connectionpool.py
python
HTTPConnectionPool._new_conn
(self)
return HTTPConnection(host=self.host, port=self.port, strict=self.strict)
Return a fresh :class:`httplib.HTTPConnection`.
Return a fresh :class:`httplib.HTTPConnection`.
[ "Return", "a", "fresh", ":", "class", ":", "httplib", ".", "HTTPConnection", "." ]
def _new_conn(self): """ Return a fresh :class:`httplib.HTTPConnection`. """ self.num_connections += 1 log.info("Starting new HTTP connection (%d): %s" % (self.num_connections, self.host)) return HTTPConnection(host=self.host, port=self.port, strict=self.strict)
[ "def", "_new_conn", "(", "self", ")", ":", "self", ".", "num_connections", "+=", "1", "log", ".", "info", "(", "\"Starting new HTTP connection (%d): %s\"", "%", "(", "self", ".", "num_connections", ",", "self", ".", "host", ")", ")", "return", "HTTPConnection", "(", "host", "=", "self", ".", "host", ",", "port", "=", "self", ".", "port", ",", "strict", "=", "self", ".", "strict", ")" ]
https://github.com/styxit/HTPC-Manager/blob/490697460b4fa1797106aece27d873bc256b2ff1/libs/requests/packages/urllib3/connectionpool.py#L196-L205
Kaggle/kaggle-api
49057db362903d158b1e71a43d888b981dd27159
kaggle/models/dataset_upload_file.py
python
DatasetUploadFile.columns
(self, columns)
Sets the columns of this DatasetUploadFile. A list of dataset column metadata # noqa: E501 :param columns: The columns of this DatasetUploadFile. # noqa: E501 :type: list[DatasetColumn]
Sets the columns of this DatasetUploadFile.
[ "Sets", "the", "columns", "of", "this", "DatasetUploadFile", "." ]
def columns(self, columns): """Sets the columns of this DatasetUploadFile. A list of dataset column metadata # noqa: E501 :param columns: The columns of this DatasetUploadFile. # noqa: E501 :type: list[DatasetColumn] """ self._columns = columns
[ "def", "columns", "(", "self", ",", "columns", ")", ":", "self", ".", "_columns", "=", "columns" ]
https://github.com/Kaggle/kaggle-api/blob/49057db362903d158b1e71a43d888b981dd27159/kaggle/models/dataset_upload_file.py#L136-L145
OctoPrint/OctoPrint
4b12b0e6f06c3abfb31b1840a0605e2de8e911d2
src/octoprint/filemanager/storage.py
python
LocalFileStorage.sanitize_name
(self, name)
return sanitize_filename(name, really_universal=self._really_universal)
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise sanitizes the given ``name`` using ``octoprint.files.sanitize_filename``. Also strips any leading ``.``.
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise sanitizes the given ``name`` using ``octoprint.files.sanitize_filename``. Also strips any leading ``.``.
[ "Raises", "a", ":", "class", ":", "ValueError", "for", "a", "name", "containing", "/", "or", "\\\\", ".", "Otherwise", "sanitizes", "the", "given", "name", "using", "octoprint", ".", "files", ".", "sanitize_filename", ".", "Also", "strips", "any", "leading", ".", "." ]
def sanitize_name(self, name): """ Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise sanitizes the given ``name`` using ``octoprint.files.sanitize_filename``. Also strips any leading ``.``. """ return sanitize_filename(name, really_universal=self._really_universal)
[ "def", "sanitize_name", "(", "self", ",", "name", ")", ":", "return", "sanitize_filename", "(", "name", ",", "really_universal", "=", "self", ".", "_really_universal", ")" ]
https://github.com/OctoPrint/OctoPrint/blob/4b12b0e6f06c3abfb31b1840a0605e2de8e911d2/src/octoprint/filemanager/storage.py#L1168-L1174
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/venv/lib/python2.7/site-packages/pip/_vendor/distlib/util.py
python
EventMixin.add
(self, event, subscriber, append=True)
Add a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be added (and called when the event is published). :param append: Whether to append or prepend the subscriber to an existing subscriber list for the event.
Add a subscriber for an event.
[ "Add", "a", "subscriber", "for", "an", "event", "." ]
def add(self, event, subscriber, append=True): """ Add a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be added (and called when the event is published). :param append: Whether to append or prepend the subscriber to an existing subscriber list for the event. """ subs = self._subscribers if event not in subs: subs[event] = deque([subscriber]) else: sq = subs[event] if append: sq.append(subscriber) else: sq.appendleft(subscriber)
[ "def", "add", "(", "self", ",", "event", ",", "subscriber", ",", "append", "=", "True", ")", ":", "subs", "=", "self", ".", "_subscribers", "if", "event", "not", "in", "subs", ":", "subs", "[", "event", "]", "=", "deque", "(", "[", "subscriber", "]", ")", "else", ":", "sq", "=", "subs", "[", "event", "]", "if", "append", ":", "sq", ".", "append", "(", "subscriber", ")", "else", ":", "sq", ".", "appendleft", "(", "subscriber", ")" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/venv/lib/python2.7/site-packages/pip/_vendor/distlib/util.py#L825-L843
microsoft/nlp-recipes
7db6d204e5116da07bb3c549df546e49cb7ab5a5
utils_nlp/eval/rouge/rouge_ext.py
python
RougeExt.tokenize_text
(self, text)
return self.word_tokenize(text, self.language)
Tokenize text in the specific language Args: text: The string text to tokenize language: Language of the text Returns: List of tokens of text
Tokenize text in the specific language
[ "Tokenize", "text", "in", "the", "specific", "language" ]
def tokenize_text(self, text): """ Tokenize text in the specific language Args: text: The string text to tokenize language: Language of the text Returns: List of tokens of text """ return self.word_tokenize(text, self.language)
[ "def", "tokenize_text", "(", "self", ",", "text", ")", ":", "return", "self", ".", "word_tokenize", "(", "text", ",", "self", ".", "language", ")" ]
https://github.com/microsoft/nlp-recipes/blob/7db6d204e5116da07bb3c549df546e49cb7ab5a5/utils_nlp/eval/rouge/rouge_ext.py#L190-L201
yandex/yandex-tank
b41bcc04396c4ed46fc8b28a261197320854fd33
yandextank/core/tankcore.py
python
TankCore.add_artifact_file
(self, filename, keep_original=False)
Add file to be stored as result artifact on post-process phase
Add file to be stored as result artifact on post-process phase
[ "Add", "file", "to", "be", "stored", "as", "result", "artifact", "on", "post", "-", "process", "phase" ]
def add_artifact_file(self, filename, keep_original=False): """ Add file to be stored as result artifact on post-process phase """ if filename: logger.debug( "Adding artifact file to collect (keep=%s): %s", keep_original, filename) self.artifact_files[filename] = keep_original
[ "def", "add_artifact_file", "(", "self", ",", "filename", ",", "keep_original", "=", "False", ")", ":", "if", "filename", ":", "logger", ".", "debug", "(", "\"Adding artifact file to collect (keep=%s): %s\"", ",", "keep_original", ",", "filename", ")", "self", ".", "artifact_files", "[", "filename", "]", "=", "keep_original" ]
https://github.com/yandex/yandex-tank/blob/b41bcc04396c4ed46fc8b28a261197320854fd33/yandextank/core/tankcore.py#L456-L464
privacyidea/privacyidea
9490c12ddbf77a34ac935b082d09eb583dfafa2c
privacyidea/lib/applications/luks.py
python
MachineApplication.get_authentication_item
(token_type, serial, challenge=None, options=None, filter_param=None)
return ret
:param token_type: the type of the token. At the moment we only support yubikeys, tokentype "TOTP". :param serial: the serial number of the token. The challenge response token needs to start with "UBOM". :param challenge: A challenge, for which a response get calculated. If none is presented, we create one. :type challenge: hex string :return auth_item: For Yubikey token type it returns a dictionary with a "challenge" and a "response".
:param token_type: the type of the token. At the moment we only support yubikeys, tokentype "TOTP". :param serial: the serial number of the token. The challenge response token needs to start with "UBOM". :param challenge: A challenge, for which a response get calculated. If none is presented, we create one. :type challenge: hex string :return auth_item: For Yubikey token type it returns a dictionary with a "challenge" and a "response".
[ ":", "param", "token_type", ":", "the", "type", "of", "the", "token", ".", "At", "the", "moment", "we", "only", "support", "yubikeys", "tokentype", "TOTP", ".", ":", "param", "serial", ":", "the", "serial", "number", "of", "the", "token", ".", "The", "challenge", "response", "token", "needs", "to", "start", "with", "UBOM", ".", ":", "param", "challenge", ":", "A", "challenge", "for", "which", "a", "response", "get", "calculated", ".", "If", "none", "is", "presented", "we", "create", "one", ".", ":", "type", "challenge", ":", "hex", "string", ":", "return", "auth_item", ":", "For", "Yubikey", "token", "type", "it", "returns", "a", "dictionary", "with", "a", "challenge", "and", "a", "response", "." ]
def get_authentication_item(token_type, serial, challenge=None, options=None, filter_param=None): """ :param token_type: the type of the token. At the moment we only support yubikeys, tokentype "TOTP". :param serial: the serial number of the token. The challenge response token needs to start with "UBOM". :param challenge: A challenge, for which a response get calculated. If none is presented, we create one. :type challenge: hex string :return auth_item: For Yubikey token type it returns a dictionary with a "challenge" and a "response". """ ret = {} options = options or {} if token_type.lower() == "totp" and serial.startswith("UBOM"): # create a challenge of 32 byte # Although the yubikey is capable of doing 64byte challenges # the hmac module calculates different responses for 64 bytes. if challenge is None: challenge = geturandom(32) challenge_hex = hexlify_and_unicode(challenge) else: challenge_hex = challenge ret["challenge"] = challenge_hex # create the response. We need to get # the HMAC key and calculate a HMAC response for # the challenge toks = get_tokens(serial=serial, active=True) if len(toks) == 1: # tokenclass is a TimeHmacTokenClass (_r, _p, otp, _c) = toks[0].get_otp(challenge=challenge_hex, do_truncation=False) ret["response"] = otp else: log.info("Token %r, type %r is not supported by " "LUKS application module" % (serial, token_type)) return ret
[ "def", "get_authentication_item", "(", "token_type", ",", "serial", ",", "challenge", "=", "None", ",", "options", "=", "None", ",", "filter_param", "=", "None", ")", ":", "ret", "=", "{", "}", "options", "=", "options", "or", "{", "}", "if", "token_type", ".", "lower", "(", ")", "==", "\"totp\"", "and", "serial", ".", "startswith", "(", "\"UBOM\"", ")", ":", "# create a challenge of 32 byte", "# Although the yubikey is capable of doing 64byte challenges", "# the hmac module calculates different responses for 64 bytes.", "if", "challenge", "is", "None", ":", "challenge", "=", "geturandom", "(", "32", ")", "challenge_hex", "=", "hexlify_and_unicode", "(", "challenge", ")", "else", ":", "challenge_hex", "=", "challenge", "ret", "[", "\"challenge\"", "]", "=", "challenge_hex", "# create the response. We need to get", "# the HMAC key and calculate a HMAC response for", "# the challenge", "toks", "=", "get_tokens", "(", "serial", "=", "serial", ",", "active", "=", "True", ")", "if", "len", "(", "toks", ")", "==", "1", ":", "# tokenclass is a TimeHmacTokenClass", "(", "_r", ",", "_p", ",", "otp", ",", "_c", ")", "=", "toks", "[", "0", "]", ".", "get_otp", "(", "challenge", "=", "challenge_hex", ",", "do_truncation", "=", "False", ")", "ret", "[", "\"response\"", "]", "=", "otp", "else", ":", "log", ".", "info", "(", "\"Token %r, type %r is not supported by \"", "\"LUKS application module\"", "%", "(", "serial", ",", "token_type", ")", ")", "return", "ret" ]
https://github.com/privacyidea/privacyidea/blob/9490c12ddbf77a34ac935b082d09eb583dfafa2c/privacyidea/lib/applications/luks.py#L40-L82
blockchain-certificates/cert-issuer
eeb2c1d7c6b90eb9f09763ee84479b2fe447c0cc
cert_issuer/blockchain_handlers/bitcoin/tx_utils.py
python
calculate_tx_total
(tx_cost_constants, num_inputs, num_outputs)
return total
:param tx_cost_constants: :param num_inputs: :param num_outputs: :return:
[]
def calculate_tx_total(tx_cost_constants, num_inputs, num_outputs): """ :param tx_cost_constants: :param num_inputs: :param num_outputs: :return: """ tx_fee = calculate_tx_fee(tx_cost_constants, num_inputs, num_outputs) coin_per_output = tx_cost_constants.get_minimum_output_coin() total = coin_per_output * num_outputs + tx_fee return total
[ "def", "calculate_tx_total", "(", "tx_cost_constants", ",", "num_inputs", ",", "num_outputs", ")", ":", "tx_fee", "=", "calculate_tx_fee", "(", "tx_cost_constants", ",", "num_inputs", ",", "num_outputs", ")", "coin_per_output", "=", "tx_cost_constants", ".", "get_minimum_output_coin", "(", ")", "total", "=", "coin_per_output", "*", "num_outputs", "+", "tx_fee", "return", "total" ]
https://github.com/blockchain-certificates/cert-issuer/blob/eeb2c1d7c6b90eb9f09763ee84479b2fe447c0cc/cert_issuer/blockchain_handlers/bitcoin/tx_utils.py#L124-L135
fancompute/ceviche
5da9df12cb2b15cc25ca1a3d4b5eb827eb89e195
examples/optimize_mode_converter.py
python
operator_blur
(rho, radius=2)
return conv(rho, kernel, mode='full')[radius:-radius,radius:-radius]
Blur operator implemented via two-dimensional convolution
Blur operator implemented via two-dimensional convolution
[ "Blur", "operator", "implemented", "via", "two", "-", "dimensional", "convolution" ]
def operator_blur(rho, radius=2): """Blur operator implemented via two-dimensional convolution """ rr, cc = circle(radius, radius, radius+1) kernel = np.zeros((2*radius+1, 2*radius+1), dtype=np.float) kernel[rr, cc] = 1 kernel=kernel/kernel.sum() # For whatever reason HIPS autograd doesn't support 'same' mode, so we need to manually crop the output return conv(rho, kernel, mode='full')[radius:-radius,radius:-radius]
[ "def", "operator_blur", "(", "rho", ",", "radius", "=", "2", ")", ":", "rr", ",", "cc", "=", "circle", "(", "radius", ",", "radius", ",", "radius", "+", "1", ")", "kernel", "=", "np", ".", "zeros", "(", "(", "2", "*", "radius", "+", "1", ",", "2", "*", "radius", "+", "1", ")", ",", "dtype", "=", "np", ".", "float", ")", "kernel", "[", "rr", ",", "cc", "]", "=", "1", "kernel", "=", "kernel", "/", "kernel", ".", "sum", "(", ")", "# For whatever reason HIPS autograd doesn't support 'same' mode, so we need to manually crop the output", "return", "conv", "(", "rho", ",", "kernel", ",", "mode", "=", "'full'", ")", "[", "radius", ":", "-", "radius", ",", "radius", ":", "-", "radius", "]" ]
https://github.com/fancompute/ceviche/blob/5da9df12cb2b15cc25ca1a3d4b5eb827eb89e195/examples/optimize_mode_converter.py#L57-L65
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/__init__.py
python
RcParams.find_all
(self, pattern)
return RcParams((key, value) for key, value in self.items() if pattern_re.search(key))
Return the subset of this RcParams dictionary whose keys match, using :func:`re.search`, the given ``pattern``. .. note:: Changes to the returned dictionary are *not* propagated to the parent RcParams dictionary.
Return the subset of this RcParams dictionary whose keys match, using :func:`re.search`, the given ``pattern``.
[ "Return", "the", "subset", "of", "this", "RcParams", "dictionary", "whose", "keys", "match", "using", ":", "func", ":", "re", ".", "search", "the", "given", "pattern", "." ]
def find_all(self, pattern): """ Return the subset of this RcParams dictionary whose keys match, using :func:`re.search`, the given ``pattern``. .. note:: Changes to the returned dictionary are *not* propagated to the parent RcParams dictionary. """ pattern_re = re.compile(pattern) return RcParams((key, value) for key, value in self.items() if pattern_re.search(key))
[ "def", "find_all", "(", "self", ",", "pattern", ")", ":", "pattern_re", "=", "re", ".", "compile", "(", "pattern", ")", "return", "RcParams", "(", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "self", ".", "items", "(", ")", "if", "pattern_re", ".", "search", "(", "key", ")", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/__init__.py#L916-L930
ilius/pyglossary
d599b3beda3ae17642af5debd83bb991148e6425
pyglossary/plugins/dict_cc.py
python
Reader.close
(self)
[]
def close(self): if self._cur: self._cur.close() if self._con: self._con.close() self._clear()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_cur", ":", "self", ".", "_cur", ".", "close", "(", ")", "if", "self", ".", "_con", ":", "self", ".", "_con", ".", "close", "(", ")", "self", ".", "_clear", "(", ")" ]
https://github.com/ilius/pyglossary/blob/d599b3beda3ae17642af5debd83bb991148e6425/pyglossary/plugins/dict_cc.py#L165-L170
aws-cloudformation/cfn-lint
16df5d0ca0d8ebcf9330ebea701e83d883b47217
src/cfnlint/rules/functions/DynamicReferenceSecureString.py
python
DynamicReferenceSecureString.match_resource_properties
(self, properties, resource_type, path, cfn)
return matches
Check CloudFormation Properties
Check CloudFormation Properties
[ "Check", "CloudFormation", "Properties" ]
def match_resource_properties(self, properties, resource_type, path, cfn): """Check CloudFormation Properties""" matches = [] resource_specs = self.resource_specs.get(resource_type, {}).get('Properties', {}) matches.extend(self.check(cfn, properties, resource_specs, resource_type, path)) return matches
[ "def", "match_resource_properties", "(", "self", ",", "properties", ",", "resource_type", ",", "path", ",", "cfn", ")", ":", "matches", "=", "[", "]", "resource_specs", "=", "self", ".", "resource_specs", ".", "get", "(", "resource_type", ",", "{", "}", ")", ".", "get", "(", "'Properties'", ",", "{", "}", ")", "matches", ".", "extend", "(", "self", ".", "check", "(", "cfn", ",", "properties", ",", "resource_specs", ",", "resource_type", ",", "path", ")", ")", "return", "matches" ]
https://github.com/aws-cloudformation/cfn-lint/blob/16df5d0ca0d8ebcf9330ebea701e83d883b47217/src/cfnlint/rules/functions/DynamicReferenceSecureString.py#L130-L136
taomujian/linbing
fe772a58f41e3b046b51a866bdb7e4655abaf51a
python/app/thirdparty/oneforall/modules/search/zoomeye_api.py
python
ZoomEyeAPI.login
(self)
登陆获取查询taken
登陆获取查询taken
[ "登陆获取查询taken" ]
def login(self): """ 登陆获取查询taken """ url = 'https://api.zoomeye.org/user/login' data = {'username': self.user, 'password': self.pwd} resp = self.post(url=url, json=data) if not resp: logger.log('ALERT', f'{self.source} module login failed') return None data = resp.json() if resp.status_code == 200: logger.log('DEBUG', f'{self.source} module login success') return data.get('access_token') else: logger.log('ALERT', data.get('message')) return None
[ "def", "login", "(", "self", ")", ":", "url", "=", "'https://api.zoomeye.org/user/login'", "data", "=", "{", "'username'", ":", "self", ".", "user", ",", "'password'", ":", "self", ".", "pwd", "}", "resp", "=", "self", ".", "post", "(", "url", "=", "url", ",", "json", "=", "data", ")", "if", "not", "resp", ":", "logger", ".", "log", "(", "'ALERT'", ",", "f'{self.source} module login failed'", ")", "return", "None", "data", "=", "resp", ".", "json", "(", ")", "if", "resp", ".", "status_code", "==", "200", ":", "logger", ".", "log", "(", "'DEBUG'", ",", "f'{self.source} module login success'", ")", "return", "data", ".", "get", "(", "'access_token'", ")", "else", ":", "logger", ".", "log", "(", "'ALERT'", ",", "data", ".", "get", "(", "'message'", ")", ")", "return", "None" ]
https://github.com/taomujian/linbing/blob/fe772a58f41e3b046b51a866bdb7e4655abaf51a/python/app/thirdparty/oneforall/modules/search/zoomeye_api.py#L18-L34
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/solvers/ode.py
python
_nonlinear_2eq_order1_type5
(func, t, eq)
return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))}
r""" Clairaut system of ODEs .. math:: x = t x' + F(x',y') .. math:: y = t y' + G(x',y') The following are solutions of the system `(i)` straight lines: .. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2) where `C_1` and `C_2` are arbitrary constants; `(ii)` envelopes of the above lines; `(iii)` continuously differentiable lines made up from segments of the lines `(i)` and `(ii)`.
r""" Clairaut system of ODEs
[ "r", "Clairaut", "system", "of", "ODEs" ]
def _nonlinear_2eq_order1_type5(func, t, eq): r""" Clairaut system of ODEs .. math:: x = t x' + F(x',y') .. math:: y = t y' + G(x',y') The following are solutions of the system `(i)` straight lines: .. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2) where `C_1` and `C_2` are arbitrary constants; `(ii)` envelopes of the above lines; `(iii)` continuously differentiable lines made up from segments of the lines `(i)` and `(ii)`. """ C1, C2 = get_numbered_constants(eq, num=2) f = Wild('f') g = Wild('g') def check_type(x, y): r1 = eq[0].match(t*diff(x(t),t) - x(t) + f) r2 = eq[1].match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t) r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t) if not (r1 and r2): r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f) r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t) r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t) return [r1, r2] for func_ in func: if isinstance(func_, list): x = func[0][0].func y = func[0][1].func [r1, r2] = check_type(x, y) if not (r1 and r2): [r1, r2] = check_type(y, x) x, y = y, x x1 = diff(x(t),t); y1 = diff(y(t),t) return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))}
[ "def", "_nonlinear_2eq_order1_type5", "(", "func", ",", "t", ",", "eq", ")", ":", "C1", ",", "C2", "=", "get_numbered_constants", "(", "eq", ",", "num", "=", "2", ")", "f", "=", "Wild", "(", "'f'", ")", "g", "=", "Wild", "(", "'g'", ")", "def", "check_type", "(", "x", ",", "y", ")", ":", "r1", "=", "eq", "[", "0", "]", ".", "match", "(", "t", "*", "diff", "(", "x", "(", "t", ")", ",", "t", ")", "-", "x", "(", "t", ")", "+", "f", ")", "r2", "=", "eq", "[", "1", "]", ".", "match", "(", "t", "*", "diff", "(", "y", "(", "t", ")", ",", "t", ")", "-", "y", "(", "t", ")", "+", "g", ")", "if", "not", "(", "r1", "and", "r2", ")", ":", "r1", "=", "eq", "[", "0", "]", ".", "match", "(", "diff", "(", "x", "(", "t", ")", ",", "t", ")", "-", "x", "(", "t", ")", "/", "t", "+", "f", "/", "t", ")", "r2", "=", "eq", "[", "1", "]", ".", "match", "(", "diff", "(", "y", "(", "t", ")", ",", "t", ")", "-", "y", "(", "t", ")", "/", "t", "+", "g", "/", "t", ")", "if", "not", "(", "r1", "and", "r2", ")", ":", "r1", "=", "(", "-", "eq", "[", "0", "]", ")", ".", "match", "(", "t", "*", "diff", "(", "x", "(", "t", ")", ",", "t", ")", "-", "x", "(", "t", ")", "+", "f", ")", "r2", "=", "(", "-", "eq", "[", "1", "]", ")", ".", "match", "(", "t", "*", "diff", "(", "y", "(", "t", ")", ",", "t", ")", "-", "y", "(", "t", ")", "+", "g", ")", "if", "not", "(", "r1", "and", "r2", ")", ":", "r1", "=", "(", "-", "eq", "[", "0", "]", ")", ".", "match", "(", "diff", "(", "x", "(", "t", ")", ",", "t", ")", "-", "x", "(", "t", ")", "/", "t", "+", "f", "/", "t", ")", "r2", "=", "(", "-", "eq", "[", "1", "]", ")", ".", "match", "(", "diff", "(", "y", "(", "t", ")", ",", "t", ")", "-", "y", "(", "t", ")", "/", "t", "+", "g", "/", "t", ")", "return", "[", "r1", ",", "r2", "]", "for", "func_", "in", "func", ":", "if", "isinstance", "(", "func_", ",", "list", ")", ":", "x", "=", "func", "[", "0", "]", "[", "0", "]", ".", "func", "y", "=", "func", "[", "0", "]", "[", "1", "]", ".", "func", "[", "r1", ",", "r2", "]", "=", "check_type", "(", "x", ",", "y", ")", "if", "not", "(", "r1", "and", "r2", ")", ":", "[", "r1", ",", "r2", "]", "=", "check_type", "(", "y", ",", "x", ")", "x", ",", "y", "=", "y", ",", "x", "x1", "=", "diff", "(", "x", "(", "t", ")", ",", "t", ")", "y1", "=", "diff", "(", "y", "(", "t", ")", ",", "t", ")", "return", "{", "Eq", "(", "x", "(", "t", ")", ",", "C1", "*", "t", "+", "r1", "[", "f", "]", ".", "subs", "(", "x1", ",", "C1", ")", ".", "subs", "(", "y1", ",", "C2", ")", ")", ",", "Eq", "(", "y", "(", "t", ")", ",", "C2", "*", "t", "+", "r2", "[", "g", "]", ".", "subs", "(", "x1", ",", "C1", ")", ".", "subs", "(", "y1", ",", "C2", ")", ")", "}" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/solvers/ode.py#L8958-L9005
coderholic/pyradio
cd3ee2d6b369fedfd009371a59aca23ab39b020f
pyradio/log.py
python
Log.__init__
(self)
[]
def __init__(self): self.width = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "width", "=", "None" ]
https://github.com/coderholic/pyradio/blob/cd3ee2d6b369fedfd009371a59aca23ab39b020f/pyradio/log.py#L30-L31
steeve/xbmctorrent
e6bcb1037668959e1e3cb5ba8cf3e379c6638da9
resources/site-packages/html5lib/inputstream.py
python
HTMLBinaryInputStream.detectBOM
(self)
return encoding
Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None
Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None
[ "Attempts", "to", "detect", "at", "BOM", "at", "the", "start", "of", "the", "stream", ".", "If", "an", "encoding", "can", "be", "determined", "from", "the", "BOM", "return", "the", "name", "of", "the", "encoding", "otherwise", "return", "None" ]
def detectBOM(self): """Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None""" bomDict = { codecs.BOM_UTF8: 'utf-8', codecs.BOM_UTF16_LE: 'utf-16-le', codecs.BOM_UTF16_BE: 'utf-16-be', codecs.BOM_UTF32_LE: 'utf-32-le', codecs.BOM_UTF32_BE: 'utf-32-be' } # Go to beginning of file and read in 4 bytes string = self.rawStream.read(4) assert isinstance(string, bytes) # Try detecting the BOM using bytes from the string encoding = bomDict.get(string[:3]) # UTF-8 seek = 3 if not encoding: # Need to detect UTF-32 before UTF-16 encoding = bomDict.get(string) # UTF-32 seek = 4 if not encoding: encoding = bomDict.get(string[:2]) # UTF-16 seek = 2 # Set the read position past the BOM if one was found, otherwise # set it to the start of the stream self.rawStream.seek(encoding and seek or 0) return encoding
[ "def", "detectBOM", "(", "self", ")", ":", "bomDict", "=", "{", "codecs", ".", "BOM_UTF8", ":", "'utf-8'", ",", "codecs", ".", "BOM_UTF16_LE", ":", "'utf-16-le'", ",", "codecs", ".", "BOM_UTF16_BE", ":", "'utf-16-be'", ",", "codecs", ".", "BOM_UTF32_LE", ":", "'utf-32-le'", ",", "codecs", ".", "BOM_UTF32_BE", ":", "'utf-32-be'", "}", "# Go to beginning of file and read in 4 bytes", "string", "=", "self", ".", "rawStream", ".", "read", "(", "4", ")", "assert", "isinstance", "(", "string", ",", "bytes", ")", "# Try detecting the BOM using bytes from the string", "encoding", "=", "bomDict", ".", "get", "(", "string", "[", ":", "3", "]", ")", "# UTF-8", "seek", "=", "3", "if", "not", "encoding", ":", "# Need to detect UTF-32 before UTF-16", "encoding", "=", "bomDict", ".", "get", "(", "string", ")", "# UTF-32", "seek", "=", "4", "if", "not", "encoding", ":", "encoding", "=", "bomDict", ".", "get", "(", "string", "[", ":", "2", "]", ")", "# UTF-16", "seek", "=", "2", "# Set the read position past the BOM if one was found, otherwise", "# set it to the start of the stream", "self", ".", "rawStream", ".", "seek", "(", "encoding", "and", "seek", "or", "0", ")", "return", "encoding" ]
https://github.com/steeve/xbmctorrent/blob/e6bcb1037668959e1e3cb5ba8cf3e379c6638da9/resources/site-packages/html5lib/inputstream.py#L500-L529
ray-project/ray
703c1610348615dcb8c2d141a0c46675084660f5
python/ray/util/collective/collective.py
python
recv
(tensor, src_rank: int, group_name: str = "default")
Receive a tensor from a remote process synchronously. Args: tensor: the received tensor. src_rank (int): the rank of the source process. group_name (str): the name of the collective group. Returns: None
Receive a tensor from a remote process synchronously.
[ "Receive", "a", "tensor", "from", "a", "remote", "process", "synchronously", "." ]
def recv(tensor, src_rank: int, group_name: str = "default"): """Receive a tensor from a remote process synchronously. Args: tensor: the received tensor. src_rank (int): the rank of the source process. group_name (str): the name of the collective group. Returns: None """ _check_single_tensor_input(tensor) g = _check_and_get_group(group_name) _check_rank_valid(g, src_rank) if src_rank == g.rank: raise RuntimeError( "The destination rank '{}' is self.".format(src_rank)) opts = types.RecvOptions() opts.src_rank = src_rank g.recv([tensor], opts)
[ "def", "recv", "(", "tensor", ",", "src_rank", ":", "int", ",", "group_name", ":", "str", "=", "\"default\"", ")", ":", "_check_single_tensor_input", "(", "tensor", ")", "g", "=", "_check_and_get_group", "(", "group_name", ")", "_check_rank_valid", "(", "g", ",", "src_rank", ")", "if", "src_rank", "==", "g", ".", "rank", ":", "raise", "RuntimeError", "(", "\"The destination rank '{}' is self.\"", ".", "format", "(", "src_rank", ")", ")", "opts", "=", "types", ".", "RecvOptions", "(", ")", "opts", ".", "src_rank", "=", "src_rank", "g", ".", "recv", "(", "[", "tensor", "]", ",", "opts", ")" ]
https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/python/ray/util/collective/collective.py#L583-L602
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Demo/rpc/rpc.py
python
unix_epoch
()
return _unix_epoch
Very painful calculation of when the Unix Epoch is. This is defined as the return value of time.time() on Jan 1st, 1970, 00:00:00 GMT. On a Unix system, this should always return 0.0. On a Mac, the calculations are needed -- and hard because of integer overflow and other limitations.
Very painful calculation of when the Unix Epoch is.
[ "Very", "painful", "calculation", "of", "when", "the", "Unix", "Epoch", "is", "." ]
def unix_epoch(): """Very painful calculation of when the Unix Epoch is. This is defined as the return value of time.time() on Jan 1st, 1970, 00:00:00 GMT. On a Unix system, this should always return 0.0. On a Mac, the calculations are needed -- and hard because of integer overflow and other limitations. """ global _unix_epoch if _unix_epoch >= 0: return _unix_epoch import time now = time.time() localt = time.localtime(now) # (y, m, d, hh, mm, ss, ..., ..., ...) gmt = time.gmtime(now) offset = time.mktime(localt) - time.mktime(gmt) y, m, d, hh, mm, ss = 1970, 1, 1, 0, 0, 0 offset, ss = divmod(ss + offset, 60) offset, mm = divmod(mm + offset, 60) offset, hh = divmod(hh + offset, 24) d = d + offset _unix_epoch = time.mktime((y, m, d, hh, mm, ss, 0, 0, 0)) print "Unix epoch:", time.ctime(_unix_epoch) return _unix_epoch
[ "def", "unix_epoch", "(", ")", ":", "global", "_unix_epoch", "if", "_unix_epoch", ">=", "0", ":", "return", "_unix_epoch", "import", "time", "now", "=", "time", ".", "time", "(", ")", "localt", "=", "time", ".", "localtime", "(", "now", ")", "# (y, m, d, hh, mm, ss, ..., ..., ...)", "gmt", "=", "time", ".", "gmtime", "(", "now", ")", "offset", "=", "time", ".", "mktime", "(", "localt", ")", "-", "time", ".", "mktime", "(", "gmt", ")", "y", ",", "m", ",", "d", ",", "hh", ",", "mm", ",", "ss", "=", "1970", ",", "1", ",", "1", ",", "0", ",", "0", ",", "0", "offset", ",", "ss", "=", "divmod", "(", "ss", "+", "offset", ",", "60", ")", "offset", ",", "mm", "=", "divmod", "(", "mm", "+", "offset", ",", "60", ")", "offset", ",", "hh", "=", "divmod", "(", "hh", "+", "offset", ",", "24", ")", "d", "=", "d", "+", "offset", "_unix_epoch", "=", "time", ".", "mktime", "(", "(", "y", ",", "m", ",", "d", ",", "hh", ",", "mm", ",", "ss", ",", "0", ",", "0", ",", "0", ")", ")", "print", "\"Unix epoch:\"", ",", "time", ".", "ctime", "(", "_unix_epoch", ")", "return", "_unix_epoch" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Demo/rpc/rpc.py#L172-L197
microsoft/unilm
65f15af2a307ebb64cfb25adf54375b002e6fe8d
xtune/src/transformers/tokenization_xlm.py
python
XLMTokenizer.convert_tokens_to_string
(self, tokens)
return out_string
Converts a sequence of tokens (string) in a single string.
Converts a sequence of tokens (string) in a single string.
[ "Converts", "a", "sequence", "of", "tokens", "(", "string", ")", "in", "a", "single", "string", "." ]
def convert_tokens_to_string(self, tokens): """ Converts a sequence of tokens (string) in a single string. """ out_string = "".join(tokens).replace("</w>", " ").strip() return out_string
[ "def", "convert_tokens_to_string", "(", "self", ",", "tokens", ")", ":", "out_string", "=", "\"\"", ".", "join", "(", "tokens", ")", ".", "replace", "(", "\"</w>\"", ",", "\" \"", ")", ".", "strip", "(", ")", "return", "out_string" ]
https://github.com/microsoft/unilm/blob/65f15af2a307ebb64cfb25adf54375b002e6fe8d/xtune/src/transformers/tokenization_xlm.py#L850-L853
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/class/oc_group.py
python
OCGroup.group
(self)
return self._group
property function service
property function service
[ "property", "function", "service" ]
def group(self): ''' property function service''' if not self._group: self.get() return self._group
[ "def", "group", "(", "self", ")", ":", "if", "not", "self", ".", "_group", ":", "self", ".", "get", "(", ")", "return", "self", ".", "_group" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/class/oc_group.py#L19-L23
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/pymysql/connections.py
python
Connection.get_autocommit
(self)
return bool(self.server_status & SERVER_STATUS.SERVER_STATUS_AUTOCOMMIT)
[]
def get_autocommit(self): return bool(self.server_status & SERVER_STATUS.SERVER_STATUS_AUTOCOMMIT)
[ "def", "get_autocommit", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "server_status", "&", "SERVER_STATUS", ".", "SERVER_STATUS_AUTOCOMMIT", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/pymysql/connections.py#L391-L393
diefenbach/django-lfs
3bbcb3453d324c181ec68d11d5d35115a60a2fd5
lfs/core/templatetags/lfs_tags.py
python
do_cheapest_variant
(parser, token)
return CheapestVariantNode(bits[1])
Returns the cheapest variant for the product with given id.
Returns the cheapest variant for the product with given id.
[ "Returns", "the", "cheapest", "variant", "for", "the", "product", "with", "given", "id", "." ]
def do_cheapest_variant(parser, token): """ Returns the cheapest variant for the product with given id. """ bits = token.contents.split() len_bits = len(bits) if len_bits != 2: raise TemplateSyntaxError('%s tag needs product id as argument' % bits[0]) return CheapestVariantNode(bits[1])
[ "def", "do_cheapest_variant", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "contents", ".", "split", "(", ")", "len_bits", "=", "len", "(", "bits", ")", "if", "len_bits", "!=", "2", ":", "raise", "TemplateSyntaxError", "(", "'%s tag needs product id as argument'", "%", "bits", "[", "0", "]", ")", "return", "CheapestVariantNode", "(", "bits", "[", "1", "]", ")" ]
https://github.com/diefenbach/django-lfs/blob/3bbcb3453d324c181ec68d11d5d35115a60a2fd5/lfs/core/templatetags/lfs_tags.py#L333-L341
P1sec/pycrate
d12bbccf1df8c9c7891a26967a9d2635610ec5b8
pycrate_core/elt.py
python
Atom.set_attrs
(self, **kw)
Updates the attributes of self Args: kw (dict): dict of attributes and associated values attributes can be name, desc, rep, hier, bl, val, trans and dic Returns: None
Updates the attributes of self Args: kw (dict): dict of attributes and associated values attributes can be name, desc, rep, hier, bl, val, trans and dic Returns: None
[ "Updates", "the", "attributes", "of", "self", "Args", ":", "kw", "(", "dict", ")", ":", "dict", "of", "attributes", "and", "associated", "values", "attributes", "can", "be", "name", "desc", "rep", "hier", "bl", "val", "trans", "and", "dic", "Returns", ":", "None" ]
def set_attrs(self, **kw): """Updates the attributes of self Args: kw (dict): dict of attributes and associated values attributes can be name, desc, rep, hier, bl, val, trans and dic Returns: None """ if 'name' in kw and isinstance(kw['name'], str): self._name = kw['name'] if 'desc' in kw and isinstance(kw['desc'], str) and kw['desc'] != self.__class__._desc: self._desc = str(kw['desc']) if 'rep' in kw and kw['rep'] in self.REPR_TYPES and \ kw['rep'] != self.__class__._rep: self._rep = kw['rep'] if 'hier' in kw and kw['hier'] != self.__class__._hier: self._hier = kw['hier'] if 'bl' in kw and kw['bl'] != self.__class__._bl: self._bl = kw['bl'] if 'val' in kw and kw['val'] != self.__class__._val: self._val = kw['val'] if 'trans' in kw and kw['trans'] != self.__class__._trans: self._trans = kw['trans'] if 'dic' in kw and kw['dic'] != self.__class__._dic: self._dic = kw['dic'] # if self._SAFE_STAT: self._chk_hier() self._chk_bl() self._chk_val() self._chk_trans() self._chk_dic()
[ "def", "set_attrs", "(", "self", ",", "*", "*", "kw", ")", ":", "if", "'name'", "in", "kw", "and", "isinstance", "(", "kw", "[", "'name'", "]", ",", "str", ")", ":", "self", ".", "_name", "=", "kw", "[", "'name'", "]", "if", "'desc'", "in", "kw", "and", "isinstance", "(", "kw", "[", "'desc'", "]", ",", "str", ")", "and", "kw", "[", "'desc'", "]", "!=", "self", ".", "__class__", ".", "_desc", ":", "self", ".", "_desc", "=", "str", "(", "kw", "[", "'desc'", "]", ")", "if", "'rep'", "in", "kw", "and", "kw", "[", "'rep'", "]", "in", "self", ".", "REPR_TYPES", "and", "kw", "[", "'rep'", "]", "!=", "self", ".", "__class__", ".", "_rep", ":", "self", ".", "_rep", "=", "kw", "[", "'rep'", "]", "if", "'hier'", "in", "kw", "and", "kw", "[", "'hier'", "]", "!=", "self", ".", "__class__", ".", "_hier", ":", "self", ".", "_hier", "=", "kw", "[", "'hier'", "]", "if", "'bl'", "in", "kw", "and", "kw", "[", "'bl'", "]", "!=", "self", ".", "__class__", ".", "_bl", ":", "self", ".", "_bl", "=", "kw", "[", "'bl'", "]", "if", "'val'", "in", "kw", "and", "kw", "[", "'val'", "]", "!=", "self", ".", "__class__", ".", "_val", ":", "self", ".", "_val", "=", "kw", "[", "'val'", "]", "if", "'trans'", "in", "kw", "and", "kw", "[", "'trans'", "]", "!=", "self", ".", "__class__", ".", "_trans", ":", "self", ".", "_trans", "=", "kw", "[", "'trans'", "]", "if", "'dic'", "in", "kw", "and", "kw", "[", "'dic'", "]", "!=", "self", ".", "__class__", ".", "_dic", ":", "self", ".", "_dic", "=", "kw", "[", "'dic'", "]", "#", "if", "self", ".", "_SAFE_STAT", ":", "self", ".", "_chk_hier", "(", ")", "self", ".", "_chk_bl", "(", ")", "self", ".", "_chk_val", "(", ")", "self", ".", "_chk_trans", "(", ")", "self", ".", "_chk_dic", "(", ")" ]
https://github.com/P1sec/pycrate/blob/d12bbccf1df8c9c7891a26967a9d2635610ec5b8/pycrate_core/elt.py#L1346-L1379
edgedb/edgedb
872bf5abbb10f7c72df21f57635238ed27b9f280
edb/schema/delta.py
python
CommandContext.is_deleting
(self, obj: so.Object)
return any(isinstance(ctx.op, DeleteObject) and ctx.op.scls == obj for ctx in self.stack)
Return True if *obj* is being deleted in this context. :param obj: The object in question. :returns: True if *obj* is being deleted in this context.
Return True if *obj* is being deleted in this context.
[ "Return", "True", "if", "*", "obj", "*", "is", "being", "deleted", "in", "this", "context", "." ]
def is_deleting(self, obj: so.Object) -> bool: """Return True if *obj* is being deleted in this context. :param obj: The object in question. :returns: True if *obj* is being deleted in this context. """ return any(isinstance(ctx.op, DeleteObject) and ctx.op.scls == obj for ctx in self.stack)
[ "def", "is_deleting", "(", "self", ",", "obj", ":", "so", ".", "Object", ")", "->", "bool", ":", "return", "any", "(", "isinstance", "(", "ctx", ".", "op", ",", "DeleteObject", ")", "and", "ctx", ".", "op", ".", "scls", "==", "obj", "for", "ctx", "in", "self", ".", "stack", ")" ]
https://github.com/edgedb/edgedb/blob/872bf5abbb10f7c72df21f57635238ed27b9f280/edb/schema/delta.py#L1321-L1331
POSTECH-CVLab/PyTorch-StudioGAN
bebb33f612759b86a224392f6fe941d0cc81d3c4
src/sync_batchnorm/comm.py
python
SyncMaster.__getstate__
(self)
return {'master_callback': self._master_callback}
[]
def __getstate__(self): return {'master_callback': self._master_callback}
[ "def", "__getstate__", "(", "self", ")", ":", "return", "{", "'master_callback'", ":", "self", ".", "_master_callback", "}" ]
https://github.com/POSTECH-CVLab/PyTorch-StudioGAN/blob/bebb33f612759b86a224392f6fe941d0cc81d3c4/src/sync_batchnorm/comm.py#L99-L100
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/pymongo/monitoring.py
python
CommandSucceededEvent.duration_micros
(self)
return self.__duration_micros
The duration of this operation in microseconds.
The duration of this operation in microseconds.
[ "The", "duration", "of", "this", "operation", "in", "microseconds", "." ]
def duration_micros(self): """The duration of this operation in microseconds.""" return self.__duration_micros
[ "def", "duration_micros", "(", "self", ")", ":", "return", "self", ".", "__duration_micros" ]
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/pymongo/monitoring.py#L253-L255
fabioz/PyDev.Debugger
0f8c02a010fe5690405da1dd30ed72326191ce63
stubs/_django_manager_body.py
python
aggregate
(self, *args, **kwargs)
Returns a dictionary containing the calculations (aggregation) over the current queryset If args is present the expression is passed as a kwarg using the Aggregate object's default alias.
Returns a dictionary containing the calculations (aggregation) over the current queryset If args is present the expression is passed as a kwarg using the Aggregate object's default alias.
[ "Returns", "a", "dictionary", "containing", "the", "calculations", "(", "aggregation", ")", "over", "the", "current", "queryset", "If", "args", "is", "present", "the", "expression", "is", "passed", "as", "a", "kwarg", "using", "the", "Aggregate", "object", "s", "default", "alias", "." ]
def aggregate(self, *args, **kwargs): """ Returns a dictionary containing the calculations (aggregation) over the current queryset If args is present the expression is passed as a kwarg using the Aggregate object's default alias. """
[ "def", "aggregate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":" ]
https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/stubs/_django_manager_body.py#L77-L84
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
get_fop3
(*args)
return _idaapi.get_fop3(*args)
get_fop3(ea) -> ssize_t
get_fop3(ea) -> ssize_t
[ "get_fop3", "(", "ea", ")", "-", ">", "ssize_t" ]
def get_fop3(*args): """ get_fop3(ea) -> ssize_t """ return _idaapi.get_fop3(*args)
[ "def", "get_fop3", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "get_fop3", "(", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L6704-L6708
lium-lst/nmtpy
dc0a1618f217d5117d6abeacdc15a22443561acf
nmtpy/models/basemodel.py
python
BaseModel.update_shared_variables
(self, _from)
Reset some variables from _from dict.
Reset some variables from _from dict.
[ "Reset", "some", "variables", "from", "_from", "dict", "." ]
def update_shared_variables(self, _from): """Reset some variables from _from dict.""" for kk in _from.keys(): self.tparams[kk].set_value(_from[kk])
[ "def", "update_shared_variables", "(", "self", ",", "_from", ")", ":", "for", "kk", "in", "_from", ".", "keys", "(", ")", ":", "self", ".", "tparams", "[", "kk", "]", ".", "set_value", "(", "_from", "[", "kk", "]", ")" ]
https://github.com/lium-lst/nmtpy/blob/dc0a1618f217d5117d6abeacdc15a22443561acf/nmtpy/models/basemodel.py#L112-L115
mpenning/ciscoconfparse
a6a176e6ceac7c5f3e974272fa70273476ba84a3
ciscoconfparse/ccp_util.py
python
IPv6Obj.__contains__
(self, val)
[]
def __contains__(self, val): # Used for "foo in bar"... python calls bar.__contains__(foo) try: if self.network_object.prefixlen == 0: return True elif self.network_object.prefixlen > val.network_object.prefixlen: # obvious shortcut... if this object's mask is longer than # val, this object cannot contain val return False else: # NOTE: We cannot use the same algorithm as IPv4Obj.__contains__() because IPv6Obj doesn't have .broadcast # return (val.network in self.network) # ## Last used: 2020-07-12... version 1.5.6 # return (self.network <= val.network) and ( # (self.as_decimal + self.numhosts - 1) # >= (val.as_decimal + val.numhosts - 1) # ) return (self.as_decimal_network <= val.as_decimal_network) and ( (self.as_decimal_network + self.numhosts - 1) >= (val.as_decimal_network + val.numhosts - 1) ) except (Exception) as e: raise ValueError( "Could not check whether '{0}' is contained in '{1}': {2}".format( val, self, e ) )
[ "def", "__contains__", "(", "self", ",", "val", ")", ":", "# Used for \"foo in bar\"... python calls bar.__contains__(foo)", "try", ":", "if", "self", ".", "network_object", ".", "prefixlen", "==", "0", ":", "return", "True", "elif", "self", ".", "network_object", ".", "prefixlen", ">", "val", ".", "network_object", ".", "prefixlen", ":", "# obvious shortcut... if this object's mask is longer than", "# val, this object cannot contain val", "return", "False", "else", ":", "# NOTE: We cannot use the same algorithm as IPv4Obj.__contains__() because IPv6Obj doesn't have .broadcast", "# return (val.network in self.network)", "#", "## Last used: 2020-07-12... version 1.5.6", "# return (self.network <= val.network) and (", "# (self.as_decimal + self.numhosts - 1)", "# >= (val.as_decimal + val.numhosts - 1)", "# )", "return", "(", "self", ".", "as_decimal_network", "<=", "val", ".", "as_decimal_network", ")", "and", "(", "(", "self", ".", "as_decimal_network", "+", "self", ".", "numhosts", "-", "1", ")", ">=", "(", "val", ".", "as_decimal_network", "+", "val", ".", "numhosts", "-", "1", ")", ")", "except", "(", "Exception", ")", "as", "e", ":", "raise", "ValueError", "(", "\"Could not check whether '{0}' is contained in '{1}': {2}\"", ".", "format", "(", "val", ",", "self", ",", "e", ")", ")" ]
https://github.com/mpenning/ciscoconfparse/blob/a6a176e6ceac7c5f3e974272fa70273476ba84a3/ciscoconfparse/ccp_util.py#L1381-L1409
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1_component_condition.py
python
V1ComponentCondition.to_dict
(self)
return result
Returns the model properties as a dict
Returns the model properties as a dict
[ "Returns", "the", "model", "properties", "as", "a", "dict" ]
def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "attr", ",", "_", "in", "iteritems", "(", "self", ".", "swagger_types", ")", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "isinstance", "(", "value", ",", "list", ")", ":", "result", "[", "attr", "]", "=", "list", "(", "map", "(", "lambda", "x", ":", "x", ".", "to_dict", "(", ")", "if", "hasattr", "(", "x", ",", "\"to_dict\"", ")", "else", "x", ",", "value", ")", ")", "elif", "hasattr", "(", "value", ",", "\"to_dict\"", ")", ":", "result", "[", "attr", "]", "=", "value", ".", "to_dict", "(", ")", "elif", "isinstance", "(", "value", ",", "dict", ")", ":", "result", "[", "attr", "]", "=", "dict", "(", "map", "(", "lambda", "item", ":", "(", "item", "[", "0", "]", ",", "item", "[", "1", "]", ".", "to_dict", "(", ")", ")", "if", "hasattr", "(", "item", "[", "1", "]", ",", "\"to_dict\"", ")", "else", "item", ",", "value", ".", "items", "(", ")", ")", ")", "else", ":", "result", "[", "attr", "]", "=", "value", "return", "result" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_component_condition.py#L148-L172
skylander86/lambda-text-extractor
6da52d077a2fc571e38bfe29c33ae68f6443cd5a
lib-linux_x64/odf/odf2xhtml.py
python
ODF2XHTML.e_dc_title
(self, tag, attrs)
Get the title from the meta data and create a HTML <title>
Get the title from the meta data and create a HTML <title>
[ "Get", "the", "title", "from", "the", "meta", "data", "and", "create", "a", "HTML", "<title", ">" ]
def e_dc_title(self, tag, attrs): """ Get the title from the meta data and create a HTML <title> """ self.title = ''.join(self.data) #self.metatags.append('<title>%s</title>\n' % escape(self.title)) self.data = []
[ "def", "e_dc_title", "(", "self", ",", "tag", ",", "attrs", ")", ":", "self", ".", "title", "=", "''", ".", "join", "(", "self", ".", "data", ")", "#self.metatags.append('<title>%s</title>\\n' % escape(self.title))", "self", ".", "data", "=", "[", "]" ]
https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/odf/odf2xhtml.py#L622-L627
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/secure_information_retrieval/secure_information_retrieval_host.py
python
SecureInformationRetrievalHost._sync_block_num
(self)
[]
def _sync_block_num(self): self.block_num = self.transfer_variable.block_num.get(idx=0) LOGGER.info("got block num {} from guest".format(self.block_num))
[ "def", "_sync_block_num", "(", "self", ")", ":", "self", ".", "block_num", "=", "self", ".", "transfer_variable", ".", "block_num", ".", "get", "(", "idx", "=", "0", ")", "LOGGER", ".", "info", "(", "\"got block num {} from guest\"", ".", "format", "(", "self", ".", "block_num", ")", ")" ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/secure_information_retrieval/secure_information_retrieval_host.py#L181-L183
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/asyncio/streams.py
python
StreamReader._wait_for_data
(self, func_name)
Wait until feed_data() or feed_eof() is called. If stream was paused, automatically resume it.
Wait until feed_data() or feed_eof() is called.
[ "Wait", "until", "feed_data", "()", "or", "feed_eof", "()", "is", "called", "." ]
def _wait_for_data(self, func_name): """Wait until feed_data() or feed_eof() is called. If stream was paused, automatically resume it. """ # StreamReader uses a future to link the protocol feed_data() method # to a read coroutine. Running two read coroutines at the same time # would have an unexpected behaviour. It would not possible to know # which coroutine would get the next data. if self._waiter is not None: raise RuntimeError('%s() called while another coroutine is ' 'already waiting for incoming data' % func_name) assert not self._eof, '_wait_for_data after EOF' # Waiting for data while paused will make deadlock, so prevent it. # This is essential for readexactly(n) for case when n > self._limit. if self._paused: self._paused = False self._transport.resume_reading() self._waiter = self._loop.create_future() try: yield from self._waiter finally: self._waiter = None
[ "def", "_wait_for_data", "(", "self", ",", "func_name", ")", ":", "# StreamReader uses a future to link the protocol feed_data() method", "# to a read coroutine. Running two read coroutines at the same time", "# would have an unexpected behaviour. It would not possible to know", "# which coroutine would get the next data.", "if", "self", ".", "_waiter", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'%s() called while another coroutine is '", "'already waiting for incoming data'", "%", "func_name", ")", "assert", "not", "self", ".", "_eof", ",", "'_wait_for_data after EOF'", "# Waiting for data while paused will make deadlock, so prevent it.", "# This is essential for readexactly(n) for case when n > self._limit.", "if", "self", ".", "_paused", ":", "self", ".", "_paused", "=", "False", "self", ".", "_transport", ".", "resume_reading", "(", ")", "self", ".", "_waiter", "=", "self", ".", "_loop", ".", "create_future", "(", ")", "try", ":", "yield", "from", "self", ".", "_waiter", "finally", ":", "self", ".", "_waiter", "=", "None" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/asyncio/streams.py#L435-L460
zopefoundation/Zope
ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb
src/Products/PageTemplates/PageTemplateFile.py
python
PageTemplateFile._read_file
(self)
return text, type_
[]
def _read_file(self): __traceback_info__ = self.filename with open(self.filename, "rb") as f: text = f.read(XML_PREFIX_MAX_LENGTH) type_ = sniff_type(text) text += f.read() if type_ != "text/xml": text, type_ = self._prepare_html(text) else: text, type_ = self._prepare_xml(text) f.close() return text, type_
[ "def", "_read_file", "(", "self", ")", ":", "__traceback_info__", "=", "self", ".", "filename", "with", "open", "(", "self", ".", "filename", ",", "\"rb\"", ")", "as", "f", ":", "text", "=", "f", ".", "read", "(", "XML_PREFIX_MAX_LENGTH", ")", "type_", "=", "sniff_type", "(", "text", ")", "text", "+=", "f", ".", "read", "(", ")", "if", "type_", "!=", "\"text/xml\"", ":", "text", ",", "type_", "=", "self", ".", "_prepare_html", "(", "text", ")", "else", ":", "text", ",", "type_", "=", "self", ".", "_prepare_xml", "(", "text", ")", "f", ".", "close", "(", ")", "return", "text", ",", "type_" ]
https://github.com/zopefoundation/Zope/blob/ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb/src/Products/PageTemplates/PageTemplateFile.py#L192-L203
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/spread/pb.py
python
IUsernameMD5Password.checkMD5Password
(password)
Validate these credentials against the correct MD5 digest of the password. @type password: C{str} @param password: The correct MD5 digest of a password against which to check. @rtype: C{bool} or L{Deferred} @return: C{True} if the credentials represented by this object match the given digest, C{False} if they do not, or a L{Deferred} which will be called back with one of these values.
Validate these credentials against the correct MD5 digest of the password.
[ "Validate", "these", "credentials", "against", "the", "correct", "MD5", "digest", "of", "the", "password", "." ]
def checkMD5Password(password): """ Validate these credentials against the correct MD5 digest of the password. @type password: C{str} @param password: The correct MD5 digest of a password against which to check. @rtype: C{bool} or L{Deferred} @return: C{True} if the credentials represented by this object match the given digest, C{False} if they do not, or a L{Deferred} which will be called back with one of these values. """
[ "def", "checkMD5Password", "(", "password", ")", ":" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/spread/pb.py#L1489-L1502
hangoutsbot/hangoutsbot
aabe1059d5873f53691e28c19273277817fb34ba
hangupsbot/plugins/_chatbridge/chatbridge_syncrooms.py
python
BridgeInstance.applicable_configuration
(self, conv_id)
return applicable_configurations
customised (legacy) configuration structure: "syncing_enabled": true, "sync_rooms": [ [ "<internal chat/group/team id>", "<internal chat/group/team id>" ] ]
customised (legacy) configuration structure:
[ "customised", "(", "legacy", ")", "configuration", "structure", ":" ]
def applicable_configuration(self, conv_id): """customised (legacy) configuration structure: "syncing_enabled": true, "sync_rooms": [ [ "<internal chat/group/team id>", "<internal chat/group/team id>" ] ] """ if not self.bot.get_config_option('syncing_enabled'): return False self.load_configuration(self.configkey) applicable_configurations = [] syncouts = self.configuration for sync_rooms_list in syncouts: if conv_id in sync_rooms_list: syncout = list(sync_rooms_list) # clones the list syncout.remove(conv_id) if syncout: # ensures at least 2 items were in the list, trigger conv_id was removed applicable_configurations.append({ "trigger": conv_id, "config.json": { "hangouts": syncout }}) return applicable_configurations
[ "def", "applicable_configuration", "(", "self", ",", "conv_id", ")", ":", "if", "not", "self", ".", "bot", ".", "get_config_option", "(", "'syncing_enabled'", ")", ":", "return", "False", "self", ".", "load_configuration", "(", "self", ".", "configkey", ")", "applicable_configurations", "=", "[", "]", "syncouts", "=", "self", ".", "configuration", "for", "sync_rooms_list", "in", "syncouts", ":", "if", "conv_id", "in", "sync_rooms_list", ":", "syncout", "=", "list", "(", "sync_rooms_list", ")", "# clones the list", "syncout", ".", "remove", "(", "conv_id", ")", "if", "syncout", ":", "# ensures at least 2 items were in the list, trigger conv_id was removed", "applicable_configurations", ".", "append", "(", "{", "\"trigger\"", ":", "conv_id", ",", "\"config.json\"", ":", "{", "\"hangouts\"", ":", "syncout", "}", "}", ")", "return", "applicable_configurations" ]
https://github.com/hangoutsbot/hangoutsbot/blob/aabe1059d5873f53691e28c19273277817fb34ba/hangupsbot/plugins/_chatbridge/chatbridge_syncrooms.py#L19-L48
deepmind/dm_control
806a10e896e7c887635328bfa8352604ad0fedae
dm_control/locomotion/arenas/mazes.py
python
MazeWithTargets.z_height
(self)
return self._z_height
[]
def z_height(self): return self._z_height
[ "def", "z_height", "(", "self", ")", ":", "return", "self", ".", "_z_height" ]
https://github.com/deepmind/dm_control/blob/806a10e896e7c887635328bfa8352604ad0fedae/dm_control/locomotion/arenas/mazes.py#L170-L171
sametmax/Django--an-app-at-a-time
99eddf12ead76e6dfbeb09ce0bae61e282e22f8a
ignore_this_directory/django/utils/_os.py
python
upath
(path)
return path
Always return a unicode path (did something for Python 2).
Always return a unicode path (did something for Python 2).
[ "Always", "return", "a", "unicode", "path", "(", "did", "something", "for", "Python", "2", ")", "." ]
def upath(path): """Always return a unicode path (did something for Python 2).""" return path
[ "def", "upath", "(", "path", ")", ":", "return", "path" ]
https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/utils/_os.py#L11-L13
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/conch/ssh/transport.py
python
SSHTransportBase._getKey
(self, c, sharedSecret, exchangeHash)
return k1 + k2
Get one of the keys for authentication/encryption. @type c: C{str} @type sharedSecret: C{str} @type exchangeHash: C{str}
Get one of the keys for authentication/encryption.
[ "Get", "one", "of", "the", "keys", "for", "authentication", "/", "encryption", "." ]
def _getKey(self, c, sharedSecret, exchangeHash): """ Get one of the keys for authentication/encryption. @type c: C{str} @type sharedSecret: C{str} @type exchangeHash: C{str} """ k1 = sha1(sharedSecret + exchangeHash + c + self.sessionID) k1 = k1.digest() k2 = sha1(sharedSecret + exchangeHash + k1).digest() return k1 + k2
[ "def", "_getKey", "(", "self", ",", "c", ",", "sharedSecret", ",", "exchangeHash", ")", ":", "k1", "=", "sha1", "(", "sharedSecret", "+", "exchangeHash", "+", "c", "+", "self", ".", "sessionID", ")", "k1", "=", "k1", ".", "digest", "(", ")", "k2", "=", "sha1", "(", "sharedSecret", "+", "exchangeHash", "+", "k1", ")", ".", "digest", "(", ")", "return", "k1", "+", "k2" ]
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/conch/ssh/transport.py#L693-L704
lmcinnes/umap
ec9832cbdb7f106a727e6bbd4c54c78fae30f26f
umap/distances.py
python
hamming
(x, y)
return float(result) / x.shape[0]
[]
def hamming(x, y): result = 0.0 for i in range(x.shape[0]): if x[i] != y[i]: result += 1.0 return float(result) / x.shape[0]
[ "def", "hamming", "(", "x", ",", "y", ")", ":", "result", "=", "0.0", "for", "i", "in", "range", "(", "x", ".", "shape", "[", "0", "]", ")", ":", "if", "x", "[", "i", "]", "!=", "y", "[", "i", "]", ":", "result", "+=", "1.0", "return", "float", "(", "result", ")", "/", "x", ".", "shape", "[", "0", "]" ]
https://github.com/lmcinnes/umap/blob/ec9832cbdb7f106a727e6bbd4c54c78fae30f26f/umap/distances.py#L313-L319
google/rekall
55d1925f2df9759a989b35271b4fa48fc54a1c86
rekall-core/rekall/plugins/core.py
python
FindDTB.address_space_hits
(self)
Finds DTBs and yields virtual address spaces that expose kernel. Yields: BaseAddressSpace-derived instances, validated using the VerifyHit() method.
Finds DTBs and yields virtual address spaces that expose kernel.
[ "Finds", "DTBs", "and", "yields", "virtual", "address", "spaces", "that", "expose", "kernel", "." ]
def address_space_hits(self): """Finds DTBs and yields virtual address spaces that expose kernel. Yields: BaseAddressSpace-derived instances, validated using the VerifyHit() method. """ for hit in self.dtb_hits(): address_space = self.VerifyHit(hit) if address_space is not None: yield address_space
[ "def", "address_space_hits", "(", "self", ")", ":", "for", "hit", "in", "self", ".", "dtb_hits", "(", ")", ":", "address_space", "=", "self", ".", "VerifyHit", "(", "hit", ")", "if", "address_space", "is", "not", "None", ":", "yield", "address_space" ]
https://github.com/google/rekall/blob/55d1925f2df9759a989b35271b4fa48fc54a1c86/rekall-core/rekall/plugins/core.py#L250-L260
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/celery/celery/result.py
python
ResultSet.remove
(self, result)
Removes result from the set; it must be a member. :raises KeyError: if the result is not a member.
Removes result from the set; it must be a member.
[ "Removes", "result", "from", "the", "set", ";", "it", "must", "be", "a", "member", "." ]
def remove(self, result): """Removes result from the set; it must be a member. :raises KeyError: if the result is not a member. """ if isinstance(result, basestring): result = AsyncResult(result) try: self.results.remove(result) except ValueError: raise KeyError(result)
[ "def", "remove", "(", "self", ",", "result", ")", ":", "if", "isinstance", "(", "result", ",", "basestring", ")", ":", "result", "=", "AsyncResult", "(", "result", ")", "try", ":", "self", ".", "results", ".", "remove", "(", "result", ")", "except", "ValueError", ":", "raise", "KeyError", "(", "result", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/celery/celery/result.py#L239-L250
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/core/leoGui.py
python
LeoGui.runMainLoop
(self)
Run the gui's main loop.
Run the gui's main loop.
[ "Run", "the", "gui", "s", "main", "loop", "." ]
def runMainLoop(self): """Run the gui's main loop.""" self.oops()
[ "def", "runMainLoop", "(", "self", ")", ":", "self", ".", "oops", "(", ")" ]
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/core/leoGui.py#L151-L153
alanhamlett/pip-update-requirements
ce875601ef278c8ce00ad586434a978731525561
pur/packages/pip/_internal/index.py
python
PackageFinder._get_index_urls_locations
(self, project_name)
return [mkurl_pypi_url(url) for url in self.index_urls]
Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations
Returns the locations found via self.index_urls
[ "Returns", "the", "locations", "found", "via", "self", ".", "index_urls" ]
def _get_index_urls_locations(self, project_name): # type: (str) -> List[str] """Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations """ def mkurl_pypi_url(url): loc = posixpath.join( url, urllib_parse.quote(canonicalize_name(project_name))) # For maximum compatibility with easy_install, ensure the path # ends in a trailing slash. Although this isn't in the spec # (and PyPI can handle it without the slash) some other index # implementations might break if they relied on easy_install's # behavior. if not loc.endswith('/'): loc = loc + '/' return loc return [mkurl_pypi_url(url) for url in self.index_urls]
[ "def", "_get_index_urls_locations", "(", "self", ",", "project_name", ")", ":", "# type: (str) -> List[str]", "def", "mkurl_pypi_url", "(", "url", ")", ":", "loc", "=", "posixpath", ".", "join", "(", "url", ",", "urllib_parse", ".", "quote", "(", "canonicalize_name", "(", "project_name", ")", ")", ")", "# For maximum compatibility with easy_install, ensure the path", "# ends in a trailing slash. Although this isn't in the spec", "# (and PyPI can handle it without the slash) some other index", "# implementations might break if they relied on easy_install's", "# behavior.", "if", "not", "loc", ".", "endswith", "(", "'/'", ")", ":", "loc", "=", "loc", "+", "'/'", "return", "loc", "return", "[", "mkurl_pypi_url", "(", "url", ")", "for", "url", "in", "self", ".", "index_urls", "]" ]
https://github.com/alanhamlett/pip-update-requirements/blob/ce875601ef278c8ce00ad586434a978731525561/pur/packages/pip/_internal/index.py#L541-L562
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/mako/util.py
python
LRUCache.__init__
(self, capacity, threshold=0.5)
[]
def __init__(self, capacity, threshold=0.5): self.capacity = capacity self.threshold = threshold
[ "def", "__init__", "(", "self", ",", "capacity", ",", "threshold", "=", "0.5", ")", ":", "self", ".", "capacity", "=", "capacity", "self", ".", "threshold", "=", "threshold" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/mako/util.py#L191-L193
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
calendarserver/tools/calverify.py
python
SchedulingMismatchService.buildResourceInfo
(self, rows, onlyOrganizer=False, onlyAttendee=False)
For each resource, determine whether it is an organizer or attendee event, and also cache the attendee partstats. @param rows: set of DB query rows @type rows: C{list} @param onlyOrganizer: whether organizer information only is required @type onlyOrganizer: C{bool} @param onlyAttendee: whether attendee information only is required @type onlyAttendee: C{bool}
For each resource, determine whether it is an organizer or attendee event, and also cache the attendee partstats.
[ "For", "each", "resource", "determine", "whether", "it", "is", "an", "organizer", "or", "attendee", "event", "and", "also", "cache", "the", "attendee", "partstats", "." ]
def buildResourceInfo(self, rows, onlyOrganizer=False, onlyAttendee=False): """ For each resource, determine whether it is an organizer or attendee event, and also cache the attendee partstats. @param rows: set of DB query rows @type rows: C{list} @param onlyOrganizer: whether organizer information only is required @type onlyOrganizer: C{bool} @param onlyAttendee: whether attendee information only is required @type onlyAttendee: C{bool} """ skipped = 0 inboxes = 0 for owner, resid, uid, calname, md5, organizer, created, modified in rows: # Skip owners not enabled for calendaring if not (yield self.testForCalendaringUUID(owner)): skipped += 1 continue # Skip inboxes if calname == "inbox": inboxes += 1 continue # If targeting a specific organizer, skip events belonging to others if self.options["uuid"]: if not organizer.startswith("urn:x-uid:") or self.options["uuid"] != organizer[10:]: continue # Cache organizer/attendee states if organizer.startswith("urn:x-uid:") and owner == organizer[10:]: if not onlyAttendee: self.organized.append((owner, resid, uid, md5, organizer, created, modified,)) self.organized_byuid[uid] = (owner, resid, uid, md5, organizer, created, modified,) else: if not onlyOrganizer: self.attended.append((owner, resid, uid, md5, organizer, created, modified,)) self.attended_byuid[uid].append((owner, resid, uid, md5, organizer, created, modified,)) returnValue((skipped, inboxes))
[ "def", "buildResourceInfo", "(", "self", ",", "rows", ",", "onlyOrganizer", "=", "False", ",", "onlyAttendee", "=", "False", ")", ":", "skipped", "=", "0", "inboxes", "=", "0", "for", "owner", ",", "resid", ",", "uid", ",", "calname", ",", "md5", ",", "organizer", ",", "created", ",", "modified", "in", "rows", ":", "# Skip owners not enabled for calendaring", "if", "not", "(", "yield", "self", ".", "testForCalendaringUUID", "(", "owner", ")", ")", ":", "skipped", "+=", "1", "continue", "# Skip inboxes", "if", "calname", "==", "\"inbox\"", ":", "inboxes", "+=", "1", "continue", "# If targeting a specific organizer, skip events belonging to others", "if", "self", ".", "options", "[", "\"uuid\"", "]", ":", "if", "not", "organizer", ".", "startswith", "(", "\"urn:x-uid:\"", ")", "or", "self", ".", "options", "[", "\"uuid\"", "]", "!=", "organizer", "[", "10", ":", "]", ":", "continue", "# Cache organizer/attendee states", "if", "organizer", ".", "startswith", "(", "\"urn:x-uid:\"", ")", "and", "owner", "==", "organizer", "[", "10", ":", "]", ":", "if", "not", "onlyAttendee", ":", "self", ".", "organized", ".", "append", "(", "(", "owner", ",", "resid", ",", "uid", ",", "md5", ",", "organizer", ",", "created", ",", "modified", ",", ")", ")", "self", ".", "organized_byuid", "[", "uid", "]", "=", "(", "owner", ",", "resid", ",", "uid", ",", "md5", ",", "organizer", ",", "created", ",", "modified", ",", ")", "else", ":", "if", "not", "onlyOrganizer", ":", "self", ".", "attended", ".", "append", "(", "(", "owner", ",", "resid", ",", "uid", ",", "md5", ",", "organizer", ",", "created", ",", "modified", ",", ")", ")", "self", ".", "attended_byuid", "[", "uid", "]", ".", "append", "(", "(", "owner", ",", "resid", ",", "uid", ",", "md5", ",", "organizer", ",", "created", ",", "modified", ",", ")", ")", "returnValue", "(", "(", "skipped", ",", "inboxes", ")", ")" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/calendarserver/tools/calverify.py#L1449-L1491
cyverse/atmosphere
4a3e522f1f7b58abd9fa944c10b7455dc5cddac1
features/steps/api_with_persona_steps.py
python
i_log_in_with_valid_xsede_project_required
(context)
:type context: behave.runner.Context
:type context: behave.runner.Context
[ ":", "type", "context", ":", "behave", ".", "runner", ".", "Context" ]
def i_log_in_with_valid_xsede_project_required(context): """ :type context: behave.runner.Context """ assert context.persona client = rest_framework.test.APIClient() context.persona['client'] = client is_tas_up = True if hasattr(context.scenario, '_row') and context.scenario._row: example = dict( zip(context.scenario._row.headings, context.scenario._row.cells) ) is_tas_up = example.get('is_tas_up', 'Yes') == 'Yes' with django.test.override_settings( AUTHENTICATION_BACKENDS=[ 'django_cyverse_auth.authBackends.MockLoginBackend' ], ALWAYS_AUTH_USER=context.persona['username'], DEFAULT_QUOTA_PLUGINS=[ 'jetstream.plugins.quota.default_quota.JetstreamSpecialAllocationQuota' ], VALIDATION_PLUGINS=[ 'jetstream.plugins.auth.validation.XsedeProjectRequired' ] ): with mock.patch.multiple( 'jetstream.allocation', tacc_api_post=mock.DEFAULT, tacc_api_get=mock.DEFAULT, ) as mock_methods: mock_methods[ 'tacc_api_post' ].side_effect = jetstream.tests.tas_api_mock_utils._make_mock_tacc_api_post( context, is_tas_up ) mock_methods[ 'tacc_api_get' ].side_effect = jetstream.tests.tas_api_mock_utils._make_mock_tacc_api_get( context, is_tas_up ) login_result = client.login( username=context.persona['username'], password=context.persona['password'] ) context.persona['login_result'] = login_result
[ "def", "i_log_in_with_valid_xsede_project_required", "(", "context", ")", ":", "assert", "context", ".", "persona", "client", "=", "rest_framework", ".", "test", ".", "APIClient", "(", ")", "context", ".", "persona", "[", "'client'", "]", "=", "client", "is_tas_up", "=", "True", "if", "hasattr", "(", "context", ".", "scenario", ",", "'_row'", ")", "and", "context", ".", "scenario", ".", "_row", ":", "example", "=", "dict", "(", "zip", "(", "context", ".", "scenario", ".", "_row", ".", "headings", ",", "context", ".", "scenario", ".", "_row", ".", "cells", ")", ")", "is_tas_up", "=", "example", ".", "get", "(", "'is_tas_up'", ",", "'Yes'", ")", "==", "'Yes'", "with", "django", ".", "test", ".", "override_settings", "(", "AUTHENTICATION_BACKENDS", "=", "[", "'django_cyverse_auth.authBackends.MockLoginBackend'", "]", ",", "ALWAYS_AUTH_USER", "=", "context", ".", "persona", "[", "'username'", "]", ",", "DEFAULT_QUOTA_PLUGINS", "=", "[", "'jetstream.plugins.quota.default_quota.JetstreamSpecialAllocationQuota'", "]", ",", "VALIDATION_PLUGINS", "=", "[", "'jetstream.plugins.auth.validation.XsedeProjectRequired'", "]", ")", ":", "with", "mock", ".", "patch", ".", "multiple", "(", "'jetstream.allocation'", ",", "tacc_api_post", "=", "mock", ".", "DEFAULT", ",", "tacc_api_get", "=", "mock", ".", "DEFAULT", ",", ")", "as", "mock_methods", ":", "mock_methods", "[", "'tacc_api_post'", "]", ".", "side_effect", "=", "jetstream", ".", "tests", ".", "tas_api_mock_utils", ".", "_make_mock_tacc_api_post", "(", "context", ",", "is_tas_up", ")", "mock_methods", "[", "'tacc_api_get'", "]", ".", "side_effect", "=", "jetstream", ".", "tests", ".", "tas_api_mock_utils", ".", "_make_mock_tacc_api_get", "(", "context", ",", "is_tas_up", ")", "login_result", "=", "client", ".", "login", "(", "username", "=", "context", ".", "persona", "[", "'username'", "]", ",", "password", "=", "context", ".", "persona", "[", "'password'", "]", ")", "context", ".", "persona", "[", "'login_result'", "]", "=", "login_result" ]
https://github.com/cyverse/atmosphere/blob/4a3e522f1f7b58abd9fa944c10b7455dc5cddac1/features/steps/api_with_persona_steps.py#L123-L167
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_vendor/distlib/database.py
python
DistributionPath._get_cache_enabled
(self)
return self._cache_enabled
[]
def _get_cache_enabled(self): return self._cache_enabled
[ "def", "_get_cache_enabled", "(", "self", ")", ":", "return", "self", ".", "_cache_enabled" ]
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/distlib/database.py#L99-L100
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
examples/legacy/multiple_choice/utils_multiple_choice.py
python
convert_examples_to_features
( examples: List[InputExample], label_list: List[str], max_length: int, tokenizer: PreTrainedTokenizer, )
return features
Loads a data file into a list of `InputFeatures`
Loads a data file into a list of `InputFeatures`
[ "Loads", "a", "data", "file", "into", "a", "list", "of", "InputFeatures" ]
def convert_examples_to_features( examples: List[InputExample], label_list: List[str], max_length: int, tokenizer: PreTrainedTokenizer, ) -> List[InputFeatures]: """ Loads a data file into a list of `InputFeatures` """ label_map = {label: i for i, label in enumerate(label_list)} features = [] for (ex_index, example) in tqdm.tqdm(enumerate(examples), desc="convert examples to features"): if ex_index % 10000 == 0: logger.info("Writing example %d of %d" % (ex_index, len(examples))) choices_inputs = [] for ending_idx, (context, ending) in enumerate(zip(example.contexts, example.endings)): text_a = context if example.question.find("_") != -1: # this is for cloze question text_b = example.question.replace("_", ending) else: text_b = example.question + " " + ending inputs = tokenizer( text_a, text_b, add_special_tokens=True, max_length=max_length, padding="max_length", truncation=True, return_overflowing_tokens=True, ) if "num_truncated_tokens" in inputs and inputs["num_truncated_tokens"] > 0: logger.info( "Attention! you are cropping tokens (swag task is ok). " "If you are training ARC and RACE and you are poping question + options," "you need to try to use a bigger max seq length!" ) choices_inputs.append(inputs) label = label_map[example.label] input_ids = [x["input_ids"] for x in choices_inputs] attention_mask = ( [x["attention_mask"] for x in choices_inputs] if "attention_mask" in choices_inputs[0] else None ) token_type_ids = ( [x["token_type_ids"] for x in choices_inputs] if "token_type_ids" in choices_inputs[0] else None ) features.append( InputFeatures( example_id=example.example_id, input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, label=label, ) ) for f in features[:2]: logger.info("*** Example ***") logger.info("feature: %s" % f) return features
[ "def", "convert_examples_to_features", "(", "examples", ":", "List", "[", "InputExample", "]", ",", "label_list", ":", "List", "[", "str", "]", ",", "max_length", ":", "int", ",", "tokenizer", ":", "PreTrainedTokenizer", ",", ")", "->", "List", "[", "InputFeatures", "]", ":", "label_map", "=", "{", "label", ":", "i", "for", "i", ",", "label", "in", "enumerate", "(", "label_list", ")", "}", "features", "=", "[", "]", "for", "(", "ex_index", ",", "example", ")", "in", "tqdm", ".", "tqdm", "(", "enumerate", "(", "examples", ")", ",", "desc", "=", "\"convert examples to features\"", ")", ":", "if", "ex_index", "%", "10000", "==", "0", ":", "logger", ".", "info", "(", "\"Writing example %d of %d\"", "%", "(", "ex_index", ",", "len", "(", "examples", ")", ")", ")", "choices_inputs", "=", "[", "]", "for", "ending_idx", ",", "(", "context", ",", "ending", ")", "in", "enumerate", "(", "zip", "(", "example", ".", "contexts", ",", "example", ".", "endings", ")", ")", ":", "text_a", "=", "context", "if", "example", ".", "question", ".", "find", "(", "\"_\"", ")", "!=", "-", "1", ":", "# this is for cloze question", "text_b", "=", "example", ".", "question", ".", "replace", "(", "\"_\"", ",", "ending", ")", "else", ":", "text_b", "=", "example", ".", "question", "+", "\" \"", "+", "ending", "inputs", "=", "tokenizer", "(", "text_a", ",", "text_b", ",", "add_special_tokens", "=", "True", ",", "max_length", "=", "max_length", ",", "padding", "=", "\"max_length\"", ",", "truncation", "=", "True", ",", "return_overflowing_tokens", "=", "True", ",", ")", "if", "\"num_truncated_tokens\"", "in", "inputs", "and", "inputs", "[", "\"num_truncated_tokens\"", "]", ">", "0", ":", "logger", ".", "info", "(", "\"Attention! you are cropping tokens (swag task is ok). \"", "\"If you are training ARC and RACE and you are poping question + options,\"", "\"you need to try to use a bigger max seq length!\"", ")", "choices_inputs", ".", "append", "(", "inputs", ")", "label", "=", "label_map", "[", "example", ".", "label", "]", "input_ids", "=", "[", "x", "[", "\"input_ids\"", "]", "for", "x", "in", "choices_inputs", "]", "attention_mask", "=", "(", "[", "x", "[", "\"attention_mask\"", "]", "for", "x", "in", "choices_inputs", "]", "if", "\"attention_mask\"", "in", "choices_inputs", "[", "0", "]", "else", "None", ")", "token_type_ids", "=", "(", "[", "x", "[", "\"token_type_ids\"", "]", "for", "x", "in", "choices_inputs", "]", "if", "\"token_type_ids\"", "in", "choices_inputs", "[", "0", "]", "else", "None", ")", "features", ".", "append", "(", "InputFeatures", "(", "example_id", "=", "example", ".", "example_id", ",", "input_ids", "=", "input_ids", ",", "attention_mask", "=", "attention_mask", ",", "token_type_ids", "=", "token_type_ids", ",", "label", "=", "label", ",", ")", ")", "for", "f", "in", "features", "[", ":", "2", "]", ":", "logger", ".", "info", "(", "\"*** Example ***\"", ")", "logger", ".", "info", "(", "\"feature: %s\"", "%", "f", ")", "return", "features" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/examples/legacy/multiple_choice/utils_multiple_choice.py#L508-L575
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/libmproxy/flow.py
python
Request.get_cookies
(self)
return dict(cookies)
[]
def get_cookies(self): cookie_headers = self.headers.get("cookie") if not cookie_headers: return None cookies = [] for header in cookie_headers: pairs = [pair.partition("=") for pair in header.split(';')] cookies.extend((pair[0],(pair[2],{})) for pair in pairs) return dict(cookies)
[ "def", "get_cookies", "(", "self", ")", ":", "cookie_headers", "=", "self", ".", "headers", ".", "get", "(", "\"cookie\"", ")", "if", "not", "cookie_headers", ":", "return", "None", "cookies", "=", "[", "]", "for", "header", "in", "cookie_headers", ":", "pairs", "=", "[", "pair", ".", "partition", "(", "\"=\"", ")", "for", "pair", "in", "header", ".", "split", "(", "';'", ")", "]", "cookies", ".", "extend", "(", "(", "pair", "[", "0", "]", ",", "(", "pair", "[", "2", "]", ",", "{", "}", ")", ")", "for", "pair", "in", "pairs", ")", "return", "dict", "(", "cookies", ")" ]
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/libmproxy/flow.py#L505-L514
windelbouwman/ppci
915c069e0667042c085ec42c78e9e3c9a5295324
ppci/lang/bf.py
python
BrainFuckGenerator.generate
(self, src, module_name="main", function_name="main")
return self.builder.module
Takes a brainfuck program and returns the IR-code module
Takes a brainfuck program and returns the IR-code module
[ "Takes", "a", "brainfuck", "program", "and", "returns", "the", "IR", "-", "code", "module" ]
def generate(self, src, module_name="main", function_name="main"): """ Takes a brainfuck program and returns the IR-code module """ self.logger.info("Generating IR-code from brainfuck") # Assembler code will call sample_start self.builder.module = ir.Module(module_name) ir_func = self.builder.new_procedure(function_name, ir.Binding.GLOBAL) self.builder.set_function(ir_func) block1 = self.builder.new_block() ir_func.entry = block1 self.builder.set_block(block1) # Allocate space on stack for ptr register: ptr_var = self.builder.emit( ir.Alloc("ptr_alloc", self.arch.get_size(ir.i32), 4) ) ptr_var = self.builder.emit(ir.AddressOf(ptr_var, "ptr_addr")) bf_mem_size = 30000 # Construct global array: data = ir.Variable( "data", ir.Binding.GLOBAL, bf_mem_size * self.arch.get_size(ir.i8), 4, ) self.builder.module.add_variable(data) # bsp puts function: bsp_putc = ir.ExternalProcedure("bsp_putc", [ir.u8]) self.builder.module.add_external(bsp_putc) # Locate '1' and '0' constants: one_i32_ins = self.builder.emit_const(1, ir.i32) one_ins = self.builder.emit(ir.Cast(one_i32_ins, "val_inc", ir.i8)) prc_inc = self.builder.emit(ir.Cast(one_i32_ins, "ptr_incr", ir.ptr)) zero_ins = self.builder.emit_const(0, ir.i32) zero_ptr = self.builder.emit(ir.Cast(zero_ins, "zero_ptr", ir.ptr)) zero_byte = self.builder.emit(ir.Cast(zero_ins, "zero_ptr", ir.i8)) array_size = self.builder.emit_const(bf_mem_size, ir.ptr) # Store initial value of ptr: self.builder.emit(ir.Store(zero_ptr, ptr_var)) # Initialize array to zero: block3 = self.builder.new_block() block_init = self.builder.new_block() self.builder.emit(ir.Jump(block_init)) self.builder.set_block(block_init) ptr_val = self.builder.emit_load(ptr_var, ir.ptr) cell_addr = self.builder.emit_add(data, ptr_val, ir.ptr) self.builder.emit(ir.Store(zero_ins, cell_addr)) add_ins = self.builder.emit_add(ptr_val, prc_inc, ir.ptr) self.builder.emit(ir.Store(add_ins, ptr_var)) self.builder.emit( ir.CJump(add_ins, "==", array_size, block3, block_init) ) self.builder.set_block(block3) # Start with ptr at 'data' ptr address: ptr = data # A stack of all nested loops: loops = [] # A mapping of all loop entries to the phi functions of ptr: phi_map = {} # Implement all instructions: for char in src: if char == ">": # ptr++; ptr = self.builder.emit_add(ptr, prc_inc, ir.ptr) elif char == "<": # ptr--; ptr = self.builder.emit_sub(ptr, prc_inc, ir.ptr) elif char == "+": # data[ptr]++; val_ins = self.builder.emit_load(ptr, ir.i8) add_ins = self.builder.emit_add(val_ins, one_ins, ir.i8) self.builder.emit(ir.Store(add_ins, ptr)) elif char == "-": # data[ptr]--; val_ins = self.builder.emit_load(ptr, ir.i8) sub_ins = self.builder.emit_sub(val_ins, one_ins, ir.i8) self.builder.emit(ir.Store(sub_ins, ptr)) elif char == ".": # putc(data[ptr]) val_ins = self.builder.emit_load(ptr, ir.i8) self.builder.emit(ir.ProcedureCall(bsp_putc, [val_ins])) elif char == ",": # pragma: no cover # data[ptr] = getchar() raise NotImplementedError('"," operator not implemented') elif char == "[": entry_block = self.builder.new_block() body = self.builder.new_block() exit_block = self.builder.new_block() current_block = self.builder.block # Register phi node into entry: ptr_phi = ir.Phi("ptr_phi", ir.ptr) ptr_phi.set_incoming(current_block, ptr) phi_map[entry_block] = ptr_phi # Jump to entry: self.builder.emit_jump(entry_block) self.builder.set_block(entry_block) # Register the phi node: self.builder.emit(ptr_phi) ptr = ptr_phi # Create test, jump to exit when *ptr == 0: val_ins = self.builder.emit_load(ptr, ir.i8) self.builder.emit( ir.CJump(val_ins, "==", zero_byte, exit_block, body) ) # Set body as current block: self.builder.set_block(body) loops.append((entry_block, exit_block)) elif char == "]": # Jump back to condition code: entry_block, exit_block = loops.pop(-1) # Set incoming branch to phi node: current_block = self.builder.block ptr_phi = phi_map[entry_block] ptr_phi.set_incoming(current_block, ptr) # Jump to entry again: self.builder.emit_jump(entry_block) self.builder.set_block(exit_block) # Set ptr to phi value front entry: ptr = ptr_phi if loops: raise CompilerError("[ requires matching ]") # Close current block: self.builder.emit_exit() # Yield module return self.builder.module
[ "def", "generate", "(", "self", ",", "src", ",", "module_name", "=", "\"main\"", ",", "function_name", "=", "\"main\"", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Generating IR-code from brainfuck\"", ")", "# Assembler code will call sample_start", "self", ".", "builder", ".", "module", "=", "ir", ".", "Module", "(", "module_name", ")", "ir_func", "=", "self", ".", "builder", ".", "new_procedure", "(", "function_name", ",", "ir", ".", "Binding", ".", "GLOBAL", ")", "self", ".", "builder", ".", "set_function", "(", "ir_func", ")", "block1", "=", "self", ".", "builder", ".", "new_block", "(", ")", "ir_func", ".", "entry", "=", "block1", "self", ".", "builder", ".", "set_block", "(", "block1", ")", "# Allocate space on stack for ptr register:", "ptr_var", "=", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Alloc", "(", "\"ptr_alloc\"", ",", "self", ".", "arch", ".", "get_size", "(", "ir", ".", "i32", ")", ",", "4", ")", ")", "ptr_var", "=", "self", ".", "builder", ".", "emit", "(", "ir", ".", "AddressOf", "(", "ptr_var", ",", "\"ptr_addr\"", ")", ")", "bf_mem_size", "=", "30000", "# Construct global array:", "data", "=", "ir", ".", "Variable", "(", "\"data\"", ",", "ir", ".", "Binding", ".", "GLOBAL", ",", "bf_mem_size", "*", "self", ".", "arch", ".", "get_size", "(", "ir", ".", "i8", ")", ",", "4", ",", ")", "self", ".", "builder", ".", "module", ".", "add_variable", "(", "data", ")", "# bsp puts function:", "bsp_putc", "=", "ir", ".", "ExternalProcedure", "(", "\"bsp_putc\"", ",", "[", "ir", ".", "u8", "]", ")", "self", ".", "builder", ".", "module", ".", "add_external", "(", "bsp_putc", ")", "# Locate '1' and '0' constants:", "one_i32_ins", "=", "self", ".", "builder", ".", "emit_const", "(", "1", ",", "ir", ".", "i32", ")", "one_ins", "=", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Cast", "(", "one_i32_ins", ",", "\"val_inc\"", ",", "ir", ".", "i8", ")", ")", "prc_inc", "=", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Cast", "(", "one_i32_ins", ",", "\"ptr_incr\"", ",", "ir", ".", "ptr", ")", ")", "zero_ins", "=", "self", ".", "builder", ".", "emit_const", "(", "0", ",", "ir", ".", "i32", ")", "zero_ptr", "=", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Cast", "(", "zero_ins", ",", "\"zero_ptr\"", ",", "ir", ".", "ptr", ")", ")", "zero_byte", "=", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Cast", "(", "zero_ins", ",", "\"zero_ptr\"", ",", "ir", ".", "i8", ")", ")", "array_size", "=", "self", ".", "builder", ".", "emit_const", "(", "bf_mem_size", ",", "ir", ".", "ptr", ")", "# Store initial value of ptr:", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Store", "(", "zero_ptr", ",", "ptr_var", ")", ")", "# Initialize array to zero:", "block3", "=", "self", ".", "builder", ".", "new_block", "(", ")", "block_init", "=", "self", ".", "builder", ".", "new_block", "(", ")", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Jump", "(", "block_init", ")", ")", "self", ".", "builder", ".", "set_block", "(", "block_init", ")", "ptr_val", "=", "self", ".", "builder", ".", "emit_load", "(", "ptr_var", ",", "ir", ".", "ptr", ")", "cell_addr", "=", "self", ".", "builder", ".", "emit_add", "(", "data", ",", "ptr_val", ",", "ir", ".", "ptr", ")", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Store", "(", "zero_ins", ",", "cell_addr", ")", ")", "add_ins", "=", "self", ".", "builder", ".", "emit_add", "(", "ptr_val", ",", "prc_inc", ",", "ir", ".", "ptr", ")", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Store", "(", "add_ins", ",", "ptr_var", ")", ")", "self", ".", "builder", ".", "emit", "(", "ir", ".", "CJump", "(", "add_ins", ",", "\"==\"", ",", "array_size", ",", "block3", ",", "block_init", ")", ")", "self", ".", "builder", ".", "set_block", "(", "block3", ")", "# Start with ptr at 'data' ptr address:", "ptr", "=", "data", "# A stack of all nested loops:", "loops", "=", "[", "]", "# A mapping of all loop entries to the phi functions of ptr:", "phi_map", "=", "{", "}", "# Implement all instructions:", "for", "char", "in", "src", ":", "if", "char", "==", "\">\"", ":", "# ptr++;", "ptr", "=", "self", ".", "builder", ".", "emit_add", "(", "ptr", ",", "prc_inc", ",", "ir", ".", "ptr", ")", "elif", "char", "==", "\"<\"", ":", "# ptr--;", "ptr", "=", "self", ".", "builder", ".", "emit_sub", "(", "ptr", ",", "prc_inc", ",", "ir", ".", "ptr", ")", "elif", "char", "==", "\"+\"", ":", "# data[ptr]++;", "val_ins", "=", "self", ".", "builder", ".", "emit_load", "(", "ptr", ",", "ir", ".", "i8", ")", "add_ins", "=", "self", ".", "builder", ".", "emit_add", "(", "val_ins", ",", "one_ins", ",", "ir", ".", "i8", ")", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Store", "(", "add_ins", ",", "ptr", ")", ")", "elif", "char", "==", "\"-\"", ":", "# data[ptr]--;", "val_ins", "=", "self", ".", "builder", ".", "emit_load", "(", "ptr", ",", "ir", ".", "i8", ")", "sub_ins", "=", "self", ".", "builder", ".", "emit_sub", "(", "val_ins", ",", "one_ins", ",", "ir", ".", "i8", ")", "self", ".", "builder", ".", "emit", "(", "ir", ".", "Store", "(", "sub_ins", ",", "ptr", ")", ")", "elif", "char", "==", "\".\"", ":", "# putc(data[ptr])", "val_ins", "=", "self", ".", "builder", ".", "emit_load", "(", "ptr", ",", "ir", ".", "i8", ")", "self", ".", "builder", ".", "emit", "(", "ir", ".", "ProcedureCall", "(", "bsp_putc", ",", "[", "val_ins", "]", ")", ")", "elif", "char", "==", "\",\"", ":", "# pragma: no cover", "# data[ptr] = getchar()", "raise", "NotImplementedError", "(", "'\",\" operator not implemented'", ")", "elif", "char", "==", "\"[\"", ":", "entry_block", "=", "self", ".", "builder", ".", "new_block", "(", ")", "body", "=", "self", ".", "builder", ".", "new_block", "(", ")", "exit_block", "=", "self", ".", "builder", ".", "new_block", "(", ")", "current_block", "=", "self", ".", "builder", ".", "block", "# Register phi node into entry:", "ptr_phi", "=", "ir", ".", "Phi", "(", "\"ptr_phi\"", ",", "ir", ".", "ptr", ")", "ptr_phi", ".", "set_incoming", "(", "current_block", ",", "ptr", ")", "phi_map", "[", "entry_block", "]", "=", "ptr_phi", "# Jump to entry:", "self", ".", "builder", ".", "emit_jump", "(", "entry_block", ")", "self", ".", "builder", ".", "set_block", "(", "entry_block", ")", "# Register the phi node:", "self", ".", "builder", ".", "emit", "(", "ptr_phi", ")", "ptr", "=", "ptr_phi", "# Create test, jump to exit when *ptr == 0:", "val_ins", "=", "self", ".", "builder", ".", "emit_load", "(", "ptr", ",", "ir", ".", "i8", ")", "self", ".", "builder", ".", "emit", "(", "ir", ".", "CJump", "(", "val_ins", ",", "\"==\"", ",", "zero_byte", ",", "exit_block", ",", "body", ")", ")", "# Set body as current block:", "self", ".", "builder", ".", "set_block", "(", "body", ")", "loops", ".", "append", "(", "(", "entry_block", ",", "exit_block", ")", ")", "elif", "char", "==", "\"]\"", ":", "# Jump back to condition code:", "entry_block", ",", "exit_block", "=", "loops", ".", "pop", "(", "-", "1", ")", "# Set incoming branch to phi node:", "current_block", "=", "self", ".", "builder", ".", "block", "ptr_phi", "=", "phi_map", "[", "entry_block", "]", "ptr_phi", ".", "set_incoming", "(", "current_block", ",", "ptr", ")", "# Jump to entry again:", "self", ".", "builder", ".", "emit_jump", "(", "entry_block", ")", "self", ".", "builder", ".", "set_block", "(", "exit_block", ")", "# Set ptr to phi value front entry:", "ptr", "=", "ptr_phi", "if", "loops", ":", "raise", "CompilerError", "(", "\"[ requires matching ]\"", ")", "# Close current block:", "self", ".", "builder", ".", "emit_exit", "(", ")", "# Yield module", "return", "self", ".", "builder", ".", "module" ]
https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/lang/bf.py#L30-L176
tztztztztz/eql.detectron2
29224acf4ea549c53264e6229da69868bd5470f3
detectron2/utils/video_visualizer.py
python
VideoVisualizer.draw_sem_seg
(self, frame, sem_seg, area_threshold=None)
return frame_visualizer.output
Args: sem_seg (ndarray or Tensor): semantic segmentation of shape (H, W), each value is the integer label. area_threshold (Optional[int]): only draw segmentations larger than the threshold
Args: sem_seg (ndarray or Tensor): semantic segmentation of shape (H, W), each value is the integer label. area_threshold (Optional[int]): only draw segmentations larger than the threshold
[ "Args", ":", "sem_seg", "(", "ndarray", "or", "Tensor", ")", ":", "semantic", "segmentation", "of", "shape", "(", "H", "W", ")", "each", "value", "is", "the", "integer", "label", ".", "area_threshold", "(", "Optional", "[", "int", "]", ")", ":", "only", "draw", "segmentations", "larger", "than", "the", "threshold" ]
def draw_sem_seg(self, frame, sem_seg, area_threshold=None): """ Args: sem_seg (ndarray or Tensor): semantic segmentation of shape (H, W), each value is the integer label. area_threshold (Optional[int]): only draw segmentations larger than the threshold """ # don't need to do anything special frame_visualizer = Visualizer(frame, self.metadata) frame_visualizer.draw_sem_seg(sem_seg, area_threshold=None) return frame_visualizer.output
[ "def", "draw_sem_seg", "(", "self", ",", "frame", ",", "sem_seg", ",", "area_threshold", "=", "None", ")", ":", "# don't need to do anything special", "frame_visualizer", "=", "Visualizer", "(", "frame", ",", "self", ".", "metadata", ")", "frame_visualizer", ".", "draw_sem_seg", "(", "sem_seg", ",", "area_threshold", "=", "None", ")", "return", "frame_visualizer", ".", "output" ]
https://github.com/tztztztztz/eql.detectron2/blob/29224acf4ea549c53264e6229da69868bd5470f3/detectron2/utils/video_visualizer.py#L112-L122
pygeos/pygeos
0835379a5bc534be63037696b1b70cf4337e3841
pygeos/strtree.py
python
STRtree.query_bulk
(self, geometry, predicate=None, distance=None)
return self._tree.query_bulk(geometry, predicate)
Returns all combinations of each input geometry and geometries in the tree where the envelope of each input geometry intersects with the envelope of a tree geometry. If predicate is provided, a prepared version of each input geometry is tested using the predicate function against each item whose extent intersects the envelope of the input geometry: predicate(geometry, tree_geometry). The 'dwithin' predicate requires GEOS >= 3.10. This returns an array with shape (2,n) where the subarrays correspond to the indexes of the input geometries and indexes of the tree geometries associated with each. To generate an array of pairs of input geometry index and tree geometry index, simply transpose the results. In the context of a spatial join, input geometries are the "left" geometries that determine the order of the results, and tree geometries are "right" geometries that are joined against the left geometries. This effectively performs an inner join, where only those combinations of geometries that can be joined based on envelope overlap or optional predicate are returned. Any geometry that is None or empty in the input geometries is omitted from the output. Parameters ---------- geometry : Geometry or array_like Input geometries to query the tree. The envelope of each geometry is automatically calculated for querying the tree. predicate : {None, 'intersects', 'within', 'contains', 'overlaps', 'crosses',\ 'touches', 'covers', 'covered_by', 'contains_properly', 'dwithin'}, optional The predicate to use for testing geometries from the tree that are within the input geometry's envelope. distance : number or array_like, optional Distances around each input geometry within which to query the tree for the 'dwithin' predicate. If array_like, shape must be broadcastable to shape of geometry. Required if predicate='dwithin'. Returns ------- ndarray with shape (2, n) The first subarray contains input geometry indexes. The second subarray contains tree geometry indexes. Examples -------- >>> import pygeos >>> tree = pygeos.STRtree(pygeos.points(np.arange(10), np.arange(10))) >>> tree.query_bulk([pygeos.box(2, 2, 4, 4), pygeos.box(5, 5, 6, 6)]).tolist() [[0, 0, 0, 1, 1], [2, 3, 4, 5, 6]] >>> # Query for geometries that contain tree geometries >>> tree.query_bulk([pygeos.box(2, 2, 4, 4), pygeos.box(5, 5, 6, 6)], predicate='contains').tolist() [[0], [3]] >>> # To get an array of pairs of index of input geometry, index of tree geometry, >>> # transpose the output: >>> tree.query_bulk([pygeos.box(2, 2, 4, 4), pygeos.box(5, 5, 6, 6)]).T.tolist() [[0, 2], [0, 3], [0, 4], [1, 5], [1, 6]] >>> # Query for tree geometries within 1 unit distance of input geometries >>> tree.query_bulk([pygeos.points(0.5, 0.5)], predicate='dwithin', distance=1.0).tolist() # doctest: +SKIP [[0, 0], [0, 1]]
Returns all combinations of each input geometry and geometries in the tree where the envelope of each input geometry intersects with the envelope of a tree geometry.
[ "Returns", "all", "combinations", "of", "each", "input", "geometry", "and", "geometries", "in", "the", "tree", "where", "the", "envelope", "of", "each", "input", "geometry", "intersects", "with", "the", "envelope", "of", "a", "tree", "geometry", "." ]
def query_bulk(self, geometry, predicate=None, distance=None): """Returns all combinations of each input geometry and geometries in the tree where the envelope of each input geometry intersects with the envelope of a tree geometry. If predicate is provided, a prepared version of each input geometry is tested using the predicate function against each item whose extent intersects the envelope of the input geometry: predicate(geometry, tree_geometry). The 'dwithin' predicate requires GEOS >= 3.10. This returns an array with shape (2,n) where the subarrays correspond to the indexes of the input geometries and indexes of the tree geometries associated with each. To generate an array of pairs of input geometry index and tree geometry index, simply transpose the results. In the context of a spatial join, input geometries are the "left" geometries that determine the order of the results, and tree geometries are "right" geometries that are joined against the left geometries. This effectively performs an inner join, where only those combinations of geometries that can be joined based on envelope overlap or optional predicate are returned. Any geometry that is None or empty in the input geometries is omitted from the output. Parameters ---------- geometry : Geometry or array_like Input geometries to query the tree. The envelope of each geometry is automatically calculated for querying the tree. predicate : {None, 'intersects', 'within', 'contains', 'overlaps', 'crosses',\ 'touches', 'covers', 'covered_by', 'contains_properly', 'dwithin'}, optional The predicate to use for testing geometries from the tree that are within the input geometry's envelope. distance : number or array_like, optional Distances around each input geometry within which to query the tree for the 'dwithin' predicate. If array_like, shape must be broadcastable to shape of geometry. Required if predicate='dwithin'. Returns ------- ndarray with shape (2, n) The first subarray contains input geometry indexes. The second subarray contains tree geometry indexes. Examples -------- >>> import pygeos >>> tree = pygeos.STRtree(pygeos.points(np.arange(10), np.arange(10))) >>> tree.query_bulk([pygeos.box(2, 2, 4, 4), pygeos.box(5, 5, 6, 6)]).tolist() [[0, 0, 0, 1, 1], [2, 3, 4, 5, 6]] >>> # Query for geometries that contain tree geometries >>> tree.query_bulk([pygeos.box(2, 2, 4, 4), pygeos.box(5, 5, 6, 6)], predicate='contains').tolist() [[0], [3]] >>> # To get an array of pairs of index of input geometry, index of tree geometry, >>> # transpose the output: >>> tree.query_bulk([pygeos.box(2, 2, 4, 4), pygeos.box(5, 5, 6, 6)]).T.tolist() [[0, 2], [0, 3], [0, 4], [1, 5], [1, 6]] >>> # Query for tree geometries within 1 unit distance of input geometries >>> tree.query_bulk([pygeos.points(0.5, 0.5)], predicate='dwithin', distance=1.0).tolist() # doctest: +SKIP [[0, 0], [0, 1]] """ geometry = np.asarray(geometry) if geometry.ndim == 0: geometry = np.expand_dims(geometry, 0) if predicate is None: return self._tree.query_bulk(geometry, 0) # Requires GEOS >= 3.10 elif predicate == "dwithin": if lib.geos_version < (3, 10, 0): raise UnsupportedGEOSOperation( "dwithin predicate requires GEOS >= 3.10" ) if distance is None: raise ValueError( "distance parameter must be provided for dwithin predicate" ) distance = np.asarray(distance, dtype="float64") if distance.ndim > 1: raise ValueError("Distance array should be one dimensional") try: distance = np.broadcast_to(distance, geometry.shape) except ValueError: raise ValueError("Could not broadcast distance to match geometry") return self._tree.dwithin(geometry, distance) predicate = BinaryPredicate.get_value(predicate) return self._tree.query_bulk(geometry, predicate)
[ "def", "query_bulk", "(", "self", ",", "geometry", ",", "predicate", "=", "None", ",", "distance", "=", "None", ")", ":", "geometry", "=", "np", ".", "asarray", "(", "geometry", ")", "if", "geometry", ".", "ndim", "==", "0", ":", "geometry", "=", "np", ".", "expand_dims", "(", "geometry", ",", "0", ")", "if", "predicate", "is", "None", ":", "return", "self", ".", "_tree", ".", "query_bulk", "(", "geometry", ",", "0", ")", "# Requires GEOS >= 3.10", "elif", "predicate", "==", "\"dwithin\"", ":", "if", "lib", ".", "geos_version", "<", "(", "3", ",", "10", ",", "0", ")", ":", "raise", "UnsupportedGEOSOperation", "(", "\"dwithin predicate requires GEOS >= 3.10\"", ")", "if", "distance", "is", "None", ":", "raise", "ValueError", "(", "\"distance parameter must be provided for dwithin predicate\"", ")", "distance", "=", "np", ".", "asarray", "(", "distance", ",", "dtype", "=", "\"float64\"", ")", "if", "distance", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"Distance array should be one dimensional\"", ")", "try", ":", "distance", "=", "np", ".", "broadcast_to", "(", "distance", ",", "geometry", ".", "shape", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Could not broadcast distance to match geometry\"", ")", "return", "self", ".", "_tree", ".", "dwithin", "(", "geometry", ",", "distance", ")", "predicate", "=", "BinaryPredicate", ".", "get_value", "(", "predicate", ")", "return", "self", ".", "_tree", ".", "query_bulk", "(", "geometry", ",", "predicate", ")" ]
https://github.com/pygeos/pygeos/blob/0835379a5bc534be63037696b1b70cf4337e3841/pygeos/strtree.py#L135-L228
veusz/veusz
5a1e2af5f24df0eb2a2842be51f2997c4999c7fb
veusz/setting/controls.py
python
ListSet._updateRowCol
(self, row, col, val)
Update value on row and column.
Update value on row and column.
[ "Update", "value", "on", "row", "and", "column", "." ]
def _updateRowCol(self, row, col, val): """Update value on row and column.""" rows = list(self.setting.val) items = list(rows[row]) items[col] = val rows[row] = tuple(items) self.sigSettingChanged.emit(self, self.setting, rows)
[ "def", "_updateRowCol", "(", "self", ",", "row", ",", "col", ",", "val", ")", ":", "rows", "=", "list", "(", "self", ".", "setting", ".", "val", ")", "items", "=", "list", "(", "rows", "[", "row", "]", ")", "items", "[", "col", "]", "=", "val", "rows", "[", "row", "]", "=", "tuple", "(", "items", ")", "self", ".", "sigSettingChanged", ".", "emit", "(", "self", ",", "self", ".", "setting", ",", "rows", ")" ]
https://github.com/veusz/veusz/blob/5a1e2af5f24df0eb2a2842be51f2997c4999c7fb/veusz/setting/controls.py#L1300-L1306
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
vta/python/vta/top/graphpack.py
python
run_opt_pass
(expr, opt_pass)
return entry if isinstance(expr, relay.Function) else entry.body
Exectue a relay pass.
Exectue a relay pass.
[ "Exectue", "a", "relay", "pass", "." ]
def run_opt_pass(expr, opt_pass): """Exectue a relay pass.""" assert isinstance(opt_pass, tvm.transform.Pass) mod = tvm.IRModule.from_expr(expr) mod = opt_pass(mod) entry = mod["main"] return entry if isinstance(expr, relay.Function) else entry.body
[ "def", "run_opt_pass", "(", "expr", ",", "opt_pass", ")", ":", "assert", "isinstance", "(", "opt_pass", ",", "tvm", ".", "transform", ".", "Pass", ")", "mod", "=", "tvm", ".", "IRModule", ".", "from_expr", "(", "expr", ")", "mod", "=", "opt_pass", "(", "mod", ")", "entry", "=", "mod", "[", "\"main\"", "]", "return", "entry", "if", "isinstance", "(", "expr", ",", "relay", ".", "Function", ")", "else", "entry", ".", "body" ]
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/vta/python/vta/top/graphpack.py#L26-L32
aws-samples/aws-etl-orchestrator
6477b181054ac39f5661e6f2cacb4cc885c2f7a5
build.py
python
updatelambda
(*functions)
return
Directly update lambda function code in AWS (without upload to S3).
Directly update lambda function code in AWS (without upload to S3).
[ "Directly", "update", "lambda", "function", "code", "in", "AWS", "(", "without", "upload", "to", "S3", ")", "." ]
def updatelambda(*functions): '''Directly update lambda function code in AWS (without upload to S3).''' lambda_client = boto3.client('lambda') if len(functions) == 0: functions = ("athenarunner", "gluerunner", "ons3objectcreated") for function in functions: with open('build/%s.zip' % function, 'rb') as zipf: lambda_client.update_function_code( FunctionName=function, ZipFile=zipf.read() ) return
[ "def", "updatelambda", "(", "*", "functions", ")", ":", "lambda_client", "=", "boto3", ".", "client", "(", "'lambda'", ")", "if", "len", "(", "functions", ")", "==", "0", ":", "functions", "=", "(", "\"athenarunner\"", ",", "\"gluerunner\"", ",", "\"ons3objectcreated\"", ")", "for", "function", "in", "functions", ":", "with", "open", "(", "'build/%s.zip'", "%", "function", ",", "'rb'", ")", "as", "zipf", ":", "lambda_client", ".", "update_function_code", "(", "FunctionName", "=", "function", ",", "ZipFile", "=", "zipf", ".", "read", "(", ")", ")", "return" ]
https://github.com/aws-samples/aws-etl-orchestrator/blob/6477b181054ac39f5661e6f2cacb4cc885c2f7a5/build.py#L101-L114
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/pydoc.py
python
HTMLDoc.heading
(self, title, fgcol, bgcol, extras='')
return ''' <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="%s"> <td valign=bottom>&nbsp;<br> <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td ><td align=right valign=bottom ><font color="%s" face="helvetica, arial">%s</font></td></tr></table> ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
Format a page heading.
Format a page heading.
[ "Format", "a", "page", "heading", "." ]
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return ''' <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="%s"> <td valign=bottom>&nbsp;<br> <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td ><td align=right valign=bottom ><font color="%s" face="helvetica, arial">%s</font></td></tr></table> ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
[ "def", "heading", "(", "self", ",", "title", ",", "fgcol", ",", "bgcol", ",", "extras", "=", "''", ")", ":", "return", "'''\n<table width=\"100%%\" cellspacing=0 cellpadding=2 border=0 summary=\"heading\">\n<tr bgcolor=\"%s\">\n<td valign=bottom>&nbsp;<br>\n<font color=\"%s\" face=\"helvetica, arial\">&nbsp;<br>%s</font></td\n><td align=right valign=bottom\n><font color=\"%s\" face=\"helvetica, arial\">%s</font></td></tr></table>\n '''", "%", "(", "bgcol", ",", "fgcol", ",", "title", ",", "fgcol", ",", "extras", "or", "'&nbsp;'", ")" ]
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/pydoc.py#L434-L443
PySimpleGUI/PySimpleGUI
6c0d1fb54f493d45e90180b322fbbe70f7a5af3c
DemoPrograms/Demo_Desktop_Widget_Email_Notification.py
python
read_mail
(window)
Reads late emails from IMAP server and displays them in the Window :param window: window to display emails in :return:
Reads late emails from IMAP server and displays them in the Window :param window: window to display emails in :return:
[ "Reads", "late", "emails", "from", "IMAP", "server", "and", "displays", "them", "in", "the", "Window", ":", "param", "window", ":", "window", "to", "display", "emails", "in", ":", "return", ":" ]
def read_mail(window): """ Reads late emails from IMAP server and displays them in the Window :param window: window to display emails in :return: """ mail = imaplib.IMAP4_SSL(IMAP_SERVER) (retcode, capabilities) = mail.login(LOGIN_EMAIL, LOGIN_PASSWORD) mail.list() typ, data = mail.select('Inbox') n = 0 now = datetime.now() # get messages from today search_string = '(SENTON {}-{}-{})'.format(now.day, calendar.month_abbr[now.month], now.year) (retcode, messages) = mail.search(None, search_string) if retcode == 'OK': # message numbers are separated by spaces, turn into list msg_list = messages[0].split() msg_list.sort(reverse=True) # sort messages descending for n, message in enumerate(msg_list): if n >= MAX_EMAILS: break from_elem = window['{}from'.format(n)] date_elem = window['{}date'.format(n)] from_elem.update('') # erase them so you know they're changing date_elem.update('') window.refresh() typ, data = mail.fetch(message, '(RFC822)') for response_part in data: if isinstance(response_part, tuple): original = email.message_from_bytes(response_part[1]) date_str = original['Date'][:22] from_elem.update(original['From']) date_elem.update(date_str) window.refresh()
[ "def", "read_mail", "(", "window", ")", ":", "mail", "=", "imaplib", ".", "IMAP4_SSL", "(", "IMAP_SERVER", ")", "(", "retcode", ",", "capabilities", ")", "=", "mail", ".", "login", "(", "LOGIN_EMAIL", ",", "LOGIN_PASSWORD", ")", "mail", ".", "list", "(", ")", "typ", ",", "data", "=", "mail", ".", "select", "(", "'Inbox'", ")", "n", "=", "0", "now", "=", "datetime", ".", "now", "(", ")", "# get messages from today", "search_string", "=", "'(SENTON {}-{}-{})'", ".", "format", "(", "now", ".", "day", ",", "calendar", ".", "month_abbr", "[", "now", ".", "month", "]", ",", "now", ".", "year", ")", "(", "retcode", ",", "messages", ")", "=", "mail", ".", "search", "(", "None", ",", "search_string", ")", "if", "retcode", "==", "'OK'", ":", "# message numbers are separated by spaces, turn into list", "msg_list", "=", "messages", "[", "0", "]", ".", "split", "(", ")", "msg_list", ".", "sort", "(", "reverse", "=", "True", ")", "# sort messages descending", "for", "n", ",", "message", "in", "enumerate", "(", "msg_list", ")", ":", "if", "n", ">=", "MAX_EMAILS", ":", "break", "from_elem", "=", "window", "[", "'{}from'", ".", "format", "(", "n", ")", "]", "date_elem", "=", "window", "[", "'{}date'", ".", "format", "(", "n", ")", "]", "from_elem", ".", "update", "(", "''", ")", "# erase them so you know they're changing", "date_elem", ".", "update", "(", "''", ")", "window", ".", "refresh", "(", ")", "typ", ",", "data", "=", "mail", ".", "fetch", "(", "message", ",", "'(RFC822)'", ")", "for", "response_part", "in", "data", ":", "if", "isinstance", "(", "response_part", ",", "tuple", ")", ":", "original", "=", "email", ".", "message_from_bytes", "(", "response_part", "[", "1", "]", ")", "date_str", "=", "original", "[", "'Date'", "]", "[", ":", "22", "]", "from_elem", ".", "update", "(", "original", "[", "'From'", "]", ")", "date_elem", ".", "update", "(", "date_str", ")", "window", ".", "refresh", "(", ")" ]
https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/DemoPrograms/Demo_Desktop_Widget_Email_Notification.py#L68-L108
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/urllib.py
python
getproxies_environment
()
return proxies
Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named <scheme>_proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor.
Return a dictionary of scheme -> proxy server URL mappings.
[ "Return", "a", "dictionary", "of", "scheme", "-", ">", "proxy", "server", "URL", "mappings", "." ]
def getproxies_environment(): """Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named <scheme>_proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor. """ proxies = {} for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value return proxies
[ "def", "getproxies_environment", "(", ")", ":", "proxies", "=", "{", "}", "for", "name", ",", "value", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "if", "value", "and", "name", "[", "-", "6", ":", "]", "==", "'_proxy'", ":", "proxies", "[", "name", "[", ":", "-", "6", "]", "]", "=", "value", "return", "proxies" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/urllib.py#L1367-L1381
googlearchive/appengine-flask-skeleton
8c25461d003a0bd99a9ff3b339c2791ee6919242
lib/jinja2/environment.py
python
Environment.get_or_select_template
(self, template_name_or_list, parent=None, globals=None)
return self.select_template(template_name_or_list, parent, globals)
Does a typecheck and dispatches to :meth:`select_template` if an iterable of template names is given, otherwise to :meth:`get_template`. .. versionadded:: 2.3
Does a typecheck and dispatches to :meth:`select_template` if an iterable of template names is given, otherwise to :meth:`get_template`.
[ "Does", "a", "typecheck", "and", "dispatches", "to", ":", "meth", ":", "select_template", "if", "an", "iterable", "of", "template", "names", "is", "given", "otherwise", "to", ":", "meth", ":", "get_template", "." ]
def get_or_select_template(self, template_name_or_list, parent=None, globals=None): """Does a typecheck and dispatches to :meth:`select_template` if an iterable of template names is given, otherwise to :meth:`get_template`. .. versionadded:: 2.3 """ if isinstance(template_name_or_list, string_types): return self.get_template(template_name_or_list, parent, globals) elif isinstance(template_name_or_list, Template): return template_name_or_list return self.select_template(template_name_or_list, parent, globals)
[ "def", "get_or_select_template", "(", "self", ",", "template_name_or_list", ",", "parent", "=", "None", ",", "globals", "=", "None", ")", ":", "if", "isinstance", "(", "template_name_or_list", ",", "string_types", ")", ":", "return", "self", ".", "get_template", "(", "template_name_or_list", ",", "parent", ",", "globals", ")", "elif", "isinstance", "(", "template_name_or_list", ",", "Template", ")", ":", "return", "template_name_or_list", "return", "self", ".", "select_template", "(", "template_name_or_list", ",", "parent", ",", "globals", ")" ]
https://github.com/googlearchive/appengine-flask-skeleton/blob/8c25461d003a0bd99a9ff3b339c2791ee6919242/lib/jinja2/environment.py#L842-L854
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
controllers/default.py
python
tables
()
return s3_rest_controller("s3", "table", rheader = s3db.s3_table_rheader, csv_template = ("s3", "table"), csv_stylesheet = ("s3", "table.xsl"), )
RESTful CRUD Controller for Dynamic Table Models
RESTful CRUD Controller for Dynamic Table Models
[ "RESTful", "CRUD", "Controller", "for", "Dynamic", "Table", "Models" ]
def tables(): """ RESTful CRUD Controller for Dynamic Table Models """ return s3_rest_controller("s3", "table", rheader = s3db.s3_table_rheader, csv_template = ("s3", "table"), csv_stylesheet = ("s3", "table.xsl"), )
[ "def", "tables", "(", ")", ":", "return", "s3_rest_controller", "(", "\"s3\"", ",", "\"table\"", ",", "rheader", "=", "s3db", ".", "s3_table_rheader", ",", "csv_template", "=", "(", "\"s3\"", ",", "\"table\"", ")", ",", "csv_stylesheet", "=", "(", "\"s3\"", ",", "\"table.xsl\"", ")", ",", ")" ]
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/controllers/default.py#L1346-L1355