index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
28,940 | yampex.options | set_colors |
Sets the list of colors. Call with no args to clear the list and
revert to default color scheme.
Supply a list of color codes, either as a single argument or
with one entry per argument.
| def set_colors(self, *args):
"""
Sets the list of colors. Call with no args to clear the list and
revert to default color scheme.
Supply a list of color codes, either as a single argument or
with one entry per argument.
"""
if len(args) == 1 and hasattr(args[0], '__iter__'):
args = args[0]
self.opts['colors'] = list(args)
| (self, *args) |
28,941 | yampex.options | set_firstVectorTop |
Has the first dependent vector (the second argument to the
L{Plotter} object call) determine the top (maximum) of the
displayed plot boundary.
| def set_firstVectorTop(self):
"""
Has the first dependent vector (the second argument to the
L{Plotter} object call) determine the top (maximum) of the
displayed plot boundary.
"""
self.opts['firstVectorTop'] = True
| (self) |
28,942 | yampex.options | set_fontsize |
Sets the I{fontsize} of the specified artist I{name}.
Recognized names are 'title', 'xlabel', 'ylabel', 'legend',
'annotations', and 'textbox'.
| def set_fontsize(self, name, fontsize):
"""
Sets the I{fontsize} of the specified artist I{name}.
Recognized names are 'title', 'xlabel', 'ylabel', 'legend',
'annotations', and 'textbox'.
"""
self.opts['fontsizes'][name] = fontsize
| (self, name, fontsize) |
28,943 | yampex.options | set_legend |
Sets the list of legend entries.
Supply a list of legend entries, either as a single argument
or with one entry per argument. You can set the I{fontsize}
keyword to the desired fontsize of the legend; the default is
'small'.
@see: L{add_legend}, L{clear_legend}.
| def set_legend(self, *args, **kw):
"""
Sets the list of legend entries.
Supply a list of legend entries, either as a single argument
or with one entry per argument. You can set the I{fontsize}
keyword to the desired fontsize of the legend; the default is
'small'.
@see: L{add_legend}, L{clear_legend}.
"""
if len(args) == 1 and hasattr(args[0], '__iter__'):
args = args[0]
self.opts['legend'] = list(args)
if 'fontsize' in kw:
self.opts['fontsizes']['legend'] = kw['fontsize']
| (self, *args, **kw) |
28,944 | yampex.options | set_tickSpacing |
Sets the major tick spacing for I{axisName} ("x" or "y"), and
minor tick spacing as well.
For each setting, an C{int} will set a maximum number of tick
intervals, and a C{float} will set a spacing between
intervals.
You can set I{minor} C{True} to have minor ticks set
automatically, or C{False} to have them turned off. (Major
ticks are set automatically by default, and cannot be turned
off.)
| def set_tickSpacing(self, axisName, major, minor=None):
"""
Sets the major tick spacing for I{axisName} ("x" or "y"), and
minor tick spacing as well.
For each setting, an C{int} will set a maximum number of tick
intervals, and a C{float} will set a spacing between
intervals.
You can set I{minor} C{True} to have minor ticks set
automatically, or C{False} to have them turned off. (Major
ticks are set automatically by default, and cannot be turned
off.)
"""
key = optkey(axisName, 'major')
self.opts['ticks'][key] = major
if minor is None: return
key = optkey(axisName, 'minor')
self.opts['ticks'][key] = minor
| (self, axisName, major, minor=None) |
28,945 | yampex.options | set_title |
Sets a title for all subplots (if called out of context) or for
just the present subplot (if called in context).
You may include a text I{proto}type with format-substitution
I{args}, or just supply the final text string with no further
arguments.
| def set_title(self, proto, *args):
"""
Sets a title for all subplots (if called out of context) or for
just the present subplot (if called in context).
You may include a text I{proto}type with format-substitution
I{args}, or just supply the final text string with no further
arguments.
"""
text = sub(proto, *args)
if self._isSubplot:
self.opts['title'] = text
else: self._figTitle = text
| (self, proto, *args) |
28,946 | yampex.options | set_xlabel |
Sets the x-axis label.
Ignored if time-x mode has been activated with a call to
L{set_timex}. If called out of context, on the L{Plotter}
instance, this x-label is used for all subplots and only
appears in the last (bottom) subplot of each column of
subplots.
| def set_xlabel(self, x):
"""
Sets the x-axis label.
Ignored if time-x mode has been activated with a call to
L{set_timex}. If called out of context, on the L{Plotter}
instance, this x-label is used for all subplots and only
appears in the last (bottom) subplot of each column of
subplots.
"""
self.opts['xlabel'] = x
if not self._isSubplot:
self._universal_xlabel = True
| (self, x) |
28,947 | yampex.options | set_ylabel |
Sets the y-axis label.
| def set_ylabel(self, x):
"""
Sets the y-axis label.
"""
self.opts['ylabel'] = x
| (self, x) |
28,948 | yampex.options | set_zeroBottom |
Sets the bottom (minimum) of the Y-axis range to zero, unless
called with C{False}.
This is useful for plotting values that are never negative and
where zero is a meaningful absolute minimum.
| def set_zeroBottom(self, yes=True):
"""
Sets the bottom (minimum) of the Y-axis range to zero, unless
called with C{False}.
This is useful for plotting values that are never negative and
where zero is a meaningful absolute minimum.
"""
self.opts['zeroBottom'] = yes
| (self, yes=True) |
28,949 | yampex.options | set_zeroLine |
Draws a horizontal line at the specified I{y} value (default is
y=0) if the Y-axis range includes that value.
If y is C{None} or C{False}, clears any previously set line.
@keyword color: Set the line color (default: black).
@keyword linestyle: Set the line type (default: '--').
@keyword linewidth: Set the line width (default: 1).
| def set_zeroLine(self, y=0, color="black", linestyle='--', linewidth=1):
"""
Draws a horizontal line at the specified I{y} value (default is
y=0) if the Y-axis range includes that value.
If y is C{None} or C{False}, clears any previously set line.
@keyword color: Set the line color (default: black).
@keyword linestyle: Set the line type (default: '--').
@keyword linewidth: Set the line width (default: 1).
"""
self.opts['zeroLine'] = {
'y': y,
'color': color,
'linestyle': linestyle,
'linewidth': linewidth,
}
| (self, y=0, color='black', linestyle='--', linewidth=1) |
28,950 | yampex.plot | show |
Call this to show the figure with suplots after the last call to
my instance.
If I have a non-C{None} I{fc} attribute (which must reference
an instance of Qt's C{FigureCanvas}, then the FigureCanvas is
drawn instead of PyPlot doing a window show.
You can supply an open file-like object for PNG data to be
written to (instead of a Matplotlib Figure being displayed)
with the I{fh} keyword. (It's up to you to close the file
object.)
Or, with the I{filePath} keyword, you can specify the file
path of a PNG file for me to create or overwrite. (That
overrides any I{filePath} you set in the constructor.)
| def show(self, windowTitle=None, fh=None, filePath=None, noShow=False):
"""
Call this to show the figure with suplots after the last call to
my instance.
If I have a non-C{None} I{fc} attribute (which must reference
an instance of Qt's C{FigureCanvas}, then the FigureCanvas is
drawn instead of PyPlot doing a window show.
You can supply an open file-like object for PNG data to be
written to (instead of a Matplotlib Figure being displayed)
with the I{fh} keyword. (It's up to you to close the file
object.)
Or, with the I{filePath} keyword, you can specify the file
path of a PNG file for me to create or overwrite. (That
overrides any I{filePath} you set in the constructor.)
"""
try:
self.fig.tight_layout()
except ValueError as e:
if self.verbose:
proto = "WARNING: ValueError '{}' doing tight_layout "+\
"on {:.5g} x {:.5g} figure"
print((sub(proto, e.message, self.width, self.height)))
self.subplots_adjust()
# Calling plt.draw massively slows things down when generating
# plot images on Rpi. And without it, the (un-annotated) plot
# still updates!
if False and self.annotators:
# This is not actually run, see above comment
self.plt.draw()
for annotator in list(self.annotators.values()):
if self.verbose: annotator.setVerbose()
annotator.update()
if fh is None:
if not filePath:
filePath = self.filePath
if filePath:
fh = open(filePath, 'wb+')
if fh is None:
self.plt.draw()
if windowTitle: self.fig.canvas.set_window_title(windowTitle)
if self.fc is not None: self.fc.draw()
elif not noShow: self.plt.show()
else:
self.fig.savefig(fh, format='png')
self.plt.close()
if filePath is not None:
# Only close a file handle I opened myself
fh.close()
if not noShow: self.clear()
| (self, windowTitle=None, fh=None, filePath=None, noShow=False) |
28,951 | yampex.plot | start |
An alternative to the context-manager way of using me. Just call
this method and a reference to myself as a subplotting tool
will be returned.
Call L{done} when finished, which is the same thing as exiting
my subplotting context.
| def start(self):
"""
An alternative to the context-manager way of using me. Just call
this method and a reference to myself as a subplotting tool
will be returned.
Call L{done} when finished, which is the same thing as exiting
my subplotting context.
"""
if self._isSubplot:
raise Exception("You are already in a subplotting context!")
return self.__enter__()
| (self) |
28,952 | yampex.plot | subplots_adjust |
Adjusts spacings.
| def subplots_adjust(self, *args):
"""
Adjusts spacings.
"""
dimThing = args[0] if args else self.fig.get_window_extent()
fWidth, fHeight = [getattr(dimThing, x) for x in ('width', 'height')]
self.adj.updateFigSize(fWidth, fHeight)
if self._figTitle:
kw = {
'm': 10,
'fontsize': self.fontsize('title', 14),
'alpha': 1.0,
'fDims': (fWidth, fHeight),
}
ax = self.fig.get_axes()[0]
if self.tbmTitle: self.tbmTitle.remove()
self.tbmTitle = TextBoxMaker(self.fig, **kw)("N", self._figTitle)
titleObj = self.tbmTitle.tList[0]
else: self.tbmTitle = titleObj = None
kw = self.adj(self._universal_xlabel, titleObj)
try:
self.fig.subplots_adjust(**kw)
except ValueError as e:
if self.verbose:
print((sub(
"WARNING: ValueError '{}' doing subplots_adjust({})",
e.message, ", ".join(
[sub("{}={}", x, kw[x]) for x in kw]))))
self.updateAnnotations()
| (self, *args) |
28,953 | yampex.plot | updateAnnotations |
Updates the positions of all annotations in an already-drawn plot.
When L{PlotHelper} calls this, it will supply the annotator
for its subplot.
| def updateAnnotations(self, annotator=None):
"""
Updates the positions of all annotations in an already-drawn plot.
When L{PlotHelper} calls this, it will supply the annotator
for its subplot.
"""
plt = self.plt
updated = False
if annotator is None:
for annotator in self.annotators.values():
if annotator.update():
updated = True
elif annotator.update(): updated = True
if updated:
# This raises a warning with newer matplotlib
#plt.pause(0.0001)
plt.draw()
| (self, annotator=None) |
28,954 | yampex.options | use_bump |
Bumps up the common y-axis upper limit to 120% of what Matplotlib
decides. Call with C{False} to disable the bump.
| def use_bump(self, yes=True):
"""
Bumps up the common y-axis upper limit to 120% of what Matplotlib
decides. Call with C{False} to disable the bump.
"""
self.opts['bump'] = yes
| (self, yes=True) |
28,955 | yampex.options | use_grid |
Adds a grid, unless called with C{False}.
The behavior this method is a little different than it used to
be. You can still enable a default grid by calling it with no
arguments, or turn off the grid entirely by supplying C{False}
as that sole argument. But now specifying a custom grid has
become a lot more powerful.
To turn gridlines on for just one axis's major tics, supply
that axis name as an argument followed by 'major'. (Not
case-sensitive.) For example, C{use_grid('x', 'major')}
enables only vertical grid lines at major tics of the 'x'
axis.
To turn gridlines on for both major and minor ticks, use
'both', like this: C{use_grid('both')}. Or, for major and
minor ticks on just the 'y' axis, for example, C{use_grid('y',
'both')}. You can also use the term 'minor' to have grid lines
just at minor ticks, though it's not evident why you would
want that as opposed to 'both'.
To have different grid lines for different axes, supply each
axis name followed by its tick specifier. For example, to have
horizontal grid lines at both major and minor ticks of the 'y'
axis but vertical lines just at major tick locations on the
'x' axis, do this:::
use_grid('x', 'both', 'y', 'major')
| def use_grid(self, *args):
"""
Adds a grid, unless called with C{False}.
The behavior this method is a little different than it used to
be. You can still enable a default grid by calling it with no
arguments, or turn off the grid entirely by supplying C{False}
as that sole argument. But now specifying a custom grid has
become a lot more powerful.
To turn gridlines on for just one axis's major tics, supply
that axis name as an argument followed by 'major'. (Not
case-sensitive.) For example, C{use_grid('x', 'major')}
enables only vertical grid lines at major tics of the 'x'
axis.
To turn gridlines on for both major and minor ticks, use
'both', like this: C{use_grid('both')}. Or, for major and
minor ticks on just the 'y' axis, for example, C{use_grid('y',
'both')}. You can also use the term 'minor' to have grid lines
just at minor ticks, though it's not evident why you would
want that as opposed to 'both'.
To have different grid lines for different axes, supply each
axis name followed by its tick specifier. For example, to have
horizontal grid lines at both major and minor ticks of the 'y'
axis but vertical lines just at major tick locations on the
'x' axis, do this:::
use_grid('x', 'both', 'y', 'major')
"""
x, y = self.opts['grid']
if not args:
# Default, no arg behavior
x = 'major'
y = 'major'
elif args[0]:
# Not just None or False
args = [x.lower() for x in args]
while args:
arg = args.pop(0)
if arg == 'x':
if args:
x = args.pop(0)
else: x = None
elif arg == 'y':
if args:
y = args.pop(0)
else: y = None
else:
x = y = arg
break
self.opts['grid'] = (x, y)
| (self, *args) |
28,956 | yampex.options | use_labels |
Has annotation labels point to each plot line instead of a legend,
with text taken from the legend list. (Works best in
interactive apps.)
Call with C{False} to revert to default legend-box behavior.
| def use_labels(self, yes=True):
"""
Has annotation labels point to each plot line instead of a legend,
with text taken from the legend list. (Works best in
interactive apps.)
Call with C{False} to revert to default legend-box behavior.
"""
self.opts['useLabels'] = yes
| (self, yes=True) |
28,957 | yampex.options | use_legend |
Has an automatic legend entry added for each plot line, unless
called with C{False}.
| def use_legend(self, yes=True):
"""
Has an automatic legend entry added for each plot line, unless
called with C{False}.
"""
self.opts['autolegend'] = yes
| (self, yes=True) |
28,958 | yampex.options | use_minorTicks |
Enables minor ticks for I{axisName} ("x" or "y", omit for
both). Call with C{False} after the I{axisName} to disable.
To enable with a specific tick spacing, supply a float instead
of just C{True}. Or, for a specific number of ticks, supply
that as an int.
Note that, due to a Matplotlib limitation, you can't enable
minor ticks for just one axis, although you can independently
set the tick spacings.
| def use_minorTicks(self, axisName=None, yes=True):
"""
Enables minor ticks for I{axisName} ("x" or "y", omit for
both). Call with C{False} after the I{axisName} to disable.
To enable with a specific tick spacing, supply a float instead
of just C{True}. Or, for a specific number of ticks, supply
that as an int.
Note that, due to a Matplotlib limitation, you can't enable
minor ticks for just one axis, although you can independently
set the tick spacings.
"""
if axisName is None:
for axisName in ('x', 'y'):
self.use_minorTicks(axisName, yes)
return
key = optkey(axisName, 'minor')
self.opts['ticks'][key] = yes
| (self, axisName=None, yes=True) |
28,959 | yampex.options | use_timex |
Uses intelligent time scaling for the x-axis, unless called with
C{False}.
If your x-axis is for time with units in seconds, you can call
this to have the X values rescaled to the most sensible units,
e.g., nanoseconds for values < 1E-6. Any I{xlabel} option is
disregarded in such case because the x label is set
automatically.
| def use_timex(self, yes=True):
"""
Uses intelligent time scaling for the x-axis, unless called with
C{False}.
If your x-axis is for time with units in seconds, you can call
this to have the X values rescaled to the most sensible units,
e.g., nanoseconds for values < 1E-6. Any I{xlabel} option is
disregarded in such case because the x label is set
automatically.
"""
self.opts['timex'] = yes
if not self._isSubplot:
self._universal_xlabel = True
| (self, yes=True) |
28,960 | yampex.plot | xBounds |
See L{Subplotter.xBounds}.
| def xBounds(self, *args, **kw):
"""
See L{Subplotter.xBounds}.
"""
self.sp.xBounds(*args, **kw)
| (self, *args, **kw) |
28,961 | yampex.plot | yBounds |
See L{Subplotter.yBounds}.
| def yBounds(self, *args, **kw):
"""
See L{Subplotter.yBounds}.
"""
self.sp.yBounds(*args, **kw)
| (self, *args, **kw) |
28,964 | contextlib | contextmanager | @contextmanager decorator.
Typical usage:
@contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>
This makes this:
with some_generator(<arguments>) as <variable>:
<body>
equivalent to this:
<setup>
try:
<variable> = <value>
<body>
finally:
<cleanup>
| def contextmanager(func):
"""@contextmanager decorator.
Typical usage:
@contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>
This makes this:
with some_generator(<arguments>) as <variable>:
<body>
equivalent to this:
<setup>
try:
<variable> = <value>
<body>
finally:
<cleanup>
"""
@wraps(func)
def helper(*args, **kwds):
return _GeneratorContextManager(func, args, kwds)
return helper
| (func) |
28,972 | yampex | xy |
A quick way to do a simple plot with a grid and zero-crossing
line. You can provide one or more vectors to plot as args. If two
or more, the first one will be used for the x axis.
@keyword plot: Set to the name of a plot type, e.g., "semilogy" if
a particular plot type is desired.
@keyword dots: Set C{True} to show a marker at each coordinate
pair.
@keyword figSize: Set to a 2-sequence with figure width and height
if not using the default, which is just shy of your entire
monitor size. Dimensions are in inches, converted to pixels at
100 DPI, unless both are integers and either exceeds 75. Then
they are considered to specify the pixel dimensions directly.
@keyword width: Specify the figure width part of I{figSize}.
@keyword height: Specify the figure height part of I{figSize}.
@see: L{xyc}, on which this function is based.
| def xy(*args, **kw):
"""
A quick way to do a simple plot with a grid and zero-crossing
line. You can provide one or more vectors to plot as args. If two
or more, the first one will be used for the x axis.
@keyword plot: Set to the name of a plot type, e.g., "semilogy" if
a particular plot type is desired.
@keyword dots: Set C{True} to show a marker at each coordinate
pair.
@keyword figSize: Set to a 2-sequence with figure width and height
if not using the default, which is just shy of your entire
monitor size. Dimensions are in inches, converted to pixels at
100 DPI, unless both are integers and either exceeds 75. Then
they are considered to specify the pixel dimensions directly.
@keyword width: Specify the figure width part of I{figSize}.
@keyword height: Specify the figure height part of I{figSize}.
@see: L{xyc}, on which this function is based.
"""
with xyc(*args, **kw) as sp:
pass
| (*args, **kw) |
28,973 | yampex | xyc |
Call L{xy} in context. Yields a L{SpecialAx} object for the
(single) subplot in context so you can add to it. Then shows the
plot.
| null | (*args, **kw) |
28,975 | sphinx_cache.setup | setup | null | def setup(app: Sphinx) -> Dict[str, Any]:
# Define config values
app.add_config_value("cache_store_path", ".cache/", "html", types=[str])
app.add_config_value("cache_doctree_path", "_build/.doctrees", "html", types=[str])
# Make connections to events
app.connect("config-inited", config_init)
app.connect("builder-inited", build_init)
app.connect("build-finished", write_cache)
return {
"version": __version__,
"parallel_read_safe": True,
"parallel_write_safe": True,
}
| (app: sphinx.application.Sphinx) -> Dict[str, Any] |
28,978 | aiomcache.client | Client | null | class Client(FlagClient[bytes]):
def __init__(self, host: str, port: int = 11211, *,
pool_size: int = 2, pool_minsize: Optional[int] = None,
conn_args: Optional[Mapping[str, Any]] = None):
super().__init__(host, port, pool_size=pool_size, pool_minsize=pool_minsize,
conn_args=conn_args,
get_flag_handler=None, set_flag_handler=None)
| (host: str, port: int = 11211, *, pool_size: int = 2, pool_minsize: Optional[int] = None, conn_args: Optional[Mapping[str, Any]] = None) |
28,979 | aiomcache.client | __init__ | null | def __init__(self, host: str, port: int = 11211, *,
pool_size: int = 2, pool_minsize: Optional[int] = None,
conn_args: Optional[Mapping[str, Any]] = None):
super().__init__(host, port, pool_size=pool_size, pool_minsize=pool_minsize,
conn_args=conn_args,
get_flag_handler=None, set_flag_handler=None)
| (self, host: str, port: int = 11211, *, pool_size: int = 2, pool_minsize: Optional[int] = None, conn_args: Optional[Mapping[str, Any]] = None) |
28,980 | aiomcache.client | _execute_simple_command | null | def _validate_key(self, key: bytes) -> bytes:
if not isinstance(key, bytes): # avoid bugs subtle and otherwise
raise ValidationException('key must be bytes', key)
# Must decode to str for unicode-aware comparison.
key_str = key.decode()
m = self._valid_key_re.match(key_str)
if m:
# in python re, $ matches either end of line or right before
# \n at end of line. We can't allow latter case, so
# making sure length matches is simplest way to detect
if len(m.group(0)) != len(key_str):
raise ValidationException('trailing newline', key)
else:
raise ValidationException('invalid key', key)
return key
| (self, conn: aiomcache.pool.Connection, raw_command: bytes) -> bytes |
28,981 | aiomcache.client | _incr_decr | null | @acquire
async def prepend(self, conn: Connection, key: bytes, value: bytes, exptime: int = 0) -> bool:
"""Add data to an existing key before existing data
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
"""
return await self._storage_command(conn, b"prepend", key, value, exptime)
| (self, conn: aiomcache.pool.Connection, command: bytes, key: bytes, delta: int) -> Optional[int] |
28,982 | aiomcache.client | _multi_get | null | @overload
async def _multi_get(self, conn: Connection, *keys: bytes,
with_cas: Literal[False]) -> _Result[_T, None]:
...
| (self, conn: aiomcache.pool.Connection, *keys: bytes, with_cas: bool = True) -> Tuple[Dict[bytes, Union[bytes, ~_T]], Dict[bytes, Optional[int]]] |
28,983 | aiomcache.client | _storage_command | null | @acquire
async def stats(
self, conn: Connection, args: Optional[bytes] = None
) -> Dict[bytes, Optional[bytes]]:
"""Runs a stats command on the server."""
# req - stats [additional args]\r\n
# resp - STAT <name> <value>\r\n (one per result)
# END\r\n
if args is None:
args = b''
conn.writer.write(b''.join((b'stats ', args, b'\r\n')))
result: Dict[bytes, Optional[bytes]] = {}
resp = await conn.reader.readline()
while resp != b'END\r\n':
terms = resp.split()
if len(terms) == 2 and terms[0] == b'STAT':
result[terms[1]] = None
elif len(terms) == 3 and terms[0] == b'STAT':
result[terms[1]] = terms[2]
elif len(terms) >= 3 and terms[0] == b'STAT':
result[terms[1]] = b' '.join(terms[2:])
else:
raise ClientException('stats failed', resp)
resp = await conn.reader.readline()
return result
| (self, conn: aiomcache.pool.Connection, command: bytes, key: bytes, value: Union[bytes, ~_T], exptime: int = 0, cas: Optional[int] = None) -> bool |
28,985 | aiomcache.client | add | Store this data, but only if the server *doesn't* already
hold data for this key.
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes, value: Union[bytes, ~_T], exptime: int = 0) -> bool |
28,986 | aiomcache.client | append | Add data to an existing key after existing data
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes, value: Union[bytes, ~_T], exptime: int = 0) -> bool |
28,987 | aiomcache.client | cas | Sets a key to a value on the server
with an optional exptime (0 means don't auto-expire)
only if value hasn't changed from first retrieval
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int``, is expiration time. If it's 0, the
item never expires.
:param cas_token: ``int``, unique cas token retrieve from previous
``gets``
:return: ``bool``, True in case of success.
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes, value: Union[bytes, ~_T], cas_token: int, exptime: int = 0) -> bool |
28,988 | aiomcache.client | close | Closes the sockets if its open. | def _validate_key(self, key: bytes) -> bytes:
if not isinstance(key, bytes): # avoid bugs subtle and otherwise
raise ValidationException('key must be bytes', key)
# Must decode to str for unicode-aware comparison.
key_str = key.decode()
m = self._valid_key_re.match(key_str)
if m:
# in python re, $ matches either end of line or right before
# \n at end of line. We can't allow latter case, so
# making sure length matches is simplest way to detect
if len(m.group(0)) != len(key_str):
raise ValidationException('trailing newline', key)
else:
raise ValidationException('invalid key', key)
return key
| (self) -> NoneType |
28,989 | aiomcache.client | decr | Command is used to change data for some item in-place,
decrementing it. The data for the item is treated as decimal
representation of a 64-bit unsigned integer.
:param key: ``bytes``, is the key of the item the client wishes
to change
:param decrement: ``int``, is the amount by which the client
wants to decrease the item.
:return: ``int`` new value of the item's data,
after the increment or ``None`` to indicate the item with
this value was not found
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes, decrement: int = 1) -> Optional[int] |
28,990 | aiomcache.client | delete | Deletes a key/value pair from the server.
:param key: is the key to delete.
:return: True if case values was deleted or False to indicate
that the item with this key was not found.
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes) -> bool |
28,991 | aiomcache.client | flush_all | Its effect is to invalidate all existing items immediately | def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection) -> NoneType |
28,992 | aiomcache.client | get | Gets a single value from the server.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, is the data for this specified key.
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, /, key: bytes, default: Optional[~_U] = None) -> Union[bytes, ~_T, ~_U, NoneType] |
28,993 | aiomcache.client | gets | Gets a single value from the server together with the cas token.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, ``bytes tuple with the value and the cas
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes, default: Optional[bytes] = None) -> Tuple[Union[bytes, ~_T, NoneType], Optional[int]] |
28,994 | aiomcache.client | incr | Command is used to change data for some item in-place,
incrementing it. The data for the item is treated as decimal
representation of a 64-bit unsigned integer.
:param key: ``bytes``, is the key of the item the client wishes
to change
:param increment: ``int``, is the amount by which the client
wants to increase the item.
:return: ``int``, new value of the item's data,
after the increment or ``None`` to indicate the item with
this value was not found
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes, increment: int = 1) -> Optional[int] |
28,995 | aiomcache.client | multi_get | Takes a list of keys and returns a list of values.
:param keys: ``list`` keys for the item being fetched.
:return: ``list`` of values for the specified keys.
:raises:``ValidationException``, ``ClientException``,
and socket errors
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, *keys: bytes) -> Tuple[Union[bytes, ~_T, NoneType], ...] |
28,996 | aiomcache.client | prepend | Add data to an existing key before existing data
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes, value: bytes, exptime: int = 0) -> bool |
28,997 | aiomcache.client | replace | Store this data, but only if the server *does*
already hold data for this key.
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes, value: Union[bytes, ~_T], exptime: int = 0) -> bool |
28,998 | aiomcache.client | set | Sets a key to a value on the server
with an optional exptime (0 means don't auto-expire)
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int``, is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes, value: Union[bytes, ~_T], exptime: int = 0) -> bool |
28,999 | aiomcache.client | stats | Runs a stats command on the server. | def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, args: Optional[bytes] = None) -> Dict[bytes, Optional[bytes]] |
29,000 | aiomcache.client | touch | The command is used to update the expiration time of
an existing item without fetching it.
:param key: ``bytes``, is the key to update expiration time
:param exptime: ``int``, is expiration time. This replaces the existing
expiration time.
:return: ``bool``, True in case of success.
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection, key: bytes, exptime: int) -> bool |
29,001 | aiomcache.client | version | Current version of the server.
:return: ``bytes``, memcached version for current the server.
| def acquire(
func: Callable[Concatenate[_Client, Connection, _P], Awaitable[_T]]
) -> Callable[Concatenate[_Client, _P], Awaitable[_T]]:
@functools.wraps(func)
async def wrapper(self: _Client, *args: _P.args, # type: ignore[misc]
**kwargs: _P.kwargs) -> _T:
conn = await self._pool.acquire()
try:
return await func(self, conn, *args, **kwargs)
except Exception as exc:
conn[0].set_exception(exc)
raise
finally:
self._pool.release(conn)
return wrapper
| (self, conn: aiomcache.pool.Connection) -> bytes |
29,002 | aiomcache.exceptions | ClientException | Raised when the server does something we don't expect. | class ClientException(Exception):
"""Raised when the server does something we don't expect."""
def __init__(self, msg: str, item: Optional[object] = None):
if item is not None:
msg = '%s: %r' % (msg, item)
super().__init__(msg)
| (msg: str, item: Optional[object] = None) |
29,003 | aiomcache.exceptions | __init__ | null | def __init__(self, msg: str, item: Optional[object] = None):
if item is not None:
msg = '%s: %r' % (msg, item)
super().__init__(msg)
| (self, msg: str, item: Optional[object] = None) |
29,004 | aiomcache.client | FlagClient | null | class FlagClient(Generic[_T]):
def __init__(self, host: str, port: int = 11211, *,
pool_size: int = 2, pool_minsize: Optional[int] = None,
conn_args: Optional[Mapping[str, Any]] = None,
get_flag_handler: Optional[_GetFlagHandler[_T]] = None,
set_flag_handler: Optional[_SetFlagHandler[_T]] = None):
"""
Creates new Client instance.
:param host: memcached host
:param port: memcached port
:param pool_size: max connection pool size
:param pool_minsize: min connection pool size
:param conn_args: extra arguments passed to
asyncio.open_connection(). For details, see:
https://docs.python.org/3/library/asyncio-stream.html#asyncio.open_connection.
:param get_flag_handler: async method to call to convert flagged
values. Method takes tuple: (value, flags) and should return
processed value or raise ClientException if not supported.
:param set_flag_handler: async method to call to convert non bytes
value to flagged value. Method takes value and must return tuple:
(value, flags).
"""
if not pool_minsize:
pool_minsize = pool_size
self._pool = MemcachePool(
host, port, minsize=pool_minsize, maxsize=pool_size,
conn_args=conn_args)
self._get_flag_handler = get_flag_handler
self._set_flag_handler = set_flag_handler
# key may be anything except whitespace and control chars, upto 250 characters.
# Must be str for unicode-aware regex.
_valid_key_re = re.compile("^[^\\s\x00-\x1F\x7F-\x9F]{1,250}$")
def _validate_key(self, key: bytes) -> bytes:
if not isinstance(key, bytes): # avoid bugs subtle and otherwise
raise ValidationException('key must be bytes', key)
# Must decode to str for unicode-aware comparison.
key_str = key.decode()
m = self._valid_key_re.match(key_str)
if m:
# in python re, $ matches either end of line or right before
# \n at end of line. We can't allow latter case, so
# making sure length matches is simplest way to detect
if len(m.group(0)) != len(key_str):
raise ValidationException('trailing newline', key)
else:
raise ValidationException('invalid key', key)
return key
async def _execute_simple_command(self, conn: Connection, raw_command: bytes) -> bytes:
response, line = bytearray(), b''
conn.writer.write(raw_command)
await conn.writer.drain()
while not line.endswith(b'\r\n'):
line = await conn.reader.readline()
response.extend(line)
return response[:-2]
async def close(self) -> None:
"""Closes the sockets if its open."""
await self._pool.clear()
@overload
async def _multi_get(self, conn: Connection, *keys: bytes,
with_cas: Literal[True] = ...) -> _Result[_T, int]:
...
@overload
async def _multi_get(self, conn: Connection, *keys: bytes,
with_cas: Literal[False]) -> _Result[_T, None]:
...
async def _multi_get( # type: ignore[misc]
self, conn: Connection, *keys: bytes,
with_cas: bool = True) -> _Result[_T, Optional[int]]:
# req - get <key> [<key> ...]\r\n
# resp - VALUE <key> <flags> <bytes> [<cas unique>]\r\n
# <data block>\r\n (if exists)
# [...]
# END\r\n
if not keys:
return {}, {}
[self._validate_key(key) for key in keys]
if len(set(keys)) != len(keys):
raise ClientException('duplicate keys passed to multi_get')
cmd = b'gets ' if with_cas else b'get '
conn.writer.write(cmd + b' '.join(keys) + b'\r\n')
received = {}
cas_tokens = {}
line = await conn.reader.readline()
while line != b'END\r\n':
terms = line.split()
if terms and terms[0] == b"VALUE": # exists
key = terms[1]
flags = int(terms[2])
length = int(terms[3])
val_bytes = (await conn.reader.readexactly(length+2))[:-2]
if key in received:
raise ClientException('duplicate results from server')
if flags:
if not self._get_flag_handler:
raise ClientException("received flags without handler")
val: Union[bytes, _T] = await self._get_flag_handler(val_bytes, flags)
else:
val = val_bytes
received[key] = val
cas_tokens[key] = int(terms[4]) if with_cas else None
else:
raise ClientException('get failed', line)
line = await conn.reader.readline()
if len(received) > len(keys):
raise ClientException('received too many responses')
return received, cas_tokens
@acquire
async def delete(self, conn: Connection, key: bytes) -> bool:
"""Deletes a key/value pair from the server.
:param key: is the key to delete.
:return: True if case values was deleted or False to indicate
that the item with this key was not found.
"""
self._validate_key(key)
command = b'delete ' + key + b'\r\n'
response = await self._execute_simple_command(conn, command)
if response not in (const.DELETED, const.NOT_FOUND):
raise ClientException('Memcached delete failed', response)
return response == const.DELETED
@acquire
@overload
async def get(self, conn: Connection, /, key: bytes,
default: None = ...) -> Union[bytes, _T, None]:
...
@acquire
@overload
async def get(self, conn: Connection, /, key: bytes, default: _U) -> Union[bytes, _T, _U]:
...
@acquire
async def get(
self, conn: Connection, /, key: bytes, default: Optional[_U] = None
) -> Union[bytes, _T, _U, None]:
"""Gets a single value from the server.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, is the data for this specified key.
"""
values, _ = await self._multi_get(conn, key, with_cas=False)
return values.get(key, default)
@acquire
async def gets(
self, conn: Connection, key: bytes, default: Optional[bytes] = None
) -> Tuple[Union[bytes, _T, None], Optional[int]]:
"""Gets a single value from the server together with the cas token.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, ``bytes tuple with the value and the cas
"""
values, cas_tokens = await self._multi_get(conn, key, with_cas=True)
return values.get(key, default), cas_tokens.get(key)
@acquire
async def multi_get(
self, conn: Connection, *keys: bytes
) -> Tuple[Union[bytes, _T, None], ...]:
"""Takes a list of keys and returns a list of values.
:param keys: ``list`` keys for the item being fetched.
:return: ``list`` of values for the specified keys.
:raises:``ValidationException``, ``ClientException``,
and socket errors
"""
values, _ = await self._multi_get(conn, *keys)
return tuple(values.get(key) for key in keys)
@acquire
async def stats(
self, conn: Connection, args: Optional[bytes] = None
) -> Dict[bytes, Optional[bytes]]:
"""Runs a stats command on the server."""
# req - stats [additional args]\r\n
# resp - STAT <name> <value>\r\n (one per result)
# END\r\n
if args is None:
args = b''
conn.writer.write(b''.join((b'stats ', args, b'\r\n')))
result: Dict[bytes, Optional[bytes]] = {}
resp = await conn.reader.readline()
while resp != b'END\r\n':
terms = resp.split()
if len(terms) == 2 and terms[0] == b'STAT':
result[terms[1]] = None
elif len(terms) == 3 and terms[0] == b'STAT':
result[terms[1]] = terms[2]
elif len(terms) >= 3 and terms[0] == b'STAT':
result[terms[1]] = b' '.join(terms[2:])
else:
raise ClientException('stats failed', resp)
resp = await conn.reader.readline()
return result
async def _storage_command(self, conn: Connection, command: bytes, key: bytes,
value: Union[bytes, _T], exptime: int = 0,
cas: Optional[int] = None) -> bool:
# req - set <key> <flags> <exptime> <bytes> [noreply]\r\n
# <data block>\r\n
# resp - STORED\r\n (or others)
# req - set <key> <flags> <exptime> <bytes> <cas> [noreply]\r\n
# <data block>\r\n
# resp - STORED\r\n (or others)
# typically, if val is > 1024**2 bytes server returns:
# SERVER_ERROR object too large for cache\r\n
# however custom-compiled memcached can have different limit
# so, we'll let the server decide what's too much
self._validate_key(key)
if not isinstance(exptime, int):
raise ValidationException('exptime not int', exptime)
elif exptime < 0:
raise ValidationException('exptime negative', exptime)
flags = 0
if not isinstance(value, bytes):
# flag handler only invoked on non-byte values,
# consistent with only being invoked on non-zero flags on retrieval
if self._set_flag_handler is None:
raise ValidationException("flag handler must be set for non-byte values")
value, flags = await self._set_flag_handler(value)
args = [str(a).encode('utf-8') for a in (flags, exptime, len(value))]
_cmd = b' '.join([command, key] + args)
if cas:
_cmd += b' ' + str(cas).encode('utf-8')
cmd = _cmd + b'\r\n' + value + b'\r\n'
resp = await self._execute_simple_command(conn, cmd)
if resp not in (
const.STORED, const.NOT_STORED, const.EXISTS, const.NOT_FOUND):
raise ClientException('stats {} failed'.format(command.decode()), resp)
return resp == const.STORED
@acquire
async def set(self, conn: Connection, key: bytes, value: Union[bytes, _T],
exptime: int = 0) -> bool:
"""Sets a key to a value on the server
with an optional exptime (0 means don't auto-expire)
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int``, is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
"""
return await self._storage_command(conn, b"set", key, value, exptime)
@acquire
async def cas(self, conn: Connection, key: bytes, value: Union[bytes, _T], cas_token: int,
exptime: int = 0) -> bool:
"""Sets a key to a value on the server
with an optional exptime (0 means don't auto-expire)
only if value hasn't changed from first retrieval
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int``, is expiration time. If it's 0, the
item never expires.
:param cas_token: ``int``, unique cas token retrieve from previous
``gets``
:return: ``bool``, True in case of success.
"""
return await self._storage_command(conn, b"cas", key, value, exptime,
cas=cas_token)
@acquire
async def add(self, conn: Connection, key: bytes, value: Union[bytes, _T],
exptime: int = 0) -> bool:
"""Store this data, but only if the server *doesn't* already
hold data for this key.
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
"""
return await self._storage_command(conn, b"add", key, value, exptime)
@acquire
async def replace(self, conn: Connection, key: bytes, value: Union[bytes, _T],
exptime: int = 0) -> bool:
"""Store this data, but only if the server *does*
already hold data for this key.
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
"""
return await self._storage_command(conn, b"replace", key, value, exptime)
@acquire
async def append(self, conn: Connection, key: bytes, value: Union[bytes, _T],
exptime: int = 0) -> bool:
"""Add data to an existing key after existing data
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
"""
return await self._storage_command(conn, b"append", key, value, exptime)
@acquire
async def prepend(self, conn: Connection, key: bytes, value: bytes, exptime: int = 0) -> bool:
"""Add data to an existing key before existing data
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int`` is expiration time. If it's 0, the
item never expires.
:return: ``bool``, True in case of success.
"""
return await self._storage_command(conn, b"prepend", key, value, exptime)
async def _incr_decr(
self, conn: Connection, command: bytes, key: bytes, delta: int
) -> Optional[int]:
delta_byte = str(delta).encode('utf-8')
cmd = b' '.join([command, key, delta_byte]) + b'\r\n'
resp = await self._execute_simple_command(conn, cmd)
if not resp.isdigit() or resp == const.NOT_FOUND:
raise ClientException(
'Memcached {} command failed'.format(str(command)), resp)
return int(resp) if resp.isdigit() else None
@acquire
async def incr(self, conn: Connection, key: bytes, increment: int = 1) -> Optional[int]:
"""Command is used to change data for some item in-place,
incrementing it. The data for the item is treated as decimal
representation of a 64-bit unsigned integer.
:param key: ``bytes``, is the key of the item the client wishes
to change
:param increment: ``int``, is the amount by which the client
wants to increase the item.
:return: ``int``, new value of the item's data,
after the increment or ``None`` to indicate the item with
this value was not found
"""
self._validate_key(key)
return await self._incr_decr(conn, b"incr", key, increment)
@acquire
async def decr(self, conn: Connection, key: bytes, decrement: int = 1) -> Optional[int]:
"""Command is used to change data for some item in-place,
decrementing it. The data for the item is treated as decimal
representation of a 64-bit unsigned integer.
:param key: ``bytes``, is the key of the item the client wishes
to change
:param decrement: ``int``, is the amount by which the client
wants to decrease the item.
:return: ``int`` new value of the item's data,
after the increment or ``None`` to indicate the item with
this value was not found
"""
self._validate_key(key)
return await self._incr_decr(conn, b"decr", key, decrement)
@acquire
async def touch(self, conn: Connection, key: bytes, exptime: int) -> bool:
"""The command is used to update the expiration time of
an existing item without fetching it.
:param key: ``bytes``, is the key to update expiration time
:param exptime: ``int``, is expiration time. This replaces the existing
expiration time.
:return: ``bool``, True in case of success.
"""
self._validate_key(key)
_cmd = b' '.join([b'touch', key, str(exptime).encode('utf-8')])
cmd = _cmd + b'\r\n'
resp = await self._execute_simple_command(conn, cmd)
if resp not in (const.TOUCHED, const.NOT_FOUND):
raise ClientException('Memcached touch failed', resp)
return resp == const.TOUCHED
@acquire
async def version(self, conn: Connection) -> bytes:
"""Current version of the server.
:return: ``bytes``, memcached version for current the server.
"""
command = b'version\r\n'
response = await self._execute_simple_command(conn, command)
if not response.startswith(const.VERSION):
raise ClientException('Memcached version failed', response)
version, number = response.rstrip(b"\r\n").split(maxsplit=1)
return number
@acquire
async def flush_all(self, conn: Connection) -> None:
"""Its effect is to invalidate all existing items immediately"""
command = b'flush_all\r\n'
response = await self._execute_simple_command(conn, command)
if const.OK != response:
raise ClientException('Memcached flush_all failed', response)
| (host: str, port: int = 11211, *, pool_size: int = 2, pool_minsize: Optional[int] = None, conn_args: Optional[Mapping[str, Any]] = None, get_flag_handler: Optional[Callable[[bytes, int], Awaitable[~_T]]] = None, set_flag_handler: Optional[Callable[[~_T], Awaitable[Tuple[bytes, int]]]] = None) |
29,005 | aiomcache.client | __init__ |
Creates new Client instance.
:param host: memcached host
:param port: memcached port
:param pool_size: max connection pool size
:param pool_minsize: min connection pool size
:param conn_args: extra arguments passed to
asyncio.open_connection(). For details, see:
https://docs.python.org/3/library/asyncio-stream.html#asyncio.open_connection.
:param get_flag_handler: async method to call to convert flagged
values. Method takes tuple: (value, flags) and should return
processed value or raise ClientException if not supported.
:param set_flag_handler: async method to call to convert non bytes
value to flagged value. Method takes value and must return tuple:
(value, flags).
| def __init__(self, host: str, port: int = 11211, *,
pool_size: int = 2, pool_minsize: Optional[int] = None,
conn_args: Optional[Mapping[str, Any]] = None,
get_flag_handler: Optional[_GetFlagHandler[_T]] = None,
set_flag_handler: Optional[_SetFlagHandler[_T]] = None):
"""
Creates new Client instance.
:param host: memcached host
:param port: memcached port
:param pool_size: max connection pool size
:param pool_minsize: min connection pool size
:param conn_args: extra arguments passed to
asyncio.open_connection(). For details, see:
https://docs.python.org/3/library/asyncio-stream.html#asyncio.open_connection.
:param get_flag_handler: async method to call to convert flagged
values. Method takes tuple: (value, flags) and should return
processed value or raise ClientException if not supported.
:param set_flag_handler: async method to call to convert non bytes
value to flagged value. Method takes value and must return tuple:
(value, flags).
"""
if not pool_minsize:
pool_minsize = pool_size
self._pool = MemcachePool(
host, port, minsize=pool_minsize, maxsize=pool_size,
conn_args=conn_args)
self._get_flag_handler = get_flag_handler
self._set_flag_handler = set_flag_handler
| (self, host: str, port: int = 11211, *, pool_size: int = 2, pool_minsize: Optional[int] = None, conn_args: Optional[Mapping[str, Any]] = None, get_flag_handler: Optional[Callable[[bytes, int], Awaitable[~_T]]] = None, set_flag_handler: Optional[Callable[[~_T], Awaitable[Tuple[bytes, int]]]] = None) |
29,028 | aiomcache.exceptions | ValidationException | Raised when an invalid parameter is passed to a ``Client`` function. | class ValidationException(ClientException):
"""Raised when an invalid parameter is passed to a ``Client`` function."""
| (msg: str, item: Optional[object] = None) |
29,051 | pytrie | NULL | null | class NULL:
pass
| () |
29,052 | pytrie | Node | Trie node class.
Subclasses may extend it to replace :attr:`ChildrenFactory` with a different
mapping class (e.g. `sorteddict <http://pypi.python.org/pypi/sorteddict/>`_)
:ivar value: The value of the key corresponding to this node or
:const:`NULL` if there is no such key.
:ivar children: A ``{key-part : child-node}`` mapping.
| class Node:
"""Trie node class.
Subclasses may extend it to replace :attr:`ChildrenFactory` with a different
mapping class (e.g. `sorteddict <http://pypi.python.org/pypi/sorteddict/>`_)
:ivar value: The value of the key corresponding to this node or
:const:`NULL` if there is no such key.
:ivar children: A ``{key-part : child-node}`` mapping.
"""
__slots__ = ('value', 'children')
#: A callable for creating a new :attr:`children` mapping.
ChildrenFactory = dict
def __init__(self, value=NULL):
self.value = value
self.children = self.ChildrenFactory()
def __len__(self):
"""Return the number of keys in the subtree rooted at this node."""
return int(self.value is not NULL) + sum(map(len, self.children.values()))
def __repr__(self):
return '(%s, {%s})' % (
self.value is NULL and 'NULL' or repr(self.value),
', '.join('%r: %r' % t for t in self.children.items()))
def __copy__(self):
clone = self.__class__(self.value)
clone_children = clone.children
for key, child in self.children.items():
clone_children[key] = child.__copy__()
return clone
def __getstate__(self):
return self.value, self.children
def __setstate__(self, state):
self.value, self.children = state
| (value=<class 'pytrie.NULL'>) |
29,053 | pytrie | __copy__ | null | def __copy__(self):
clone = self.__class__(self.value)
clone_children = clone.children
for key, child in self.children.items():
clone_children[key] = child.__copy__()
return clone
| (self) |
29,054 | pytrie | __getstate__ | null | def __getstate__(self):
return self.value, self.children
| (self) |
29,055 | pytrie | __init__ | null | def __init__(self, value=NULL):
self.value = value
self.children = self.ChildrenFactory()
| (self, value=<class 'pytrie.NULL'>) |
29,056 | pytrie | __len__ | Return the number of keys in the subtree rooted at this node. | def __len__(self):
"""Return the number of keys in the subtree rooted at this node."""
return int(self.value is not NULL) + sum(map(len, self.children.values()))
| (self) |
29,057 | pytrie | __repr__ | null | def __repr__(self):
return '(%s, {%s})' % (
self.value is NULL and 'NULL' or repr(self.value),
', '.join('%r: %r' % t for t in self.children.items()))
| (self) |
29,058 | pytrie | __setstate__ | null | def __setstate__(self, state):
self.value, self.children = state
| (self, state) |
29,059 | pytrie | SortedStringTrie |
A :class:`Trie` that is both a :class:`StringTrie` and a :class:`SortedTrie`
| class SortedStringTrie(SortedTrie, StringTrie):
"""
A :class:`Trie` that is both a :class:`StringTrie` and a :class:`SortedTrie`
"""
| (*args, **kwargs) |
29,060 | pytrie | __bool__ | null | def __bool__(self):
return self._root.value is not NULL or bool(self._root.children)
| (self) |
29,061 | pytrie | __contains__ | null | def __contains__(self, key):
node = self._find(key)
return node is not None and node.value is not NULL
| (self, key) |
29,062 | pytrie | __delitem__ | null | def __delitem__(self, key):
nodes_parts = []
append = nodes_parts.append
node = self._root
for part in key:
append((node, part))
node = node.children.get(part)
if node is None:
break
if node is None or node.value is NULL:
raise KeyError
node.value = NULL
pop = nodes_parts.pop
while node.value is NULL and not node.children and nodes_parts:
node, part = pop()
del node.children[part]
| (self, key) |
29,064 | pytrie | __getitem__ | null | def __getitem__(self, key):
node = self._find(key)
if node is None or node.value is NULL:
raise KeyError
return node.value
| (self, key) |
29,065 | pytrie | __init__ | Create a new trie.
Parameters are the same with ``dict()``.
| def __init__(self, *args, **kwargs):
"""Create a new trie.
Parameters are the same with ``dict()``.
"""
self._root = self.NodeFactory()
self.update(*args, **kwargs)
| (self, *args, **kwargs) |
29,066 | pytrie | __iter__ | null | def __iter__(self):
return self.iterkeys()
| (self) |
29,067 | pytrie | __len__ | null | def __len__(self):
return len(self._root)
| (self) |
29,068 | pytrie | __repr__ | null | def __repr__(self):
return '%s({%s})' % (
self.__class__.__name__,
', '.join('%r: %r' % t for t in self.iteritems()))
| (self) |
29,069 | pytrie | __setitem__ | null | def __setitem__(self, key, value):
node = self._root
factory = self.NodeFactory
for part in key:
next_node = node.children.get(part)
if next_node is None:
node = node.children.setdefault(part, factory())
else:
node = next_node
node.value = value
| (self, key, value) |
29,070 | pytrie | _find | null | def _find(self, key):
node = self._root
for part in key:
node = node.children.get(part)
if node is None:
break
return node
| (self, key) |
29,071 | pytrie | clear | null | def clear(self):
self._root.children.clear()
| (self) |
29,072 | pytrie | copy | null | def copy(self):
clone = copy(super(Trie, self))
clone._root = copy(self._root) # pylint: disable=protected-access
return clone
| (self) |
29,074 | pytrie | items | Return a list of this trie's items (``(key,value)`` tuples).
:param prefix: If not None, return only the items associated with keys
prefixed by ``prefix``.
| def items(self, prefix=None):
"""Return a list of this trie's items (``(key,value)`` tuples).
:param prefix: If not None, return only the items associated with keys
prefixed by ``prefix``.
"""
return list(self.iteritems(prefix))
| (self, prefix=None) |
29,075 | pytrie | iter_prefix_items | Return an iterator over the items (``(key,value)`` tuples) of this
trie that are associated with keys that are prefixes of ``key``.
| def iter_prefix_items(self, key):
"""Return an iterator over the items (``(key,value)`` tuples) of this
trie that are associated with keys that are prefixes of ``key``.
"""
key_factory = self.KeyFactory
prefix = []
append = prefix.append
node = self._root
if node.value is not NULL:
yield (key_factory(prefix), node.value)
for part in key:
node = node.children.get(part)
if node is None:
break
append(part)
if node.value is not NULL:
yield (key_factory(prefix), node.value)
| (self, key) |
29,076 | pytrie | iter_prefix_values | Return an iterator over the values of this trie that are associated
with keys that are prefixes of ``key``.
| def iter_prefix_values(self, key):
"""Return an iterator over the values of this trie that are associated
with keys that are prefixes of ``key``.
"""
node = self._root
if node.value is not NULL:
yield node.value
for part in key:
node = node.children.get(part)
if node is None:
break
if node.value is not NULL:
yield node.value
| (self, key) |
29,077 | pytrie | iter_prefixes |
Return an iterator over the keys of this trie that are prefixes of
``key``.
| def iter_prefixes(self, key):
"""
Return an iterator over the keys of this trie that are prefixes of
``key``.
"""
key_factory = self.KeyFactory
prefix = []
append = prefix.append
node = self._root
if node.value is not NULL:
yield key_factory(prefix)
for part in key:
node = node.children.get(part)
if node is None:
break
append(part)
if node.value is not NULL:
yield key_factory(prefix)
| (self, key) |
29,078 | pytrie | iteritems | Return an iterator over this trie's items (``(key,value)`` tuples).
:param prefix: If not None, yield only the items associated with keys
prefixed by ``prefix``.
| def iteritems(self, prefix=None):
"""Return an iterator over this trie's items (``(key,value)`` tuples).
:param prefix: If not None, yield only the items associated with keys
prefixed by ``prefix``.
"""
parts = []
append = parts.append
# pylint: disable=dangerous-default-value
def generator(node, key_factory=self.KeyFactory, parts=parts,
append=append, null=NULL):
if node.value is not null:
yield (key_factory(parts), node.value)
for part, child in node.children.items():
append(part)
for subresult in generator(child):
yield subresult
del parts[-1]
root = self._root
if prefix is not None:
for part in prefix:
append(part)
root = root.children.get(part)
if root is None:
root = self.NodeFactory()
break
return generator(root)
| (self, prefix=None) |
29,079 | pytrie | iterkeys | Return an iterator over this trie's keys.
:param prefix: If not None, yield only the keys prefixed by ``prefix``.
| def iterkeys(self, prefix=None):
"""Return an iterator over this trie's keys.
:param prefix: If not None, yield only the keys prefixed by ``prefix``.
"""
return (key for key, value in self.iteritems(prefix))
| (self, prefix=None) |
29,080 | pytrie | itervalues | Return an iterator over this trie's values.
:param prefix: If not None, yield only the values associated with keys
prefixed by ``prefix``.
| def itervalues(self, prefix=None):
"""Return an iterator over this trie's values.
:param prefix: If not None, yield only the values associated with keys
prefixed by ``prefix``.
"""
def generator(node, null=NULL):
if node.value is not null:
yield node.value
for child in node.children.values():
for subresult in generator(child):
yield subresult
if prefix is None:
root = self._root
else:
root = self._find(prefix)
if root is None:
root = self.NodeFactory()
return generator(root)
| (self, prefix=None) |
29,081 | pytrie | keys | Return a list of this trie's keys.
:param prefix: If not None, return only the keys prefixed by ``prefix``.
| def keys(self, prefix=None):
"""Return a list of this trie's keys.
:param prefix: If not None, return only the keys prefixed by ``prefix``.
"""
return list(self.iterkeys(prefix))
| (self, prefix=None) |
29,082 | pytrie | longest_prefix | Return the longest key in this trie that is a prefix of ``key``.
If the trie doesn't contain any prefix of ``key``:
- if ``default`` is given, return it
- otherwise raise ``KeyError``
| def longest_prefix(self, key, default=NULL):
"""Return the longest key in this trie that is a prefix of ``key``.
If the trie doesn't contain any prefix of ``key``:
- if ``default`` is given, return it
- otherwise raise ``KeyError``
"""
try:
return self.longest_prefix_item(key)[0]
except KeyError:
if default is not NULL:
return default
raise
| (self, key, default=<class 'pytrie.NULL'>) |
29,083 | pytrie | longest_prefix_item | Return the item (``(key,value)`` tuple) associated with the longest
key in this trie that is a prefix of ``key``.
If the trie doesn't contain any prefix of ``key``:
- if ``default`` is given, return it
- otherwise raise ``KeyError``
| def longest_prefix_item(self, key, default=NULL):
"""Return the item (``(key,value)`` tuple) associated with the longest
key in this trie that is a prefix of ``key``.
If the trie doesn't contain any prefix of ``key``:
- if ``default`` is given, return it
- otherwise raise ``KeyError``
"""
prefix = []
append = prefix.append
node = self._root
longest_prefix_value = node.value
max_non_null_index = -1
for i, part in enumerate(key):
node = node.children.get(part)
if node is None:
break
append(part)
value = node.value
if value is not NULL:
longest_prefix_value = value
max_non_null_index = i
if longest_prefix_value is not NULL:
del prefix[max_non_null_index+1:]
return self.KeyFactory(prefix), longest_prefix_value
elif default is not NULL:
return default
else:
raise KeyError
| (self, key, default=<class 'pytrie.NULL'>) |
29,084 | pytrie | longest_prefix_value | Return the value associated with the longest key in this trie that is
a prefix of ``key``.
If the trie doesn't contain any prefix of ``key``:
- if ``default`` is given, return it
- otherwise raise ``KeyError``
| def longest_prefix_value(self, key, default=NULL):
"""Return the value associated with the longest key in this trie that is
a prefix of ``key``.
If the trie doesn't contain any prefix of ``key``:
- if ``default`` is given, return it
- otherwise raise ``KeyError``
"""
node = self._root
longest_prefix_value = node.value
for part in key:
node = node.children.get(part)
if node is None:
break
value = node.value
if value is not NULL:
longest_prefix_value = value
if longest_prefix_value is not NULL:
return longest_prefix_value
elif default is not NULL:
return default
else:
raise KeyError
| (self, key, default=<class 'pytrie.NULL'>) |
29,089 | pytrie | values | Return a list of this trie's values.
:param prefix: If not None, return only the values associated with keys
prefixed by ``prefix``.
| def values(self, prefix=None):
"""Return a list of this trie's values.
:param prefix: If not None, return only the values associated with keys
prefixed by ``prefix``.
"""
return list(self.itervalues(prefix))
| (self, prefix=None) |
29,090 | pytrie | SortedTrie |
A :class:`Trie` that returns its keys (and associated values/items) sorted.
| class SortedTrie(Trie):
"""
A :class:`Trie` that returns its keys (and associated values/items) sorted.
"""
NodeFactory = _SortedNode
| (*args, **kwargs) |
29,121 | pytrie | StringTrie | A more appropriate for string keys :class:`Trie`. | class StringTrie(Trie):
"""A more appropriate for string keys :class:`Trie`."""
KeyFactory = ''.join
| (*args, **kwargs) |
29,152 | pytrie | Trie | Base trie class.
As with regular dicts, keys are not necessarily returned sorted. Use
:class:`SortedTrie` if sorting is required.
| class Trie(MutableMapping):
"""Base trie class.
As with regular dicts, keys are not necessarily returned sorted. Use
:class:`SortedTrie` if sorting is required.
"""
#: Callable for forming a key from its parts.
KeyFactory = tuple
#: Callable for creating new trie nodes.
NodeFactory = Node
def __init__(self, *args, **kwargs):
"""Create a new trie.
Parameters are the same with ``dict()``.
"""
self._root = self.NodeFactory()
self.update(*args, **kwargs)
@classmethod
def fromkeys(cls, iterable, value=None):
"""
Create a new trie with keys from ``iterable`` and values set to
``value``.
Parameters are the same with ``dict.fromkeys()``.
"""
trie = cls()
for key in iterable:
trie[key] = value
return trie
#----- trie-specific methods -----------------------------------------------
def longest_prefix(self, key, default=NULL):
"""Return the longest key in this trie that is a prefix of ``key``.
If the trie doesn't contain any prefix of ``key``:
- if ``default`` is given, return it
- otherwise raise ``KeyError``
"""
try:
return self.longest_prefix_item(key)[0]
except KeyError:
if default is not NULL:
return default
raise
def longest_prefix_value(self, key, default=NULL):
"""Return the value associated with the longest key in this trie that is
a prefix of ``key``.
If the trie doesn't contain any prefix of ``key``:
- if ``default`` is given, return it
- otherwise raise ``KeyError``
"""
node = self._root
longest_prefix_value = node.value
for part in key:
node = node.children.get(part)
if node is None:
break
value = node.value
if value is not NULL:
longest_prefix_value = value
if longest_prefix_value is not NULL:
return longest_prefix_value
elif default is not NULL:
return default
else:
raise KeyError
def longest_prefix_item(self, key, default=NULL):
"""Return the item (``(key,value)`` tuple) associated with the longest
key in this trie that is a prefix of ``key``.
If the trie doesn't contain any prefix of ``key``:
- if ``default`` is given, return it
- otherwise raise ``KeyError``
"""
prefix = []
append = prefix.append
node = self._root
longest_prefix_value = node.value
max_non_null_index = -1
for i, part in enumerate(key):
node = node.children.get(part)
if node is None:
break
append(part)
value = node.value
if value is not NULL:
longest_prefix_value = value
max_non_null_index = i
if longest_prefix_value is not NULL:
del prefix[max_non_null_index+1:]
return self.KeyFactory(prefix), longest_prefix_value
elif default is not NULL:
return default
else:
raise KeyError
def iter_prefixes(self, key):
"""
Return an iterator over the keys of this trie that are prefixes of
``key``.
"""
key_factory = self.KeyFactory
prefix = []
append = prefix.append
node = self._root
if node.value is not NULL:
yield key_factory(prefix)
for part in key:
node = node.children.get(part)
if node is None:
break
append(part)
if node.value is not NULL:
yield key_factory(prefix)
def iter_prefix_values(self, key):
"""Return an iterator over the values of this trie that are associated
with keys that are prefixes of ``key``.
"""
node = self._root
if node.value is not NULL:
yield node.value
for part in key:
node = node.children.get(part)
if node is None:
break
if node.value is not NULL:
yield node.value
def iter_prefix_items(self, key):
"""Return an iterator over the items (``(key,value)`` tuples) of this
trie that are associated with keys that are prefixes of ``key``.
"""
key_factory = self.KeyFactory
prefix = []
append = prefix.append
node = self._root
if node.value is not NULL:
yield (key_factory(prefix), node.value)
for part in key:
node = node.children.get(part)
if node is None:
break
append(part)
if node.value is not NULL:
yield (key_factory(prefix), node.value)
#----- extended mapping API methods ----------------------------------------
# pylint: disable=arguments-differ
def keys(self, prefix=None):
"""Return a list of this trie's keys.
:param prefix: If not None, return only the keys prefixed by ``prefix``.
"""
return list(self.iterkeys(prefix))
def values(self, prefix=None):
"""Return a list of this trie's values.
:param prefix: If not None, return only the values associated with keys
prefixed by ``prefix``.
"""
return list(self.itervalues(prefix))
def items(self, prefix=None):
"""Return a list of this trie's items (``(key,value)`` tuples).
:param prefix: If not None, return only the items associated with keys
prefixed by ``prefix``.
"""
return list(self.iteritems(prefix))
def iterkeys(self, prefix=None):
"""Return an iterator over this trie's keys.
:param prefix: If not None, yield only the keys prefixed by ``prefix``.
"""
return (key for key, value in self.iteritems(prefix))
def itervalues(self, prefix=None):
"""Return an iterator over this trie's values.
:param prefix: If not None, yield only the values associated with keys
prefixed by ``prefix``.
"""
def generator(node, null=NULL):
if node.value is not null:
yield node.value
for child in node.children.values():
for subresult in generator(child):
yield subresult
if prefix is None:
root = self._root
else:
root = self._find(prefix)
if root is None:
root = self.NodeFactory()
return generator(root)
def iteritems(self, prefix=None):
"""Return an iterator over this trie's items (``(key,value)`` tuples).
:param prefix: If not None, yield only the items associated with keys
prefixed by ``prefix``.
"""
parts = []
append = parts.append
# pylint: disable=dangerous-default-value
def generator(node, key_factory=self.KeyFactory, parts=parts,
append=append, null=NULL):
if node.value is not null:
yield (key_factory(parts), node.value)
for part, child in node.children.items():
append(part)
for subresult in generator(child):
yield subresult
del parts[-1]
root = self._root
if prefix is not None:
for part in prefix:
append(part)
root = root.children.get(part)
if root is None:
root = self.NodeFactory()
break
return generator(root)
# pylint: enable=arguments-differ
#----- original mapping API methods ----------------------------------------
def __len__(self):
return len(self._root)
def __bool__(self):
return self._root.value is not NULL or bool(self._root.children)
def __iter__(self):
return self.iterkeys()
def __contains__(self, key):
node = self._find(key)
return node is not None and node.value is not NULL
def __getitem__(self, key):
node = self._find(key)
if node is None or node.value is NULL:
raise KeyError
return node.value
def __setitem__(self, key, value):
node = self._root
factory = self.NodeFactory
for part in key:
next_node = node.children.get(part)
if next_node is None:
node = node.children.setdefault(part, factory())
else:
node = next_node
node.value = value
def __delitem__(self, key):
nodes_parts = []
append = nodes_parts.append
node = self._root
for part in key:
append((node, part))
node = node.children.get(part)
if node is None:
break
if node is None or node.value is NULL:
raise KeyError
node.value = NULL
pop = nodes_parts.pop
while node.value is NULL and not node.children and nodes_parts:
node, part = pop()
del node.children[part]
def clear(self):
self._root.children.clear()
def copy(self):
clone = copy(super(Trie, self))
clone._root = copy(self._root) # pylint: disable=protected-access
return clone
def __repr__(self):
return '%s({%s})' % (
self.__class__.__name__,
', '.join('%r: %r' % t for t in self.iteritems()))
def _find(self, key):
node = self._root
for part in key:
node = node.children.get(part)
if node is None:
break
return node
| (*args, **kwargs) |
29,183 | pytrie | _SortedNode | null | class _SortedNode(Node):
ChildrenFactory = sortedcontainers.SortedDict
| (value=<class 'pytrie.NULL'>) |
29,190 | copy | copy | Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
| def copy(x):
"""Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
cls = type(x)
copier = _copy_dispatch.get(cls)
if copier:
return copier(x)
if issubclass(cls, type):
# treat it as a regular class:
return _copy_immutable(x)
copier = getattr(cls, "__copy__", None)
if copier is not None:
return copier(x)
reductor = dispatch_table.get(cls)
if reductor is not None:
rv = reductor(x)
else:
reductor = getattr(x, "__reduce_ex__", None)
if reductor is not None:
rv = reductor(4)
else:
reductor = getattr(x, "__reduce__", None)
if reductor:
rv = reductor()
else:
raise Error("un(shallow)copyable object of type %s" % cls)
if isinstance(rv, str):
return x
return _reconstruct(x, None, *rv)
| (x) |
29,193 | _io | BufferedReader | Create a new buffered reader using the given readable raw IO object. | from _io import BufferedReader
| (raw, buffer_size=8192) |
29,194 | os | PathLike | Abstract base class for implementing the file system path protocol. | class PathLike(abc.ABC):
"""Abstract base class for implementing the file system path protocol."""
@abc.abstractmethod
def __fspath__(self):
"""Return the file system path representation of the object."""
raise NotImplementedError
@classmethod
def __subclasshook__(cls, subclass):
if cls is PathLike:
return _check_methods(subclass, '__fspath__')
return NotImplemented
__class_getitem__ = classmethod(GenericAlias)
| () |
29,195 | os | __fspath__ | Return the file system path representation of the object. | @abc.abstractmethod
def __fspath__(self):
"""Return the file system path representation of the object."""
raise NotImplementedError
| (self) |
29,198 | pygrib._pygrib | gribmessage |
Grib message object.
Each grib message has attributes corresponding to GRIB
`keys <https://confluence.ecmwf.int/display/ECC/GRIB+Keys>`__.
Parameter names are described by the ``name``, ``shortName`` and ``paramID`` keys.
pygrib also defines some special attributes which are defined below
:ivar messagenumber: The grib message number in the file.
:ivar projparams: A dictionary containing proj4 key/value pairs describing
the grid. Set to ``None`` for unsupported grid types.
:ivar expand_reduced: If True (default), reduced lat/lon and gaussian grids
will be expanded to regular grids when data is accessed via ``values`` key. If
False, data is kept on unstructured reduced grid, and is returned in a 1-d
array.
:ivar fcstimeunits: A string representing the forecast time units
(an empty string if not defined).
:ivar analDate: A python datetime instance describing the analysis date
and time for the forecast. Only set if forecastTime and julianDay keys
exist.
:ivar validDate: A python datetime instance describing the valid date
and time for the forecast. Only set if forecastTime and julianDay keys
exist, and fcstimeunits is defined. If forecast time
is a range, then ``validDate`` corresponds to the end of the range.
| from pygrib._pygrib import gribmessage
| null |
29,199 | pygrib._pygrib | index |
index(filename, *args)
returns grib index object given GRIB filename indexed by keys given in
*args. The :py:class:`select` or ``__call__`` method can then be used to selected grib messages
based on specified values of indexed keys.
Unlike :py:meth:`open.select`, containers or callables cannot be used to
select multiple key values.
However, using :py:meth:`index.select` is much faster than :py:meth:`open.select`.
**Warning**: Searching for data within multi-field grib messages does not
work using an index and is not supported by ECCODES library. NCEP
often puts u and v winds together in a single multi-field grib message. You
will get incorrect results if you try to use an index to find data in these
messages. Use the slower, but more robust :py:meth:`open.select` in this case.
If no key are given (i.e. *args is empty), it is assumed the filename represents a previously
saved index (created using the ``grib_index_build`` tool or :py:meth:`index.write`) instead of a GRIB file.
Example usage:
>>> import pygrib
>>> grbindx=pygrib.index('sampledata/gfs.grb','shortName','typeOfLevel','level')
>>> grbindx.keys
['shortName', 'level']
>>> selected_grbs=grbindx.select(shortName='gh',typeOfLevel='isobaricInhPa',level=500)
>>> for grb in selected_grbs:
>>> grb
1:Geopotential height:gpm (instant):regular_ll:isobaricInhPa:level 500 Pa:fcst time 72 hrs:from 200412091200:lo res cntl fcst
>>> # __call__ method does same thing as select
>>> selected_grbs=grbindx(shortName='u',typeOfLevel='isobaricInhPa',level=250)
>>> for grb in selected_grbs:
>>> grb
1:u-component of wind:m s**-1 (instant):regular_ll:isobaricInhPa:level 250 Pa:fcst time 72 hrs:from 200412091200:lo res cntl fcst
>>> grbindx.write('gfs.grb.idx') # save index to a file
>>> grbindx.close()
>>> grbindx = pygrib.index('gfs.grb.idx') # re-open index (no keys specified)
>>> grbindx.keys # not set when opening a saved index file.
None
>>> for grb in selected_grbs:
>>> grb
1:u-component of wind:m s**-1 (instant):regular_ll:isobaricInhPa:level 250 Pa:fcst time 72 hrs:from 200412091200:lo res cntl fcst
:ivar keys: list of strings containing keys used in the index. Set to ``None``
when opening a previously saved grib index file.
:ivar types: if keys are typed, this list contains the type declarations
(``l``, ``s`` or ``d``). Type declarations are specified by appending to the key
name (i.e. ``level:l`` will search for values of ``level`` that are longs). Set
to ``None`` when opening a previously saved grib index file.
| from pygrib._pygrib import index
| null |
29,202 | pygrib._pygrib | open |
open(filepath_or_buffer)
returns GRIB file iterator object given GRIB file path (:py:class:`str` or
:py:class:`os.PathLike` object) or buffer (:py:class:`io.BufferedReader` object).
When iterated, returns
instances of the :py:class:`gribmessage` class. Behaves much like a python file
object, with :py:meth:`seek`, :py:meth:`tell`, :py:meth:`read`
:py:meth:`readline` and :py:meth:`close` methods
except that offsets are measured in grib messages instead of bytes.
Additional methods include :py:meth:`rewind` (like ``seek(0)``),
:py:meth:`message`
(like ``seek(N-1)``; followed by ``readline()``), and :py:meth:`select` (filters
messages based on specified conditions). The ``__call__`` method forwards
to :py:meth:`select`, and instances can be sliced with ``__getitem__`` (returning
lists of :py:class:`gribmessage` instances). The position of the iterator is not
altered by slicing with ``__getitem__``.
:ivar messages: The total number of grib messages in the file.
:ivar messagenumber: The grib message number that the iterator currently
points to (the value returned by :py:meth:`tell`).
:ivar name: The GRIB file which the instance represents. | from pygrib._pygrib import open
| null |
29,204 | pkg_resources | parse_version | null | def parse_version(v):
try:
return packaging.version.Version(v)
except packaging.version.InvalidVersion:
warnings.warn(
f"{v} is an invalid version and will not be supported in "
"a future release",
PkgResourcesDeprecationWarning,
)
return packaging.version.LegacyVersion(v)
| (v) |
29,208 | efficientnet | get_submodules_from_kwargs | null | def get_submodules_from_kwargs(kwargs):
backend = kwargs.get('backend', _KERAS_BACKEND)
layers = kwargs.get('layers', _KERAS_LAYERS)
models = kwargs.get('models', _KERAS_MODELS)
utils = kwargs.get('utils', _KERAS_UTILS)
for key in kwargs.keys():
if key not in ['backend', 'layers', 'models', 'utils']:
raise TypeError('Invalid keyword argument: %s', key)
return backend, layers, models, utils
| (kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.