repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
derpston/python-multitail2 | src/multitail2.py | TailedFile.hasBeenRotated | def hasBeenRotated(self):
"""Returns a boolean indicating whether the file has been removed and recreated during the time it has been open."""
try:
# If the inodes don't match, it means the file has been replaced.
# The inode number cannot be recycled as long as we hold the
# filehandle open, so this test can be trusted.
return os.stat(self._path).st_ino != self._inode
except OSError:
# If the file doesn't exist, let's call it "rotated".
return True | python | def hasBeenRotated(self):
"""Returns a boolean indicating whether the file has been removed and recreated during the time it has been open."""
try:
# If the inodes don't match, it means the file has been replaced.
# The inode number cannot be recycled as long as we hold the
# filehandle open, so this test can be trusted.
return os.stat(self._path).st_ino != self._inode
except OSError:
# If the file doesn't exist, let's call it "rotated".
return True | [
"def",
"hasBeenRotated",
"(",
"self",
")",
":",
"try",
":",
"# If the inodes don't match, it means the file has been replaced.",
"# The inode number cannot be recycled as long as we hold the",
"# filehandle open, so this test can be trusted.",
"return",
"os",
".",
"stat",
"(",
"self"... | Returns a boolean indicating whether the file has been removed and recreated during the time it has been open. | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"file",
"has",
"been",
"removed",
"and",
"recreated",
"during",
"the",
"time",
"it",
"has",
"been",
"open",
"."
] | train | https://github.com/derpston/python-multitail2/blob/4f05311da3b18f7a8cfe2877e68e35e88c07298d/src/multitail2.py#L68-L77 |
derpston/python-multitail2 | src/multitail2.py | TailedFile.reopen | def reopen(self):
"""Reopens the file. Usually used after it has been rotated."""
# Read any remaining content in the file and store it in a buffer.
self._read()
# Close it to ensure we don't leak file descriptors
self._close()
# Reopen the file.
try:
self._open(self._path, skip_to_end = False)
return True
except OSError:
# If opening fails, it was probably deleted.
return False | python | def reopen(self):
"""Reopens the file. Usually used after it has been rotated."""
# Read any remaining content in the file and store it in a buffer.
self._read()
# Close it to ensure we don't leak file descriptors
self._close()
# Reopen the file.
try:
self._open(self._path, skip_to_end = False)
return True
except OSError:
# If opening fails, it was probably deleted.
return False | [
"def",
"reopen",
"(",
"self",
")",
":",
"# Read any remaining content in the file and store it in a buffer.",
"self",
".",
"_read",
"(",
")",
"# Close it to ensure we don't leak file descriptors",
"self",
".",
"_close",
"(",
")",
"# Reopen the file.",
"try",
":",
"self",
... | Reopens the file. Usually used after it has been rotated. | [
"Reopens",
"the",
"file",
".",
"Usually",
"used",
"after",
"it",
"has",
"been",
"rotated",
"."
] | train | https://github.com/derpston/python-multitail2/blob/4f05311da3b18f7a8cfe2877e68e35e88c07298d/src/multitail2.py#L79-L92 |
derpston/python-multitail2 | src/multitail2.py | TailedFile.readlines | def readlines(self):
"""A generator producing lines from the file."""
# If the file is not open, there's nothing to return
if not self._fh:
raise StopIteration
at_eof = False
while True:
# Clean the buffer sometimes.
if self._bufoffset > (self._maxreadsize / 2):
self._buf = self._buf[self._bufoffset:]
self._bufoffset = 0
# Fill up the buffer if necessary.
if len(self._buf) < self._maxreadsize:
at_eof = not self._read(self._maxreadsize)
# Look for the next line.
try:
next_newline = self._buf.index("\n", self._bufoffset)
line = self._buf[self._bufoffset:next_newline]
self._bufoffset = next_newline + 1
# Save the current file offset for yielding and advance the file offset.
offset = self._offset
self._offset += len(line) + 1
if self._longline:
# This is the remaining chunk of a long line, we're not going
# to yield it.
self._longline = False
else:
yield line, offset
except ValueError:
# Reached the end of the buffer without finding any newlines.
if not at_eof:
# Line is longer than the half the buffer size? - Nope
logger.warning("Skipping over longline at %s:%d", self._path,
self._offset)
self._bufoffset = len(self._buf) - 1
self._longline = True
raise StopIteration | python | def readlines(self):
"""A generator producing lines from the file."""
# If the file is not open, there's nothing to return
if not self._fh:
raise StopIteration
at_eof = False
while True:
# Clean the buffer sometimes.
if self._bufoffset > (self._maxreadsize / 2):
self._buf = self._buf[self._bufoffset:]
self._bufoffset = 0
# Fill up the buffer if necessary.
if len(self._buf) < self._maxreadsize:
at_eof = not self._read(self._maxreadsize)
# Look for the next line.
try:
next_newline = self._buf.index("\n", self._bufoffset)
line = self._buf[self._bufoffset:next_newline]
self._bufoffset = next_newline + 1
# Save the current file offset for yielding and advance the file offset.
offset = self._offset
self._offset += len(line) + 1
if self._longline:
# This is the remaining chunk of a long line, we're not going
# to yield it.
self._longline = False
else:
yield line, offset
except ValueError:
# Reached the end of the buffer without finding any newlines.
if not at_eof:
# Line is longer than the half the buffer size? - Nope
logger.warning("Skipping over longline at %s:%d", self._path,
self._offset)
self._bufoffset = len(self._buf) - 1
self._longline = True
raise StopIteration | [
"def",
"readlines",
"(",
"self",
")",
":",
"# If the file is not open, there's nothing to return",
"if",
"not",
"self",
".",
"_fh",
":",
"raise",
"StopIteration",
"at_eof",
"=",
"False",
"while",
"True",
":",
"# Clean the buffer sometimes.",
"if",
"self",
".",
"_buf... | A generator producing lines from the file. | [
"A",
"generator",
"producing",
"lines",
"from",
"the",
"file",
"."
] | train | https://github.com/derpston/python-multitail2/blob/4f05311da3b18f7a8cfe2877e68e35e88c07298d/src/multitail2.py#L94-L135 |
derpston/python-multitail2 | src/multitail2.py | MultiTail._rescan | def _rescan(self, skip_to_end = True):
"""Check for new files, deleted files, and rotated files."""
# Get listing of matching files.
paths = []
for single_glob in self._globspec:
paths.extend(glob.glob(single_glob))
# Remove files that don't appear in the new list.
for path in self._tailedfiles.keys():
if path not in paths:
self._tailedfiles[path]._close()
del self._tailedfiles[path]
# Add any files we don't have open yet.
for path in paths:
try:
# If the file has been rotated, reopen it.
if self._tailedfiles[path].hasBeenRotated():
# If it can't be reopened, close it.
if not self._tailedfiles[path].reopen():
del self._tailedfiles[path]
except KeyError:
# Open a file that we haven't seen yet.
self._tailedfiles[path] = TailedFile(path, skip_to_end = skip_to_end, offset = self._offsets.get(path, None)) | python | def _rescan(self, skip_to_end = True):
"""Check for new files, deleted files, and rotated files."""
# Get listing of matching files.
paths = []
for single_glob in self._globspec:
paths.extend(glob.glob(single_glob))
# Remove files that don't appear in the new list.
for path in self._tailedfiles.keys():
if path not in paths:
self._tailedfiles[path]._close()
del self._tailedfiles[path]
# Add any files we don't have open yet.
for path in paths:
try:
# If the file has been rotated, reopen it.
if self._tailedfiles[path].hasBeenRotated():
# If it can't be reopened, close it.
if not self._tailedfiles[path].reopen():
del self._tailedfiles[path]
except KeyError:
# Open a file that we haven't seen yet.
self._tailedfiles[path] = TailedFile(path, skip_to_end = skip_to_end, offset = self._offsets.get(path, None)) | [
"def",
"_rescan",
"(",
"self",
",",
"skip_to_end",
"=",
"True",
")",
":",
"# Get listing of matching files.",
"paths",
"=",
"[",
"]",
"for",
"single_glob",
"in",
"self",
".",
"_globspec",
":",
"paths",
".",
"extend",
"(",
"glob",
".",
"glob",
"(",
"single_... | Check for new files, deleted files, and rotated files. | [
"Check",
"for",
"new",
"files",
"deleted",
"files",
"and",
"rotated",
"files",
"."
] | train | https://github.com/derpston/python-multitail2/blob/4f05311da3b18f7a8cfe2877e68e35e88c07298d/src/multitail2.py#L153-L176 |
derpston/python-multitail2 | src/multitail2.py | MultiTail.poll | def poll(self, force_rescan = False):
"""A generator producing (path, line) tuples with lines seen since the last time poll() was called. Will not block. Checks for new/deleted/rotated files every `interval` seconds, but will check every time if `force_rescan` is True. (default False)"""
# Check for new, deleted, and rotated files.
if force_rescan or time.time() > self._last_scan + self._interval:
self._rescan(skip_to_end = False)
self._last_scan = time.time()
filereaders = {}
for path, tailedfile in self._tailedfiles.iteritems():
filereaders[path] = tailedfile.readlines()
# One line is read from each file in turn, in an attempt to read
# from all files evenly. They'll be in an undefined order because
# of using a dict for filereaders, but that's not a problem
# because some entropy here is desirable for evenness.
while len(filereaders) > 0:
for path in filereaders.keys():
lines = filereaders[path]
try:
line, offset = lines.next()
except StopIteration:
# Reached end the of this file.
del filereaders[path]
break
yield (path, offset), line | python | def poll(self, force_rescan = False):
"""A generator producing (path, line) tuples with lines seen since the last time poll() was called. Will not block. Checks for new/deleted/rotated files every `interval` seconds, but will check every time if `force_rescan` is True. (default False)"""
# Check for new, deleted, and rotated files.
if force_rescan or time.time() > self._last_scan + self._interval:
self._rescan(skip_to_end = False)
self._last_scan = time.time()
filereaders = {}
for path, tailedfile in self._tailedfiles.iteritems():
filereaders[path] = tailedfile.readlines()
# One line is read from each file in turn, in an attempt to read
# from all files evenly. They'll be in an undefined order because
# of using a dict for filereaders, but that's not a problem
# because some entropy here is desirable for evenness.
while len(filereaders) > 0:
for path in filereaders.keys():
lines = filereaders[path]
try:
line, offset = lines.next()
except StopIteration:
# Reached end the of this file.
del filereaders[path]
break
yield (path, offset), line | [
"def",
"poll",
"(",
"self",
",",
"force_rescan",
"=",
"False",
")",
":",
"# Check for new, deleted, and rotated files.",
"if",
"force_rescan",
"or",
"time",
".",
"time",
"(",
")",
">",
"self",
".",
"_last_scan",
"+",
"self",
".",
"_interval",
":",
"self",
".... | A generator producing (path, line) tuples with lines seen since the last time poll() was called. Will not block. Checks for new/deleted/rotated files every `interval` seconds, but will check every time if `force_rescan` is True. (default False) | [
"A",
"generator",
"producing",
"(",
"path",
"line",
")",
"tuples",
"with",
"lines",
"seen",
"since",
"the",
"last",
"time",
"poll",
"()",
"was",
"called",
".",
"Will",
"not",
"block",
".",
"Checks",
"for",
"new",
"/",
"deleted",
"/",
"rotated",
"files",
... | train | https://github.com/derpston/python-multitail2/blob/4f05311da3b18f7a8cfe2877e68e35e88c07298d/src/multitail2.py#L178-L203 |
derpston/python-multitail2 | src/multitail2.py | MultiTail.offsets | def offsets(self):
"""A generator producing a (path, offset) tuple for all tailed files."""
for path, tailedfile in self._tailedfiles.iteritems():
yield path, tailedfile._offset | python | def offsets(self):
"""A generator producing a (path, offset) tuple for all tailed files."""
for path, tailedfile in self._tailedfiles.iteritems():
yield path, tailedfile._offset | [
"def",
"offsets",
"(",
"self",
")",
":",
"for",
"path",
",",
"tailedfile",
"in",
"self",
".",
"_tailedfiles",
".",
"iteritems",
"(",
")",
":",
"yield",
"path",
",",
"tailedfile",
".",
"_offset"
] | A generator producing a (path, offset) tuple for all tailed files. | [
"A",
"generator",
"producing",
"a",
"(",
"path",
"offset",
")",
"tuple",
"for",
"all",
"tailed",
"files",
"."
] | train | https://github.com/derpston/python-multitail2/blob/4f05311da3b18f7a8cfe2877e68e35e88c07298d/src/multitail2.py#L213-L216 |
twisted/epsilon | epsilon/amprouter.py | Route.connectTo | def connectTo(self, remoteRouteName):
"""
Set the name of the route which will be added to outgoing boxes.
"""
self.remoteRouteName = remoteRouteName
# This route must not be started before its router is started. If
# sender is None, then the router is not started. When the router is
# started, it will start this route.
if self.router._sender is not None:
self.start() | python | def connectTo(self, remoteRouteName):
"""
Set the name of the route which will be added to outgoing boxes.
"""
self.remoteRouteName = remoteRouteName
# This route must not be started before its router is started. If
# sender is None, then the router is not started. When the router is
# started, it will start this route.
if self.router._sender is not None:
self.start() | [
"def",
"connectTo",
"(",
"self",
",",
"remoteRouteName",
")",
":",
"self",
".",
"remoteRouteName",
"=",
"remoteRouteName",
"# This route must not be started before its router is started. If",
"# sender is None, then the router is not started. When the router is",
"# started, it will ... | Set the name of the route which will be added to outgoing boxes. | [
"Set",
"the",
"name",
"of",
"the",
"route",
"which",
"will",
"be",
"added",
"to",
"outgoing",
"boxes",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/amprouter.py#L54-L63 |
twisted/epsilon | epsilon/amprouter.py | Route.sendBox | def sendBox(self, box):
"""
Add the route and send the box.
"""
if self.remoteRouteName is _unspecified:
raise RouteNotConnected()
if self.remoteRouteName is not None:
box[_ROUTE] = self.remoteRouteName.encode('ascii')
self.router._sender.sendBox(box) | python | def sendBox(self, box):
"""
Add the route and send the box.
"""
if self.remoteRouteName is _unspecified:
raise RouteNotConnected()
if self.remoteRouteName is not None:
box[_ROUTE] = self.remoteRouteName.encode('ascii')
self.router._sender.sendBox(box) | [
"def",
"sendBox",
"(",
"self",
",",
"box",
")",
":",
"if",
"self",
".",
"remoteRouteName",
"is",
"_unspecified",
":",
"raise",
"RouteNotConnected",
"(",
")",
"if",
"self",
".",
"remoteRouteName",
"is",
"not",
"None",
":",
"box",
"[",
"_ROUTE",
"]",
"=",
... | Add the route and send the box. | [
"Add",
"the",
"route",
"and",
"send",
"the",
"box",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/amprouter.py#L87-L95 |
twisted/epsilon | epsilon/amprouter.py | Router.bindRoute | def bindRoute(self, receiver, routeName=_unspecified):
"""
Create a new route to associate the given route name with the given
receiver.
@type routeName: C{unicode} or L{NoneType}
@param routeName: The identifier for the newly created route. If
C{None}, boxes with no route in them will be delivered to this
receiver.
@rtype: L{Route}
"""
if routeName is _unspecified:
routeName = self.createRouteIdentifier()
# self._sender may yet be None; if so, this route goes into _unstarted
# and will have its sender set correctly in startReceivingBoxes below.
route = Route(self, receiver, routeName)
mapping = self._routes
if mapping is None:
mapping = self._unstarted
mapping[routeName] = route
return route | python | def bindRoute(self, receiver, routeName=_unspecified):
"""
Create a new route to associate the given route name with the given
receiver.
@type routeName: C{unicode} or L{NoneType}
@param routeName: The identifier for the newly created route. If
C{None}, boxes with no route in them will be delivered to this
receiver.
@rtype: L{Route}
"""
if routeName is _unspecified:
routeName = self.createRouteIdentifier()
# self._sender may yet be None; if so, this route goes into _unstarted
# and will have its sender set correctly in startReceivingBoxes below.
route = Route(self, receiver, routeName)
mapping = self._routes
if mapping is None:
mapping = self._unstarted
mapping[routeName] = route
return route | [
"def",
"bindRoute",
"(",
"self",
",",
"receiver",
",",
"routeName",
"=",
"_unspecified",
")",
":",
"if",
"routeName",
"is",
"_unspecified",
":",
"routeName",
"=",
"self",
".",
"createRouteIdentifier",
"(",
")",
"# self._sender may yet be None; if so, this route goes i... | Create a new route to associate the given route name with the given
receiver.
@type routeName: C{unicode} or L{NoneType}
@param routeName: The identifier for the newly created route. If
C{None}, boxes with no route in them will be delivered to this
receiver.
@rtype: L{Route} | [
"Create",
"a",
"new",
"route",
"to",
"associate",
"the",
"given",
"route",
"name",
"with",
"the",
"given",
"receiver",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/amprouter.py#L147-L168 |
twisted/epsilon | epsilon/amprouter.py | Router.startReceivingBoxes | def startReceivingBoxes(self, sender):
"""
Initialize route tracking objects.
"""
self._sender = sender
for routeName, route in self._unstarted.iteritems():
# Any route which has been bound but which does not yet have a
# remote route name should not yet be started. These will be
# started in Route.connectTo.
if route.remoteRouteName is not _unspecified:
route.start()
self._routes = self._unstarted
self._unstarted = None | python | def startReceivingBoxes(self, sender):
"""
Initialize route tracking objects.
"""
self._sender = sender
for routeName, route in self._unstarted.iteritems():
# Any route which has been bound but which does not yet have a
# remote route name should not yet be started. These will be
# started in Route.connectTo.
if route.remoteRouteName is not _unspecified:
route.start()
self._routes = self._unstarted
self._unstarted = None | [
"def",
"startReceivingBoxes",
"(",
"self",
",",
"sender",
")",
":",
"self",
".",
"_sender",
"=",
"sender",
"for",
"routeName",
",",
"route",
"in",
"self",
".",
"_unstarted",
".",
"iteritems",
"(",
")",
":",
"# Any route which has been bound but which does not yet ... | Initialize route tracking objects. | [
"Initialize",
"route",
"tracking",
"objects",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/amprouter.py#L171-L183 |
twisted/epsilon | epsilon/amprouter.py | Router.ampBoxReceived | def ampBoxReceived(self, box):
"""
Dispatch the given box to the L{IBoxReceiver} associated with the route
indicated by the box, or handle it directly if there is no route.
"""
route = box.pop(_ROUTE, None)
self._routes[route].receiver.ampBoxReceived(box) | python | def ampBoxReceived(self, box):
"""
Dispatch the given box to the L{IBoxReceiver} associated with the route
indicated by the box, or handle it directly if there is no route.
"""
route = box.pop(_ROUTE, None)
self._routes[route].receiver.ampBoxReceived(box) | [
"def",
"ampBoxReceived",
"(",
"self",
",",
"box",
")",
":",
"route",
"=",
"box",
".",
"pop",
"(",
"_ROUTE",
",",
"None",
")",
"self",
".",
"_routes",
"[",
"route",
"]",
".",
"receiver",
".",
"ampBoxReceived",
"(",
"box",
")"
] | Dispatch the given box to the L{IBoxReceiver} associated with the route
indicated by the box, or handle it directly if there is no route. | [
"Dispatch",
"the",
"given",
"box",
"to",
"the",
"L",
"{",
"IBoxReceiver",
"}",
"associated",
"with",
"the",
"route",
"indicated",
"by",
"the",
"box",
"or",
"handle",
"it",
"directly",
"if",
"there",
"is",
"no",
"route",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/amprouter.py#L186-L192 |
twisted/epsilon | epsilon/amprouter.py | Router.stopReceivingBoxes | def stopReceivingBoxes(self, reason):
"""
Stop all the L{IBoxReceiver}s which have been added to this router.
"""
for routeName, route in self._routes.iteritems():
route.stop(reason)
self._routes = None | python | def stopReceivingBoxes(self, reason):
"""
Stop all the L{IBoxReceiver}s which have been added to this router.
"""
for routeName, route in self._routes.iteritems():
route.stop(reason)
self._routes = None | [
"def",
"stopReceivingBoxes",
"(",
"self",
",",
"reason",
")",
":",
"for",
"routeName",
",",
"route",
"in",
"self",
".",
"_routes",
".",
"iteritems",
"(",
")",
":",
"route",
".",
"stop",
"(",
"reason",
")",
"self",
".",
"_routes",
"=",
"None"
] | Stop all the L{IBoxReceiver}s which have been added to this router. | [
"Stop",
"all",
"the",
"L",
"{",
"IBoxReceiver",
"}",
"s",
"which",
"have",
"been",
"added",
"to",
"this",
"router",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/amprouter.py#L195-L201 |
CivicSpleen/ambry | ambry/util/ambrys3.py | AmbryS3FS._s3bukt | def _s3bukt(self):
""" Overrides the original _s3bukt method to get the bucket without vlaidation when
the return to the original validation is not a 404.
:return:
"""
from boto.exception import S3ResponseError
import time
try:
(b, ctime) = self._tlocal.s3bukt
if time.time() - ctime > 60:
raise AttributeError
return b
except AttributeError:
try:
# Validate by listing the bucket if there is no prefix.
# If there is a prefix, validate by listing only the prefix
# itself, to avoid errors when an IAM policy has been applied.
if self._prefix:
b = self._s3conn.get_bucket(self._bucket_name, validate=0)
b.get_key(self._prefix)
else:
b = self._s3conn.get_bucket(self._bucket_name, validate=1)
except S3ResponseError as e:
if "404 Not Found" in str(e):
raise
b = self._s3conn.get_bucket(self._bucket_name, validate=0)
self._tlocal.s3bukt = (b, time.time())
return b | python | def _s3bukt(self):
""" Overrides the original _s3bukt method to get the bucket without vlaidation when
the return to the original validation is not a 404.
:return:
"""
from boto.exception import S3ResponseError
import time
try:
(b, ctime) = self._tlocal.s3bukt
if time.time() - ctime > 60:
raise AttributeError
return b
except AttributeError:
try:
# Validate by listing the bucket if there is no prefix.
# If there is a prefix, validate by listing only the prefix
# itself, to avoid errors when an IAM policy has been applied.
if self._prefix:
b = self._s3conn.get_bucket(self._bucket_name, validate=0)
b.get_key(self._prefix)
else:
b = self._s3conn.get_bucket(self._bucket_name, validate=1)
except S3ResponseError as e:
if "404 Not Found" in str(e):
raise
b = self._s3conn.get_bucket(self._bucket_name, validate=0)
self._tlocal.s3bukt = (b, time.time())
return b | [
"def",
"_s3bukt",
"(",
"self",
")",
":",
"from",
"boto",
".",
"exception",
"import",
"S3ResponseError",
"import",
"time",
"try",
":",
"(",
"b",
",",
"ctime",
")",
"=",
"self",
".",
"_tlocal",
".",
"s3bukt",
"if",
"time",
".",
"time",
"(",
")",
"-",
... | Overrides the original _s3bukt method to get the bucket without vlaidation when
the return to the original validation is not a 404.
:return: | [
"Overrides",
"the",
"original",
"_s3bukt",
"method",
"to",
"get",
"the",
"bucket",
"without",
"vlaidation",
"when",
"the",
"return",
"to",
"the",
"original",
"validation",
"is",
"not",
"a",
"404",
".",
":",
"return",
":"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/ambrys3.py#L12-L44 |
project-ncl/pnc-cli | pnc_cli/brewpush.py | push_build | def push_build(id, tag_prefix):
"""
Push build to Brew
"""
req = swagger_client.BuildRecordPushRequestRest()
req.tag_prefix = tag_prefix
req.build_record_id = id
response = utils.checked_api_call(pnc_api.build_push, 'push', body=req)
if response:
return utils.format_json_list(response) | python | def push_build(id, tag_prefix):
"""
Push build to Brew
"""
req = swagger_client.BuildRecordPushRequestRest()
req.tag_prefix = tag_prefix
req.build_record_id = id
response = utils.checked_api_call(pnc_api.build_push, 'push', body=req)
if response:
return utils.format_json_list(response) | [
"def",
"push_build",
"(",
"id",
",",
"tag_prefix",
")",
":",
"req",
"=",
"swagger_client",
".",
"BuildRecordPushRequestRest",
"(",
")",
"req",
".",
"tag_prefix",
"=",
"tag_prefix",
"req",
".",
"build_record_id",
"=",
"id",
"response",
"=",
"utils",
".",
"che... | Push build to Brew | [
"Push",
"build",
"to",
"Brew"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/brewpush.py#L16-L25 |
project-ncl/pnc-cli | pnc_cli/brewpush.py | push_build_set | def push_build_set(id, tag_prefix):
"""
Push build set to Brew
"""
req = swagger_client.BuildConfigSetRecordPushRequestRest()
req.tag_prefix = tag_prefix
req.build_config_set_record_id = id
response = utils.checked_api_call(pnc_api.build_push, 'push_record_set', body=req)
if response:
return utils.format_json_list(response) | python | def push_build_set(id, tag_prefix):
"""
Push build set to Brew
"""
req = swagger_client.BuildConfigSetRecordPushRequestRest()
req.tag_prefix = tag_prefix
req.build_config_set_record_id = id
response = utils.checked_api_call(pnc_api.build_push, 'push_record_set', body=req)
if response:
return utils.format_json_list(response) | [
"def",
"push_build_set",
"(",
"id",
",",
"tag_prefix",
")",
":",
"req",
"=",
"swagger_client",
".",
"BuildConfigSetRecordPushRequestRest",
"(",
")",
"req",
".",
"tag_prefix",
"=",
"tag_prefix",
"req",
".",
"build_config_set_record_id",
"=",
"id",
"response",
"=",
... | Push build set to Brew | [
"Push",
"build",
"set",
"to",
"Brew"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/brewpush.py#L31-L40 |
project-ncl/pnc-cli | pnc_cli/brewpush.py | push_build_status | def push_build_status(id):
"""
Get status of Brew push.
"""
response = utils.checked_api_call(pnc_api.build_push, 'status', build_record_id=id)
if response:
return utils.format_json(response) | python | def push_build_status(id):
"""
Get status of Brew push.
"""
response = utils.checked_api_call(pnc_api.build_push, 'status', build_record_id=id)
if response:
return utils.format_json(response) | [
"def",
"push_build_status",
"(",
"id",
")",
":",
"response",
"=",
"utils",
".",
"checked_api_call",
"(",
"pnc_api",
".",
"build_push",
",",
"'status'",
",",
"build_record_id",
"=",
"id",
")",
"if",
"response",
":",
"return",
"utils",
".",
"format_json",
"(",... | Get status of Brew push. | [
"Get",
"status",
"of",
"Brew",
"push",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/brewpush.py#L45-L51 |
SmartTeleMax/iktomi | iktomi/db/files.py | FileManager.create_transient | def create_transient(self, input_stream, original_name, length=None):
'''Create TransientFile and file on FS from given input stream and
original file name.'''
ext = os.path.splitext(original_name)[1]
transient = self.new_transient(ext)
if not os.path.isdir(self.transient_root):
os.makedirs(self.transient_root)
self._copy_file(input_stream, transient.path, length=length)
return transient | python | def create_transient(self, input_stream, original_name, length=None):
'''Create TransientFile and file on FS from given input stream and
original file name.'''
ext = os.path.splitext(original_name)[1]
transient = self.new_transient(ext)
if not os.path.isdir(self.transient_root):
os.makedirs(self.transient_root)
self._copy_file(input_stream, transient.path, length=length)
return transient | [
"def",
"create_transient",
"(",
"self",
",",
"input_stream",
",",
"original_name",
",",
"length",
"=",
"None",
")",
":",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"original_name",
")",
"[",
"1",
"]",
"transient",
"=",
"self",
".",
"new_transie... | Create TransientFile and file on FS from given input stream and
original file name. | [
"Create",
"TransientFile",
"and",
"file",
"on",
"FS",
"from",
"given",
"input",
"stream",
"and",
"original",
"file",
"name",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/db/files.py#L149-L158 |
SmartTeleMax/iktomi | iktomi/db/files.py | FileManager.new_transient | def new_transient(self, ext=''):
'''Creates empty TransientFile with random name and given extension.
File on FS is not created'''
name = random_name(self.transient_length) + ext
return TransientFile(self.transient_root, name, self) | python | def new_transient(self, ext=''):
'''Creates empty TransientFile with random name and given extension.
File on FS is not created'''
name = random_name(self.transient_length) + ext
return TransientFile(self.transient_root, name, self) | [
"def",
"new_transient",
"(",
"self",
",",
"ext",
"=",
"''",
")",
":",
"name",
"=",
"random_name",
"(",
"self",
".",
"transient_length",
")",
"+",
"ext",
"return",
"TransientFile",
"(",
"self",
".",
"transient_root",
",",
"name",
",",
"self",
")"
] | Creates empty TransientFile with random name and given extension.
File on FS is not created | [
"Creates",
"empty",
"TransientFile",
"with",
"random",
"name",
"and",
"given",
"extension",
".",
"File",
"on",
"FS",
"is",
"not",
"created"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/db/files.py#L160-L164 |
SmartTeleMax/iktomi | iktomi/db/files.py | FileManager.get_transient | def get_transient(self, name):
'''Restores TransientFile object with given name.
Should be used when form is submitted with file name and no file'''
# security checks: basically no folders are allowed
assert not ('/' in name or '\\' in name or name[0] in '.~')
transient = TransientFile(self.transient_root, name, self)
if not os.path.isfile(transient.path):
raise OSError(errno.ENOENT, 'Transient file has been lost',
transient.path)
return transient | python | def get_transient(self, name):
'''Restores TransientFile object with given name.
Should be used when form is submitted with file name and no file'''
# security checks: basically no folders are allowed
assert not ('/' in name or '\\' in name or name[0] in '.~')
transient = TransientFile(self.transient_root, name, self)
if not os.path.isfile(transient.path):
raise OSError(errno.ENOENT, 'Transient file has been lost',
transient.path)
return transient | [
"def",
"get_transient",
"(",
"self",
",",
"name",
")",
":",
"# security checks: basically no folders are allowed",
"assert",
"not",
"(",
"'/'",
"in",
"name",
"or",
"'\\\\'",
"in",
"name",
"or",
"name",
"[",
"0",
"]",
"in",
"'.~'",
")",
"transient",
"=",
"Tra... | Restores TransientFile object with given name.
Should be used when form is submitted with file name and no file | [
"Restores",
"TransientFile",
"object",
"with",
"given",
"name",
".",
"Should",
"be",
"used",
"when",
"form",
"is",
"submitted",
"with",
"file",
"name",
"and",
"no",
"file"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/db/files.py#L166-L175 |
SmartTeleMax/iktomi | iktomi/db/files.py | FileManager.store | def store(self, transient_file, persistent_file):
'''Makes PersistentFile from TransientFile'''
#for i in range(5):
# persistent_file = PersistentFile(self.persistent_root,
# persistent_name, self)
# if not os.path.exists(persistent_file.path):
# break
#else:
# raise Exception('Unable to find free file name')
dirname = os.path.dirname(persistent_file.path)
if not os.path.isdir(dirname):
os.makedirs(dirname)
os.rename(transient_file.path, persistent_file.path)
return persistent_file | python | def store(self, transient_file, persistent_file):
'''Makes PersistentFile from TransientFile'''
#for i in range(5):
# persistent_file = PersistentFile(self.persistent_root,
# persistent_name, self)
# if not os.path.exists(persistent_file.path):
# break
#else:
# raise Exception('Unable to find free file name')
dirname = os.path.dirname(persistent_file.path)
if not os.path.isdir(dirname):
os.makedirs(dirname)
os.rename(transient_file.path, persistent_file.path)
return persistent_file | [
"def",
"store",
"(",
"self",
",",
"transient_file",
",",
"persistent_file",
")",
":",
"#for i in range(5):",
"# persistent_file = PersistentFile(self.persistent_root,",
"# persistent_name, self)",
"# if not os.path.exists(persistent_file.path):",
... | Makes PersistentFile from TransientFile | [
"Makes",
"PersistentFile",
"from",
"TransientFile"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/db/files.py#L177-L190 |
cosven/feeluown-core | fuocore/xiami/api.py | API._sign_payload | def _sign_payload(self, payload):
"""使用 appkey 对 payload 进行签名,返回新的请求参数
"""
app_key = self._app_key
t = int(time.time() * 1000)
requestStr = {
'header': self._req_header,
'model': payload
}
data = json.dumps({'requestStr': json.dumps(requestStr)})
data_str = '{}&{}&{}&{}'.format(self._req_token, t, app_key, data)
sign = hashlib.md5(data_str.encode('utf-8')).hexdigest()
params = {
't': t,
'appKey': app_key,
'sign': sign,
'data': data,
}
return params | python | def _sign_payload(self, payload):
"""使用 appkey 对 payload 进行签名,返回新的请求参数
"""
app_key = self._app_key
t = int(time.time() * 1000)
requestStr = {
'header': self._req_header,
'model': payload
}
data = json.dumps({'requestStr': json.dumps(requestStr)})
data_str = '{}&{}&{}&{}'.format(self._req_token, t, app_key, data)
sign = hashlib.md5(data_str.encode('utf-8')).hexdigest()
params = {
't': t,
'appKey': app_key,
'sign': sign,
'data': data,
}
return params | [
"def",
"_sign_payload",
"(",
"self",
",",
"payload",
")",
":",
"app_key",
"=",
"self",
".",
"_app_key",
"t",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1000",
")",
"requestStr",
"=",
"{",
"'header'",
":",
"self",
".",
"_req_header",
",",
... | 使用 appkey 对 payload 进行签名,返回新的请求参数 | [
"使用",
"appkey",
"对",
"payload",
"进行签名,返回新的请求参数"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/xiami/api.py#L54-L72 |
cosven/feeluown-core | fuocore/xiami/api.py | API.request | def request(self, action, payload, timeout=3):
"""
虾米 API 请求流程:
1. 获取一个 token:随便访问一个网页,服务端会 set cookie。
根据观察,这个 token 一般是 7 天过期
2. 对请求签名:见 _sign_payload 方法
3. 发送请求
"""
if self._req_token is None: # 获取 token
self._fetch_token()
url = _gen_url(action)
params = self._sign_payload(payload)
response = self.http.get(url, params=params,
cookies=self._cookies.get('cookie'),
timeout=timeout)
rv = response.json()
code, msg = rv['ret'][0].split('::')
# app id 和 key 不匹配,一般应该不会出现这种情况
if code == 'FAIL_SYS_PARAMINVALID_ERROR':
raise RuntimeError('Xiami api app id and key not match.')
elif code == 'FAIL_SYS_TOKEN_EXOIRED': # 刷新 token
self._fetch_token()
elif code == 'FAIL_BIZ_GLOBAL_NEED_LOGIN':
# TODO: 单独定义一个 Exception
raise RuntimeError('Xiami api need access token.')
else:
if code != 'SUCCESS':
logger.warning('Xiami request failed:: '
'req_action: {}, req_payload: {}\n'
'response: {}'
.format(action, payload, rv))
return code, msg, rv | python | def request(self, action, payload, timeout=3):
"""
虾米 API 请求流程:
1. 获取一个 token:随便访问一个网页,服务端会 set cookie。
根据观察,这个 token 一般是 7 天过期
2. 对请求签名:见 _sign_payload 方法
3. 发送请求
"""
if self._req_token is None: # 获取 token
self._fetch_token()
url = _gen_url(action)
params = self._sign_payload(payload)
response = self.http.get(url, params=params,
cookies=self._cookies.get('cookie'),
timeout=timeout)
rv = response.json()
code, msg = rv['ret'][0].split('::')
# app id 和 key 不匹配,一般应该不会出现这种情况
if code == 'FAIL_SYS_PARAMINVALID_ERROR':
raise RuntimeError('Xiami api app id and key not match.')
elif code == 'FAIL_SYS_TOKEN_EXOIRED': # 刷新 token
self._fetch_token()
elif code == 'FAIL_BIZ_GLOBAL_NEED_LOGIN':
# TODO: 单独定义一个 Exception
raise RuntimeError('Xiami api need access token.')
else:
if code != 'SUCCESS':
logger.warning('Xiami request failed:: '
'req_action: {}, req_payload: {}\n'
'response: {}'
.format(action, payload, rv))
return code, msg, rv | [
"def",
"request",
"(",
"self",
",",
"action",
",",
"payload",
",",
"timeout",
"=",
"3",
")",
":",
"if",
"self",
".",
"_req_token",
"is",
"None",
":",
"# 获取 token",
"self",
".",
"_fetch_token",
"(",
")",
"url",
"=",
"_gen_url",
"(",
"action",
")",
"pa... | 虾米 API 请求流程:
1. 获取一个 token:随便访问一个网页,服务端会 set cookie。
根据观察,这个 token 一般是 7 天过期
2. 对请求签名:见 _sign_payload 方法
3. 发送请求 | [
"虾米",
"API",
"请求流程:"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/xiami/api.py#L82-L115 |
cosven/feeluown-core | fuocore/xiami/api.py | API.login | def login(self, email, password):
"""
:password: user password md5 digest
"""
payload = {
'account': email,
'password': password
}
code, msg, rv = self.request(
'mtop.alimusic.xuser.facade.xiamiuserservice.login',
payload
)
if code == 'SUCCESS':
# TODO: 保存 refreshToken 和过期时间等更多信息
# 根据目前观察,token 过期时间有三年
accessToken = rv['data']['data']['accessToken']
self.set_access_token(accessToken)
return rv | python | def login(self, email, password):
"""
:password: user password md5 digest
"""
payload = {
'account': email,
'password': password
}
code, msg, rv = self.request(
'mtop.alimusic.xuser.facade.xiamiuserservice.login',
payload
)
if code == 'SUCCESS':
# TODO: 保存 refreshToken 和过期时间等更多信息
# 根据目前观察,token 过期时间有三年
accessToken = rv['data']['data']['accessToken']
self.set_access_token(accessToken)
return rv | [
"def",
"login",
"(",
"self",
",",
"email",
",",
"password",
")",
":",
"payload",
"=",
"{",
"'account'",
":",
"email",
",",
"'password'",
":",
"password",
"}",
"code",
",",
"msg",
",",
"rv",
"=",
"self",
".",
"request",
"(",
"'mtop.alimusic.xuser.facade.x... | :password: user password md5 digest | [
":",
"password",
":",
"user",
"password",
"md5",
"digest"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/xiami/api.py#L118-L135 |
cosven/feeluown-core | fuocore/xiami/api.py | API.playlist_detail | def playlist_detail(self, playlist_id):
"""获取歌单详情
如果歌单歌曲数超过 100 时,该接口的 songs 字段不会包含所有歌曲,
但是它有个 allSongs 字段,会包含所有歌曲的 ID。
"""
action = 'mtop.alimusic.music.list.collectservice.getcollectdetail'
payload = {'listId': playlist_id}
code, msg, rv = self.request(action, payload)
return rv['data']['data']['collectDetail'] | python | def playlist_detail(self, playlist_id):
"""获取歌单详情
如果歌单歌曲数超过 100 时,该接口的 songs 字段不会包含所有歌曲,
但是它有个 allSongs 字段,会包含所有歌曲的 ID。
"""
action = 'mtop.alimusic.music.list.collectservice.getcollectdetail'
payload = {'listId': playlist_id}
code, msg, rv = self.request(action, payload)
return rv['data']['data']['collectDetail'] | [
"def",
"playlist_detail",
"(",
"self",
",",
"playlist_id",
")",
":",
"action",
"=",
"'mtop.alimusic.music.list.collectservice.getcollectdetail'",
"payload",
"=",
"{",
"'listId'",
":",
"playlist_id",
"}",
"code",
",",
"msg",
",",
"rv",
"=",
"self",
".",
"request",
... | 获取歌单详情
如果歌单歌曲数超过 100 时,该接口的 songs 字段不会包含所有歌曲,
但是它有个 allSongs 字段,会包含所有歌曲的 ID。 | [
"获取歌单详情"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/xiami/api.py#L216-L225 |
cosven/feeluown-core | fuocore/xiami/api.py | API.user_playlists | def user_playlists(self, user_id, page=1, limit=30):
"""
NOTE: 用户歌单有可能是仅自己可见
"""
action = 'mtop.alimusic.music.list.collectservice.getcollectbyuser'
payload = {
'userId': user_id,
'pagingVO': {
'page': page,
'pageSize': limit
}
}
code, msg, rv = self.request(action, payload)
# TODO: 支持获取更多
return rv['data']['data']['collects'] | python | def user_playlists(self, user_id, page=1, limit=30):
"""
NOTE: 用户歌单有可能是仅自己可见
"""
action = 'mtop.alimusic.music.list.collectservice.getcollectbyuser'
payload = {
'userId': user_id,
'pagingVO': {
'page': page,
'pageSize': limit
}
}
code, msg, rv = self.request(action, payload)
# TODO: 支持获取更多
return rv['data']['data']['collects'] | [
"def",
"user_playlists",
"(",
"self",
",",
"user_id",
",",
"page",
"=",
"1",
",",
"limit",
"=",
"30",
")",
":",
"action",
"=",
"'mtop.alimusic.music.list.collectservice.getcollectbyuser'",
"payload",
"=",
"{",
"'userId'",
":",
"user_id",
",",
"'pagingVO'",
":",
... | NOTE: 用户歌单有可能是仅自己可见 | [
"NOTE",
":",
"用户歌单有可能是仅自己可见"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/xiami/api.py#L234-L248 |
cosven/feeluown-core | fuocore/xiami/api.py | API.update_favorite_song | def update_favorite_song(self, song_id, op):
"""
:param str op: `add` or `del`
"""
op = 'un' if op == 'del' else ''
action = 'mtop.alimusic.fav.songfavoriteservice.{}favoritesong'.format(op)
payload = {
'songId': song_id
}
code, msg, rv = self.request(action, payload)
return rv['data']['data']['status'] == 'true' | python | def update_favorite_song(self, song_id, op):
"""
:param str op: `add` or `del`
"""
op = 'un' if op == 'del' else ''
action = 'mtop.alimusic.fav.songfavoriteservice.{}favoritesong'.format(op)
payload = {
'songId': song_id
}
code, msg, rv = self.request(action, payload)
return rv['data']['data']['status'] == 'true' | [
"def",
"update_favorite_song",
"(",
"self",
",",
"song_id",
",",
"op",
")",
":",
"op",
"=",
"'un'",
"if",
"op",
"==",
"'del'",
"else",
"''",
"action",
"=",
"'mtop.alimusic.fav.songfavoriteservice.{}favoritesong'",
".",
"format",
"(",
"op",
")",
"payload",
"=",... | :param str op: `add` or `del` | [
":",
"param",
"str",
"op",
":",
"add",
"or",
"del"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/xiami/api.py#L279-L289 |
cosven/feeluown-core | fuocore/xiami/api.py | API.update_playlist_song | def update_playlist_song(self, playlist_id, song_id, op):
"""从播放列表删除或者增加一首歌曲
如果歌曲不存在与歌单中,删除时返回 True;如果歌曲已经存在于
歌单,添加时也返回 True。
"""
action = 'mtop.alimusic.music.list.collectservice.{}songs'.format(
'delete' if op == 'del' else 'add')
payload = {
'listId': playlist_id,
'songIds': [song_id]
}
code, msg, rv = self.request(action, payload)
return rv['data']['data']['success'] == 'true' | python | def update_playlist_song(self, playlist_id, song_id, op):
"""从播放列表删除或者增加一首歌曲
如果歌曲不存在与歌单中,删除时返回 True;如果歌曲已经存在于
歌单,添加时也返回 True。
"""
action = 'mtop.alimusic.music.list.collectservice.{}songs'.format(
'delete' if op == 'del' else 'add')
payload = {
'listId': playlist_id,
'songIds': [song_id]
}
code, msg, rv = self.request(action, payload)
return rv['data']['data']['success'] == 'true' | [
"def",
"update_playlist_song",
"(",
"self",
",",
"playlist_id",
",",
"song_id",
",",
"op",
")",
":",
"action",
"=",
"'mtop.alimusic.music.list.collectservice.{}songs'",
".",
"format",
"(",
"'delete'",
"if",
"op",
"==",
"'del'",
"else",
"'add'",
")",
"payload",
"... | 从播放列表删除或者增加一首歌曲
如果歌曲不存在与歌单中,删除时返回 True;如果歌曲已经存在于
歌单,添加时也返回 True。 | [
"从播放列表删除或者增加一首歌曲"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/xiami/api.py#L291-L304 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.add_dependency | def add_dependency(self, id, **kwargs):
"""
Adds a dependency to the specified config
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.add_dependency(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param BuildConfigurationRest body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.add_dependency_with_http_info(id, **kwargs)
else:
(data) = self.add_dependency_with_http_info(id, **kwargs)
return data | python | def add_dependency(self, id, **kwargs):
"""
Adds a dependency to the specified config
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.add_dependency(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param BuildConfigurationRest body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.add_dependency_with_http_info(id, **kwargs)
else:
(data) = self.add_dependency_with_http_info(id, **kwargs)
return data | [
"def",
"add_dependency",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"add_dependency_with_http_info",
... | Adds a dependency to the specified config
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.add_dependency(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param BuildConfigurationRest body:
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Adds",
"a",
"dependency",
"to",
"the",
"specified",
"config",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L42-L67 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.add_product_version | def add_product_version(self, id, **kwargs):
"""
Associates a product version to the specified config
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.add_product_version(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param ProductVersionRest body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.add_product_version_with_http_info(id, **kwargs)
else:
(data) = self.add_product_version_with_http_info(id, **kwargs)
return data | python | def add_product_version(self, id, **kwargs):
"""
Associates a product version to the specified config
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.add_product_version(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param ProductVersionRest body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.add_product_version_with_http_info(id, **kwargs)
else:
(data) = self.add_product_version_with_http_info(id, **kwargs)
return data | [
"def",
"add_product_version",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"add_product_version_with_ht... | Associates a product version to the specified config
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.add_product_version(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param ProductVersionRest body:
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Associates",
"a",
"product",
"version",
"to",
"the",
"specified",
"config",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"fu... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L152-L177 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.clone | def clone(self, id, **kwargs):
"""
Clones an existing Build Configuration
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.clone(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:return: BuildConfigurationSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.clone_with_http_info(id, **kwargs)
else:
(data) = self.clone_with_http_info(id, **kwargs)
return data | python | def clone(self, id, **kwargs):
"""
Clones an existing Build Configuration
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.clone(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:return: BuildConfigurationSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.clone_with_http_info(id, **kwargs)
else:
(data) = self.clone_with_http_info(id, **kwargs)
return data | [
"def",
"clone",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"clone_with_http_info",
"(",
"id",
"... | Clones an existing Build Configuration
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.clone(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:return: BuildConfigurationSingleton
If the method is called asynchronously,
returns the request thread. | [
"Clones",
"an",
"existing",
"Build",
"Configuration",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",
"be",
"i... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L262-L286 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.get_all_by_product_id | def get_all_by_product_id(self, product_id, **kwargs):
"""
Gets all Build Configurations of a Product
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_all_by_product_id(product_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int product_id: Product id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_by_product_id_with_http_info(product_id, **kwargs)
else:
(data) = self.get_all_by_product_id_with_http_info(product_id, **kwargs)
return data | python | def get_all_by_product_id(self, product_id, **kwargs):
"""
Gets all Build Configurations of a Product
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_all_by_product_id(product_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int product_id: Product id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_by_product_id_with_http_info(product_id, **kwargs)
else:
(data) = self.get_all_by_product_id_with_http_info(product_id, **kwargs)
return data | [
"def",
"get_all_by_product_id",
"(",
"self",
",",
"product_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_all_by_produc... | Gets all Build Configurations of a Product
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_all_by_product_id(product_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int product_id: Product id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"all",
"Build",
"Configurations",
"of",
"a",
"Product",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L692-L720 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.get_all_by_project_id | def get_all_by_project_id(self, project_id, **kwargs):
"""
Gets all Build Configurations of a Project
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_all_by_project_id(project_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int project_id: Project id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_by_project_id_with_http_info(project_id, **kwargs)
else:
(data) = self.get_all_by_project_id_with_http_info(project_id, **kwargs)
return data | python | def get_all_by_project_id(self, project_id, **kwargs):
"""
Gets all Build Configurations of a Project
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_all_by_project_id(project_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int project_id: Project id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_by_project_id_with_http_info(project_id, **kwargs)
else:
(data) = self.get_all_by_project_id_with_http_info(project_id, **kwargs)
return data | [
"def",
"get_all_by_project_id",
"(",
"self",
",",
"project_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_all_by_projec... | Gets all Build Configurations of a Project
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_all_by_project_id(project_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int project_id: Project id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"all",
"Build",
"Configurations",
"of",
"a",
"Project",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L943-L971 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.get_builds | def get_builds(self, id, **kwargs):
"""
Get all BuildRecords (running and archived) associated with this Build Configuration, returns empty list if no build records are found
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_builds(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_builds_with_http_info(id, **kwargs)
else:
(data) = self.get_builds_with_http_info(id, **kwargs)
return data | python | def get_builds(self, id, **kwargs):
"""
Get all BuildRecords (running and archived) associated with this Build Configuration, returns empty list if no build records are found
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_builds(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_builds_with_http_info(id, **kwargs)
else:
(data) = self.get_builds_with_http_info(id, **kwargs)
return data | [
"def",
"get_builds",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_builds_with_http_info",
"(",
... | Get all BuildRecords (running and archived) associated with this Build Configuration, returns empty list if no build records are found
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_builds(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildRecordPage
If the method is called asynchronously,
returns the request thread. | [
"Get",
"all",
"BuildRecords",
"(",
"running",
"and",
"archived",
")",
"associated",
"with",
"this",
"Build",
"Configuration",
"returns",
"empty",
"list",
"if",
"no",
"build",
"records",
"are",
"found",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"re... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L1309-L1337 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.get_dependencies | def get_dependencies(self, id, **kwargs):
"""
Get the direct dependencies of the specified configuration
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_dependencies(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_dependencies_with_http_info(id, **kwargs)
else:
(data) = self.get_dependencies_with_http_info(id, **kwargs)
return data | python | def get_dependencies(self, id, **kwargs):
"""
Get the direct dependencies of the specified configuration
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_dependencies(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_dependencies_with_http_info(id, **kwargs)
else:
(data) = self.get_dependencies_with_http_info(id, **kwargs)
return data | [
"def",
"get_dependencies",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_dependencies_with_http_inf... | Get the direct dependencies of the specified configuration
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_dependencies(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationPage
If the method is called asynchronously,
returns the request thread. | [
"Get",
"the",
"direct",
"dependencies",
"of",
"the",
"specified",
"configuration",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L1431-L1459 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.get_product_versions | def get_product_versions(self, id, **kwargs):
"""
Get associated Product Versions of the specified Configuration
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_product_versions(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: ProductVersionPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_product_versions_with_http_info(id, **kwargs)
else:
(data) = self.get_product_versions_with_http_info(id, **kwargs)
return data | python | def get_product_versions(self, id, **kwargs):
"""
Get associated Product Versions of the specified Configuration
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_product_versions(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: ProductVersionPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_product_versions_with_http_info(id, **kwargs)
else:
(data) = self.get_product_versions_with_http_info(id, **kwargs)
return data | [
"def",
"get_product_versions",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_product_versions_with_... | Get associated Product Versions of the specified Configuration
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_product_versions(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: ProductVersionPage
If the method is called asynchronously,
returns the request thread. | [
"Get",
"associated",
"Product",
"Versions",
"of",
"the",
"specified",
"Configuration",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callba... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L1663-L1691 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.get_revision | def get_revision(self, id, rev, **kwargs):
"""
Get specific audited revision of this build configuration
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_revision(id, rev, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int rev: Build configuration rev (required)
:return: BuildConfigurationAuditedSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_revision_with_http_info(id, rev, **kwargs)
else:
(data) = self.get_revision_with_http_info(id, rev, **kwargs)
return data | python | def get_revision(self, id, rev, **kwargs):
"""
Get specific audited revision of this build configuration
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_revision(id, rev, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int rev: Build configuration rev (required)
:return: BuildConfigurationAuditedSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_revision_with_http_info(id, rev, **kwargs)
else:
(data) = self.get_revision_with_http_info(id, rev, **kwargs)
return data | [
"def",
"get_revision",
"(",
"self",
",",
"id",
",",
"rev",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_revision_with_... | Get specific audited revision of this build configuration
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_revision(id, rev, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int rev: Build configuration rev (required)
:return: BuildConfigurationAuditedSingleton
If the method is called asynchronously,
returns the request thread. | [
"Get",
"specific",
"audited",
"revision",
"of",
"this",
"build",
"configuration",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L1785-L1810 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.get_revisions | def get_revisions(self, id, **kwargs):
"""
Gets audited revisions of this build configuration
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_revisions(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:return: BuildConfigurationAuditedPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_revisions_with_http_info(id, **kwargs)
else:
(data) = self.get_revisions_with_http_info(id, **kwargs)
return data | python | def get_revisions(self, id, **kwargs):
"""
Gets audited revisions of this build configuration
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_revisions(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:return: BuildConfigurationAuditedPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_revisions_with_http_info(id, **kwargs)
else:
(data) = self.get_revisions_with_http_info(id, **kwargs)
return data | [
"def",
"get_revisions",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_revisions_with_http_info",
... | Gets audited revisions of this build configuration
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_revisions(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:return: BuildConfigurationAuditedPage
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"audited",
"revisions",
"of",
"this",
"build",
"configuration",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L1898-L1925 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.get_supported_generic_parameters | def get_supported_generic_parameters(self, **kwargs):
"""
Gets the minimal set of supported genericParameters and their description for the BuildConfiguration. There can be also other supported parameters not know by core.
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_supported_generic_parameters(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_supported_generic_parameters_with_http_info(**kwargs)
else:
(data) = self.get_supported_generic_parameters_with_http_info(**kwargs)
return data | python | def get_supported_generic_parameters(self, **kwargs):
"""
Gets the minimal set of supported genericParameters and their description for the BuildConfiguration. There can be also other supported parameters not know by core.
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_supported_generic_parameters(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_supported_generic_parameters_with_http_info(**kwargs)
else:
(data) = self.get_supported_generic_parameters_with_http_info(**kwargs)
return data | [
"def",
"get_supported_generic_parameters",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_supported_generic_paramet... | Gets the minimal set of supported genericParameters and their description for the BuildConfiguration. There can be also other supported parameters not know by core.
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_supported_generic_parameters(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"the",
"minimal",
"set",
"of",
"supported",
"genericParameters",
"and",
"their",
"description",
"for",
"the",
"BuildConfiguration",
".",
"There",
"can",
"be",
"also",
"other",
"supported",
"parameters",
"not",
"know",
"by",
"core",
".",
"This",
"method",... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L2122-L2145 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.remove_dependency | def remove_dependency(self, id, dependency_id, **kwargs):
"""
Removes a configuration from the specified config set
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.remove_dependency(id, dependency_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int dependency_id: Build configuration id (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.remove_dependency_with_http_info(id, dependency_id, **kwargs)
else:
(data) = self.remove_dependency_with_http_info(id, dependency_id, **kwargs)
return data | python | def remove_dependency(self, id, dependency_id, **kwargs):
"""
Removes a configuration from the specified config set
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.remove_dependency(id, dependency_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int dependency_id: Build configuration id (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.remove_dependency_with_http_info(id, dependency_id, **kwargs)
else:
(data) = self.remove_dependency_with_http_info(id, dependency_id, **kwargs)
return data | [
"def",
"remove_dependency",
"(",
"self",
",",
"id",
",",
"dependency_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"rem... | Removes a configuration from the specified config set
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.remove_dependency(id, dependency_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int dependency_id: Build configuration id (required)
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Removes",
"a",
"configuration",
"from",
"the",
"specified",
"config",
"set",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"f... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L2220-L2245 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.remove_product_version | def remove_product_version(self, id, product_version_id, **kwargs):
"""
Removes a product version from the specified config set
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.remove_product_version(id, product_version_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int product_version_id: Product version id (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.remove_product_version_with_http_info(id, product_version_id, **kwargs)
else:
(data) = self.remove_product_version_with_http_info(id, product_version_id, **kwargs)
return data | python | def remove_product_version(self, id, product_version_id, **kwargs):
"""
Removes a product version from the specified config set
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.remove_product_version(id, product_version_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int product_version_id: Product version id (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.remove_product_version_with_http_info(id, product_version_id, **kwargs)
else:
(data) = self.remove_product_version_with_http_info(id, product_version_id, **kwargs)
return data | [
"def",
"remove_product_version",
"(",
"self",
",",
"id",
",",
"product_version_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
"... | Removes a product version from the specified config set
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.remove_product_version(id, product_version_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build configuration set id (required)
:param int product_version_id: Product version id (required)
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Removes",
"a",
"product",
"version",
"from",
"the",
"specified",
"config",
"set",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L2333-L2358 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.trigger | def trigger(self, id, **kwargs):
"""
Triggers a build of a specific Build Configuration
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.trigger(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool build_dependencies: Should we build also dependencies of this BuildConfiguration?
:param bool keep_pod_on_failure: Should we keep the build container running, if the build fails?
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild the configuration; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildRecordSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.trigger_with_http_info(id, **kwargs)
else:
(data) = self.trigger_with_http_info(id, **kwargs)
return data | python | def trigger(self, id, **kwargs):
"""
Triggers a build of a specific Build Configuration
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.trigger(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool build_dependencies: Should we build also dependencies of this BuildConfiguration?
:param bool keep_pod_on_failure: Should we keep the build container running, if the build fails?
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild the configuration; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildRecordSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.trigger_with_http_info(id, **kwargs)
else:
(data) = self.trigger_with_http_info(id, **kwargs)
return data | [
"def",
"trigger",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"trigger_with_http_info",
"(",
"id",... | Triggers a build of a specific Build Configuration
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.trigger(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool build_dependencies: Should we build also dependencies of this BuildConfiguration?
:param bool keep_pod_on_failure: Should we keep the build container running, if the build fails?
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild the configuration; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildRecordSingleton
If the method is called asynchronously,
returns the request thread. | [
"Triggers",
"a",
"build",
"of",
"a",
"specific",
"Build",
"Configuration",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"func... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L2446-L2477 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.trigger_audited | def trigger_audited(self, id, rev, **kwargs):
"""
Triggers a build of a specific Build Configuration in a specific revision
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.trigger_audited(id, rev, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param int rev: Revision of a Build Configuration (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool build_dependencies: Should we build also dependencies of this BuildConfiguration?
:param bool keep_pod_on_failure: Should we keep the build container running, if the build fails?
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild the configuration; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildRecordSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.trigger_audited_with_http_info(id, rev, **kwargs)
else:
(data) = self.trigger_audited_with_http_info(id, rev, **kwargs)
return data | python | def trigger_audited(self, id, rev, **kwargs):
"""
Triggers a build of a specific Build Configuration in a specific revision
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.trigger_audited(id, rev, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param int rev: Revision of a Build Configuration (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool build_dependencies: Should we build also dependencies of this BuildConfiguration?
:param bool keep_pod_on_failure: Should we keep the build container running, if the build fails?
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild the configuration; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildRecordSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.trigger_audited_with_http_info(id, rev, **kwargs)
else:
(data) = self.trigger_audited_with_http_info(id, rev, **kwargs)
return data | [
"def",
"trigger_audited",
"(",
"self",
",",
"id",
",",
"rev",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"trigger_audited... | Triggers a build of a specific Build Configuration in a specific revision
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.trigger_audited(id, rev, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param int rev: Revision of a Build Configuration (required)
:param str callback_url: Optional Callback URL
:param bool temporary_build: Is it a temporary build or a standard build?
:param bool force_rebuild: DEPRECATED: Use RebuildMode.
:param bool build_dependencies: Should we build also dependencies of this BuildConfiguration?
:param bool keep_pod_on_failure: Should we keep the build container running, if the build fails?
:param bool timestamp_alignment: Should we add a timestamp during the alignment? Valid only for temporary builds.
:param str rebuild_mode: Rebuild Modes: FORCE: always rebuild the configuration; EXPLICIT_DEPENDENCY_CHECK: check if any of user defined dependencies has been update; IMPLICIT_DEPENDENCY_CHECK: check if any captured dependency has been updated;
:return: BuildRecordSingleton
If the method is called asynchronously,
returns the request thread. | [
"Triggers",
"a",
"build",
"of",
"a",
"specific",
"Build",
"Configuration",
"in",
"a",
"specific",
"revision",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L2580-L2612 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildconfigurations_api.py | BuildconfigurationsApi.update_and_get_audited | def update_and_get_audited(self, id, **kwargs):
"""
Updates an existing Build Configuration and returns BuildConfigurationAudited entity
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.update_and_get_audited(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param BuildConfigurationRest body:
:return: BuildConfigurationAuditedSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_and_get_audited_with_http_info(id, **kwargs)
else:
(data) = self.update_and_get_audited_with_http_info(id, **kwargs)
return data | python | def update_and_get_audited(self, id, **kwargs):
"""
Updates an existing Build Configuration and returns BuildConfigurationAudited entity
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.update_and_get_audited(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param BuildConfigurationRest body:
:return: BuildConfigurationAuditedSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_and_get_audited_with_http_info(id, **kwargs)
else:
(data) = self.update_and_get_audited_with_http_info(id, **kwargs)
return data | [
"def",
"update_and_get_audited",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"update_and_get_audited_w... | Updates an existing Build Configuration and returns BuildConfigurationAudited entity
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.update_and_get_audited(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Build Configuration id (required)
:param BuildConfigurationRest body:
:return: BuildConfigurationAuditedSingleton
If the method is called asynchronously,
returns the request thread. | [
"Updates",
"an",
"existing",
"Build",
"Configuration",
"and",
"returns",
"BuildConfigurationAudited",
"entity",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurations_api.py#L2831-L2856 |
CivicSpleen/ambry | ambry/util/debug.py | debug_break | def debug_break(sig, frame):
"""Interrupt running process, and provide a python prompt for interactive
debugging."""
d = {'_frame': frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
i = code.InteractiveConsole(d)
message = "Signal recieved : entering python shell.\nTraceback:\n"
message += ''.join(traceback.format_stack(frame))
i.interact(message) | python | def debug_break(sig, frame):
"""Interrupt running process, and provide a python prompt for interactive
debugging."""
d = {'_frame': frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
i = code.InteractiveConsole(d)
message = "Signal recieved : entering python shell.\nTraceback:\n"
message += ''.join(traceback.format_stack(frame))
i.interact(message) | [
"def",
"debug_break",
"(",
"sig",
",",
"frame",
")",
":",
"d",
"=",
"{",
"'_frame'",
":",
"frame",
"}",
"# Allow access to frame object.",
"d",
".",
"update",
"(",
"frame",
".",
"f_globals",
")",
"# Unless shadowed by global",
"d",
".",
"update",
"(",
"frame... | Interrupt running process, and provide a python prompt for interactive
debugging. | [
"Interrupt",
"running",
"process",
"and",
"provide",
"a",
"python",
"prompt",
"for",
"interactive",
"debugging",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/debug.py#L19-L29 |
CivicSpleen/ambry | ambry/util/debug.py | trace | def trace(fn): # pragma: no cover
""" Prints parameteters and return values of the each call of the wrapped function.
Usage:
decorate appropriate function or method:
@trace
def myf():
...
"""
def wrapped(*args, **kwargs):
msg = []
msg.append('Enter {}('.format(fn.__name__))
if args:
msg.append(', '.join([str(x) for x in args]))
if kwargs:
kwargs_str = ', '.join(['{}={}'.format(k, v) for k, v in list(kwargs.items())])
if args:
msg.append(', ')
msg.append(kwargs_str)
msg.append(')')
print(''.join(msg))
ret = fn(*args, **kwargs)
print('Return {}'.format(ret))
return ret
return wrapped | python | def trace(fn): # pragma: no cover
""" Prints parameteters and return values of the each call of the wrapped function.
Usage:
decorate appropriate function or method:
@trace
def myf():
...
"""
def wrapped(*args, **kwargs):
msg = []
msg.append('Enter {}('.format(fn.__name__))
if args:
msg.append(', '.join([str(x) for x in args]))
if kwargs:
kwargs_str = ', '.join(['{}={}'.format(k, v) for k, v in list(kwargs.items())])
if args:
msg.append(', ')
msg.append(kwargs_str)
msg.append(')')
print(''.join(msg))
ret = fn(*args, **kwargs)
print('Return {}'.format(ret))
return ret
return wrapped | [
"def",
"trace",
"(",
"fn",
")",
":",
"# pragma: no cover",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"[",
"]",
"msg",
".",
"append",
"(",
"'Enter {}('",
".",
"format",
"(",
"fn",
".",
"__name__",
")",
")",
... | Prints parameteters and return values of the each call of the wrapped function.
Usage:
decorate appropriate function or method:
@trace
def myf():
... | [
"Prints",
"parameteters",
"and",
"return",
"values",
"of",
"the",
"each",
"call",
"of",
"the",
"wrapped",
"function",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/debug.py#L37-L63 |
CivicSpleen/ambry | ambry/util/debug.py | patch_file_open | def patch_file_open(): # pragma: no cover
"""A Monkey patch to log opening and closing of files, which is useful for
debugging file descriptor exhaustion."""
openfiles = set()
oldfile = builtins.file
class newfile(oldfile):
def __init__(self, *args, **kwargs):
self.x = args[0]
all_fds = count_open_fds()
print('### {} OPENING {} ( {} total )###'.format(
len(openfiles), str(self.x), all_fds))
oldfile.__init__(self, *args, **kwargs)
openfiles.add(self)
def close(self):
print('### {} CLOSING {} ###'.format(len(openfiles), str(self.x)))
oldfile.close(self)
openfiles.remove(self)
def newopen(*args, **kwargs):
return newfile(*args, **kwargs)
builtins.file = newfile
builtins.open = newopen | python | def patch_file_open(): # pragma: no cover
"""A Monkey patch to log opening and closing of files, which is useful for
debugging file descriptor exhaustion."""
openfiles = set()
oldfile = builtins.file
class newfile(oldfile):
def __init__(self, *args, **kwargs):
self.x = args[0]
all_fds = count_open_fds()
print('### {} OPENING {} ( {} total )###'.format(
len(openfiles), str(self.x), all_fds))
oldfile.__init__(self, *args, **kwargs)
openfiles.add(self)
def close(self):
print('### {} CLOSING {} ###'.format(len(openfiles), str(self.x)))
oldfile.close(self)
openfiles.remove(self)
def newopen(*args, **kwargs):
return newfile(*args, **kwargs)
builtins.file = newfile
builtins.open = newopen | [
"def",
"patch_file_open",
"(",
")",
":",
"# pragma: no cover",
"openfiles",
"=",
"set",
"(",
")",
"oldfile",
"=",
"builtins",
".",
"file",
"class",
"newfile",
"(",
"oldfile",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"k... | A Monkey patch to log opening and closing of files, which is useful for
debugging file descriptor exhaustion. | [
"A",
"Monkey",
"patch",
"to",
"log",
"opening",
"and",
"closing",
"of",
"files",
"which",
"is",
"useful",
"for",
"debugging",
"file",
"descriptor",
"exhaustion",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/debug.py#L66-L94 |
CivicSpleen/ambry | ambry/util/debug.py | traceit | def traceit(frame, event, arg):
"""
Trace every lie of a program. Use:
import sys
sys.settrace(traceit)
:param frame:
:param event:
:param arg:
:return:
"""
import linecache
try:
if event == "line":
lineno = frame.f_lineno
filename = frame.f_globals.get("__file__")
if (filename.endswith(".pyc") or filename.endswith(".pyo")):
filename = filename[:-1]
name = frame.f_globals["__name__"]
line = linecache.getline(filename, lineno)
if name.startswith('ambry'):
print "%s:%s: %s" % (name, lineno, line.rstrip())
finally:
return traceit | python | def traceit(frame, event, arg):
"""
Trace every lie of a program. Use:
import sys
sys.settrace(traceit)
:param frame:
:param event:
:param arg:
:return:
"""
import linecache
try:
if event == "line":
lineno = frame.f_lineno
filename = frame.f_globals.get("__file__")
if (filename.endswith(".pyc") or filename.endswith(".pyo")):
filename = filename[:-1]
name = frame.f_globals["__name__"]
line = linecache.getline(filename, lineno)
if name.startswith('ambry'):
print "%s:%s: %s" % (name, lineno, line.rstrip())
finally:
return traceit | [
"def",
"traceit",
"(",
"frame",
",",
"event",
",",
"arg",
")",
":",
"import",
"linecache",
"try",
":",
"if",
"event",
"==",
"\"line\"",
":",
"lineno",
"=",
"frame",
".",
"f_lineno",
"filename",
"=",
"frame",
".",
"f_globals",
".",
"get",
"(",
"\"__file... | Trace every lie of a program. Use:
import sys
sys.settrace(traceit)
:param frame:
:param event:
:param arg:
:return: | [
"Trace",
"every",
"lie",
"of",
"a",
"program",
".",
"Use",
":",
"import",
"sys",
"sys",
".",
"settrace",
"(",
"traceit",
")"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/debug.py#L97-L124 |
twisted/epsilon | epsilon/ampauth.py | login | def login(client, credentials):
"""
Authenticate using the given L{AMP} instance. The protocol must be
connected to a server with responders for L{PasswordLogin} and
L{PasswordChallengeResponse}.
@param client: A connected L{AMP} instance which will be used to issue
authentication commands.
@param credentials: An object providing L{IUsernamePassword} which will
be used to authenticate this connection to the server.
@return: A L{Deferred} which fires when authentication has succeeded or
which fails with L{UnauthorizedLogin} if the server rejects the
authentication attempt.
"""
if not IUsernamePassword.providedBy(credentials):
raise UnhandledCredentials()
d = client.callRemote(
PasswordLogin, username=credentials.username)
def cbChallenge(response):
args = PasswordChallengeResponse.determineFrom(
response['challenge'], credentials.password)
d = client.callRemote(PasswordChallengeResponse, **args)
return d.addCallback(lambda ignored: client)
d.addCallback(cbChallenge)
return d | python | def login(client, credentials):
"""
Authenticate using the given L{AMP} instance. The protocol must be
connected to a server with responders for L{PasswordLogin} and
L{PasswordChallengeResponse}.
@param client: A connected L{AMP} instance which will be used to issue
authentication commands.
@param credentials: An object providing L{IUsernamePassword} which will
be used to authenticate this connection to the server.
@return: A L{Deferred} which fires when authentication has succeeded or
which fails with L{UnauthorizedLogin} if the server rejects the
authentication attempt.
"""
if not IUsernamePassword.providedBy(credentials):
raise UnhandledCredentials()
d = client.callRemote(
PasswordLogin, username=credentials.username)
def cbChallenge(response):
args = PasswordChallengeResponse.determineFrom(
response['challenge'], credentials.password)
d = client.callRemote(PasswordChallengeResponse, **args)
return d.addCallback(lambda ignored: client)
d.addCallback(cbChallenge)
return d | [
"def",
"login",
"(",
"client",
",",
"credentials",
")",
":",
"if",
"not",
"IUsernamePassword",
".",
"providedBy",
"(",
"credentials",
")",
":",
"raise",
"UnhandledCredentials",
"(",
")",
"d",
"=",
"client",
".",
"callRemote",
"(",
"PasswordLogin",
",",
"user... | Authenticate using the given L{AMP} instance. The protocol must be
connected to a server with responders for L{PasswordLogin} and
L{PasswordChallengeResponse}.
@param client: A connected L{AMP} instance which will be used to issue
authentication commands.
@param credentials: An object providing L{IUsernamePassword} which will
be used to authenticate this connection to the server.
@return: A L{Deferred} which fires when authentication has succeeded or
which fails with L{UnauthorizedLogin} if the server rejects the
authentication attempt. | [
"Authenticate",
"using",
"the",
"given",
"L",
"{",
"AMP",
"}",
"instance",
".",
"The",
"protocol",
"must",
"be",
"connected",
"to",
"a",
"server",
"with",
"responders",
"for",
"L",
"{",
"PasswordLogin",
"}",
"and",
"L",
"{",
"PasswordChallengeResponse",
"}",... | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/ampauth.py#L275-L301 |
twisted/epsilon | epsilon/ampauth.py | PasswordChallengeResponse.determineFrom | def determineFrom(cls, challenge, password):
"""
Create a nonce and use it, along with the given challenge and password,
to generate the parameters for a response.
@return: A C{dict} suitable to be used as the keyword arguments when
calling this command.
"""
nonce = secureRandom(16)
response = _calcResponse(challenge, nonce, password)
return dict(cnonce=nonce, response=response) | python | def determineFrom(cls, challenge, password):
"""
Create a nonce and use it, along with the given challenge and password,
to generate the parameters for a response.
@return: A C{dict} suitable to be used as the keyword arguments when
calling this command.
"""
nonce = secureRandom(16)
response = _calcResponse(challenge, nonce, password)
return dict(cnonce=nonce, response=response) | [
"def",
"determineFrom",
"(",
"cls",
",",
"challenge",
",",
"password",
")",
":",
"nonce",
"=",
"secureRandom",
"(",
"16",
")",
"response",
"=",
"_calcResponse",
"(",
"challenge",
",",
"nonce",
",",
"password",
")",
"return",
"dict",
"(",
"cnonce",
"=",
"... | Create a nonce and use it, along with the given challenge and password,
to generate the parameters for a response.
@return: A C{dict} suitable to be used as the keyword arguments when
calling this command. | [
"Create",
"a",
"nonce",
"and",
"use",
"it",
"along",
"with",
"the",
"given",
"challenge",
"and",
"password",
"to",
"generate",
"the",
"parameters",
"for",
"a",
"response",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/ampauth.py#L102-L112 |
twisted/epsilon | epsilon/ampauth.py | _AMPUsernamePassword.checkPassword | def checkPassword(self, password):
"""
Check the given plaintext password against the response in this
credentials object.
@type password: C{str}
@param password: The known correct password associated with
C{self.username}.
@return: A C{bool}, C{True} if this credentials object agrees with the
given password, C{False} otherwise.
"""
if isinstance(password, unicode):
password = password.encode('utf-8')
correctResponse = _calcResponse(self.challenge, self.nonce, password)
return correctResponse == self.response | python | def checkPassword(self, password):
"""
Check the given plaintext password against the response in this
credentials object.
@type password: C{str}
@param password: The known correct password associated with
C{self.username}.
@return: A C{bool}, C{True} if this credentials object agrees with the
given password, C{False} otherwise.
"""
if isinstance(password, unicode):
password = password.encode('utf-8')
correctResponse = _calcResponse(self.challenge, self.nonce, password)
return correctResponse == self.response | [
"def",
"checkPassword",
"(",
"self",
",",
"password",
")",
":",
"if",
"isinstance",
"(",
"password",
",",
"unicode",
")",
":",
"password",
"=",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
"correctResponse",
"=",
"_calcResponse",
"(",
"self",
".",
"chal... | Check the given plaintext password against the response in this
credentials object.
@type password: C{str}
@param password: The known correct password associated with
C{self.username}.
@return: A C{bool}, C{True} if this credentials object agrees with the
given password, C{False} otherwise. | [
"Check",
"the",
"given",
"plaintext",
"password",
"against",
"the",
"response",
"in",
"this",
"credentials",
"object",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/ampauth.py#L123-L138 |
twisted/epsilon | epsilon/ampauth.py | CredReceiver.passwordLogin | def passwordLogin(self, username):
"""
Generate a new challenge for the given username.
"""
self.challenge = secureRandom(16)
self.username = username
return {'challenge': self.challenge} | python | def passwordLogin(self, username):
"""
Generate a new challenge for the given username.
"""
self.challenge = secureRandom(16)
self.username = username
return {'challenge': self.challenge} | [
"def",
"passwordLogin",
"(",
"self",
",",
"username",
")",
":",
"self",
".",
"challenge",
"=",
"secureRandom",
"(",
"16",
")",
"self",
".",
"username",
"=",
"username",
"return",
"{",
"'challenge'",
":",
"self",
".",
"challenge",
"}"
] | Generate a new challenge for the given username. | [
"Generate",
"a",
"new",
"challenge",
"for",
"the",
"given",
"username",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/ampauth.py#L182-L188 |
twisted/epsilon | epsilon/ampauth.py | CredReceiver._login | def _login(self, credentials):
"""
Actually login to our portal with the given credentials.
"""
d = self.portal.login(credentials, None, IBoxReceiver)
def cbLoggedIn((interface, avatar, logout)):
self.logout = logout
self.boxReceiver = avatar
self.boxReceiver.startReceivingBoxes(self.boxSender)
return {}
d.addCallback(cbLoggedIn)
return d | python | def _login(self, credentials):
"""
Actually login to our portal with the given credentials.
"""
d = self.portal.login(credentials, None, IBoxReceiver)
def cbLoggedIn((interface, avatar, logout)):
self.logout = logout
self.boxReceiver = avatar
self.boxReceiver.startReceivingBoxes(self.boxSender)
return {}
d.addCallback(cbLoggedIn)
return d | [
"def",
"_login",
"(",
"self",
",",
"credentials",
")",
":",
"d",
"=",
"self",
".",
"portal",
".",
"login",
"(",
"credentials",
",",
"None",
",",
"IBoxReceiver",
")",
"def",
"cbLoggedIn",
"(",
"(",
"interface",
",",
"avatar",
",",
"logout",
")",
")",
... | Actually login to our portal with the given credentials. | [
"Actually",
"login",
"to",
"our",
"portal",
"with",
"the",
"given",
"credentials",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/ampauth.py#L191-L202 |
twisted/epsilon | epsilon/ampauth.py | CredReceiver.passwordChallengeResponse | def passwordChallengeResponse(self, cnonce, response):
"""
Verify the response to a challenge.
"""
return self._login(_AMPUsernamePassword(
self.username, self.challenge, cnonce, response)) | python | def passwordChallengeResponse(self, cnonce, response):
"""
Verify the response to a challenge.
"""
return self._login(_AMPUsernamePassword(
self.username, self.challenge, cnonce, response)) | [
"def",
"passwordChallengeResponse",
"(",
"self",
",",
"cnonce",
",",
"response",
")",
":",
"return",
"self",
".",
"_login",
"(",
"_AMPUsernamePassword",
"(",
"self",
".",
"username",
",",
"self",
".",
"challenge",
",",
"cnonce",
",",
"response",
")",
")"
] | Verify the response to a challenge. | [
"Verify",
"the",
"response",
"to",
"a",
"challenge",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/ampauth.py#L206-L211 |
twisted/epsilon | epsilon/ampauth.py | CredReceiver.connectionLost | def connectionLost(self, reason):
"""
If a login has happened, perform a logout.
"""
AMP.connectionLost(self, reason)
if self.logout is not None:
self.logout()
self.boxReceiver = self.logout = None | python | def connectionLost(self, reason):
"""
If a login has happened, perform a logout.
"""
AMP.connectionLost(self, reason)
if self.logout is not None:
self.logout()
self.boxReceiver = self.logout = None | [
"def",
"connectionLost",
"(",
"self",
",",
"reason",
")",
":",
"AMP",
".",
"connectionLost",
"(",
"self",
",",
"reason",
")",
"if",
"self",
".",
"logout",
"is",
"not",
"None",
":",
"self",
".",
"logout",
"(",
")",
"self",
".",
"boxReceiver",
"=",
"se... | If a login has happened, perform a logout. | [
"If",
"a",
"login",
"has",
"happened",
"perform",
"a",
"logout",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/ampauth.py#L222-L229 |
cosven/feeluown-core | fuocore/live_lyric.py | LiveLyric.on_position_changed | def on_position_changed(self, position):
"""bind position changed signal with this"""
if not self._lyric:
return
pos = find_previous(position*1000 + 300, self._pos_list)
if pos is not None and pos != self._pos:
self.current_sentence = self._pos_s_map[pos]
self._pos = pos | python | def on_position_changed(self, position):
"""bind position changed signal with this"""
if not self._lyric:
return
pos = find_previous(position*1000 + 300, self._pos_list)
if pos is not None and pos != self._pos:
self.current_sentence = self._pos_s_map[pos]
self._pos = pos | [
"def",
"on_position_changed",
"(",
"self",
",",
"position",
")",
":",
"if",
"not",
"self",
".",
"_lyric",
":",
"return",
"pos",
"=",
"find_previous",
"(",
"position",
"*",
"1000",
"+",
"300",
",",
"self",
".",
"_pos_list",
")",
"if",
"pos",
"is",
"not"... | bind position changed signal with this | [
"bind",
"position",
"changed",
"signal",
"with",
"this"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/live_lyric.py#L44-L52 |
cosven/feeluown-core | fuocore/live_lyric.py | LiveLyric.on_song_changed | def on_song_changed(self, song):
"""bind song changed signal with this"""
if song is None or song.lyric is None:
self._lyric = None
self._pos_s_map = {}
else:
self._lyric = song.lyric.content
self._pos_s_map = parse(self._lyric)
self._pos_list = sorted(list(self._pos_s_map.keys()))
self._pos = None
self.current_sentence = '' | python | def on_song_changed(self, song):
"""bind song changed signal with this"""
if song is None or song.lyric is None:
self._lyric = None
self._pos_s_map = {}
else:
self._lyric = song.lyric.content
self._pos_s_map = parse(self._lyric)
self._pos_list = sorted(list(self._pos_s_map.keys()))
self._pos = None
self.current_sentence = '' | [
"def",
"on_song_changed",
"(",
"self",
",",
"song",
")",
":",
"if",
"song",
"is",
"None",
"or",
"song",
".",
"lyric",
"is",
"None",
":",
"self",
".",
"_lyric",
"=",
"None",
"self",
".",
"_pos_s_map",
"=",
"{",
"}",
"else",
":",
"self",
".",
"_lyric... | bind song changed signal with this | [
"bind",
"song",
"changed",
"signal",
"with",
"this"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/live_lyric.py#L54-L64 |
twisted/epsilon | epsilon/extime.py | sanitizeStructTime | def sanitizeStructTime(struct):
"""
Convert struct_time tuples with possibly invalid values to valid
ones by substituting the closest valid value.
"""
maxValues = (9999, 12, 31, 23, 59, 59)
minValues = (1, 1, 1, 0, 0, 0)
newstruct = []
for value, maxValue, minValue in zip(struct[:6], maxValues, minValues):
newstruct.append(max(minValue, min(value, maxValue)))
return tuple(newstruct) + struct[6:] | python | def sanitizeStructTime(struct):
"""
Convert struct_time tuples with possibly invalid values to valid
ones by substituting the closest valid value.
"""
maxValues = (9999, 12, 31, 23, 59, 59)
minValues = (1, 1, 1, 0, 0, 0)
newstruct = []
for value, maxValue, minValue in zip(struct[:6], maxValues, minValues):
newstruct.append(max(minValue, min(value, maxValue)))
return tuple(newstruct) + struct[6:] | [
"def",
"sanitizeStructTime",
"(",
"struct",
")",
":",
"maxValues",
"=",
"(",
"9999",
",",
"12",
",",
"31",
",",
"23",
",",
"59",
",",
"59",
")",
"minValues",
"=",
"(",
"1",
",",
"1",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
")",
"newstruct",
"... | Convert struct_time tuples with possibly invalid values to valid
ones by substituting the closest valid value. | [
"Convert",
"struct_time",
"tuples",
"with",
"possibly",
"invalid",
"values",
"to",
"valid",
"ones",
"by",
"substituting",
"the",
"closest",
"valid",
"value",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L23-L33 |
twisted/epsilon | epsilon/extime.py | _timedeltaToSignHrMin | def _timedeltaToSignHrMin(offset):
"""
Return a (sign, hour, minute) triple for the offset described by timedelta.
sign is a string, either "+" or "-". In the case of 0 offset, sign is "+".
"""
minutes = round((offset.days * 3600000000 * 24
+ offset.seconds * 1000000
+ offset.microseconds)
/ 60000000.0)
if minutes < 0:
sign = '-'
minutes = -minutes
else:
sign = '+'
return (sign, minutes // 60, minutes % 60) | python | def _timedeltaToSignHrMin(offset):
"""
Return a (sign, hour, minute) triple for the offset described by timedelta.
sign is a string, either "+" or "-". In the case of 0 offset, sign is "+".
"""
minutes = round((offset.days * 3600000000 * 24
+ offset.seconds * 1000000
+ offset.microseconds)
/ 60000000.0)
if minutes < 0:
sign = '-'
minutes = -minutes
else:
sign = '+'
return (sign, minutes // 60, minutes % 60) | [
"def",
"_timedeltaToSignHrMin",
"(",
"offset",
")",
":",
"minutes",
"=",
"round",
"(",
"(",
"offset",
".",
"days",
"*",
"3600000000",
"*",
"24",
"+",
"offset",
".",
"seconds",
"*",
"1000000",
"+",
"offset",
".",
"microseconds",
")",
"/",
"60000000.0",
")... | Return a (sign, hour, minute) triple for the offset described by timedelta.
sign is a string, either "+" or "-". In the case of 0 offset, sign is "+". | [
"Return",
"a",
"(",
"sign",
"hour",
"minute",
")",
"triple",
"for",
"the",
"offset",
"described",
"by",
"timedelta",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L35-L50 |
twisted/epsilon | epsilon/extime.py | Time.fromHumanly | def fromHumanly(klass, humanStr, tzinfo=None, now=None):
"""Return a new Time instance from a string a human might type.
@param humanStr: the string to be parsed.
@param tzinfo: A tzinfo instance indicating the timezone to assume if
none is specified in humanStr. If None, assume UTC.
@param now: A Time instance to be considered "now" for when
interpreting relative dates like "tomorrow". If None, use the real now.
Total crap now, it just supports weekdays, "today" and "tomorrow" for
now. This is pretty insufficient and useless, but good enough for some
demo functionality, or something.
"""
humanStr = humanStr.strip()
if now is None:
now = Time()
if tzinfo is None:
tzinfo = FixedOffset(0, 0)
for pattern, creator in klass.humanlyPatterns:
match = pattern.match(humanStr)
if not match \
or match.span()[1] != len(humanStr):
continue
try:
return creator(klass, match, tzinfo, now)
except ValueError:
continue
raise ValueError, 'could not parse date: %r' % (humanStr,) | python | def fromHumanly(klass, humanStr, tzinfo=None, now=None):
"""Return a new Time instance from a string a human might type.
@param humanStr: the string to be parsed.
@param tzinfo: A tzinfo instance indicating the timezone to assume if
none is specified in humanStr. If None, assume UTC.
@param now: A Time instance to be considered "now" for when
interpreting relative dates like "tomorrow". If None, use the real now.
Total crap now, it just supports weekdays, "today" and "tomorrow" for
now. This is pretty insufficient and useless, but good enough for some
demo functionality, or something.
"""
humanStr = humanStr.strip()
if now is None:
now = Time()
if tzinfo is None:
tzinfo = FixedOffset(0, 0)
for pattern, creator in klass.humanlyPatterns:
match = pattern.match(humanStr)
if not match \
or match.span()[1] != len(humanStr):
continue
try:
return creator(klass, match, tzinfo, now)
except ValueError:
continue
raise ValueError, 'could not parse date: %r' % (humanStr,) | [
"def",
"fromHumanly",
"(",
"klass",
",",
"humanStr",
",",
"tzinfo",
"=",
"None",
",",
"now",
"=",
"None",
")",
":",
"humanStr",
"=",
"humanStr",
".",
"strip",
"(",
")",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"Time",
"(",
")",
"if",
"tzinfo",
... | Return a new Time instance from a string a human might type.
@param humanStr: the string to be parsed.
@param tzinfo: A tzinfo instance indicating the timezone to assume if
none is specified in humanStr. If None, assume UTC.
@param now: A Time instance to be considered "now" for when
interpreting relative dates like "tomorrow". If None, use the real now.
Total crap now, it just supports weekdays, "today" and "tomorrow" for
now. This is pretty insufficient and useless, but good enough for some
demo functionality, or something. | [
"Return",
"a",
"new",
"Time",
"instance",
"from",
"a",
"string",
"a",
"human",
"might",
"type",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L309-L339 |
twisted/epsilon | epsilon/extime.py | Time.fromISO8601TimeAndDate | def fromISO8601TimeAndDate(klass, iso8601string, tzinfo=None):
"""Return a new Time instance from a string formated as in ISO 8601.
If the given string contains no timezone, it is assumed to be in the
timezone specified by the parameter `tzinfo`, or UTC if tzinfo is None.
An input string with an explicit timezone will always override tzinfo.
If the given iso8601string does not contain all parts of the time, they
will default to 0 in the timezone given by `tzinfo`.
WARNING: this function is incomplete. ISO is dumb and their standards
are not free. Only a subset of all valid ISO 8601 dates are parsed,
because I can't find a formal description of the format. However,
common ones should work.
"""
def calculateTimezone():
if groups['zulu'] == 'Z':
return FixedOffset(0, 0)
else:
tzhour = groups.pop('tzhour')
tzmin = groups.pop('tzmin')
if tzhour is not None:
return FixedOffset(int(tzhour), int(tzmin or 0))
return tzinfo or FixedOffset(0, 0)
def coerceGroups():
groups['month'] = groups['month1'] or groups['month2']
groups['week'] = groups['week1'] or groups['week2']
# don't include fractional seconds, because it's not an integer.
defaultTo0 = ['hour', 'minute', 'second']
defaultTo1 = ['month', 'day', 'week', 'weekday', 'dayofyear']
if groups['fractionalsec'] is None:
groups['fractionalsec'] = '0'
for key in defaultTo0:
if groups[key] is None:
groups[key] = 0
for key in defaultTo1:
if groups[key] is None:
groups[key] = 1
groups['fractionalsec'] = float('.'+groups['fractionalsec'])
for key in defaultTo0 + defaultTo1 + ['year']:
groups[key] = int(groups[key])
for group, min, max in [
# some years have only 52 weeks
('week', 1, 53),
('weekday', 1, 7),
('month', 1, 12),
('day', 1, 31),
('hour', 0, 24),
('minute', 0, 59),
# Sometime in the 22nd century AD, two leap seconds will be
# required every year. In the 25th century AD, four every
# year. We'll ignore that for now though because it would be
# tricky to get right and we certainly don't need it for our
# target applications. In other words, post-singularity
# Martian users, please do not rely on this code for
# compatibility with Greater Galactic Protectorate of Earth
# date/time formatting! Apologies, but no library I know of in
# Python is sufficient for processing their dates and times
# without ADA bindings to get the radiation-safety zone counter
# correct. -glyph
('second', 0, 61),
# don't forget leap years
('dayofyear', 1, 366)]:
if not min <= groups[group] <= max:
raise ValueError, '%s must be in %i..%i' % (group, min, max)
def determineResolution():
if match.group('fractionalsec') is not None:
return max(datetime.timedelta.resolution,
datetime.timedelta(
microseconds=1 * 10 ** -len(
match.group('fractionalsec')) * 1000000))
for testGroup, resolution in [
('second', datetime.timedelta(seconds=1)),
('minute', datetime.timedelta(minutes=1)),
('hour', datetime.timedelta(hours=1)),
('weekday', datetime.timedelta(days=1)),
('dayofyear', datetime.timedelta(days=1)),
('day', datetime.timedelta(days=1)),
('week1', datetime.timedelta(weeks=1)),
('week2', datetime.timedelta(weeks=1))]:
if match.group(testGroup) is not None:
return resolution
if match.group('month1') is not None \
or match.group('month2') is not None:
if self._time.month == 12:
return datetime.timedelta(days=31)
nextMonth = self._time.replace(month=self._time.month+1)
return nextMonth - self._time
else:
nextYear = self._time.replace(year=self._time.year+1)
return nextYear - self._time
def calculateDtime(tzinfo):
"""Calculate a datetime for the start of the addressed period."""
if match.group('week1') is not None \
or match.group('week2') is not None:
if not 0 < groups['week'] <= 53:
raise ValueError(
'week must be in 1..53 (was %i)' % (groups['week'],))
dtime = datetime.datetime(
groups['year'],
1,
4,
groups['hour'],
groups['minute'],
groups['second'],
int(round(groups['fractionalsec'] * 1000000)),
tzinfo=tzinfo
)
dtime -= datetime.timedelta(days = dtime.weekday())
dtime += datetime.timedelta(
days = (groups['week']-1) * 7 + groups['weekday'] - 1)
if dtime.isocalendar() != (
groups['year'], groups['week'], groups['weekday']):
# actually the problem could be an error in my logic, but
# nothing should cause this but requesting week 53 of a
# year with 52 weeks.
raise ValueError('year %04i has no week %02i' %
(groups['year'], groups['week']))
return dtime
if match.group('dayofyear') is not None:
dtime = datetime.datetime(
groups['year'],
1,
1,
groups['hour'],
groups['minute'],
groups['second'],
int(round(groups['fractionalsec'] * 1000000)),
tzinfo=tzinfo
)
dtime += datetime.timedelta(days=groups['dayofyear']-1)
if dtime.year != groups['year']:
raise ValueError(
'year %04i has no day of year %03i' %
(groups['year'], groups['dayofyear']))
return dtime
else:
return datetime.datetime(
groups['year'],
groups['month'],
groups['day'],
groups['hour'],
groups['minute'],
groups['second'],
int(round(groups['fractionalsec'] * 1000000)),
tzinfo=tzinfo
)
match = klass.iso8601pattern.match(iso8601string)
if match is None:
raise ValueError(
'%r could not be parsed as an ISO 8601 date and time' %
(iso8601string,))
groups = match.groupdict()
coerceGroups()
if match.group('hour') is not None:
timezone = calculateTimezone()
else:
timezone = None
self = klass.fromDatetime(calculateDtime(timezone))
self.resolution = determineResolution()
return self | python | def fromISO8601TimeAndDate(klass, iso8601string, tzinfo=None):
"""Return a new Time instance from a string formated as in ISO 8601.
If the given string contains no timezone, it is assumed to be in the
timezone specified by the parameter `tzinfo`, or UTC if tzinfo is None.
An input string with an explicit timezone will always override tzinfo.
If the given iso8601string does not contain all parts of the time, they
will default to 0 in the timezone given by `tzinfo`.
WARNING: this function is incomplete. ISO is dumb and their standards
are not free. Only a subset of all valid ISO 8601 dates are parsed,
because I can't find a formal description of the format. However,
common ones should work.
"""
def calculateTimezone():
if groups['zulu'] == 'Z':
return FixedOffset(0, 0)
else:
tzhour = groups.pop('tzhour')
tzmin = groups.pop('tzmin')
if tzhour is not None:
return FixedOffset(int(tzhour), int(tzmin or 0))
return tzinfo or FixedOffset(0, 0)
def coerceGroups():
groups['month'] = groups['month1'] or groups['month2']
groups['week'] = groups['week1'] or groups['week2']
# don't include fractional seconds, because it's not an integer.
defaultTo0 = ['hour', 'minute', 'second']
defaultTo1 = ['month', 'day', 'week', 'weekday', 'dayofyear']
if groups['fractionalsec'] is None:
groups['fractionalsec'] = '0'
for key in defaultTo0:
if groups[key] is None:
groups[key] = 0
for key in defaultTo1:
if groups[key] is None:
groups[key] = 1
groups['fractionalsec'] = float('.'+groups['fractionalsec'])
for key in defaultTo0 + defaultTo1 + ['year']:
groups[key] = int(groups[key])
for group, min, max in [
# some years have only 52 weeks
('week', 1, 53),
('weekday', 1, 7),
('month', 1, 12),
('day', 1, 31),
('hour', 0, 24),
('minute', 0, 59),
# Sometime in the 22nd century AD, two leap seconds will be
# required every year. In the 25th century AD, four every
# year. We'll ignore that for now though because it would be
# tricky to get right and we certainly don't need it for our
# target applications. In other words, post-singularity
# Martian users, please do not rely on this code for
# compatibility with Greater Galactic Protectorate of Earth
# date/time formatting! Apologies, but no library I know of in
# Python is sufficient for processing their dates and times
# without ADA bindings to get the radiation-safety zone counter
# correct. -glyph
('second', 0, 61),
# don't forget leap years
('dayofyear', 1, 366)]:
if not min <= groups[group] <= max:
raise ValueError, '%s must be in %i..%i' % (group, min, max)
def determineResolution():
if match.group('fractionalsec') is not None:
return max(datetime.timedelta.resolution,
datetime.timedelta(
microseconds=1 * 10 ** -len(
match.group('fractionalsec')) * 1000000))
for testGroup, resolution in [
('second', datetime.timedelta(seconds=1)),
('minute', datetime.timedelta(minutes=1)),
('hour', datetime.timedelta(hours=1)),
('weekday', datetime.timedelta(days=1)),
('dayofyear', datetime.timedelta(days=1)),
('day', datetime.timedelta(days=1)),
('week1', datetime.timedelta(weeks=1)),
('week2', datetime.timedelta(weeks=1))]:
if match.group(testGroup) is not None:
return resolution
if match.group('month1') is not None \
or match.group('month2') is not None:
if self._time.month == 12:
return datetime.timedelta(days=31)
nextMonth = self._time.replace(month=self._time.month+1)
return nextMonth - self._time
else:
nextYear = self._time.replace(year=self._time.year+1)
return nextYear - self._time
def calculateDtime(tzinfo):
"""Calculate a datetime for the start of the addressed period."""
if match.group('week1') is not None \
or match.group('week2') is not None:
if not 0 < groups['week'] <= 53:
raise ValueError(
'week must be in 1..53 (was %i)' % (groups['week'],))
dtime = datetime.datetime(
groups['year'],
1,
4,
groups['hour'],
groups['minute'],
groups['second'],
int(round(groups['fractionalsec'] * 1000000)),
tzinfo=tzinfo
)
dtime -= datetime.timedelta(days = dtime.weekday())
dtime += datetime.timedelta(
days = (groups['week']-1) * 7 + groups['weekday'] - 1)
if dtime.isocalendar() != (
groups['year'], groups['week'], groups['weekday']):
# actually the problem could be an error in my logic, but
# nothing should cause this but requesting week 53 of a
# year with 52 weeks.
raise ValueError('year %04i has no week %02i' %
(groups['year'], groups['week']))
return dtime
if match.group('dayofyear') is not None:
dtime = datetime.datetime(
groups['year'],
1,
1,
groups['hour'],
groups['minute'],
groups['second'],
int(round(groups['fractionalsec'] * 1000000)),
tzinfo=tzinfo
)
dtime += datetime.timedelta(days=groups['dayofyear']-1)
if dtime.year != groups['year']:
raise ValueError(
'year %04i has no day of year %03i' %
(groups['year'], groups['dayofyear']))
return dtime
else:
return datetime.datetime(
groups['year'],
groups['month'],
groups['day'],
groups['hour'],
groups['minute'],
groups['second'],
int(round(groups['fractionalsec'] * 1000000)),
tzinfo=tzinfo
)
match = klass.iso8601pattern.match(iso8601string)
if match is None:
raise ValueError(
'%r could not be parsed as an ISO 8601 date and time' %
(iso8601string,))
groups = match.groupdict()
coerceGroups()
if match.group('hour') is not None:
timezone = calculateTimezone()
else:
timezone = None
self = klass.fromDatetime(calculateDtime(timezone))
self.resolution = determineResolution()
return self | [
"def",
"fromISO8601TimeAndDate",
"(",
"klass",
",",
"iso8601string",
",",
"tzinfo",
"=",
"None",
")",
":",
"def",
"calculateTimezone",
"(",
")",
":",
"if",
"groups",
"[",
"'zulu'",
"]",
"==",
"'Z'",
":",
"return",
"FixedOffset",
"(",
"0",
",",
"0",
")",
... | Return a new Time instance from a string formated as in ISO 8601.
If the given string contains no timezone, it is assumed to be in the
timezone specified by the parameter `tzinfo`, or UTC if tzinfo is None.
An input string with an explicit timezone will always override tzinfo.
If the given iso8601string does not contain all parts of the time, they
will default to 0 in the timezone given by `tzinfo`.
WARNING: this function is incomplete. ISO is dumb and their standards
are not free. Only a subset of all valid ISO 8601 dates are parsed,
because I can't find a formal description of the format. However,
common ones should work. | [
"Return",
"a",
"new",
"Time",
"instance",
"from",
"a",
"string",
"formated",
"as",
"in",
"ISO",
"8601",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L393-L568 |
twisted/epsilon | epsilon/extime.py | Time.fromStructTime | def fromStructTime(klass, structTime, tzinfo=None):
"""Return a new Time instance from a time.struct_time.
If tzinfo is None, structTime is in UTC. Otherwise, tzinfo is a
datetime.tzinfo instance coresponding to the timezone in which
structTime is.
Many of the functions in the standard time module return these things.
This will also work with a plain 9-tuple, for parity with the time
module. The last three elements, or tm_wday, tm_yday, and tm_isdst are
ignored.
"""
dtime = datetime.datetime(tzinfo=tzinfo, *structTime[:6])
self = klass.fromDatetime(dtime)
self.resolution = datetime.timedelta(seconds=1)
return self | python | def fromStructTime(klass, structTime, tzinfo=None):
"""Return a new Time instance from a time.struct_time.
If tzinfo is None, structTime is in UTC. Otherwise, tzinfo is a
datetime.tzinfo instance coresponding to the timezone in which
structTime is.
Many of the functions in the standard time module return these things.
This will also work with a plain 9-tuple, for parity with the time
module. The last three elements, or tm_wday, tm_yday, and tm_isdst are
ignored.
"""
dtime = datetime.datetime(tzinfo=tzinfo, *structTime[:6])
self = klass.fromDatetime(dtime)
self.resolution = datetime.timedelta(seconds=1)
return self | [
"def",
"fromStructTime",
"(",
"klass",
",",
"structTime",
",",
"tzinfo",
"=",
"None",
")",
":",
"dtime",
"=",
"datetime",
".",
"datetime",
"(",
"tzinfo",
"=",
"tzinfo",
",",
"*",
"structTime",
"[",
":",
"6",
"]",
")",
"self",
"=",
"klass",
".",
"from... | Return a new Time instance from a time.struct_time.
If tzinfo is None, structTime is in UTC. Otherwise, tzinfo is a
datetime.tzinfo instance coresponding to the timezone in which
structTime is.
Many of the functions in the standard time module return these things.
This will also work with a plain 9-tuple, for parity with the time
module. The last three elements, or tm_wday, tm_yday, and tm_isdst are
ignored. | [
"Return",
"a",
"new",
"Time",
"instance",
"from",
"a",
"time",
".",
"struct_time",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L572-L587 |
twisted/epsilon | epsilon/extime.py | Time.fromDatetime | def fromDatetime(klass, dtime):
"""Return a new Time instance from a datetime.datetime instance.
If the datetime instance does not have an associated timezone, it is
assumed to be UTC.
"""
self = klass.__new__(klass)
if dtime.tzinfo is not None:
self._time = dtime.astimezone(FixedOffset(0, 0)).replace(tzinfo=None)
else:
self._time = dtime
self.resolution = datetime.timedelta.resolution
return self | python | def fromDatetime(klass, dtime):
"""Return a new Time instance from a datetime.datetime instance.
If the datetime instance does not have an associated timezone, it is
assumed to be UTC.
"""
self = klass.__new__(klass)
if dtime.tzinfo is not None:
self._time = dtime.astimezone(FixedOffset(0, 0)).replace(tzinfo=None)
else:
self._time = dtime
self.resolution = datetime.timedelta.resolution
return self | [
"def",
"fromDatetime",
"(",
"klass",
",",
"dtime",
")",
":",
"self",
"=",
"klass",
".",
"__new__",
"(",
"klass",
")",
"if",
"dtime",
".",
"tzinfo",
"is",
"not",
"None",
":",
"self",
".",
"_time",
"=",
"dtime",
".",
"astimezone",
"(",
"FixedOffset",
"... | Return a new Time instance from a datetime.datetime instance.
If the datetime instance does not have an associated timezone, it is
assumed to be UTC. | [
"Return",
"a",
"new",
"Time",
"instance",
"from",
"a",
"datetime",
".",
"datetime",
"instance",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L591-L603 |
twisted/epsilon | epsilon/extime.py | Time.fromPOSIXTimestamp | def fromPOSIXTimestamp(klass, secs):
"""Return a new Time instance from seconds since the POSIX epoch.
The POSIX epoch is midnight Jan 1, 1970 UTC. According to POSIX, leap
seconds don't exist, so one UTC day is exactly 86400 seconds, even if
it wasn't.
@param secs: a number of seconds, represented as an integer, long or
float.
"""
self = klass.fromDatetime(_EPOCH + datetime.timedelta(seconds=secs))
self.resolution = datetime.timedelta()
return self | python | def fromPOSIXTimestamp(klass, secs):
"""Return a new Time instance from seconds since the POSIX epoch.
The POSIX epoch is midnight Jan 1, 1970 UTC. According to POSIX, leap
seconds don't exist, so one UTC day is exactly 86400 seconds, even if
it wasn't.
@param secs: a number of seconds, represented as an integer, long or
float.
"""
self = klass.fromDatetime(_EPOCH + datetime.timedelta(seconds=secs))
self.resolution = datetime.timedelta()
return self | [
"def",
"fromPOSIXTimestamp",
"(",
"klass",
",",
"secs",
")",
":",
"self",
"=",
"klass",
".",
"fromDatetime",
"(",
"_EPOCH",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"secs",
")",
")",
"self",
".",
"resolution",
"=",
"datetime",
".",
"timede... | Return a new Time instance from seconds since the POSIX epoch.
The POSIX epoch is midnight Jan 1, 1970 UTC. According to POSIX, leap
seconds don't exist, so one UTC day is exactly 86400 seconds, even if
it wasn't.
@param secs: a number of seconds, represented as an integer, long or
float. | [
"Return",
"a",
"new",
"Time",
"instance",
"from",
"seconds",
"since",
"the",
"POSIX",
"epoch",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L607-L619 |
twisted/epsilon | epsilon/extime.py | Time.fromRFC2822 | def fromRFC2822(klass, rfc822string):
"""
Return a new Time instance from a string formated as described in RFC 2822.
@type rfc822string: str
@raise ValueError: if the timestamp is not formatted properly (or if
certain obsoleted elements of the specification are used).
@return: a new L{Time}
"""
# parsedate_tz is going to give us a "struct_time plus", a 10-tuple
# containing the 9 values a struct_time would, i.e.: (tm_year, tm_mon,
# tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst), plus a
# bonus "offset", which is an offset (in _seconds_, of all things).
maybeStructTimePlus = parsedate_tz(rfc822string)
if maybeStructTimePlus is None:
raise ValueError, 'could not parse RFC 2822 date %r' % (rfc822string,)
structTimePlus = sanitizeStructTime(maybeStructTimePlus)
offsetInSeconds = structTimePlus[-1]
if offsetInSeconds is None:
offsetInSeconds = 0
self = klass.fromStructTime(
structTimePlus,
FixedOffset(
hours=0,
minutes=offsetInSeconds // 60))
self.resolution = datetime.timedelta(seconds=1)
return self | python | def fromRFC2822(klass, rfc822string):
"""
Return a new Time instance from a string formated as described in RFC 2822.
@type rfc822string: str
@raise ValueError: if the timestamp is not formatted properly (or if
certain obsoleted elements of the specification are used).
@return: a new L{Time}
"""
# parsedate_tz is going to give us a "struct_time plus", a 10-tuple
# containing the 9 values a struct_time would, i.e.: (tm_year, tm_mon,
# tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst), plus a
# bonus "offset", which is an offset (in _seconds_, of all things).
maybeStructTimePlus = parsedate_tz(rfc822string)
if maybeStructTimePlus is None:
raise ValueError, 'could not parse RFC 2822 date %r' % (rfc822string,)
structTimePlus = sanitizeStructTime(maybeStructTimePlus)
offsetInSeconds = structTimePlus[-1]
if offsetInSeconds is None:
offsetInSeconds = 0
self = klass.fromStructTime(
structTimePlus,
FixedOffset(
hours=0,
minutes=offsetInSeconds // 60))
self.resolution = datetime.timedelta(seconds=1)
return self | [
"def",
"fromRFC2822",
"(",
"klass",
",",
"rfc822string",
")",
":",
"# parsedate_tz is going to give us a \"struct_time plus\", a 10-tuple",
"# containing the 9 values a struct_time would, i.e.: (tm_year, tm_mon,",
"# tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst), plus a",
"# bon... | Return a new Time instance from a string formated as described in RFC 2822.
@type rfc822string: str
@raise ValueError: if the timestamp is not formatted properly (or if
certain obsoleted elements of the specification are used).
@return: a new L{Time} | [
"Return",
"a",
"new",
"Time",
"instance",
"from",
"a",
"string",
"formated",
"as",
"described",
"in",
"RFC",
"2822",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L623-L654 |
twisted/epsilon | epsilon/extime.py | Time.asDatetime | def asDatetime(self, tzinfo=None):
"""Return this time as an aware datetime.datetime instance.
The returned datetime object has the specified tzinfo, or a tzinfo
describing UTC if the tzinfo parameter is None.
"""
if tzinfo is None:
tzinfo = FixedOffset(0, 0)
if not self.isTimezoneDependent():
return self._time.replace(tzinfo=tzinfo)
else:
return self._time.replace(tzinfo=FixedOffset(0, 0)).astimezone(tzinfo) | python | def asDatetime(self, tzinfo=None):
"""Return this time as an aware datetime.datetime instance.
The returned datetime object has the specified tzinfo, or a tzinfo
describing UTC if the tzinfo parameter is None.
"""
if tzinfo is None:
tzinfo = FixedOffset(0, 0)
if not self.isTimezoneDependent():
return self._time.replace(tzinfo=tzinfo)
else:
return self._time.replace(tzinfo=FixedOffset(0, 0)).astimezone(tzinfo) | [
"def",
"asDatetime",
"(",
"self",
",",
"tzinfo",
"=",
"None",
")",
":",
"if",
"tzinfo",
"is",
"None",
":",
"tzinfo",
"=",
"FixedOffset",
"(",
"0",
",",
"0",
")",
"if",
"not",
"self",
".",
"isTimezoneDependent",
"(",
")",
":",
"return",
"self",
".",
... | Return this time as an aware datetime.datetime instance.
The returned datetime object has the specified tzinfo, or a tzinfo
describing UTC if the tzinfo parameter is None. | [
"Return",
"this",
"time",
"as",
"an",
"aware",
"datetime",
".",
"datetime",
"instance",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L671-L683 |
twisted/epsilon | epsilon/extime.py | Time.asRFC2822 | def asRFC2822(self, tzinfo=None, includeDayOfWeek=True):
"""Return this Time formatted as specified in RFC 2822.
RFC 2822 specifies the format of email messages.
RFC 2822 says times in email addresses should reflect the local
timezone. If tzinfo is a datetime.tzinfo instance, the returned
formatted string will reflect that timezone. Otherwise, the timezone
will be '-0000', which RFC 2822 defines as UTC, but with an unknown
local timezone.
RFC 2822 states that the weekday is optional. The parameter
includeDayOfWeek indicates whether or not to include it.
"""
dtime = self.asDatetime(tzinfo)
if tzinfo is None:
rfcoffset = '-0000'
else:
rfcoffset = '%s%02i%02i' % _timedeltaToSignHrMin(dtime.utcoffset())
rfcstring = ''
if includeDayOfWeek:
rfcstring += self.rfc2822Weekdays[dtime.weekday()] + ', '
rfcstring += '%i %s %4i %02i:%02i:%02i %s' % (
dtime.day,
self.rfc2822Months[dtime.month - 1],
dtime.year,
dtime.hour,
dtime.minute,
dtime.second,
rfcoffset)
return rfcstring | python | def asRFC2822(self, tzinfo=None, includeDayOfWeek=True):
"""Return this Time formatted as specified in RFC 2822.
RFC 2822 specifies the format of email messages.
RFC 2822 says times in email addresses should reflect the local
timezone. If tzinfo is a datetime.tzinfo instance, the returned
formatted string will reflect that timezone. Otherwise, the timezone
will be '-0000', which RFC 2822 defines as UTC, but with an unknown
local timezone.
RFC 2822 states that the weekday is optional. The parameter
includeDayOfWeek indicates whether or not to include it.
"""
dtime = self.asDatetime(tzinfo)
if tzinfo is None:
rfcoffset = '-0000'
else:
rfcoffset = '%s%02i%02i' % _timedeltaToSignHrMin(dtime.utcoffset())
rfcstring = ''
if includeDayOfWeek:
rfcstring += self.rfc2822Weekdays[dtime.weekday()] + ', '
rfcstring += '%i %s %4i %02i:%02i:%02i %s' % (
dtime.day,
self.rfc2822Months[dtime.month - 1],
dtime.year,
dtime.hour,
dtime.minute,
dtime.second,
rfcoffset)
return rfcstring | [
"def",
"asRFC2822",
"(",
"self",
",",
"tzinfo",
"=",
"None",
",",
"includeDayOfWeek",
"=",
"True",
")",
":",
"dtime",
"=",
"self",
".",
"asDatetime",
"(",
"tzinfo",
")",
"if",
"tzinfo",
"is",
"None",
":",
"rfcoffset",
"=",
"'-0000'",
"else",
":",
"rfco... | Return this Time formatted as specified in RFC 2822.
RFC 2822 specifies the format of email messages.
RFC 2822 says times in email addresses should reflect the local
timezone. If tzinfo is a datetime.tzinfo instance, the returned
formatted string will reflect that timezone. Otherwise, the timezone
will be '-0000', which RFC 2822 defines as UTC, but with an unknown
local timezone.
RFC 2822 states that the weekday is optional. The parameter
includeDayOfWeek indicates whether or not to include it. | [
"Return",
"this",
"Time",
"formatted",
"as",
"specified",
"in",
"RFC",
"2822",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L694-L728 |
twisted/epsilon | epsilon/extime.py | Time.asISO8601TimeAndDate | def asISO8601TimeAndDate(self, includeDelimiters=True, tzinfo=None,
includeTimezone=True):
"""Return this time formatted as specified by ISO 8861.
ISO 8601 allows optional dashes to delimit dates and colons to delimit
times. The parameter includeDelimiters (default True) defines the
inclusion of these delimiters in the output.
If tzinfo is a datetime.tzinfo instance, the output time will be in the
timezone given. If it is None (the default), then the timezone string
will not be included in the output, and the time will be in UTC.
The includeTimezone parameter coresponds to the inclusion of an
explicit timezone. The default is True.
"""
if not self.isTimezoneDependent():
tzinfo = None
dtime = self.asDatetime(tzinfo)
if includeDelimiters:
dateSep = '-'
timeSep = ':'
else:
dateSep = timeSep = ''
if includeTimezone:
if tzinfo is None:
timezone = '+00%s00' % (timeSep,)
else:
sign, hour, min = _timedeltaToSignHrMin(dtime.utcoffset())
timezone = '%s%02i%s%02i' % (sign, hour, timeSep, min)
else:
timezone = ''
microsecond = ('%06i' % (dtime.microsecond,)).rstrip('0')
if microsecond:
microsecond = '.' + microsecond
parts = [
('%04i' % (dtime.year,), datetime.timedelta(days=366)),
('%s%02i' % (dateSep, dtime.month), datetime.timedelta(days=31)),
('%s%02i' % (dateSep, dtime.day), datetime.timedelta(days=1)),
('T', datetime.timedelta(hours=1)),
('%02i' % (dtime.hour,), datetime.timedelta(hours=1)),
('%s%02i' % (timeSep, dtime.minute), datetime.timedelta(minutes=1)),
('%s%02i' % (timeSep, dtime.second), datetime.timedelta(seconds=1)),
(microsecond, datetime.timedelta(microseconds=1)),
(timezone, datetime.timedelta(hours=1))
]
formatted = ''
for part, minResolution in parts:
if self.resolution <= minResolution:
formatted += part
return formatted | python | def asISO8601TimeAndDate(self, includeDelimiters=True, tzinfo=None,
includeTimezone=True):
"""Return this time formatted as specified by ISO 8861.
ISO 8601 allows optional dashes to delimit dates and colons to delimit
times. The parameter includeDelimiters (default True) defines the
inclusion of these delimiters in the output.
If tzinfo is a datetime.tzinfo instance, the output time will be in the
timezone given. If it is None (the default), then the timezone string
will not be included in the output, and the time will be in UTC.
The includeTimezone parameter coresponds to the inclusion of an
explicit timezone. The default is True.
"""
if not self.isTimezoneDependent():
tzinfo = None
dtime = self.asDatetime(tzinfo)
if includeDelimiters:
dateSep = '-'
timeSep = ':'
else:
dateSep = timeSep = ''
if includeTimezone:
if tzinfo is None:
timezone = '+00%s00' % (timeSep,)
else:
sign, hour, min = _timedeltaToSignHrMin(dtime.utcoffset())
timezone = '%s%02i%s%02i' % (sign, hour, timeSep, min)
else:
timezone = ''
microsecond = ('%06i' % (dtime.microsecond,)).rstrip('0')
if microsecond:
microsecond = '.' + microsecond
parts = [
('%04i' % (dtime.year,), datetime.timedelta(days=366)),
('%s%02i' % (dateSep, dtime.month), datetime.timedelta(days=31)),
('%s%02i' % (dateSep, dtime.day), datetime.timedelta(days=1)),
('T', datetime.timedelta(hours=1)),
('%02i' % (dtime.hour,), datetime.timedelta(hours=1)),
('%s%02i' % (timeSep, dtime.minute), datetime.timedelta(minutes=1)),
('%s%02i' % (timeSep, dtime.second), datetime.timedelta(seconds=1)),
(microsecond, datetime.timedelta(microseconds=1)),
(timezone, datetime.timedelta(hours=1))
]
formatted = ''
for part, minResolution in parts:
if self.resolution <= minResolution:
formatted += part
return formatted | [
"def",
"asISO8601TimeAndDate",
"(",
"self",
",",
"includeDelimiters",
"=",
"True",
",",
"tzinfo",
"=",
"None",
",",
"includeTimezone",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"isTimezoneDependent",
"(",
")",
":",
"tzinfo",
"=",
"None",
"dtime",
"=... | Return this time formatted as specified by ISO 8861.
ISO 8601 allows optional dashes to delimit dates and colons to delimit
times. The parameter includeDelimiters (default True) defines the
inclusion of these delimiters in the output.
If tzinfo is a datetime.tzinfo instance, the output time will be in the
timezone given. If it is None (the default), then the timezone string
will not be included in the output, and the time will be in UTC.
The includeTimezone parameter coresponds to the inclusion of an
explicit timezone. The default is True. | [
"Return",
"this",
"time",
"formatted",
"as",
"specified",
"by",
"ISO",
"8861",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L742-L797 |
twisted/epsilon | epsilon/extime.py | Time.asStructTime | def asStructTime(self, tzinfo=None):
"""Return this time represented as a time.struct_time.
tzinfo is a datetime.tzinfo instance coresponding to the desired
timezone of the output. If is is the default None, UTC is assumed.
"""
dtime = self.asDatetime(tzinfo)
if tzinfo is None:
return dtime.utctimetuple()
else:
return dtime.timetuple() | python | def asStructTime(self, tzinfo=None):
"""Return this time represented as a time.struct_time.
tzinfo is a datetime.tzinfo instance coresponding to the desired
timezone of the output. If is is the default None, UTC is assumed.
"""
dtime = self.asDatetime(tzinfo)
if tzinfo is None:
return dtime.utctimetuple()
else:
return dtime.timetuple() | [
"def",
"asStructTime",
"(",
"self",
",",
"tzinfo",
"=",
"None",
")",
":",
"dtime",
"=",
"self",
".",
"asDatetime",
"(",
"tzinfo",
")",
"if",
"tzinfo",
"is",
"None",
":",
"return",
"dtime",
".",
"utctimetuple",
"(",
")",
"else",
":",
"return",
"dtime",
... | Return this time represented as a time.struct_time.
tzinfo is a datetime.tzinfo instance coresponding to the desired
timezone of the output. If is is the default None, UTC is assumed. | [
"Return",
"this",
"time",
"represented",
"as",
"a",
"time",
".",
"struct_time",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L799-L809 |
twisted/epsilon | epsilon/extime.py | Time.asHumanly | def asHumanly(self, tzinfo=None, now=None, precision=Precision.MINUTES):
"""Return this time as a short string, tailored to the current time.
Parts of the date that can be assumed are omitted. Consequently, the
output string depends on the current time. This is the format used for
displaying dates in most user visible places in the quotient web UI.
By default, the current time is determined by the system clock. The
current time used for formatting the time can be changed by providing a
Time instance as the parameter 'now'.
@param precision: The smallest unit of time that will be represented
in the returned string. Valid values are L{Time.Precision.MINUTES} and
L{Time.Precision.SECONDS}.
@raise InvalidPrecision: if the specified precision is not either
L{Time.Precision.MINUTES} or L{Time.Precision.SECONDS}.
"""
try:
timeFormat = Time._timeFormat[precision]
except KeyError:
raise InvalidPrecision(
'Use Time.Precision.MINUTES or Time.Precision.SECONDS')
if now is None:
now = Time().asDatetime(tzinfo)
else:
now = now.asDatetime(tzinfo)
dtime = self.asDatetime(tzinfo)
# Same day?
if dtime.date() == now.date():
if self.isAllDay():
return 'all day'
return dtime.strftime(timeFormat).lower()
else:
res = str(dtime.date().day) + dtime.strftime(' %b') # day + month
# Different year?
if not dtime.date().year == now.date().year:
res += dtime.strftime(' %Y')
if not self.isAllDay():
res += dtime.strftime(', %s' % (timeFormat,)).lower()
return res | python | def asHumanly(self, tzinfo=None, now=None, precision=Precision.MINUTES):
"""Return this time as a short string, tailored to the current time.
Parts of the date that can be assumed are omitted. Consequently, the
output string depends on the current time. This is the format used for
displaying dates in most user visible places in the quotient web UI.
By default, the current time is determined by the system clock. The
current time used for formatting the time can be changed by providing a
Time instance as the parameter 'now'.
@param precision: The smallest unit of time that will be represented
in the returned string. Valid values are L{Time.Precision.MINUTES} and
L{Time.Precision.SECONDS}.
@raise InvalidPrecision: if the specified precision is not either
L{Time.Precision.MINUTES} or L{Time.Precision.SECONDS}.
"""
try:
timeFormat = Time._timeFormat[precision]
except KeyError:
raise InvalidPrecision(
'Use Time.Precision.MINUTES or Time.Precision.SECONDS')
if now is None:
now = Time().asDatetime(tzinfo)
else:
now = now.asDatetime(tzinfo)
dtime = self.asDatetime(tzinfo)
# Same day?
if dtime.date() == now.date():
if self.isAllDay():
return 'all day'
return dtime.strftime(timeFormat).lower()
else:
res = str(dtime.date().day) + dtime.strftime(' %b') # day + month
# Different year?
if not dtime.date().year == now.date().year:
res += dtime.strftime(' %Y')
if not self.isAllDay():
res += dtime.strftime(', %s' % (timeFormat,)).lower()
return res | [
"def",
"asHumanly",
"(",
"self",
",",
"tzinfo",
"=",
"None",
",",
"now",
"=",
"None",
",",
"precision",
"=",
"Precision",
".",
"MINUTES",
")",
":",
"try",
":",
"timeFormat",
"=",
"Time",
".",
"_timeFormat",
"[",
"precision",
"]",
"except",
"KeyError",
... | Return this time as a short string, tailored to the current time.
Parts of the date that can be assumed are omitted. Consequently, the
output string depends on the current time. This is the format used for
displaying dates in most user visible places in the quotient web UI.
By default, the current time is determined by the system clock. The
current time used for formatting the time can be changed by providing a
Time instance as the parameter 'now'.
@param precision: The smallest unit of time that will be represented
in the returned string. Valid values are L{Time.Precision.MINUTES} and
L{Time.Precision.SECONDS}.
@raise InvalidPrecision: if the specified precision is not either
L{Time.Precision.MINUTES} or L{Time.Precision.SECONDS}. | [
"Return",
"this",
"time",
"as",
"a",
"short",
"string",
"tailored",
"to",
"the",
"current",
"time",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L811-L853 |
twisted/epsilon | epsilon/extime.py | Time.getBounds | def getBounds(self, tzinfo=None):
"""
Return a pair describing the bounds of self.
This returns a pair (min, max) of Time instances. It is not quite the
same as (self, self + self.resolution). This is because timezones are
insignificant for instances with a resolution greater or equal to 1
day.
To illustrate the problem, consider a Time instance::
T = Time.fromHumanly('today', tzinfo=anything)
This will return an equivalent instance independent of the tzinfo used.
The hour, minute, and second of this instance are 0, and its resolution
is one day.
Now say we have a sorted list of times, and we want to get all times
for 'today', where whoever said 'today' is in a timezone that's 5 hours
ahead of UTC. The start of 'today' in this timezone is UTC 05:00. The
example instance T above is before this, but obviously it is today.
The min and max times this returns are such that all potentially
matching instances are within this range. However, this range might
contain unmatching instances.
As an example of this, if 'today' is April first 2005, then
Time.fromISO8601TimeAndDate('2005-04-01T00:00:00') sorts in the same
place as T from above, but is not in the UTC+5 'today'.
TIME IS FUN!
"""
if self.resolution >= datetime.timedelta(days=1) \
and tzinfo is not None:
time = self._time.replace(tzinfo=tzinfo)
else:
time = self._time
return (
min(self.fromDatetime(time), self.fromDatetime(self._time)),
max(self.fromDatetime(time + self.resolution),
self.fromDatetime(self._time + self.resolution))
) | python | def getBounds(self, tzinfo=None):
"""
Return a pair describing the bounds of self.
This returns a pair (min, max) of Time instances. It is not quite the
same as (self, self + self.resolution). This is because timezones are
insignificant for instances with a resolution greater or equal to 1
day.
To illustrate the problem, consider a Time instance::
T = Time.fromHumanly('today', tzinfo=anything)
This will return an equivalent instance independent of the tzinfo used.
The hour, minute, and second of this instance are 0, and its resolution
is one day.
Now say we have a sorted list of times, and we want to get all times
for 'today', where whoever said 'today' is in a timezone that's 5 hours
ahead of UTC. The start of 'today' in this timezone is UTC 05:00. The
example instance T above is before this, but obviously it is today.
The min and max times this returns are such that all potentially
matching instances are within this range. However, this range might
contain unmatching instances.
As an example of this, if 'today' is April first 2005, then
Time.fromISO8601TimeAndDate('2005-04-01T00:00:00') sorts in the same
place as T from above, but is not in the UTC+5 'today'.
TIME IS FUN!
"""
if self.resolution >= datetime.timedelta(days=1) \
and tzinfo is not None:
time = self._time.replace(tzinfo=tzinfo)
else:
time = self._time
return (
min(self.fromDatetime(time), self.fromDatetime(self._time)),
max(self.fromDatetime(time + self.resolution),
self.fromDatetime(self._time + self.resolution))
) | [
"def",
"getBounds",
"(",
"self",
",",
"tzinfo",
"=",
"None",
")",
":",
"if",
"self",
".",
"resolution",
">=",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"1",
")",
"and",
"tzinfo",
"is",
"not",
"None",
":",
"time",
"=",
"self",
".",
"_time",
".... | Return a pair describing the bounds of self.
This returns a pair (min, max) of Time instances. It is not quite the
same as (self, self + self.resolution). This is because timezones are
insignificant for instances with a resolution greater or equal to 1
day.
To illustrate the problem, consider a Time instance::
T = Time.fromHumanly('today', tzinfo=anything)
This will return an equivalent instance independent of the tzinfo used.
The hour, minute, and second of this instance are 0, and its resolution
is one day.
Now say we have a sorted list of times, and we want to get all times
for 'today', where whoever said 'today' is in a timezone that's 5 hours
ahead of UTC. The start of 'today' in this timezone is UTC 05:00. The
example instance T above is before this, but obviously it is today.
The min and max times this returns are such that all potentially
matching instances are within this range. However, this range might
contain unmatching instances.
As an example of this, if 'today' is April first 2005, then
Time.fromISO8601TimeAndDate('2005-04-01T00:00:00') sorts in the same
place as T from above, but is not in the UTC+5 'today'.
TIME IS FUN! | [
"Return",
"a",
"pair",
"describing",
"the",
"bounds",
"of",
"self",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L859-L901 |
twisted/epsilon | epsilon/extime.py | Time.oneDay | def oneDay(self):
"""Return a Time instance representing the day of the start of self.
The returned new instance will be set to midnight of the day containing
the first instant of self in the specified timezone, and have a
resolution of datetime.timedelta(days=1).
"""
day = self.__class__.fromDatetime(self.asDatetime().replace(
hour=0, minute=0, second=0, microsecond=0))
day.resolution = datetime.timedelta(days=1)
return day | python | def oneDay(self):
"""Return a Time instance representing the day of the start of self.
The returned new instance will be set to midnight of the day containing
the first instant of self in the specified timezone, and have a
resolution of datetime.timedelta(days=1).
"""
day = self.__class__.fromDatetime(self.asDatetime().replace(
hour=0, minute=0, second=0, microsecond=0))
day.resolution = datetime.timedelta(days=1)
return day | [
"def",
"oneDay",
"(",
"self",
")",
":",
"day",
"=",
"self",
".",
"__class__",
".",
"fromDatetime",
"(",
"self",
".",
"asDatetime",
"(",
")",
".",
"replace",
"(",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
",",
"microsecond"... | Return a Time instance representing the day of the start of self.
The returned new instance will be set to midnight of the day containing
the first instant of self in the specified timezone, and have a
resolution of datetime.timedelta(days=1). | [
"Return",
"a",
"Time",
"instance",
"representing",
"the",
"day",
"of",
"the",
"start",
"of",
"self",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/extime.py#L903-L913 |
CivicSpleen/ambry | ambry/util/__init__.py | get_logger | def get_logger(name, file_name=None, stream=None, template=None, propagate=False, level=None):
"""Get a logger by name.
"""
logger = logging.getLogger(name)
running_tests = (
'test' in sys.argv # running with setup.py
or sys.argv[0].endswith('py.test')) # running with py.test
if running_tests and not level:
# testing without level, this means tester does not want to see any log messages.
level = logging.CRITICAL
if not level:
level = logging.INFO
logger.setLevel(level)
logger.propagate = propagate
formatter = logging.Formatter(template)
if not stream:
stream = sys.stdout
logger.handlers = []
handler = logging.StreamHandler(stream=stream)
handler.setFormatter(formatter)
logger.addHandler(handler)
if file_name:
handler = logging.FileHandler(file_name)
handler.setFormatter(logging.Formatter('%(asctime)s '+template))
logger.addHandler(handler)
return logger | python | def get_logger(name, file_name=None, stream=None, template=None, propagate=False, level=None):
"""Get a logger by name.
"""
logger = logging.getLogger(name)
running_tests = (
'test' in sys.argv # running with setup.py
or sys.argv[0].endswith('py.test')) # running with py.test
if running_tests and not level:
# testing without level, this means tester does not want to see any log messages.
level = logging.CRITICAL
if not level:
level = logging.INFO
logger.setLevel(level)
logger.propagate = propagate
formatter = logging.Formatter(template)
if not stream:
stream = sys.stdout
logger.handlers = []
handler = logging.StreamHandler(stream=stream)
handler.setFormatter(formatter)
logger.addHandler(handler)
if file_name:
handler = logging.FileHandler(file_name)
handler.setFormatter(logging.Formatter('%(asctime)s '+template))
logger.addHandler(handler)
return logger | [
"def",
"get_logger",
"(",
"name",
",",
"file_name",
"=",
"None",
",",
"stream",
"=",
"None",
",",
"template",
"=",
"None",
",",
"propagate",
"=",
"False",
",",
"level",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
"... | Get a logger by name. | [
"Get",
"a",
"logger",
"by",
"name",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L36-L69 |
CivicSpleen/ambry | ambry/util/__init__.py | expiring_memoize | def expiring_memoize(obj):
"""Like memoize, but forgets after 10 seconds."""
cache = obj.cache = {}
last_access = obj.last_access = defaultdict(int)
@wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if last_access[key] and last_access[key] + 10 < time():
if key in cache:
del cache[key]
last_access[key] = time()
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer | python | def expiring_memoize(obj):
"""Like memoize, but forgets after 10 seconds."""
cache = obj.cache = {}
last_access = obj.last_access = defaultdict(int)
@wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if last_access[key] and last_access[key] + 10 < time():
if key in cache:
del cache[key]
last_access[key] = time()
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer | [
"def",
"expiring_memoize",
"(",
"obj",
")",
":",
"cache",
"=",
"obj",
".",
"cache",
"=",
"{",
"}",
"last_access",
"=",
"obj",
".",
"last_access",
"=",
"defaultdict",
"(",
"int",
")",
"@",
"wraps",
"(",
"obj",
")",
"def",
"memoizer",
"(",
"*",
"args",... | Like memoize, but forgets after 10 seconds. | [
"Like",
"memoize",
"but",
"forgets",
"after",
"10",
"seconds",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L88-L108 |
CivicSpleen/ambry | ambry/util/__init__.py | lru_cache | def lru_cache(maxsize=128, maxtime=60):
'''Least-recently-used cache decorator.
Arguments to the cached function must be hashable.
Cache performance statistics stored in f.hits and f.misses.
Clear the cache with f.clear().
http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
'''
maxqueue = maxsize * 10
# @ReservedAssignment
def decorating_function(
user_function,
len=len,
iter=iter,
tuple=tuple,
sorted=sorted,
KeyError=KeyError):
cache = {} # mapping of args to results
queue = deque() # order that keys have been used
refcount = Counter() # times each key is in the queue
sentinel = object() # marker for looping around the queue
kwd_mark = object() # separate positional and keyword args
# lookup optimizations (ugly but fast)
queue_append, queue_popleft = queue.append, queue.popleft
queue_appendleft, queue_pop = queue.appendleft, queue.pop
@wraps(user_function)
def wrapper(*args, **kwds):
# cache key records both positional and keyword args
key = args
if kwds:
key += (kwd_mark,) + tuple(sorted(kwds.items()))
# record recent use of this key
queue_append(key)
refcount[key] += 1
# get cache entry or compute if not found
try:
result, expire_time = cache[key]
if expire_time and time() > expire_time:
raise KeyError('Expired')
wrapper.hits += 1
except KeyError:
result = user_function(*args, **kwds)
if maxtime:
expire_time = time() + maxtime
else:
expire_time = None
cache[key] = result, expire_time
wrapper.misses += 1
# purge least recently used cache entry
if len(cache) > maxsize:
key = queue_popleft()
refcount[key] -= 1
while refcount[key]:
key = queue_popleft()
refcount[key] -= 1
del cache[key], refcount[key]
# periodically compact the queue by eliminating duplicate keys
# while preserving order of most recent access
if len(queue) > maxqueue:
refcount.clear()
queue_appendleft(sentinel)
for key in filterfalse(refcount.__contains__, iter(queue_pop, sentinel)):
queue_appendleft(key)
refcount[key] = 1
return result
def clear():
cache.clear()
queue.clear()
refcount.clear()
wrapper.hits = wrapper.misses = 0
wrapper.hits = wrapper.misses = 0
wrapper.clear = clear
return wrapper
return decorating_function | python | def lru_cache(maxsize=128, maxtime=60):
'''Least-recently-used cache decorator.
Arguments to the cached function must be hashable.
Cache performance statistics stored in f.hits and f.misses.
Clear the cache with f.clear().
http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
'''
maxqueue = maxsize * 10
# @ReservedAssignment
def decorating_function(
user_function,
len=len,
iter=iter,
tuple=tuple,
sorted=sorted,
KeyError=KeyError):
cache = {} # mapping of args to results
queue = deque() # order that keys have been used
refcount = Counter() # times each key is in the queue
sentinel = object() # marker for looping around the queue
kwd_mark = object() # separate positional and keyword args
# lookup optimizations (ugly but fast)
queue_append, queue_popleft = queue.append, queue.popleft
queue_appendleft, queue_pop = queue.appendleft, queue.pop
@wraps(user_function)
def wrapper(*args, **kwds):
# cache key records both positional and keyword args
key = args
if kwds:
key += (kwd_mark,) + tuple(sorted(kwds.items()))
# record recent use of this key
queue_append(key)
refcount[key] += 1
# get cache entry or compute if not found
try:
result, expire_time = cache[key]
if expire_time and time() > expire_time:
raise KeyError('Expired')
wrapper.hits += 1
except KeyError:
result = user_function(*args, **kwds)
if maxtime:
expire_time = time() + maxtime
else:
expire_time = None
cache[key] = result, expire_time
wrapper.misses += 1
# purge least recently used cache entry
if len(cache) > maxsize:
key = queue_popleft()
refcount[key] -= 1
while refcount[key]:
key = queue_popleft()
refcount[key] -= 1
del cache[key], refcount[key]
# periodically compact the queue by eliminating duplicate keys
# while preserving order of most recent access
if len(queue) > maxqueue:
refcount.clear()
queue_appendleft(sentinel)
for key in filterfalse(refcount.__contains__, iter(queue_pop, sentinel)):
queue_appendleft(key)
refcount[key] = 1
return result
def clear():
cache.clear()
queue.clear()
refcount.clear()
wrapper.hits = wrapper.misses = 0
wrapper.hits = wrapper.misses = 0
wrapper.clear = clear
return wrapper
return decorating_function | [
"def",
"lru_cache",
"(",
"maxsize",
"=",
"128",
",",
"maxtime",
"=",
"60",
")",
":",
"maxqueue",
"=",
"maxsize",
"*",
"10",
"# @ReservedAssignment",
"def",
"decorating_function",
"(",
"user_function",
",",
"len",
"=",
"len",
",",
"iter",
"=",
"iter",
",",
... | Least-recently-used cache decorator.
Arguments to the cached function must be hashable.
Cache performance statistics stored in f.hits and f.misses.
Clear the cache with f.clear().
http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used | [
"Least",
"-",
"recently",
"-",
"used",
"cache",
"decorator",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L122-L211 |
CivicSpleen/ambry | ambry/util/__init__.py | configure_logging | def configure_logging(cfg, custom_level=None):
"""Don't know what this is for ...."""
import itertools as it
import operator as op
if custom_level is None:
custom_level = logging.WARNING
for entity in it.chain.from_iterable(it.imap(op.methodcaller('viewvalues'),
[cfg] + [cfg.get(k, dict()) for k in ['handlers', 'loggers']])):
if isinstance(entity, Mapping) and entity.get('level') == 'custom':
entity['level'] = custom_level
logging.config.dictConfig(cfg)
logging.captureWarnings(cfg.warnings) | python | def configure_logging(cfg, custom_level=None):
"""Don't know what this is for ...."""
import itertools as it
import operator as op
if custom_level is None:
custom_level = logging.WARNING
for entity in it.chain.from_iterable(it.imap(op.methodcaller('viewvalues'),
[cfg] + [cfg.get(k, dict()) for k in ['handlers', 'loggers']])):
if isinstance(entity, Mapping) and entity.get('level') == 'custom':
entity['level'] = custom_level
logging.config.dictConfig(cfg)
logging.captureWarnings(cfg.warnings) | [
"def",
"configure_logging",
"(",
"cfg",
",",
"custom_level",
"=",
"None",
")",
":",
"import",
"itertools",
"as",
"it",
"import",
"operator",
"as",
"op",
"if",
"custom_level",
"is",
"None",
":",
"custom_level",
"=",
"logging",
".",
"WARNING",
"for",
"entity",... | Don't know what this is for .... | [
"Don",
"t",
"know",
"what",
"this",
"is",
"for",
"...."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L561-L573 |
CivicSpleen/ambry | ambry/util/__init__.py | toposort | def toposort(data):
"""Dependencies are expressed as a dictionary whose keys are items and
whose values are a set of dependent items. Output is a list of sets in
topological order. The first set consists of items with no dependences,
each subsequent set consists of items that depend upon items in the
preceeding sets.
>>> print '\\n'.join(repr(sorted(x)) for x in toposort2({
... 2: set([11]),
... 9: set([11,8]),
... 10: set([11,3]),
... 11: set([7,5]),
... 8: set([7,3]),
... }) )
[3, 5, 7]
[8, 11]
[2, 9, 10]
"""
# Ignore self dependencies.
for k, v in iteritems(data):
v.discard(k)
# Find all items that don't depend on anything.
extra_items_in_deps = reduce(
set.union, itervalues(data)) - set(data.keys())
# Add empty dependences where needed
data.update({item: set() for item in extra_items_in_deps})
while True:
ordered = set(item for item, dep in iteritems(data) if not dep)
if not ordered:
break
yield ordered
data = {item: (dep - ordered)
for item, dep in iteritems(data)
if item not in ordered}
assert not data, 'Cyclic dependencies exist among these items:\n%s' % '\n'.join(
repr(x) for x in list(data.items())) | python | def toposort(data):
"""Dependencies are expressed as a dictionary whose keys are items and
whose values are a set of dependent items. Output is a list of sets in
topological order. The first set consists of items with no dependences,
each subsequent set consists of items that depend upon items in the
preceeding sets.
>>> print '\\n'.join(repr(sorted(x)) for x in toposort2({
... 2: set([11]),
... 9: set([11,8]),
... 10: set([11,3]),
... 11: set([7,5]),
... 8: set([7,3]),
... }) )
[3, 5, 7]
[8, 11]
[2, 9, 10]
"""
# Ignore self dependencies.
for k, v in iteritems(data):
v.discard(k)
# Find all items that don't depend on anything.
extra_items_in_deps = reduce(
set.union, itervalues(data)) - set(data.keys())
# Add empty dependences where needed
data.update({item: set() for item in extra_items_in_deps})
while True:
ordered = set(item for item, dep in iteritems(data) if not dep)
if not ordered:
break
yield ordered
data = {item: (dep - ordered)
for item, dep in iteritems(data)
if item not in ordered}
assert not data, 'Cyclic dependencies exist among these items:\n%s' % '\n'.join(
repr(x) for x in list(data.items())) | [
"def",
"toposort",
"(",
"data",
")",
":",
"# Ignore self dependencies.",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"data",
")",
":",
"v",
".",
"discard",
"(",
"k",
")",
"# Find all items that don't depend on anything.",
"extra_items_in_deps",
"=",
"reduce",
... | Dependencies are expressed as a dictionary whose keys are items and
whose values are a set of dependent items. Output is a list of sets in
topological order. The first set consists of items with no dependences,
each subsequent set consists of items that depend upon items in the
preceeding sets.
>>> print '\\n'.join(repr(sorted(x)) for x in toposort2({
... 2: set([11]),
... 9: set([11,8]),
... 10: set([11,3]),
... 11: set([7,5]),
... 8: set([7,3]),
... }) )
[3, 5, 7]
[8, 11]
[2, 9, 10] | [
"Dependencies",
"are",
"expressed",
"as",
"a",
"dictionary",
"whose",
"keys",
"are",
"items",
"and",
"whose",
"values",
"are",
"a",
"set",
"of",
"dependent",
"items",
".",
"Output",
"is",
"a",
"list",
"of",
"sets",
"in",
"topological",
"order",
".",
"The",... | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L579-L617 |
CivicSpleen/ambry | ambry/util/__init__.py | md5_for_file | def md5_for_file(f, block_size=2 ** 20):
"""Generate an MD5 has for a possibly large file by breaking it into
chunks."""
md5 = hashlib.md5()
try:
# Guess that f is a FLO.
f.seek(0)
return md5_for_stream(f, block_size=block_size)
except AttributeError:
# Nope, not a FLO. Maybe string?
file_name = f
with open(file_name, 'rb') as f:
return md5_for_file(f, block_size) | python | def md5_for_file(f, block_size=2 ** 20):
"""Generate an MD5 has for a possibly large file by breaking it into
chunks."""
md5 = hashlib.md5()
try:
# Guess that f is a FLO.
f.seek(0)
return md5_for_stream(f, block_size=block_size)
except AttributeError:
# Nope, not a FLO. Maybe string?
file_name = f
with open(file_name, 'rb') as f:
return md5_for_file(f, block_size) | [
"def",
"md5_for_file",
"(",
"f",
",",
"block_size",
"=",
"2",
"**",
"20",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"try",
":",
"# Guess that f is a FLO.",
"f",
".",
"seek",
"(",
"0",
")",
"return",
"md5_for_stream",
"(",
"f",
",",
"bloc... | Generate an MD5 has for a possibly large file by breaking it into
chunks. | [
"Generate",
"an",
"MD5",
"has",
"for",
"a",
"possibly",
"large",
"file",
"by",
"breaking",
"it",
"into",
"chunks",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L637-L653 |
CivicSpleen/ambry | ambry/util/__init__.py | make_acro | def make_acro(past, prefix, s): # pragma: no cover
"""Create a three letter acronym from the input string s.
Args:
past: A set object, for storing acronyms that have already been created
prefix: A prefix added to the acronym before storing in the set
s: The string to create the acronym from.
"""
def _make_acro(s, t=0):
"""Make an acronym of s for trial t"""
# Really should cache these ...
v = ['a', 'e', 'i', 'o', 'u', 'y']
c = [chr(x) for x in six_xrange(ord('a'), ord('z') + 1) if chr(x) not in v]
s = re.sub(r'\W+', '', s.lower())
vx = [x for x in s if x in v] # Vowels in input string
cx = [x for x in s if x in c] # Consonants in input string
if s.startswith('Mc'):
if t < 1:
return 'Mc' + v[0]
if t < 2:
return 'Mc' + c[0]
if s[0] in v: # Starts with a vowel
if t < 1:
return vx[0] + cx[0] + cx[1]
if t < 2:
return vx[0] + vx[1] + cx[0]
if s[0] in c and s[1] in c: # Two first consonants
if t < 1:
return cx[0] + cx[1] + vx[0]
if t < 2:
return cx[0] + cx[1] + cx[2]
if t < 3:
return cx[0] + vx[0] + cx[1]
if t < 4:
return cx[0] + cx[1] + cx[2]
if t < 5:
return cx[0] + vx[0] + vx[1]
if t < 6:
return cx[0] + cx[1] + cx[-1]
# These are punts; just take a substring
if t < 7:
return s[0:3]
if t < 8:
return s[1:4]
if t < 9:
return s[2:5]
if t < 10:
return s[3:6]
return None
for t in six_xrange(11): # Try multiple forms until one isn't in the past acronyms
try:
a = _make_acro(s, t)
if a is not None:
if prefix:
aps = prefix + a
else:
aps = a
if aps not in past:
past.add(aps)
return a
except IndexError:
pass
raise Exception('Could not get acronym.') | python | def make_acro(past, prefix, s): # pragma: no cover
"""Create a three letter acronym from the input string s.
Args:
past: A set object, for storing acronyms that have already been created
prefix: A prefix added to the acronym before storing in the set
s: The string to create the acronym from.
"""
def _make_acro(s, t=0):
"""Make an acronym of s for trial t"""
# Really should cache these ...
v = ['a', 'e', 'i', 'o', 'u', 'y']
c = [chr(x) for x in six_xrange(ord('a'), ord('z') + 1) if chr(x) not in v]
s = re.sub(r'\W+', '', s.lower())
vx = [x for x in s if x in v] # Vowels in input string
cx = [x for x in s if x in c] # Consonants in input string
if s.startswith('Mc'):
if t < 1:
return 'Mc' + v[0]
if t < 2:
return 'Mc' + c[0]
if s[0] in v: # Starts with a vowel
if t < 1:
return vx[0] + cx[0] + cx[1]
if t < 2:
return vx[0] + vx[1] + cx[0]
if s[0] in c and s[1] in c: # Two first consonants
if t < 1:
return cx[0] + cx[1] + vx[0]
if t < 2:
return cx[0] + cx[1] + cx[2]
if t < 3:
return cx[0] + vx[0] + cx[1]
if t < 4:
return cx[0] + cx[1] + cx[2]
if t < 5:
return cx[0] + vx[0] + vx[1]
if t < 6:
return cx[0] + cx[1] + cx[-1]
# These are punts; just take a substring
if t < 7:
return s[0:3]
if t < 8:
return s[1:4]
if t < 9:
return s[2:5]
if t < 10:
return s[3:6]
return None
for t in six_xrange(11): # Try multiple forms until one isn't in the past acronyms
try:
a = _make_acro(s, t)
if a is not None:
if prefix:
aps = prefix + a
else:
aps = a
if aps not in past:
past.add(aps)
return a
except IndexError:
pass
raise Exception('Could not get acronym.') | [
"def",
"make_acro",
"(",
"past",
",",
"prefix",
",",
"s",
")",
":",
"# pragma: no cover",
"def",
"_make_acro",
"(",
"s",
",",
"t",
"=",
"0",
")",
":",
"\"\"\"Make an acronym of s for trial t\"\"\"",
"# Really should cache these ...",
"v",
"=",
"[",
"'a'",
",",
... | Create a three letter acronym from the input string s.
Args:
past: A set object, for storing acronyms that have already been created
prefix: A prefix added to the acronym before storing in the set
s: The string to create the acronym from. | [
"Create",
"a",
"three",
"letter",
"acronym",
"from",
"the",
"input",
"string",
"s",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L656-L737 |
CivicSpleen/ambry | ambry/util/__init__.py | ensure_dir_exists | def ensure_dir_exists(path):
"""Given a file, ensure that the path to the file exists"""
import os
f_dir = os.path.dirname(path)
if not os.path.exists(f_dir):
os.makedirs(f_dir)
return f_dir | python | def ensure_dir_exists(path):
"""Given a file, ensure that the path to the file exists"""
import os
f_dir = os.path.dirname(path)
if not os.path.exists(f_dir):
os.makedirs(f_dir)
return f_dir | [
"def",
"ensure_dir_exists",
"(",
"path",
")",
":",
"import",
"os",
"f_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"f_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"f_dir",
")",
... | Given a file, ensure that the path to the file exists | [
"Given",
"a",
"file",
"ensure",
"that",
"the",
"path",
"to",
"the",
"file",
"exists"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L740-L750 |
CivicSpleen/ambry | ambry/util/__init__.py | walk_dict | def walk_dict(d):
"""Walk a tree (nested dicts).
For each 'path', or dict, in the tree, returns a 3-tuple containing:
(path, sub-dicts, values)
where:
* path is the path to the dict
* sub-dicts is a tuple of (key,dict) pairs for each sub-dict in this dict
* values is a tuple of (key,value) pairs for each (non-dict) item in this dict
"""
# nested dict keys
nested_keys = tuple(k for k in list(d.keys()) if isinstance(d[k], dict))
# key/value pairs for non-dicts
items = tuple((k, d[k]) for k in list(d.keys()) if k not in nested_keys)
# return path, key/sub-dict pairs, and key/value pairs
yield ('/', [(k, d[k]) for k in nested_keys], items)
# recurse each subdict
for k in nested_keys:
for res in walk_dict(d[k]):
# for each result, stick key in path and pass on
res = ('/%s' % k + res[0], res[1], res[2])
yield res | python | def walk_dict(d):
"""Walk a tree (nested dicts).
For each 'path', or dict, in the tree, returns a 3-tuple containing:
(path, sub-dicts, values)
where:
* path is the path to the dict
* sub-dicts is a tuple of (key,dict) pairs for each sub-dict in this dict
* values is a tuple of (key,value) pairs for each (non-dict) item in this dict
"""
# nested dict keys
nested_keys = tuple(k for k in list(d.keys()) if isinstance(d[k], dict))
# key/value pairs for non-dicts
items = tuple((k, d[k]) for k in list(d.keys()) if k not in nested_keys)
# return path, key/sub-dict pairs, and key/value pairs
yield ('/', [(k, d[k]) for k in nested_keys], items)
# recurse each subdict
for k in nested_keys:
for res in walk_dict(d[k]):
# for each result, stick key in path and pass on
res = ('/%s' % k + res[0], res[1], res[2])
yield res | [
"def",
"walk_dict",
"(",
"d",
")",
":",
"# nested dict keys",
"nested_keys",
"=",
"tuple",
"(",
"k",
"for",
"k",
"in",
"list",
"(",
"d",
".",
"keys",
"(",
")",
")",
"if",
"isinstance",
"(",
"d",
"[",
"k",
"]",
",",
"dict",
")",
")",
"# key/value pa... | Walk a tree (nested dicts).
For each 'path', or dict, in the tree, returns a 3-tuple containing:
(path, sub-dicts, values)
where:
* path is the path to the dict
* sub-dicts is a tuple of (key,dict) pairs for each sub-dict in this dict
* values is a tuple of (key,value) pairs for each (non-dict) item in this dict | [
"Walk",
"a",
"tree",
"(",
"nested",
"dicts",
")",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L753-L778 |
CivicSpleen/ambry | ambry/util/__init__.py | init_log_rate | def init_log_rate(output_f, N=None, message='', print_rate=None):
"""Initialze the log_rate function. Returnas a partial function to call for
each event.
If N is not specified but print_rate is specified, the initial N is
set to 100, and after the first message, the N value is adjusted to
emit print_rate messages per second
"""
if print_rate and not N:
N = 100
if not N:
N = 5000
d = [0, # number of items processed
time(), # start time. This one gets replaced after first message
N, # ticker to next message
N, # frequency to log a message
message,
print_rate,
deque([], maxlen=4) # Deque for averaging last N rates
]
assert isinstance(output_f, Callable)
f = partial(_log_rate, output_f, d)
f.always = output_f
f.count = lambda: d[0]
return f | python | def init_log_rate(output_f, N=None, message='', print_rate=None):
"""Initialze the log_rate function. Returnas a partial function to call for
each event.
If N is not specified but print_rate is specified, the initial N is
set to 100, and after the first message, the N value is adjusted to
emit print_rate messages per second
"""
if print_rate and not N:
N = 100
if not N:
N = 5000
d = [0, # number of items processed
time(), # start time. This one gets replaced after first message
N, # ticker to next message
N, # frequency to log a message
message,
print_rate,
deque([], maxlen=4) # Deque for averaging last N rates
]
assert isinstance(output_f, Callable)
f = partial(_log_rate, output_f, d)
f.always = output_f
f.count = lambda: d[0]
return f | [
"def",
"init_log_rate",
"(",
"output_f",
",",
"N",
"=",
"None",
",",
"message",
"=",
"''",
",",
"print_rate",
"=",
"None",
")",
":",
"if",
"print_rate",
"and",
"not",
"N",
":",
"N",
"=",
"100",
"if",
"not",
"N",
":",
"N",
"=",
"5000",
"d",
"=",
... | Initialze the log_rate function. Returnas a partial function to call for
each event.
If N is not specified but print_rate is specified, the initial N is
set to 100, and after the first message, the N value is adjusted to
emit print_rate messages per second | [
"Initialze",
"the",
"log_rate",
"function",
".",
"Returnas",
"a",
"partial",
"function",
"to",
"call",
"for",
"each",
"event",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L781-L812 |
CivicSpleen/ambry | ambry/util/__init__.py | _log_rate | def _log_rate(output_f, d, message=None):
"""Log a message for the Nth time the method is called.
d is the object returned from init_log_rate
"""
if d[2] <= 0:
if message is None:
message = d[4]
# Average the rate over the length of the deque.
d[6].append(int(d[3] / (time() - d[1])))
rate = sum(d[6]) / len(d[6])
# Prints the processing rate in 1,000 records per sec.
output_f(message + ': ' + str(rate) + '/s ' + str(d[0] / 1000) + 'K ')
d[1] = time()
# If the print_rate was specified, adjust the number of records to
# aproximate that rate.
if d[5]:
target_rate = rate * d[5]
d[3] = int((target_rate + d[3]) / 2)
d[2] = d[3]
d[0] += 1
d[2] -= 1 | python | def _log_rate(output_f, d, message=None):
"""Log a message for the Nth time the method is called.
d is the object returned from init_log_rate
"""
if d[2] <= 0:
if message is None:
message = d[4]
# Average the rate over the length of the deque.
d[6].append(int(d[3] / (time() - d[1])))
rate = sum(d[6]) / len(d[6])
# Prints the processing rate in 1,000 records per sec.
output_f(message + ': ' + str(rate) + '/s ' + str(d[0] / 1000) + 'K ')
d[1] = time()
# If the print_rate was specified, adjust the number of records to
# aproximate that rate.
if d[5]:
target_rate = rate * d[5]
d[3] = int((target_rate + d[3]) / 2)
d[2] = d[3]
d[0] += 1
d[2] -= 1 | [
"def",
"_log_rate",
"(",
"output_f",
",",
"d",
",",
"message",
"=",
"None",
")",
":",
"if",
"d",
"[",
"2",
"]",
"<=",
"0",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"d",
"[",
"4",
"]",
"# Average the rate over the length of the deque.",
... | Log a message for the Nth time the method is called.
d is the object returned from init_log_rate | [
"Log",
"a",
"message",
"for",
"the",
"Nth",
"time",
"the",
"method",
"is",
"called",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L815-L845 |
CivicSpleen/ambry | ambry/util/__init__.py | count_open_fds | def count_open_fds():
"""return the number of open file descriptors for current process.
.. warning: will only work on UNIX-like os-es.
http://stackoverflow.com/a/7142094
"""
pid = os.getpid()
procs = subprocess.check_output(
['lsof', '-w', '-Ff', '-p', str(pid)])
nprocs = len(
[s for s in procs.split('\n') if s and s[0] == 'f' and s[1:].isdigit()]
)
return nprocs | python | def count_open_fds():
"""return the number of open file descriptors for current process.
.. warning: will only work on UNIX-like os-es.
http://stackoverflow.com/a/7142094
"""
pid = os.getpid()
procs = subprocess.check_output(
['lsof', '-w', '-Ff', '-p', str(pid)])
nprocs = len(
[s for s in procs.split('\n') if s and s[0] == 'f' and s[1:].isdigit()]
)
return nprocs | [
"def",
"count_open_fds",
"(",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"procs",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'lsof'",
",",
"'-w'",
",",
"'-Ff'",
",",
"'-p'",
",",
"str",
"(",
"pid",
")",
"]",
")",
"nprocs",
"=",
... | return the number of open file descriptors for current process.
.. warning: will only work on UNIX-like os-es.
http://stackoverflow.com/a/7142094 | [
"return",
"the",
"number",
"of",
"open",
"file",
"descriptors",
"for",
"current",
"process",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L917-L933 |
CivicSpleen/ambry | ambry/util/__init__.py | parse_url_to_dict | def parse_url_to_dict(url):
"""Parse a url and return a dict with keys for all of the parts.
The urlparse function() returns a wacky combination of a namedtuple
with properties.
"""
p = urlparse(url)
return {
'scheme': p.scheme,
'netloc': p.netloc,
'path': p.path,
'params': p.params,
'query': p.query,
'fragment': p.fragment,
'username': p.username,
'password': p.password,
'hostname': p.hostname,
'port': p.port
} | python | def parse_url_to_dict(url):
"""Parse a url and return a dict with keys for all of the parts.
The urlparse function() returns a wacky combination of a namedtuple
with properties.
"""
p = urlparse(url)
return {
'scheme': p.scheme,
'netloc': p.netloc,
'path': p.path,
'params': p.params,
'query': p.query,
'fragment': p.fragment,
'username': p.username,
'password': p.password,
'hostname': p.hostname,
'port': p.port
} | [
"def",
"parse_url_to_dict",
"(",
"url",
")",
":",
"p",
"=",
"urlparse",
"(",
"url",
")",
"return",
"{",
"'scheme'",
":",
"p",
".",
"scheme",
",",
"'netloc'",
":",
"p",
".",
"netloc",
",",
"'path'",
":",
"p",
".",
"path",
",",
"'params'",
":",
"p",
... | Parse a url and return a dict with keys for all of the parts.
The urlparse function() returns a wacky combination of a namedtuple
with properties. | [
"Parse",
"a",
"url",
"and",
"return",
"a",
"dict",
"with",
"keys",
"for",
"all",
"of",
"the",
"parts",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L936-L956 |
CivicSpleen/ambry | ambry/util/__init__.py | set_url_part | def set_url_part(url, **kwargs):
"""Change one or more parts of a URL"""
d = parse_url_to_dict(url)
d.update(kwargs)
return unparse_url_dict(d) | python | def set_url_part(url, **kwargs):
"""Change one or more parts of a URL"""
d = parse_url_to_dict(url)
d.update(kwargs)
return unparse_url_dict(d) | [
"def",
"set_url_part",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"parse_url_to_dict",
"(",
"url",
")",
"d",
".",
"update",
"(",
"kwargs",
")",
"return",
"unparse_url_dict",
"(",
"d",
")"
] | Change one or more parts of a URL | [
"Change",
"one",
"or",
"more",
"parts",
"of",
"a",
"URL"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L987-L993 |
CivicSpleen/ambry | ambry/util/__init__.py | filter_url | def filter_url(url, **kwargs):
"""filter a URL by returning a URL with only the parts specified in the keywords"""
d = parse_url_to_dict(url)
d.update(kwargs)
return unparse_url_dict({k: v for k, v in list(d.items()) if v}) | python | def filter_url(url, **kwargs):
"""filter a URL by returning a URL with only the parts specified in the keywords"""
d = parse_url_to_dict(url)
d.update(kwargs)
return unparse_url_dict({k: v for k, v in list(d.items()) if v}) | [
"def",
"filter_url",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"parse_url_to_dict",
"(",
"url",
")",
"d",
".",
"update",
"(",
"kwargs",
")",
"return",
"unparse_url_dict",
"(",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"list",
... | filter a URL by returning a URL with only the parts specified in the keywords | [
"filter",
"a",
"URL",
"by",
"returning",
"a",
"URL",
"with",
"only",
"the",
"parts",
"specified",
"in",
"the",
"keywords"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L996-L1003 |
CivicSpleen/ambry | ambry/util/__init__.py | print_yaml | def print_yaml(o):
"""Pretty print an object as YAML."""
print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8')) | python | def print_yaml(o):
"""Pretty print an object as YAML."""
print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8')) | [
"def",
"print_yaml",
"(",
"o",
")",
":",
"print",
"(",
"yaml",
".",
"dump",
"(",
"o",
",",
"default_flow_style",
"=",
"False",
",",
"indent",
"=",
"4",
",",
"encoding",
"=",
"'utf-8'",
")",
")"
] | Pretty print an object as YAML. | [
"Pretty",
"print",
"an",
"object",
"as",
"YAML",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L1016-L1018 |
CivicSpleen/ambry | ambry/util/__init__.py | qualified_class_name | def qualified_class_name(o):
"""Full name of an object, including the module"""
module = o.__class__.__module__
if module is None or module == str.__class__.__module__:
return o.__class__.__name__
return module + '.' + o.__class__.__name__ | python | def qualified_class_name(o):
"""Full name of an object, including the module"""
module = o.__class__.__module__
if module is None or module == str.__class__.__module__:
return o.__class__.__name__
return module + '.' + o.__class__.__name__ | [
"def",
"qualified_class_name",
"(",
"o",
")",
":",
"module",
"=",
"o",
".",
"__class__",
".",
"__module__",
"if",
"module",
"is",
"None",
"or",
"module",
"==",
"str",
".",
"__class__",
".",
"__module__",
":",
"return",
"o",
".",
"__class__",
".",
"__name... | Full name of an object, including the module | [
"Full",
"name",
"of",
"an",
"object",
"including",
"the",
"module"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L1021-L1026 |
CivicSpleen/ambry | ambry/util/__init__.py | qualified_name | def qualified_name(cls):
"""Full name of a class, including the module. Like qualified_class_name, but when you already have a class """
module = cls.__module__
if module is None or module == str.__class__.__module__:
return cls.__name__
return module + '.' + cls.__name__ | python | def qualified_name(cls):
"""Full name of a class, including the module. Like qualified_class_name, but when you already have a class """
module = cls.__module__
if module is None or module == str.__class__.__module__:
return cls.__name__
return module + '.' + cls.__name__ | [
"def",
"qualified_name",
"(",
"cls",
")",
":",
"module",
"=",
"cls",
".",
"__module__",
"if",
"module",
"is",
"None",
"or",
"module",
"==",
"str",
".",
"__class__",
".",
"__module__",
":",
"return",
"cls",
".",
"__name__",
"return",
"module",
"+",
"'.'",... | Full name of a class, including the module. Like qualified_class_name, but when you already have a class | [
"Full",
"name",
"of",
"a",
"class",
"including",
"the",
"module",
".",
"Like",
"qualified_class_name",
"but",
"when",
"you",
"already",
"have",
"a",
"class"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L1029-L1034 |
CivicSpleen/ambry | ambry/util/__init__.py | qualified_name_import | def qualified_name_import(cls):
"""Full name of a class, including the module. Like qualified_class_name, but when you already have a class """
parts = qualified_name(cls).split('.')
return "from {} import {}".format('.'.join(parts[:-1]), parts[-1]) | python | def qualified_name_import(cls):
"""Full name of a class, including the module. Like qualified_class_name, but when you already have a class """
parts = qualified_name(cls).split('.')
return "from {} import {}".format('.'.join(parts[:-1]), parts[-1]) | [
"def",
"qualified_name_import",
"(",
"cls",
")",
":",
"parts",
"=",
"qualified_name",
"(",
"cls",
")",
".",
"split",
"(",
"'.'",
")",
"return",
"\"from {} import {}\"",
".",
"format",
"(",
"'.'",
".",
"join",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",... | Full name of a class, including the module. Like qualified_class_name, but when you already have a class | [
"Full",
"name",
"of",
"a",
"class",
"including",
"the",
"module",
".",
"Like",
"qualified_class_name",
"but",
"when",
"you",
"already",
"have",
"a",
"class"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L1036-L1041 |
CivicSpleen/ambry | ambry/util/__init__.py | drop_empty | def drop_empty(rows):
"""Transpose the columns into rows, remove all of the rows that are empty after the first cell, then
transpose back. The result is that columns that have a header but no data in the body are removed, assuming
the header is the first row. """
return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))]) | python | def drop_empty(rows):
"""Transpose the columns into rows, remove all of the rows that are empty after the first cell, then
transpose back. The result is that columns that have a header but no data in the body are removed, assuming
the header is the first row. """
return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))]) | [
"def",
"drop_empty",
"(",
"rows",
")",
":",
"return",
"zip",
"(",
"*",
"[",
"col",
"for",
"col",
"in",
"zip",
"(",
"*",
"rows",
")",
"if",
"bool",
"(",
"filter",
"(",
"bool",
",",
"col",
"[",
"1",
":",
"]",
")",
")",
"]",
")"
] | Transpose the columns into rows, remove all of the rows that are empty after the first cell, then
transpose back. The result is that columns that have a header but no data in the body are removed, assuming
the header is the first row. | [
"Transpose",
"the",
"columns",
"into",
"rows",
"remove",
"all",
"of",
"the",
"rows",
"that",
"are",
"empty",
"after",
"the",
"first",
"cell",
"then",
"transpose",
"back",
".",
"The",
"result",
"is",
"that",
"columns",
"that",
"have",
"a",
"header",
"but",
... | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L1184-L1188 |
CivicSpleen/ambry | ambry/util/__init__.py | pretty_time | def pretty_time(s, granularity=3):
"""Pretty print time in seconds. COnverts the input time in seconds into a string with
interval names, such as days, hours and minutes
From:
http://stackoverflow.com/a/24542445/1144479
"""
intervals = (
('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60
('minutes', 60),
('seconds', 1),
)
def display_time(seconds, granularity=granularity):
result = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append('{} {}'.format(int(value), name))
return ', '.join(result[:granularity])
return display_time(s, granularity) | python | def pretty_time(s, granularity=3):
"""Pretty print time in seconds. COnverts the input time in seconds into a string with
interval names, such as days, hours and minutes
From:
http://stackoverflow.com/a/24542445/1144479
"""
intervals = (
('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60
('minutes', 60),
('seconds', 1),
)
def display_time(seconds, granularity=granularity):
result = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append('{} {}'.format(int(value), name))
return ', '.join(result[:granularity])
return display_time(s, granularity) | [
"def",
"pretty_time",
"(",
"s",
",",
"granularity",
"=",
"3",
")",
":",
"intervals",
"=",
"(",
"(",
"'weeks'",
",",
"604800",
")",
",",
"# 60 * 60 * 24 * 7",
"(",
"'days'",
",",
"86400",
")",
",",
"# 60 * 60 * 24",
"(",
"'hours'",
",",
"3600",
")",
","... | Pretty print time in seconds. COnverts the input time in seconds into a string with
interval names, such as days, hours and minutes
From:
http://stackoverflow.com/a/24542445/1144479 | [
"Pretty",
"print",
"time",
"in",
"seconds",
".",
"COnverts",
"the",
"input",
"time",
"in",
"seconds",
"into",
"a",
"string",
"with",
"interval",
"names",
"such",
"as",
"days",
"hours",
"and",
"minutes"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L1205-L1235 |
CivicSpleen/ambry | ambry/util/__init__.py | delete_module | def delete_module(modname, paranoid=None):
""" Delete a module.http://stackoverflow.com/a/1668289
:param modname:
:param paranoid:
:return:
"""
from sys import modules
try:
thismod = modules[modname]
except KeyError:
raise ValueError(modname)
these_symbols = dir(thismod)
if paranoid:
try:
paranoid[:] # sequence support
except:
raise ValueError('must supply a finite list for paranoid')
else:
these_symbols = paranoid[:]
del modules[modname]
for mod in modules.values():
try:
delattr(mod, modname)
except AttributeError:
pass
if paranoid:
for symbol in these_symbols:
if symbol[:2] == '__': # ignore special symbols
continue
try:
delattr(mod, symbol)
except AttributeError:
pass | python | def delete_module(modname, paranoid=None):
""" Delete a module.http://stackoverflow.com/a/1668289
:param modname:
:param paranoid:
:return:
"""
from sys import modules
try:
thismod = modules[modname]
except KeyError:
raise ValueError(modname)
these_symbols = dir(thismod)
if paranoid:
try:
paranoid[:] # sequence support
except:
raise ValueError('must supply a finite list for paranoid')
else:
these_symbols = paranoid[:]
del modules[modname]
for mod in modules.values():
try:
delattr(mod, modname)
except AttributeError:
pass
if paranoid:
for symbol in these_symbols:
if symbol[:2] == '__': # ignore special symbols
continue
try:
delattr(mod, symbol)
except AttributeError:
pass | [
"def",
"delete_module",
"(",
"modname",
",",
"paranoid",
"=",
"None",
")",
":",
"from",
"sys",
"import",
"modules",
"try",
":",
"thismod",
"=",
"modules",
"[",
"modname",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"modname",
")",
"these_sy... | Delete a module.http://stackoverflow.com/a/1668289
:param modname:
:param paranoid:
:return: | [
"Delete",
"a",
"module",
".",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"1668289",
":",
"param",
"modname",
":",
":",
"param",
"paranoid",
":",
":",
"return",
":"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L1347-L1379 |
CivicSpleen/ambry | ambry/util/__init__.py | Proxy._create_class_proxy | def _create_class_proxy(cls, theclass):
"""creates a proxy for the given class"""
def make_method(name):
def method(self, *args, **kw):
return getattr(object.__getattribute__(self, "_obj"), name)(*args, **kw)
return method
namespace = {}
for name in cls._special_names:
if hasattr(theclass, name):
namespace[name] = make_method(name)
return type("%s(%s)" % (cls.__name__, theclass.__name__), (cls,), namespace) | python | def _create_class_proxy(cls, theclass):
"""creates a proxy for the given class"""
def make_method(name):
def method(self, *args, **kw):
return getattr(object.__getattribute__(self, "_obj"), name)(*args, **kw)
return method
namespace = {}
for name in cls._special_names:
if hasattr(theclass, name):
namespace[name] = make_method(name)
return type("%s(%s)" % (cls.__name__, theclass.__name__), (cls,), namespace) | [
"def",
"_create_class_proxy",
"(",
"cls",
",",
"theclass",
")",
":",
"def",
"make_method",
"(",
"name",
")",
":",
"def",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"getattr",
"(",
"object",
".",
"__getattribute__"... | creates a proxy for the given class | [
"creates",
"a",
"proxy",
"for",
"the",
"given",
"class"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L1312-L1324 |
trickvi/economics | economics/inflation.py | Inflation._compute_inflation | def _compute_inflation(value, reference_value):
"""
Helper function to compute the inflation/deflation based on a value and
a reference value
"""
res = value / float(reference_value)
return InflationResult(factor=res, value=res - 1) | python | def _compute_inflation(value, reference_value):
"""
Helper function to compute the inflation/deflation based on a value and
a reference value
"""
res = value / float(reference_value)
return InflationResult(factor=res, value=res - 1) | [
"def",
"_compute_inflation",
"(",
"value",
",",
"reference_value",
")",
":",
"res",
"=",
"value",
"/",
"float",
"(",
"reference_value",
")",
"return",
"InflationResult",
"(",
"factor",
"=",
"res",
",",
"value",
"=",
"res",
"-",
"1",
")"
] | Helper function to compute the inflation/deflation based on a value and
a reference value | [
"Helper",
"function",
"to",
"compute",
"the",
"inflation",
"/",
"deflation",
"based",
"on",
"a",
"value",
"and",
"a",
"reference",
"value"
] | train | https://github.com/trickvi/economics/blob/18da5ce7169472ca1ba6022272a389b933f76edd/economics/inflation.py#L46-L52 |
trickvi/economics | economics/inflation.py | Inflation.get | def get(self, reference, country, target=datetime.date.today()):
"""
Get the inflation/deflation value change for the target date based
on the reference date. Target defaults to today and the instance's
reference and country will be used if they are not provided as
parameters
"""
# Set country & reference to object's country & reference respectively
reference = self.reference if reference is None else reference
# Get the reference and target indices (values) from the source
reference_value = self.data.get(reference, country).value
target_value = self.data.get(target, country).value
# Compute the inflation value and return it
return self._compute_inflation(target_value, reference_value) | python | def get(self, reference, country, target=datetime.date.today()):
"""
Get the inflation/deflation value change for the target date based
on the reference date. Target defaults to today and the instance's
reference and country will be used if they are not provided as
parameters
"""
# Set country & reference to object's country & reference respectively
reference = self.reference if reference is None else reference
# Get the reference and target indices (values) from the source
reference_value = self.data.get(reference, country).value
target_value = self.data.get(target, country).value
# Compute the inflation value and return it
return self._compute_inflation(target_value, reference_value) | [
"def",
"get",
"(",
"self",
",",
"reference",
",",
"country",
",",
"target",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
":",
"# Set country & reference to object's country & reference respectively",
"reference",
"=",
"self",
".",
"reference",
"if",
... | Get the inflation/deflation value change for the target date based
on the reference date. Target defaults to today and the instance's
reference and country will be used if they are not provided as
parameters | [
"Get",
"the",
"inflation",
"/",
"deflation",
"value",
"change",
"for",
"the",
"target",
"date",
"based",
"on",
"the",
"reference",
"date",
".",
"Target",
"defaults",
"to",
"today",
"and",
"the",
"instance",
"s",
"reference",
"and",
"country",
"will",
"be",
... | train | https://github.com/trickvi/economics/blob/18da5ce7169472ca1ba6022272a389b933f76edd/economics/inflation.py#L54-L70 |
trickvi/economics | economics/inflation.py | Inflation.inflate | def inflate(self, amount, target=datetime.date.today(), reference=None,
country=None):
"""
Inflate a given amount to the target date from a reference date (or
the object's reference year if no reference date is provided) in a
given country (or objects country if no country is provided). The
amount has to be provided as it was valued in the reference year.
"""
country = country if country else self.country
# Get the inflation for the two dates and country
inflation = self.get(reference, country, target)
# Return the inflated/deflated amount
return amount * inflation.factor | python | def inflate(self, amount, target=datetime.date.today(), reference=None,
country=None):
"""
Inflate a given amount to the target date from a reference date (or
the object's reference year if no reference date is provided) in a
given country (or objects country if no country is provided). The
amount has to be provided as it was valued in the reference year.
"""
country = country if country else self.country
# Get the inflation for the two dates and country
inflation = self.get(reference, country, target)
# Return the inflated/deflated amount
return amount * inflation.factor | [
"def",
"inflate",
"(",
"self",
",",
"amount",
",",
"target",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
",",
"reference",
"=",
"None",
",",
"country",
"=",
"None",
")",
":",
"country",
"=",
"country",
"if",
"country",
"else",
"self",
".",
... | Inflate a given amount to the target date from a reference date (or
the object's reference year if no reference date is provided) in a
given country (or objects country if no country is provided). The
amount has to be provided as it was valued in the reference year. | [
"Inflate",
"a",
"given",
"amount",
"to",
"the",
"target",
"date",
"from",
"a",
"reference",
"date",
"(",
"or",
"the",
"object",
"s",
"reference",
"year",
"if",
"no",
"reference",
"date",
"is",
"provided",
")",
"in",
"a",
"given",
"country",
"(",
"or",
... | train | https://github.com/trickvi/economics/blob/18da5ce7169472ca1ba6022272a389b933f76edd/economics/inflation.py#L72-L85 |
SmartTeleMax/iktomi | iktomi/cli/base.py | manage | def manage(commands, argv=None, delim=':'):
'''
Parses argv and runs neccessary command. Is to be used in manage.py file.
Accept a dict with digest name as keys and instances of
:class:`Cli<iktomi.management.commands.Cli>`
objects as values.
The format of command is the following::
./manage.py digest_name:command_name[ arg1[ arg2[...]]][ --key1=kwarg1[...]]
where command_name is a part of digest instance method name, args and kwargs
are passed to the method. For details, see
:class:`Cli<iktomi.management.commands.Cli>` docs.
'''
commands = {(k.decode('utf-8') if isinstance(k, six.binary_type) else k): v
for k, v in commands.items()}
# Default django autocompletion script is registered to manage.py
# We use the same name for this script and it seems to be ok
# to implement the same interface
def perform_auto_complete(commands):
from .lazy import LazyCli
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ['COMP_CWORD'])
try:
curr = cwords[cword - 1]
except IndexError:
curr = ''
suggest = []
if len(cwords) > 1 and cwords[0] in commands.keys():
value = commands[cwords[0]]
if isinstance(value, LazyCli):
value = value.get_digest()
for cmd_name, _ in value.get_funcs():
cmd_name = cmd_name[8:]
suggest.append(cmd_name)
if curr == ":":
curr = ''
else:
suggest += list(commands.keys()) + [x+":" for x in commands.keys()]
suggest.sort()
output = u" ".join(filter(lambda x: x.startswith(curr), suggest))
sys.stdout.write(output)
auto_complete = 'IKTOMI_AUTO_COMPLETE' in os.environ or \
'DJANGO_AUTO_COMPLETE' in os.environ
if auto_complete:
perform_auto_complete(commands)
sys.exit(0)
argv = sys.argv if argv is None else argv
if len(argv) > 1:
cmd_name = argv[1]
raw_args = argv[2:]
args, kwargs = [], {}
# parsing params
for item in raw_args:
if item.startswith('--'):
splited = item[2:].split('=', 1)
if len(splited) == 2:
k,v = splited
elif len(splited) == 1:
k,v = splited[0], True
kwargs[k] = v
else:
args.append(item)
# trying to get command instance
if delim in cmd_name:
digest_name, command = cmd_name.split(delim)
else:
digest_name = cmd_name
command = None
try:
digest = commands[digest_name]
except KeyError:
_command_list(commands)
sys.exit('ERROR: Command "{}" not found'.format(digest_name))
try:
if command is None:
if isinstance(digest, Cli):
help_ = digest.description(argv[0], digest_name)
sys.stdout.write(help_)
sys.exit('ERROR: "{}" command digest requires command name'\
.format(digest_name))
digest(*args, **kwargs)
else:
digest(command, *args, **kwargs)
except CommandNotFound:
help_ = digest.description(argv[0], digest_name)
sys.stdout.write(help_)
sys.exit('ERROR: Command "{}:{}" not found'.format(digest_name, command))
else:
_command_list(commands)
sys.exit('Please provide any command') | python | def manage(commands, argv=None, delim=':'):
'''
Parses argv and runs neccessary command. Is to be used in manage.py file.
Accept a dict with digest name as keys and instances of
:class:`Cli<iktomi.management.commands.Cli>`
objects as values.
The format of command is the following::
./manage.py digest_name:command_name[ arg1[ arg2[...]]][ --key1=kwarg1[...]]
where command_name is a part of digest instance method name, args and kwargs
are passed to the method. For details, see
:class:`Cli<iktomi.management.commands.Cli>` docs.
'''
commands = {(k.decode('utf-8') if isinstance(k, six.binary_type) else k): v
for k, v in commands.items()}
# Default django autocompletion script is registered to manage.py
# We use the same name for this script and it seems to be ok
# to implement the same interface
def perform_auto_complete(commands):
from .lazy import LazyCli
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ['COMP_CWORD'])
try:
curr = cwords[cword - 1]
except IndexError:
curr = ''
suggest = []
if len(cwords) > 1 and cwords[0] in commands.keys():
value = commands[cwords[0]]
if isinstance(value, LazyCli):
value = value.get_digest()
for cmd_name, _ in value.get_funcs():
cmd_name = cmd_name[8:]
suggest.append(cmd_name)
if curr == ":":
curr = ''
else:
suggest += list(commands.keys()) + [x+":" for x in commands.keys()]
suggest.sort()
output = u" ".join(filter(lambda x: x.startswith(curr), suggest))
sys.stdout.write(output)
auto_complete = 'IKTOMI_AUTO_COMPLETE' in os.environ or \
'DJANGO_AUTO_COMPLETE' in os.environ
if auto_complete:
perform_auto_complete(commands)
sys.exit(0)
argv = sys.argv if argv is None else argv
if len(argv) > 1:
cmd_name = argv[1]
raw_args = argv[2:]
args, kwargs = [], {}
# parsing params
for item in raw_args:
if item.startswith('--'):
splited = item[2:].split('=', 1)
if len(splited) == 2:
k,v = splited
elif len(splited) == 1:
k,v = splited[0], True
kwargs[k] = v
else:
args.append(item)
# trying to get command instance
if delim in cmd_name:
digest_name, command = cmd_name.split(delim)
else:
digest_name = cmd_name
command = None
try:
digest = commands[digest_name]
except KeyError:
_command_list(commands)
sys.exit('ERROR: Command "{}" not found'.format(digest_name))
try:
if command is None:
if isinstance(digest, Cli):
help_ = digest.description(argv[0], digest_name)
sys.stdout.write(help_)
sys.exit('ERROR: "{}" command digest requires command name'\
.format(digest_name))
digest(*args, **kwargs)
else:
digest(command, *args, **kwargs)
except CommandNotFound:
help_ = digest.description(argv[0], digest_name)
sys.stdout.write(help_)
sys.exit('ERROR: Command "{}:{}" not found'.format(digest_name, command))
else:
_command_list(commands)
sys.exit('Please provide any command') | [
"def",
"manage",
"(",
"commands",
",",
"argv",
"=",
"None",
",",
"delim",
"=",
"':'",
")",
":",
"commands",
"=",
"{",
"(",
"k",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"k",
",",
"six",
".",
"binary_type",
")",
"else",
"k",
")... | Parses argv and runs neccessary command. Is to be used in manage.py file.
Accept a dict with digest name as keys and instances of
:class:`Cli<iktomi.management.commands.Cli>`
objects as values.
The format of command is the following::
./manage.py digest_name:command_name[ arg1[ arg2[...]]][ --key1=kwarg1[...]]
where command_name is a part of digest instance method name, args and kwargs
are passed to the method. For details, see
:class:`Cli<iktomi.management.commands.Cli>` docs. | [
"Parses",
"argv",
"and",
"runs",
"neccessary",
"command",
".",
"Is",
"to",
"be",
"used",
"in",
"manage",
".",
"py",
"file",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/base.py#L14-L114 |
SmartTeleMax/iktomi | iktomi/cli/base.py | Cli.description | def description(self, argv0='manage.py', command=None):
'''Description outputed to console'''
command = command or self.__class__.__name__.lower()
import inspect
_help = u''
_help += u'{}\n'.format(command)
if self.__doc__:
_help += self._fix_docstring(self.__doc__) +'\n'
else:
_help += u'{}\n'.format(command)
funcs = self.get_funcs()
funcs.sort(key=lambda x: six.get_function_code(x[1]).co_firstlineno)
for attr, func in funcs:
func = getattr(self, attr)
comm = attr.replace('command_', '', 1)
args = inspect.getargspec(func).args[1:]
args = (' [' + '] ['.join(args) + ']') if args else ''
_help += "\t{} {}:{}{}\n".format(
argv0, command, comm, args)
if func.__doc__:
_help += self._fix_docstring(func.__doc__, 2)
return _help | python | def description(self, argv0='manage.py', command=None):
'''Description outputed to console'''
command = command or self.__class__.__name__.lower()
import inspect
_help = u''
_help += u'{}\n'.format(command)
if self.__doc__:
_help += self._fix_docstring(self.__doc__) +'\n'
else:
_help += u'{}\n'.format(command)
funcs = self.get_funcs()
funcs.sort(key=lambda x: six.get_function_code(x[1]).co_firstlineno)
for attr, func in funcs:
func = getattr(self, attr)
comm = attr.replace('command_', '', 1)
args = inspect.getargspec(func).args[1:]
args = (' [' + '] ['.join(args) + ']') if args else ''
_help += "\t{} {}:{}{}\n".format(
argv0, command, comm, args)
if func.__doc__:
_help += self._fix_docstring(func.__doc__, 2)
return _help | [
"def",
"description",
"(",
"self",
",",
"argv0",
"=",
"'manage.py'",
",",
"command",
"=",
"None",
")",
":",
"command",
"=",
"command",
"or",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"import",
"inspect",
"_help",
"=",
"u''",
"_... | Description outputed to console | [
"Description",
"outputed",
"to",
"console"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/base.py#L139-L164 |
twisted/epsilon | doc/listings/amp/amp_auth_server.py | AdditionRealm.requestAvatar | def requestAvatar(self, avatarId, mind, *interfaces):
"""
Create Adder avatars for any IBoxReceiver request.
"""
if IBoxReceiver in interfaces:
return (IBoxReceiver, Adder(avatarId), lambda: None)
raise NotImplementedError() | python | def requestAvatar(self, avatarId, mind, *interfaces):
"""
Create Adder avatars for any IBoxReceiver request.
"""
if IBoxReceiver in interfaces:
return (IBoxReceiver, Adder(avatarId), lambda: None)
raise NotImplementedError() | [
"def",
"requestAvatar",
"(",
"self",
",",
"avatarId",
",",
"mind",
",",
"*",
"interfaces",
")",
":",
"if",
"IBoxReceiver",
"in",
"interfaces",
":",
"return",
"(",
"IBoxReceiver",
",",
"Adder",
"(",
"avatarId",
")",
",",
"lambda",
":",
"None",
")",
"raise... | Create Adder avatars for any IBoxReceiver request. | [
"Create",
"Adder",
"avatars",
"for",
"any",
"IBoxReceiver",
"request",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/doc/listings/amp/amp_auth_server.py#L52-L58 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.