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 ⌀ |
|---|---|---|---|---|---|
7,044 | growthbook | __init__ | null | def __init__(
self,
variationId: int,
inExperiment: bool,
value,
hashUsed: bool,
hashAttribute: str,
hashValue: str,
featureId: Optional[str],
meta: VariationMeta = None,
bucket: float = None,
stickyBucketUsed: bool = False,
) -> None:
self.variationId = variationId
s... | (self, variationId: int, inExperiment: bool, value, hashUsed: bool, hashAttribute: str, hashValue: str, featureId: Optional[str], meta: Optional[growthbook.VariationMeta] = None, bucket: Optional[float] = None, stickyBucketUsed: bool = False) -> NoneType |
7,045 | growthbook | to_dict | null | def to_dict(self) -> dict:
obj = {
"featureId": self.featureId,
"variationId": self.variationId,
"inExperiment": self.inExperiment,
"value": self.value,
"hashUsed": self.hashUsed,
"hashAttribute": self.hashAttribute,
"hashValue": self.hashValue,
"key":... | (self) -> dict |
7,046 | typing | TypedDict | A simple typed namespace. At runtime it is equivalent to a plain dict.
TypedDict creates a dictionary type that expects all of its
instances to have a certain set of keys, where each key is
associated with a value of a consistent type. This expectation
is not checked at runtime but is only enforced by ... | def TypedDict(typename, fields=None, /, *, total=True, **kwargs):
"""A simple typed namespace. At runtime it is equivalent to a plain dict.
TypedDict creates a dictionary type that expects all of its
instances to have a certain set of keys, where each key is
associated with a value of a consistent type... | (typename, fields=None, /, *, total=True, **kwargs) |
7,047 | growthbook | VariationMeta | null | class VariationMeta(TypedDict):
key: str
name: str
passthrough: bool
| null |
7,048 | abc | abstractmethod | A decorator indicating abstract methods.
Requires that the metaclass is ABCMeta or derived from it. A
class that has a metaclass derived from ABCMeta cannot be
instantiated unless all of its abstract methods are overridden.
The abstract methods can be called using any of the normal
'super' call me... | def abstractmethod(funcobj):
"""A decorator indicating abstract methods.
Requires that the metaclass is ABCMeta or derived from it. A
class that has a metaclass derived from ABCMeta cannot be
instantiated unless all of its abstract methods are overridden.
The abstract methods can be called using a... | (funcobj) |
7,050 | base64 | b64decode | Decode the Base64 encoded bytes-like object or ASCII string s.
Optional altchars must be a bytes-like object or ASCII string of length 2
which specifies the alternative alphabet used instead of the '+' and '/'
characters.
The result is returned as a bytes object. A binascii.Error is raised if
s i... | def b64decode(s, altchars=None, validate=False):
"""Decode the Base64 encoded bytes-like object or ASCII string s.
Optional altchars must be a bytes-like object or ASCII string of length 2
which specifies the alternative alphabet used instead of the '+' and '/'
characters.
The result is returned a... | (s, altchars=None, validate=False) |
7,051 | growthbook | chooseVariation | null | def chooseVariation(n: float, ranges: List[Tuple[float, float]]) -> int:
for i, r in enumerate(ranges):
if inRange(n, r):
return i
return -1
| (n: float, ranges: List[Tuple[float, float]]) -> int |
7,052 | growthbook | compare | null | def compare(val1, val2) -> int:
if (type(val1) is int or type(val1) is float) and not (type(val2) is int or type(val2) is float):
if (val2 is None):
val2 = 0
else:
val2 = float(val2)
if (type(val2) is int or type(val2) is float) and not (type(val1) is int or type(val1) i... | (val1, val2) -> int |
7,053 | growthbook | decrypt | null | def decrypt(encrypted_str: str, key_str: str) -> str:
iv_str, ct_str = encrypted_str.split(".", 2)
key = b64decode(key_str)
iv = b64decode(iv_str)
ct = b64decode(ct_str)
cipher = Cipher(algorithms.AES128(key), modes.CBC(iv))
decryptor = cipher.decryptor()
decrypted = decryptor.update(ct) ... | (encrypted_str: str, key_str: str) -> str |
7,054 | growthbook | elemMatch | null | def elemMatch(condition, attributeValue) -> bool:
if not type(attributeValue) is list:
return False
for item in attributeValue:
if isOperatorObject(condition):
if evalConditionValue(condition, item):
return True
else:
if evalCondition(item, condit... | (condition, attributeValue) -> bool |
7,055 | growthbook | evalAnd | null | def evalAnd(attributes, conditions) -> bool:
for condition in conditions:
if not evalCondition(attributes, condition):
return False
return True
| (attributes, conditions) -> bool |
7,056 | growthbook | evalCondition | null | def evalCondition(attributes: dict, condition: dict) -> bool:
if "$or" in condition:
return evalOr(attributes, condition["$or"])
if "$nor" in condition:
return not evalOr(attributes, condition["$nor"])
if "$and" in condition:
return evalAnd(attributes, condition["$and"])
if "$not... | (attributes: dict, condition: dict) -> bool |
7,057 | growthbook | evalConditionValue | null | def evalConditionValue(conditionValue, attributeValue) -> bool:
if type(conditionValue) is dict and isOperatorObject(conditionValue):
for key, value in conditionValue.items():
if not evalOperatorCondition(key, attributeValue, value):
return False
return True
return co... | (conditionValue, attributeValue) -> bool |
7,058 | growthbook | evalOperatorCondition | null | def evalOperatorCondition(operator, attributeValue, conditionValue) -> bool:
if operator == "$eq":
try:
return compare(attributeValue, conditionValue) == 0
except Exception:
return False
elif operator == "$ne":
try:
return compare(attributeValue, condi... | (operator, attributeValue, conditionValue) -> bool |
7,059 | growthbook | evalOr | null | def evalOr(attributes, conditions) -> bool:
if len(conditions) == 0:
return True
for condition in conditions:
if evalCondition(attributes, condition):
return True
return False
| (attributes, conditions) -> bool |
7,060 | growthbook | fnv1a32 | null | def fnv1a32(str: str) -> int:
hval = 0x811C9DC5
prime = 0x01000193
uint32_max = 2 ** 32
for s in str:
hval = hval ^ ord(s)
hval = (hval * prime) % uint32_max
return hval
| (str: str) -> int |
7,061 | growthbook | gbhash | null | def gbhash(seed: str, value: str, version: int) -> Optional[float]:
if version == 2:
n = fnv1a32(str(fnv1a32(seed + value)))
return (n % 10000) / 10000
if version == 1:
n = fnv1a32(value + seed)
return (n % 1000) / 1000
return None
| (seed: str, value: str, version: int) -> Optional[float] |
7,062 | growthbook | getBucketRanges | null | def getBucketRanges(
numVariations: int, coverage: float = 1, weights: List[float] = None
) -> List[Tuple[float, float]]:
if coverage < 0:
coverage = 0
if coverage > 1:
coverage = 1
if weights is None:
weights = getEqualWeights(numVariations)
if len(weights) != numVariations:... | (numVariations: int, coverage: float = 1, weights: Optional[List[float]] = None) -> List[Tuple[float, float]] |
7,063 | growthbook | getEqualWeights | null | def getEqualWeights(numVariations: int) -> List[float]:
if numVariations < 1:
return []
return [1 / numVariations for _ in range(numVariations)]
| (numVariations: int) -> List[float] |
7,064 | growthbook | getPath | null | def getPath(attributes, path):
current = attributes
for segment in path.split("."):
if type(current) is dict and segment in current:
current = current[segment]
else:
return None
return current
| (attributes, path) |
7,065 | growthbook | getQueryStringOverride | null | def getQueryStringOverride(id: str, url: str, numVariations: int) -> Optional[int]:
res = urlparse(url)
if not res.query:
return None
qs = parse_qs(res.query)
if id not in qs:
return None
variation = qs[id][0]
if variation is None or not variation.isdigit():
return None
... | (id: str, url: str, numVariations: int) -> Optional[int] |
7,066 | growthbook | getType | null | def getType(attributeValue) -> str:
t = type(attributeValue)
if attributeValue is None:
return "null"
if t is int or t is float:
return "number"
if t is str:
return "string"
if t is list or t is set:
return "array"
if t is dict:
return "object"
if t i... | (attributeValue) -> str |
7,067 | growthbook | inNamespace | null | def inNamespace(userId: str, namespace: Tuple[str, float, float]) -> bool:
n = gbhash("__" + namespace[0], userId, 1)
if n is None:
return False
return namespace[1] <= n < namespace[2]
| (userId: str, namespace: Tuple[str, float, float]) -> bool |
7,068 | growthbook | inRange | null | def inRange(n: float, range: Tuple[float, float]) -> bool:
return range[0] <= n < range[1]
| (n: float, range: Tuple[float, float]) -> bool |
7,069 | growthbook | isIn | null | def isIn(conditionValue, attributeValue) -> bool:
if type(attributeValue) is list:
return bool(set(conditionValue) & set(attributeValue))
return attributeValue in conditionValue
| (conditionValue, attributeValue) -> bool |
7,070 | growthbook | isOperatorObject | null | def isOperatorObject(obj) -> bool:
for key in obj.keys():
if key[0] != "$":
return False
return True
| (obj) -> bool |
7,074 | growthbook | paddedVersionString | null | def paddedVersionString(input) -> str:
# If input is a number, convert to a string
if type(input) is int or type(input) is float:
input = str(input)
if not input or type(input) is not str:
input = "0"
# Remove build info and leading `v` if any
input = re.sub(r"(^v|\+.*$)", "", inpu... | (input) -> str |
7,076 | urllib.parse | parse_qs | Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retain... | def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
encoding='utf-8', errors='replace', max_num_fields=None, separator='&'):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating wh... | (qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&') |
7,080 | importlib.metadata | PackageNotFoundError | The package was not found. | class PackageNotFoundError(ModuleNotFoundError):
"""The package was not found."""
def __str__(self):
return f"No package metadata was found for {self.name}"
@property
def name(self):
(name,) = self.args
return name
| null |
7,081 | importlib.metadata | __str__ | null | def __str__(self):
return f"No package metadata was found for {self.name}"
| (self) |
7,083 | mapply.mapply | mapply | Run apply on n_workers. Split in chunks if sensible, gather results, and concat.
When using :meth:`mapply.init`, the signature of this method will behave the same as
:meth:`pandas.DataFrame.apply`/:meth:`pandas.Series.apply`/:meth:`pandas.core.groupby.GroupBy.apply`.
Args:
df_or_series: Argument r... | def mapply( # noqa: PLR0913
df_or_series: Any,
func: Callable,
axis: int | str = 0,
*,
n_workers: int = -1,
chunk_size: int = DEFAULT_CHUNK_SIZE,
max_chunks_per_worker: int = DEFAULT_MAX_CHUNKS_PER_WORKER,
progressbar: bool = True,
args: tuple[Any, ...] = (),
**kwargs: Any,
) ->... | (df_or_series: Any, func: Callable, axis: int | str = 0, *, n_workers: int = -1, chunk_size: int = 100, max_chunks_per_worker: int = 8, progressbar: bool = True, args: tuple[typing.Any, ...] = (), **kwargs: Any) -> Any |
7,085 | mapply | init | Patch Pandas, adding multi-core methods to PandasObject.
Subsequent calls to this function will create/overwrite methods with new settings.
Args:
n_workers: Maximum amount of workers (processes) to spawn. Might be lowered
depending on chunk_size and max_chunks_per_worker. Will throw a warn... | def init(
*,
n_workers: int = -1,
chunk_size: int = DEFAULT_CHUNK_SIZE,
max_chunks_per_worker: int = DEFAULT_MAX_CHUNKS_PER_WORKER,
progressbar: bool = True,
apply_name: str = "mapply",
):
"""Patch Pandas, adding multi-core methods to PandasObject.
Subsequent calls to this function will... | (*, n_workers: int = -1, chunk_size: int = 100, max_chunks_per_worker: int = 8, progressbar: bool = True, apply_name: str = 'mapply') |
7,088 | functools | partialmethod | Method descriptor with partial application of the given arguments
and keywords.
Supports wrapping existing descriptors and handles non-descriptor
callables as instance methods.
| class partialmethod(object):
"""Method descriptor with partial application of the given arguments
and keywords.
Supports wrapping existing descriptors and handles non-descriptor
callables as instance methods.
"""
def __init__(self, func, /, *args, **keywords):
if not callable(func) and... | (func, /, *args, **keywords) |
7,089 | functools | __get__ | null | def __get__(self, obj, cls=None):
get = getattr(self.func, "__get__", None)
result = None
if get is not None:
new_func = get(obj, cls)
if new_func is not self.func:
# Assume __get__ returning something new indicates the
# creation of an appropriate callable
... | (self, obj, cls=None) |
7,090 | functools | __init__ | null | def __init__(self, func, /, *args, **keywords):
if not callable(func) and not hasattr(func, "__get__"):
raise TypeError("{!r} is not callable or a descriptor"
.format(func))
# func could be a descriptor like classmethod which isn't callable,
# so we can't inherit from pa... | (self, func, /, *args, **keywords) |
7,091 | functools | __repr__ | null | def __repr__(self):
args = ", ".join(map(repr, self.args))
keywords = ", ".join("{}={!r}".format(k, v)
for k, v in self.keywords.items())
format_string = "{module}.{cls}({func}, {args}, {keywords})"
return format_string.format(module=self.__class__.__module__,
... | (self) |
7,092 | functools | _make_unbound_method | null | def _make_unbound_method(self):
def _method(cls_or_self, /, *args, **keywords):
keywords = {**self.keywords, **keywords}
return self.func(cls_or_self, *self.args, *args, **keywords)
_method.__isabstractmethod__ = self.__isabstractmethod__
_method._partialmethod = self
return _method
| (self) |
7,094 | plastik.ridge | Ridge | Plot data in a ridge plot with fixed width and fixed height per ridge.
Parameters
----------
data : List
A list of n 2-tuples with (x, y)-pairs; list of n np.ndarrays: (y)
options : str
String with characters that set different options. This include 'b' (blank), 'c'
(crop x-axis... | class Ridge:
"""Plot data in a ridge plot with fixed width and fixed height per ridge.
Parameters
----------
data : List
A list of n 2-tuples with (x, y)-pairs; list of n np.ndarrays: (y)
options : str
String with characters that set different options. This include 'b' (blank), 'c'
... | (data: List[Any], options: str, y_scale: float = 1.0, xlim: List[float] = NOTHING, ylim: List[float] = NOTHING, pltype: str = 'plot', kwargs: Dict[str, Any] = NOTHING, *, xlabel: Optional[str] = '', ylabel: Optional[str] = '') -> None |
7,095 | plastik.ridge | __blank | null | def __blank(self) -> None:
spine = ["top", "bottom", "left", "right"]
for sp in spine:
self.ax_objs[-1].spines[sp].set_visible(False)
plt.tick_params(
axis="both",
which="both",
bottom=False,
left=False,
top=False,
right=False,
labelbottom=Fals... | (self) -> NoneType |
7,096 | plastik.ridge | __draw_lines | null | def __draw_lines(self, s, col) -> None:
# Plot data
p_func = getattr(self.ax_objs[-1], self.pltype)
if len(s) == 2: # noqa: PLR2004
ell = p_func(s[0], s[1], color=col, markersize=2.5, **self.kwargs)[0]
else:
ell = p_func(s, color=col, markersize=2.5, **self.kwargs)[0]
# Append in li... | (self, s, col) -> NoneType |
7,097 | plastik.ridge | __g_option | null | def __g_option(self, i) -> None:
if ("g" in self.options and "z" not in self.options) or (
"g" in self.options and len(self.data) == 1
):
plt.grid(True, which="major", ls="-", alpha=0.2)
elif "g" in self.options:
plt.minorticks_off()
alpha = 0.2 if i in (0, len(self.data) - 1... | (self, i) -> NoneType |
7,098 | plastik.ridge | __resolve_first_last_axis | null | def __resolve_first_last_axis(self, i) -> None:
if i == len(self.data) - 1:
if self.xlabel:
plt.xlabel(self.xlabel)
if len(self.data) != 1:
plt.tick_params(axis="x", which="both", top=False)
elif i == 0:
plt.tick_params(
axis="x", which="both", bottom=... | (self, i) -> NoneType |
7,099 | plastik.ridge | __resolve_options | null | def __resolve_options(self, i, spines, col) -> None:
if len(self.data) != 1:
if "z" in self.options: # Squeeze
self.__z_option(i)
elif "s" in self.options: # Slalom axis
self.__s_option(i)
for sp in spines:
self.ax_objs[-1].spines[sp].set_visible(False)
... | (self, i, spines, col) -> NoneType |
7,100 | plastik.ridge | __s_option | null | def __s_option(self, i) -> None:
if i % 2:
self.ax_objs[-1].tick_params(
axis="y", which="both", labelleft=False, labelright=True
)
| (self, i) -> NoneType |
7,101 | plastik.ridge | __setup_axis | null | def __setup_axis(
self,
y_min: float,
y_max: float,
i: int,
s: Union[Tuple[np.ndarray, np.ndarray], np.ndarray],
) -> Tuple[
float, float, Union[Tuple[np.ndarray, np.ndarray], np.ndarray], List[str]
]:
self.ax_objs.append(self.__fig.add_subplot(self.gs[i : i + 1, 0:]))
if i == 0:
... | (self, y_min: float, y_max: float, i: int, s: Union[Tuple[numpy.ndarray, numpy.ndarray], numpy.ndarray]) -> Tuple[float, float, Union[Tuple[numpy.ndarray, numpy.ndarray], numpy.ndarray], List[str]] |
7,102 | plastik.ridge | __x_limit | null | def __x_limit(self, maxx=True) -> Tuple[float, float]:
if isinstance(self.data[0], tuple):
data: List[np.ndarray] = [d[0] for d in self.data]
else:
raise ValueError("'data' must have x-values.")
t_min = data[0]
x_max = data[0][-1]
for t in data[1:]:
t_0, t_max = np.min(t), np... | (self, maxx=True) -> Tuple[float, float] |
7,103 | plastik.ridge | __z_option | null | def __z_option(self, i) -> None:
if i % 2:
self.ax_objs[-1].tick_params(
axis="y",
which="both",
left=False,
labelleft=False,
labelright=True,
)
self.ax_objs[-1].spines["left"].set_color("k")
else:
self.ax_objs[-1].tick_... | (self, i) -> NoneType |
7,104 | plastik.ridge | __eq__ | Method generated by attrs for class Ridge. | """Creates a ridge plot figure."""
import itertools
from typing import Any, Dict, List, Optional, Tuple, Union
import attr
import matplotlib as mpl
import matplotlib.gridspec as grid_spec
import matplotlib.pyplot as plt
import numpy as np
import plastik
@attr.s(auto_attribs=True)
class Ridge:
"""Plot data in a... | (self, other) |
7,105 | plastik.ridge | __ge__ | Method generated by attrs for class Ridge. | null | (self, other) |
7,112 | plastik.ridge | _check_data_type | null | @data.validator
def _check_data_type(self, _, value):
if not isinstance(value[0], tuple) and not isinstance(value[0], np.ndarray):
raise TypeError(
"data must be a list of tuples or numpy arrays, not list of"
f" {type(self.data[0])}."
)
| (self, _, value) |
7,113 | plastik.ridge | _set_ymin_ymax | null | def _set_ymin_ymax(self, y_min, y_max):
self.ax.spines["top"].set_visible(False)
self.ax.spines["bottom"].set_visible(False)
self.ax.spines["left"].set_visible(False)
self.ax.spines["right"].set_visible(False)
if self.pltype != "plot":
pltype = "log" if self.pltype in ["semilogy", "loglog"] ... | (self, y_min, y_max) |
7,114 | plastik.ridge | data_loop | Run the data loop. | def data_loop(self) -> Tuple[float, float]:
"""Run the data loop."""
# Loop through data
self.__lines: List[plt.Line2D] = []
y_min = np.inf
y_max = -np.inf
for i, s in enumerate(self.data):
col = next(self.colors)
y_min, y_max, s_, spines = self.__setup_axis(y_min, y_max, i, s)
... | (self) -> Tuple[float, float] |
7,115 | plastik.ridge | main | Run the main function. | def main(self) -> None:
"""Run the main function."""
self.set_grid()
self.set_xaxs()
if self.ylabel:
self.set_ylabel()
y1, y2 = self.data_loop()
if self.ylabel:
self.set_ylabel(y1, y2)
| (self) -> NoneType |
7,116 | plastik.ridge | set_grid | Set the gridstructure of the figure. | def set_grid(self) -> None:
"""Set the gridstructure of the figure."""
fsize = (4, self.y_scale * len(self.data))
self.gs = grid_spec.GridSpec(len(self.data), 1)
self.__fig = plt.figure(figsize=fsize)
# Set line type of horizontal grid lines
self.gls = itertools.cycle(["-", "--"])
self.ax_ob... | (self) -> NoneType |
7,117 | plastik.ridge | set_xaxs | Set the x-axis limits. | def set_xaxs(self) -> None:
"""Set the x-axis limits."""
if self.xlim:
x_min, x_max = self.xlim
elif len(self.data[0]) != 2: # noqa: PLR2004
x_min, x_max = -0.5, len(self.data[0]) - 0.5
x_min = 0.5 if self.pltype in ["loglog", "semilogx"] else x_min
elif "c" in self.options:
... | (self) -> NoneType |
7,118 | plastik.ridge | set_ylabel | Set the y-axis label. | def set_ylabel(
self, y_min: Optional[float] = None, y_max: Optional[float] = None
) -> None:
"""Set the y-axis label."""
if y_min is None or y_max is None:
self.ax = self.__fig.add_subplot(111, frame_on=False)
self.ax.tick_params(
labelcolor="w",
axis="both",
... | (self, y_min: Optional[float] = None, y_max: Optional[float] = None) -> NoneType |
7,122 | plastik.axes | dark_theme | Change plot style to fit a dark background.
This is better in e.g. beamers with dark theme.
Parameters
----------
*ax : mpl.axes.Axes
Send in any number of matplotlib axes and the changes will be applied to all
fig : mpl.figure.Figure | None, optional
The figure object that should ... | def dark_theme(
*ax: mpl.axes.Axes,
fig: mpl.figure.Figure | None = None,
keep_yaxis: bool = False,
) -> None:
"""Change plot style to fit a dark background.
This is better in e.g. beamers with dark theme.
Parameters
----------
*ax : mpl.axes.Axes
Send in any number of matplotl... | (*ax: matplotlib.axes._axes.Axes, fig: Optional[matplotlib.figure.Figure] = None, keep_yaxis: bool = False) -> NoneType |
7,128 | plastik.percentiles | percentiles | Calculate percentiles from ensemble 'y' along 'x'.
Parameters
----------
x : np.ndarray
One dimensional array, x-axis.
y : np.ndarray
Values along y-axis. Need shape (N, len(x)).
n : int
The number of percentiles, linearly spaced from 50 to 'percentile_m{in,ax}'.
Def... | def percentiles( # noqa: PLR0913
x: np.ndarray,
y: np.ndarray,
n: int = 20,
ax: mpl.axes.Axes | None = None,
plot_mean: bool = False,
plot_median: bool = True,
**kwargs: Any,
) -> mpl.axes.Axes:
"""Calculate percentiles from ensemble 'y' along 'x'.
Parameters
----------
x :... | (x: numpy.ndarray, y: numpy.ndarray, n: int = 20, ax: Optional[matplotlib.axes._axes.Axes] = None, plot_mean: bool = False, plot_median: bool = True, **kwargs: Any) -> matplotlib.axes._axes.Axes |
7,132 | plastik.legends | topside_legends | Move the legend to the top of the plot.
Parameters
----------
ax : mpl.axes.Axes
The axes object of the figure
*args : Any
Parameters given to ax.legend(), i.e. handles and labels. This is useful if you
have many axes objects with one or more lines on them, but you want all line... | def topside_legends( # noqa: PLR0913
ax: mpl.axes.Axes,
*args: Any,
c_max: int = 4,
alpha: float = 0.8,
side: Literal[
"top",
"bottom",
"right",
"left",
"top right",
"top left",
"bottom right",
"bottom left",
] = "top",
edgecol... | (ax: matplotlib.axes._axes.Axes, *args: Any, c_max: int = 4, alpha: float = 0.8, side: Literal['top', 'bottom', 'right', 'left', 'top right', 'top left', 'bottom right', 'bottom left'] = 'top', edgecolor: str | tuple[float, float, float] = '', facecolor: str | tuple[float, float, float] = '', anchor_: Optional[tuple[fl... |
7,134 | ipl3checksum | CICKind | Enum that represents a CIC kind | from ipl3checksum import CICKind
| null |
7,138 | wikitools3.api | APIDisabled | API not enabled | class APIDisabled(APIError):
"""API not enabled"""
| null |
7,139 | wikitools3.api | APIError | Base class for errors | class APIError(Exception):
"""Base class for errors"""
| null |
7,140 | wikitools3.api | APIListResult | null | class APIListResult(list):
response = []
| (iterable=(), /) |
7,141 | wikitools3.api | APIRequest | A request to the site's API | class APIRequest:
"""A request to the site's API"""
def __init__(self, wiki, data, write=False, multipart=False):
"""
wiki - A Wiki object
data - API parameters in the form of a dict
write - set to True if doing a write query, so it won't try again on error
multipart - u... | (wiki, data, write=False, multipart=False) |
7,142 | wikitools3.api | __getRaw | null | def __getRaw(self):
data = False
while not data:
try:
if self.sleep >= self.wiki.maxwaittime or self.iswrite:
catcherror = None
else:
catcherror = Exception
data = self.opener.open(self.request)
self.response = data.info()
... | (self) |
7,143 | wikitools3.api | __longQuery | For queries that require multiple requests | def __longQuery(self, initialdata):
"""For queries that require multiple requests"""
self._continues = set()
self._generator = ""
total = initialdata
res = initialdata
params = self.data
numkeys = len(res["query-continue"].keys())
while numkeys > 0:
key1 = ""
key2 = ""
... | (self, initialdata) |
7,144 | wikitools3.api | __parseJSON | null | def __parseJSON(self, data):
maxlag = True
while maxlag:
try:
maxlag = False
parsed = json.loads(data.read())
content = None
if isinstance(parsed, dict):
content = APIResult(parsed)
content.response = self.response.items()
... | (self, data) |
7,145 | wikitools3.api | __init__ |
wiki - A Wiki object
data - API parameters in the form of a dict
write - set to True if doing a write query, so it won't try again on error
multipart - use multipart data transfer, required for file uploads,
requires the poster3 package
maxlag is set by default to 5 but... | def __init__(self, wiki, data, write=False, multipart=False):
"""
wiki - A Wiki object
data - API parameters in the form of a dict
write - set to True if doing a write query, so it won't try again on error
multipart - use multipart data transfer, required for file uploads,
requires the poster3 p... | (self, wiki, data, write=False, multipart=False) |
7,146 | wikitools3.api | changeParam | Change or add a parameter after making the request object
Simply changing self.data won't work as it needs to update other things.
value can either be a normal string value, or a file-like object,
which will be uploaded, if setMultipart was called previously.
| def changeParam(self, param, value):
"""Change or add a parameter after making the request object
Simply changing self.data won't work as it needs to update other things.
value can either be a normal string value, or a file-like object,
which will be uploaded, if setMultipart was called previously.
... | (self, param, value) |
7,147 | wikitools3.api | query | Actually do the query here and return usable stuff
querycontinue - look for query-continue in the results and continue querying
until there is no more data to retrieve (DEPRECATED: use queryGen as a more
reliable and efficient alternative)
| def query(self, querycontinue=True):
"""Actually do the query here and return usable stuff
querycontinue - look for query-continue in the results and continue querying
until there is no more data to retrieve (DEPRECATED: use queryGen as a more
reliable and efficient alternative)
"""
if querycont... | (self, querycontinue=True) |
7,148 | wikitools3.api | queryGen | Unlike the old query-continue method that tried to stitch results
together, which could work poorly for complex result sets and could
use a lot of memory, this yield each set returned by the API and lets
the user process the data.
Loosely based on the recommended implementation on mediaw... | def queryGen(self):
"""Unlike the old query-continue method that tried to stitch results
together, which could work poorly for complex result sets and could
use a lot of memory, this yield each set returned by the API and lets
the user process the data.
Loosely based on the recommended implementatio... | (self) |
7,149 | wikitools3.api | setMultipart | Enable multipart data transfer, required for file uploads. | def setMultipart(self, multipart=True):
"""Enable multipart data transfer, required for file uploads."""
if not canupload and multipart:
raise APIError("The poster3 package is required for multipart support")
self.multipart = multipart
if multipart:
(datagen, headers) = multipart_encode(... | (self, multipart=True) |
7,150 | wikitools3.api | APIResult | null | class APIResult(dict):
response = []
| null |
7,151 | wikitools3.page | BadNamespace | Invalid namespace number | class BadNamespace(wiki.WikiError):
"""Invalid namespace number"""
| null |
7,152 | wikitools3.page | BadTitle | Invalid title | class BadTitle(wiki.WikiError):
"""Invalid title"""
| null |
7,153 | wikitools3.category | Category | A category on the wiki | class Category(page.Page):
"""A category on the wiki"""
def __init__(
self,
site,
title=False,
check=True,
followRedir=False,
section=False,
sectionnumber=False,
pageid=False,
):
"""
wiki - A wiki object
title - The pag... | (site, title=False, check=True, followRedir=False, section=False, sectionnumber=False, pageid=False) |
7,154 | wikitools3.category | __getMembersInternal | null | def __getMembersInternal(self, namespaces=False):
params = {
"action": "query",
"list": "categorymembers",
"cmtitle": self.title,
"cmlimit": self.site.limit,
"cmprop": "title",
}
if namespaces is not False:
params["cmnamespace"] = "|".join([str(ns) for ns in n... | (self, namespaces=False) |
7,155 | wikitools3.page | __extractToList | null | def __extractToList(self, json, stuff):
list = []
if self.pageid == 0:
self.pageid = json["query"]["pages"].keys()[0]
if stuff in json["query"]["pages"][str(self.pageid)]:
for item in json["query"]["pages"][str(self.pageid)][stuff]:
list.append(item["title"])
return list
| (self, json, stuff) |
7,156 | wikitools3.page | __getHistoryInternal | null | def __getHistoryInternal(self, direction, content, limit, rvcontinue):
if self.pageid == 0 and not self.title:
self.setPageInfo()
if not self.exists:
raise NoPage
if direction != "newer" and direction != "older":
raise wiki.WikiError("direction must be 'newer' or 'older'")
params... | (self, direction, content, limit, rvcontinue) |
7,157 | wikitools3.page | __getSection | null | def __getSection(self, section):
if not self.title:
self.setPageInfo()
params = {"action": "parse", "page": self.title, "prop": "sections"}
number = False
req = api.APIRequest(self.site, params)
response = req.query()
for item in response["parse"]["sections"]:
if section == item[... | (self, section) |
7,158 | wikitools3.page | __eq__ | null | def __eq__(self, other):
if not isinstance(other, Page):
return False
if self.title:
if self.title == other.title and self.site == other.site:
return True
else:
if self.pageid == other.pageid and self.site == other.site:
return True
return False
| (self, other) |
7,159 | wikitools3.page | __hash__ | null | def __hash__(self):
return int(self.pageid) ^ hash(self.site.apibase)
| (self) |
7,160 | wikitools3.category | __init__ |
wiki - A wiki object
title - The page title, as a string or unicode object
check - Checks for existence, normalizes title, required for most things
followRedir - follow redirects (check must be true)
section - the section name
sectionnumber - the section number
p... | def __init__(
self,
site,
title=False,
check=True,
followRedir=False,
section=False,
sectionnumber=False,
pageid=False,
):
"""
wiki - A wiki object
title - The page title, as a string or unicode object
check - Checks for existence, normalizes title, required for most thin... | (self, site, title=False, check=True, followRedir=False, section=False, sectionnumber=False, pageid=False) |
7,161 | wikitools3.page | __ne__ | null | def __ne__(self, other):
if not isinstance(other, Page):
return True
if self.title:
if self.title == other.title and self.site == other.site:
return False
else:
if self.pageid == other.pageid and self.site == other.site:
return False
return True
| (self, other) |
7,162 | wikitools3.page | __repr__ | null | def __repr__(self):
if self.title:
title = self.title
else:
title = "pageid: " + self.pageid
return (
"<"
+ self.__module__
+ "."
+ self.__class__.__name__
+ " "
+ repr(title)
+ " using "
+ repr(self.site.apibase)
+ ">"
... | (self) |
7,163 | wikitools3.page | __str__ | null | def __str__(self):
if self.title:
title = self.title
else:
title = "pageid: " + self.pageid
return (
self.__class__.__name__
+ " "
+ repr(title)
+ " from "
+ repr(self.site.domain)
)
| (self) |
7,164 | wikitools3.page | canHaveSubpages | Is the page in a namespace that allows subpages? | def canHaveSubpages(self):
"""Is the page in a namespace that allows subpages?"""
if not self.title:
self.setPageInfo()
return "subpages" in self.site.namespaces[self.namespace]
| (self) |
7,165 | wikitools3.page | delete | Delete the page
reason - summary for log
watch - add the page to your watchlist
unwatch - remove the page from your watchlist
| def delete(self, reason=False, watch=False, unwatch=False):
"""Delete the page
reason - summary for log
watch - add the page to your watchlist
unwatch - remove the page from your watchlist
"""
if not self.title and self.pageid == 0:
self.setPageInfo()
if not self.exists:
rais... | (self, reason=False, watch=False, unwatch=False) |
7,166 | wikitools3.page | edit | Edit the page
Arguments are a subset of the API's action=edit arguments, valid arguments
are defined in the validargs set
To skip the MD5 check, set "skipmd5" keyword argument to True
http://www.mediawiki.org/wiki/API:Edit_-_Create%26Edit_pages#Parameters
For backwards compatib... | def edit(self, *args, **kwargs):
"""Edit the page
Arguments are a subset of the API's action=edit arguments, valid arguments
are defined in the validargs set
To skip the MD5 check, set "skipmd5" keyword argument to True
http://www.mediawiki.org/wiki/API:Edit_-_Create%26Edit_pages#Parameters
For ... | (self, *args, **kwargs) |
7,167 | wikitools3.category | getAllMembers | Gets a list of pages in the category
titleonly - set to True to only create a list of strings,
else it will be a list of Page objects
reload - reload the list even if it was generated before
namespaces - List of namespaces to restrict to (queries with this option will not be cached)
... | def getAllMembers(self, titleonly=False, reload=False, namespaces=False):
"""Gets a list of pages in the category
titleonly - set to True to only create a list of strings,
else it will be a list of Page objects
reload - reload the list even if it was generated before
namespaces - List of namespaces ... | (self, titleonly=False, reload=False, namespaces=False) |
7,168 | wikitools3.category | getAllMembersGen | Generator function for pages in the category
titleonly - set to True to return strings,
else it will return Page objects
reload - reload the list even if it was generated before
namespaces - List of namespaces to restrict to (queries with this option will not be cached)
| def getAllMembersGen(self, titleonly=False, reload=False, namespaces=False):
"""Generator function for pages in the category
titleonly - set to True to return strings,
else it will return Page objects
reload - reload the list even if it was generated before
namespaces - List of namespaces to restric... | (self, titleonly=False, reload=False, namespaces=False) |
7,169 | wikitools3.page | getCategories | Gets all list of all the categories on the page
force - load the list even if we already loaded it before
| def getCategories(self, force=False):
"""Gets all list of all the categories on the page
force - load the list even if we already loaded it before
"""
if self.categories and not force:
return self.categories
if self.pageid == 0 and not self.title:
self.setPageInfo()
if not self.e... | (self, force=False) |
7,170 | wikitools3.page | getHistory | Get the history of a page
direction - 2 options: 'older' (default) - start with the current revision and get older ones
'newer' - start with the oldest revision and get newer ones
content - If False, get only metadata (timestamp, edit summary, user, etc)
If True (default), also ... | def getHistory(self, direction="older", content=True, limit="all"):
"""Get the history of a page
direction - 2 options: 'older' (default) - start with the current revision and get older ones
'newer' - start with the oldest revision and get newer ones
content - If False, get only metadata (timestamp,... | (self, direction='older', content=True, limit='all') |
7,171 | wikitools3.page | getHistoryGen | Generator function for page history
The interface is the same as getHistory, but it will only retrieve 1 revision at a time.
This will be slower and have much higher network overhead, but does not require storing
the entire page history in memory
| def getHistoryGen(self, direction="older", content=True, limit="all"):
"""Generator function for page history
The interface is the same as getHistory, but it will only retrieve 1 revision at a time.
This will be slower and have much higher network overhead, but does not require storing
the entire page h... | (self, direction='older', content=True, limit='all') |
7,172 | wikitools3.page | getLinks | Gets a list of all the internal links *on* the page
force - load the list even if we already loaded it before
| def getLinks(self, force=False):
"""Gets a list of all the internal links *on* the page
force - load the list even if we already loaded it before
"""
if self.links and not force:
return self.links
if self.pageid == 0 and not self.title:
self.setPageInfo()
if not self.exists:
... | (self, force=False) |
7,173 | wikitools3.page | getProtection | Returns the current protection status of the page | def getProtection(self, force=False):
"""Returns the current protection status of the page"""
if self.protection and not force:
return self.protection
if self.pageid == 0 and not self.title:
self.setPageInfo()
params = {
"action": "query",
"prop": "info",
"inprop"... | (self, force=False) |
7,174 | wikitools3.page | getTemplates | Gets all list of all the templates on the page
force - load the list even if we already loaded it before
| def getTemplates(self, force=False):
"""Gets all list of all the templates on the page
force - load the list even if we already loaded it before
"""
if self.templates and not force:
return self.templates
if self.pageid == 0 and not self.title:
self.setPageInfo()
if not self.exist... | (self, force=False) |
7,175 | wikitools3.page | getWikiText | Gets the Wikitext of the page
expandtemplates - expand the templates to wikitext instead of transclusions
force - load the text even if we already loaded it before
| def getWikiText(self, expandtemplates=False, force=False):
"""Gets the Wikitext of the page
expandtemplates - expand the templates to wikitext instead of transclusions
force - load the text even if we already loaded it before
"""
if self.wikitext and not force:
return self.wikitext
if se... | (self, expandtemplates=False, force=False) |
7,176 | wikitools3.page | isRedir | Is the page a redirect? | def isRedir(self):
"""Is the page a redirect?"""
params = {"action": "query", "redirects": ""}
if not self.exists:
raise NoPage
if self.pageid != 0 and self.exists:
params["pageids"] = self.pageid
elif self.title:
params["titles"] = self.title
else:
self.setPageIn... | (self) |
7,177 | wikitools3.page | isTalk | Is the page a discussion page? | def isTalk(self):
"""Is the page a discussion page?"""
if not self.title:
self.setPageInfo()
return self.namespace % 2 == 1 and self.namespace >= 0
| (self) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.