code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# TODO: rename to `mr_dim_idxs` or better yet get rid of need for
# this as it's really a cube internal characteristic.
# TODO: Make this return a tuple in all cases, like (), (1,), or (0, 2).
indices = tuple(
idx
for idx, d in enumerate(self.dimensions)
... | def mr_dim_ind(self) | Return int, tuple of int, or None, representing MR indices.
The return value represents the index of each multiple-response (MR)
dimension in this cube. Return value is None if there are no MR
dimensions, and int if there is one MR dimension, and a tuple of int
when there are more than ... | 8.873476 | 7.666524 | 1.157431 |
population_counts = [
slice_.population_counts(
population_size,
weighted=weighted,
include_missing=include_missing,
include_transforms_for_dims=include_transforms_for_dims,
prune=prune,
)
... | def population_counts(
self,
population_size,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
) | Return counts scaled in proportion to overall population.
The return value is a numpy.ndarray object. Count values are scaled
proportionally to approximate their value if the entire population
had been sampled. This calculation is based on the estimated size of
the population provided a... | 1.929382 | 2.630751 | 0.733396 |
# Calculate numerator from table (include all H&S dimensions).
table = self._measure(weighted).raw_cube_array
num = self._apply_subtotals(
self._apply_missings(table), include_transforms_for_dims
)
proportions = num / self._denominator(
weighted... | def proportions(
self,
axis=None,
weighted=True,
include_transforms_for_dims=None,
include_mr_cat=False,
prune=False,
) | Return percentage values for cube as `numpy.ndarray`.
This function calculates the proportions across the selected axis
of a crunch cube. For most variable types, it means the value divided
by the margin value. For a multiple-response variable, the value is
divided by the sum of selecte... | 4.833557 | 4.919864 | 0.982457 |
table = self._measure(weighted).raw_cube_array
new_axis = self._adjust_axis(axis)
index = tuple(
None if i in new_axis else slice(None) for i, _ in enumerate(table.shape)
)
hs_dims = self._hs_dims_for_den(include_transforms_for_dims, axis)
den = self... | def _denominator(self, weighted, include_transforms_for_dims, axis) | Calculate denominator for percentages.
Only include those H&S dimensions, across which we DON'T sum. These H&S
are needed because of the shape, when dividing. Those across dims
which are summed across MUST NOT be included, because they would
change the result. | 6.263795 | 5.878859 | 1.065478 |
slices_means = [ScaleMeans(slice_).data for slice_ in self.slices]
if hs_dims and self.ndim > 1:
# Intersperse scale means with nans if H&S specified, and 2D. No
# need to modify 1D, as only one mean will ever be inserted.
inserted_indices = self.inserted_hs... | def scale_means(self, hs_dims=None, prune=False) | Get cube means. | 3.829886 | 3.790684 | 1.010342 |
res = [s.zscore(weighted, prune, hs_dims) for s in self.slices]
return np.array(res) if self.ndim == 3 else res[0] | def zscore(self, weighted=True, prune=False, hs_dims=None) | Return ndarray with cube's zscore measurements.
Zscore is a measure of statistical significance of observed vs.
expected counts. It's only applicable to a 2D contingency tables.
For 3D cubes, the measures of separate slices are stacked together
and returned as the result.
:para... | 3.718393 | 4.388909 | 0.847225 |
return [slice_.wishart_pairwise_pvals(axis=axis) for slice_ in self.slices] | def wishart_pairwise_pvals(self, axis=0) | Return matrices of column-comparison p-values as list of numpy.ndarrays.
Square, symmetric matrix along *axis* of pairwise p-values for the
null hypothesis that col[i] = col[j] for each pair of columns.
*axis* (int): axis along which to perform comparison. Only columns (0)
are implemen... | 5.559543 | 9.195735 | 0.604578 |
if not self._is_axis_allowed(axis):
ca_error_msg = "Direction {} not allowed (items dimension)"
raise ValueError(ca_error_msg.format(axis))
if isinstance(axis, int):
# If single axis was provided, create a list out of it, so that
# we can do the ... | def _adjust_axis(self, axis) | Return raw axis/axes corresponding to apparent axis/axes.
This method adjusts user provided 'axis' parameter, for some of the
cube operations, mainly 'margin'. The user never sees the MR selections
dimension, and treats all MRs as single dimensions. Thus we need to
adjust the values of ... | 7.692146 | 7.129601 | 1.078903 |
# Created a copy, to preserve cached property
updated_inserted = [[i for i in dim_inds] for dim_inds in inserted_indices_list]
pruned_and_inserted = zip(prune_indices_list, updated_inserted)
for prune_inds, inserted_inds in pruned_and_inserted:
# Only prune indices i... | def _adjust_inserted_indices(inserted_indices_list, prune_indices_list) | Adjust inserted indices, if there are pruned elements. | 4.569804 | 4.381442 | 1.042991 |
# --element idxs that satisfy `include_missing` arg. Note this
# --includes MR_CAT elements so is essentially all-or-valid-elements
element_idxs = tuple(
(
d.all_elements.element_idxs
if include_missing
else d.valid_elements.el... | def _apply_missings(self, res, include_missing=False) | Return ndarray with missing and insertions as specified.
The return value is the result of the following operations on *res*,
which is a raw cube value array (raw meaning it has shape of original
cube response).
* Remove vectors (rows/cols) for missing elements if *include_missin*
... | 12.664193 | 12.763754 | 0.9922 |
if not include_transforms_for_dims:
return res
suppressed_dim_count = 0
for (dim_idx, dim) in enumerate(self._all_dimensions):
if dim.dimension_type == DT.MR_CAT:
suppressed_dim_count += 1
# ---only marginable dimensions can be subtot... | def _apply_subtotals(self, res, include_transforms_for_dims) | * Insert subtotals (and perhaps other insertions later) for
dimensions having their apparent dimension-idx in
*include_transforms_for_dims*. | 4.763191 | 4.303227 | 1.106888 |
return self._apply_subtotals(
self._apply_missings(
self._measure(weighted).raw_cube_array, include_missing=include_missing
),
include_transforms_for_dims,
) | def _as_array(
self,
include_missing=False,
get_non_selected=False,
weighted=True,
include_transforms_for_dims=False,
) | Get crunch cube as ndarray.
Args
include_missing (bool): Include rows/cols for missing values.
get_non_selected (bool): Get non-selected slices for MR vars.
weighted (bool): Take weighted or unweighted counts.
include_transforms_for_dims (list): For which dims to... | 9.243688 | 9.058848 | 1.020404 |
if axis not in [0, 1]:
raise ValueError("Unexpected value for `axis`: {}".format(axis))
V = prop_table * (1 - prop_table)
if axis == 0:
# If axis is 0, sumation is performed across the 'i' index, which
# requires the matrix to be multiplied from the ... | def _calculate_constraints_sum(cls, prop_table, prop_margin, axis) | Calculate sum of constraints (part of the standard error equation).
This method calculates the sum of the cell proportions multiplied by
row (or column) marginal proportions (margins divide by the total
count). It does this by utilizing the matrix multiplication, which
directly translat... | 3.624884 | 3.355461 | 1.080294 |
return (
self._measures.weighted_counts
if weighted
else self._measures.unweighted_counts
) | def _counts(self, weighted) | Return _BaseMeasure subclass for *weighted* counts.
The return value is a _WeightedCountMeasure object if *weighted* is
True and the cube response is weighted. Otherwise it is an
_UnweightedCountMeasure object. Any means measure that may be present
is not considered. Contrast with `._me... | 5.812038 | 4.798891 | 1.211121 |
try:
cube_response = self._cube_response_arg
# ---parse JSON to a dict when constructed with JSON---
cube_dict = (
cube_response
if isinstance(cube_response, dict)
else json.loads(cube_response)
)
... | def _cube_dict(self) | dict containing raw cube response, parsed from JSON payload. | 7.143432 | 6.179585 | 1.155973 |
# TODO: We cannot arbitrarily drop any dimension simply because it
# has a length (shape) of 1. We must target MR_CAT dimensions
# specifically. Otherwise unexpected results can occur based on
# accidents of cube category count etc. If "user-friendly" reshaping
# needs b... | def _drop_mr_cat_dims(self, array, fix_valids=False) | Return ndarray reflecting *array* with MR_CAT dims dropped.
If any (except 1st) dimension has a single element, it is
flattened in the resulting array (which is more convenient for the
users of the CrunchCube).
If the original shape of the cube is needed (e.g. to calculate the
... | 9.240646 | 9.013028 | 1.025254 |
# TODO: make this accept an immutable sequence for valid_indices
# (a tuple) and return an immutable sequence rather than mutating an
# argument.
indices = np.array(sorted(valid_indices[dim]))
slice_index = np.sum(indices <= insertion_index)
indices[slice_index:]... | def _fix_valid_indices(cls, valid_indices, insertion_index, dim) | Add indices for H&S inserted elements. | 4.763848 | 4.570493 | 1.042305 |
def iter_insertions():
for anchor_idx, addend_idxs in dimension.hs_indices:
insertion_idx = (
-1
if anchor_idx == "top"
else result.shape[dimension_index] - 1
if anchor_idx == "bottom"
... | def _insertions(self, result, dimension, dimension_index) | Return list of (idx, sum) pairs representing subtotals.
*idx* is the int offset at which to insert the ndarray subtotal
in *sum*. | 4.141159 | 3.937025 | 1.05185 |
if axis is None:
# If table direction was requested, we must ensure that each slice
# doesn't have the CA items dimension (thus the [-2:] part). It's
# OK for the 0th dimension to be items, since no calculation is
# performed over it.
if DT.CA... | def _is_axis_allowed(self, axis) | Check if axis are allowed.
In case the calculation is requested over CA items dimension, it is not
valid. It's valid in all other cases. | 9.997746 | 8.307426 | 1.203471 |
return (
self._measures.means
if self._measures.means is not None
else self._measures.weighted_counts
if weighted
else self._measures.unweighted_counts
) | def _measure(self, weighted) | _BaseMeasure subclass representing primary measure for this cube.
If the cube response includes a means measure, the return value is
means. Otherwise it is counts, with the choice between weighted or
unweighted determined by *weighted*.
Note that weighted counts are provided on an "as-... | 4.512526 | 3.575178 | 1.262182 |
mask = np.zeros(res.shape)
mr_dim_idxs = self.mr_dim_ind
for i, prune_inds in enumerate(self.prune_indices(transforms)):
rows_pruned = prune_inds[0]
cols_pruned = prune_inds[1]
rows_pruned = np.repeat(rows_pruned[:, None], len(cols_pruned), axis=1)
... | def _prune_3d_body(self, res, transforms) | Return masked array where mask indicates pruned vectors.
*res* is an ndarray (result). *transforms* is a list of ... | 2.324731 | 2.290228 | 1.015065 |
if self.ndim > 2:
return self._prune_3d_body(res, transforms)
res = self._drop_mr_cat_dims(res)
# ---determine which rows should be pruned---
row_margin = self._pruning_base(
hs_dims=transforms, axis=self.row_direction_axis
)
# ---adjust... | def _prune_body(self, res, transforms=None) | Return a masked version of *res* where pruned rows/cols are masked.
Return value is an `np.ma.MaskedArray` object. Pruning is the removal
of rows or columns whose corresponding marginal elements are either
0 or not defined (np.nan). | 5.162539 | 5.004422 | 1.031595 |
if self.ndim >= 3:
# In case of a 3D cube, return list of tuples
# (of row and col pruned indices).
return self._prune_3d_indices(transforms)
def prune_non_3d_indices(transforms):
row_margin = self._pruning_base(
hs_dims=transform... | def prune_indices(self, transforms=None) | Return indices of pruned rows and columns as list.
The return value has one of three possible forms:
* a 1-element list of row indices (in case of 1D cube)
* 2-element list of row and col indices (in case of 2D cube)
* n-element list of tuples of 2 elements (if it's 3D cube).
... | 3.655079 | 3.375757 | 1.082744 |
if not self._is_axis_allowed(axis):
# In case we encountered axis that would go across items dimension,
# we need to return at least some result, to prevent explicitly
# checking for this condition, wherever self._margin is used
return self.as_array(weigh... | def _pruning_base(self, axis=None, hs_dims=None) | Gets margin if across CAT dimension. Gets counts if across items.
Categorical variables are pruned based on their marginal values. If the
marginal is a 0 or a NaN, the corresponding row/column is pruned. In
case of a subvars (items) dimension, we only prune if all the counts
of the corr... | 14.057162 | 13.461461 | 1.044252 |
for j, (ind_insertion, value) in enumerate(insertions):
result = np.insert(
result, ind_insertion + j + 1, value, axis=dimension_index
)
return result | def _update_result(self, result, insertions, dimension_index) | Insert subtotals into resulting ndarray. | 4.469639 | 3.843829 | 1.162809 |
cube_dict = self._cube_dict
if cube_dict.get("query", {}).get("weight") is not None:
return True
if cube_dict.get("weight_var") is not None:
return True
if cube_dict.get("weight_url") is not None:
return True
unweighted_counts = cube_d... | def is_weighted(self) | True if weights have been applied to the measure(s) for this cube.
Unweighted counts are available for all cubes. Weighting applies to
any other measures provided by the cube. | 3.792822 | 3.525736 | 1.075753 |
mean_measure_dict = (
self._cube_dict.get("result", {}).get("measures", {}).get("mean")
)
if mean_measure_dict is None:
return None
return _MeanMeasure(self._cube_dict, self._all_dimensions) | def means(self) | _MeanMeasure object providing access to means values.
None when the cube response does not contain a mean measure. | 6.356893 | 4.092938 | 1.553137 |
if self.means:
return self.means.missing_count
return self._cube_dict["result"].get("missing", 0) | def missing_count(self) | numeric representing count of missing rows in cube response. | 13.549359 | 8.73512 | 1.551136 |
numerator = self._cube_dict["result"].get("filtered", {}).get("weighted_n")
denominator = self._cube_dict["result"].get("unfiltered", {}).get("weighted_n")
try:
return numerator / denominator
except ZeroDivisionError:
return np.nan
except Exceptio... | def population_fraction(self) | The filtered/unfiltered ratio for cube response.
This value is required for properly calculating population on a cube
where a filter has been applied. Returns 1.0 for an unfiltered cube.
Returns `np.nan` if the unfiltered count is zero, which would
otherwise result in a divide-by-zero e... | 4.983001 | 3.376183 | 1.475927 |
if not self.is_weighted:
return self.unweighted_counts
return _WeightedCountMeasure(self._cube_dict, self._all_dimensions) | def weighted_counts(self) | _WeightedCountMeasure object for this cube.
This object provides access to weighted counts for this cube, if
available. If the cube response is not weighted, the
_UnweightedCountMeasure object for this cube is returned. | 12.220836 | 5.575602 | 2.191842 |
if not self.is_weighted:
return float(self.unweighted_n)
return float(sum(self._cube_dict["result"]["measures"]["count"]["data"])) | def weighted_n(self) | float count of returned rows adjusted for weighting. | 12.251472 | 9.386472 | 1.305226 |
array = np.array(self._flat_values).reshape(self._all_dimensions.shape)
# ---must be read-only to avoid hard-to-find bugs---
array.flags.writeable = False
return array | def raw_cube_array(self) | Return read-only ndarray of measure values from cube-response.
The shape of the ndarray mirrors the shape of the (raw) cube
response. Specifically, it includes values for missing elements, any
MR_CAT dimensions, and any prunable rows and columns. | 9.450114 | 8.784028 | 1.075829 |
return tuple(
np.nan if type(x) is dict else x
for x in self._cube_dict["result"]["measures"]["mean"]["data"]
) | def _flat_values(self) | Return tuple of mean values as found in cube response.
Mean data may include missing items represented by a dict like
{'?': -1} in the cube response. These are replaced by np.nan in the
returned value. | 13.106736 | 6.402826 | 2.047024 |
input_dataframe_by_entity = dict()
person_entity = [entity for entity in tax_benefit_system.entities if entity.is_person][0]
person_id = np.arange(nb_persons)
input_dataframe_by_entity = dict()
input_dataframe_by_entity[person_entity.key] = pd.DataFrame({
person_entity.key + '_id': pers... | def make_input_dataframe_by_entity(tax_benefit_system, nb_persons, nb_groups) | Generate a dictionnary of dataframes containing nb_persons persons spread in nb_groups groups.
:param TaxBenefitSystem tax_benefit_system: the tax_benefit_system to use
:param int nb_persons: the number of persons in the system
:param int nb_groups: the number of collective entities in the syst... | 2.65708 | 2.552596 | 1.040932 |
variable = tax_benefit_system.variables[variable_name]
entity = variable.entity
if condition is None:
condition = True
else:
condition = input_dataframe_by_entity[entity.key].eval(condition).values
if seed is None:
seed = 42
np.random.seed(seed)
count = len(i... | def randomly_init_variable(tax_benefit_system, input_dataframe_by_entity, variable_name, max_value, condition = None, seed = None) | Initialise a variable with random values (from 0 to max_value).
If a condition vector is provided, only set the value of persons or groups for which condition is True.
Exemple:
>>> from openfisca_survey_manager.input_dataframe_generator import make_input_dataframe_by_entity
>>> from op... | 2.719612 | 2.912966 | 0.933623 |
assert variable is not None, "A variable is needed"
if table not in self.tables:
log.error("Table {} is not found in survey tables".format(table))
df = self.get_values([variable], table)
return df | def get_value(self, variable = None, table = None) | Get value
Parameters
----------
variable : string
name of the variable
table : string, default None
name of the table hosting the variable
Returns
-------
df : DataFrame, default None
A DataFrame containing the varia... | 5.545197 | 6.756849 | 0.820678 |
assert self.hdf5_file_path is not None
assert os.path.exists(self.hdf5_file_path), '{} is not a valid path'.format(
self.hdf5_file_path)
store = pandas.HDFStore(self.hdf5_file_path)
try:
df = store.select(table)
except KeyError:
log.e... | def get_values(self, variables = None, table = None, lowercase = False, rename_ident = True) | Get values
Parameters
----------
variables : list of strings, default None
list of variables names, if None return the whole table
table : string, default None
name of the table hosting the variables
lowercase : boolean, deflault True
... | 2.532968 | 2.588837 | 0.978419 |
data_frame = kwargs.pop('data_frame', None)
if data_frame is None:
data_frame = kwargs.pop('dataframe', None)
to_hdf_kwargs = kwargs.pop('to_hdf_kwargs', dict())
if data_frame is not None:
assert isinstance(data_frame, pandas.DataFrame)
if data... | def insert_table(self, label = None, name = None, **kwargs) | Insert a table in the Survey object | 2.541255 | 2.439422 | 1.041745 |
def formula(entity, period):
value = entity(variable, period)
if weight_variable is not None:
weight = entity(weight_variable, period)
weight = entity.filled_array(1)
if filter_variable is not None:
filter_value = entity(filter_variable, period)
... | def quantile(q, variable, weight_variable = None, filter_variable = None) | Return quantile of a variable with weight provided by a specific wieght variable potentially filtered | 4.364223 | 4.636698 | 0.941235 |
with open("../waliki/__init__.py") as fh:
for line in fh:
if line.startswith("__version__ = "):
return line.split("=")[-1].strip().strip("'").strip('"') | def _get_version() | Get the version from package itself. | 3.180027 | 3.098999 | 1.026147 |
rst = rst_content.split('\n')
for i, line in enumerate(rst):
if line.startswith('#'):
continue
break
return '\n'.join(rst[i:]) | def clean_meta(rst_content) | remove moinmoin metada from the top of the file | 3.240746 | 3.063663 | 1.057801 |
from waliki.plugins import get_plugins
includes = []
for plugin in get_plugins():
template_name = 'waliki/%s_%s.html' % (plugin.slug, block_name)
try:
# template exists
template.loader.get_template(template_name)
includes.append(template_name)
... | def entry_point(context, block_name) | include an snippet at the bottom of a block, if it exists
For example, if the plugin with slug 'attachments' is registered
waliki/attachments_edit_content.html will be included with
{% entry_point 'edit_content' %}
which is declared at the bottom of the block 'content' in edit.html | 3.433248 | 2.912082 | 1.178967 |
bits = token.split_contents()
format = '{% check_perms "perm1[, perm2, ...]" for user in slug as "context_var" %}'
if len(bits) != 8 or bits[2] != 'for' or bits[4] != "in" or bits[6] != 'as':
raise template.TemplateSyntaxError("get_obj_perms tag should be in "
... | def check_perms(parser, token) | Returns a list of permissions (as ``codename`` strings) for a given
``user``/``group`` and ``obj`` (Model instance).
Parses ``check_perms`` tag which should be in format::
{% check_perms "perm1[, perm2, ...]" for user in slug as "context_var" %}
or
{% check_perms "perm1[, perm2, ...]" fo... | 2.574607 | 2.144891 | 1.200344 |
request = context["request"]
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
page = None
if (page and check_perms_helper('change_page', request.user, slug)
or (not page and check_perms_helper('add_page', request.user, slug))):
form = PageForm(... | def waliki_box(context, slug, show_edit=True, *args, **kwargs) | A templatetag to render a wiki page content as a box in any webpage,
and allow rapid edition if you have permission.
It's inspired in `django-boxes`_
.. _django-boxes: https://github.com/eldarion/django-boxes | 2.62531 | 2.620841 | 1.001705 |
if isinstance(perms, string_types):
perms = {perms}
else:
perms = set(perms)
allowed_users = ACLRule.get_users_for(perms, slug)
if allowed_users:
return user in allowed_users
if perms.issubset(set(WALIKI_ANONYMOUS_USER_PERMISSIONS)):
return True
if is_aut... | def check_perms(perms, user, slug, raise_exception=False) | a helper user to check if a user has the permissions
for a given slug | 3.868529 | 3.966706 | 0.97525 |
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if check_perms(perms, request.user, kwargs['slug'], raise_exception=raise_exception):
return view_func(request, *args, **kwargs)
... | def permission_required(perms, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME) | this is analog to django's builtin ``permission_required`` decorator, but
improved to check per slug ACLRules and default permissions for
anonymous and logged in users
if there is a rule affecting a slug, the user needs to be part of the
rule's allowed users. If there isn't a matching rule, defaults pe... | 1.922377 | 1.945922 | 0.9879 |
module_name = '%s.%s' % (app, modname)
try:
module = import_module(module_name)
except ImportError as e:
if failfast:
raise e
elif verbose:
print("Could not load %r from %r: %s" % (modname, app, e))
return None
if verbose:
print("Loade... | def get_module(app, modname, verbose=False, failfast=False) | Internal function to load a module from a single app.
taken from https://github.com/ojii/django-load. | 1.849018 | 1.877132 | 0.985023 |
for app in settings.INSTALLED_APPS:
get_module(app, modname, verbose, failfast) | def load(modname, verbose=False, failfast=False) | Loads all modules with name 'modname' from all installed apps.
If verbose is True, debug information will be printed to stdout.
If failfast is True, import errors will not be surpressed. | 5.17541 | 3.836318 | 1.349057 |
if PluginClass in _cache.keys():
raise Exception("Plugin class already registered")
plugin = PluginClass()
_cache[PluginClass] = plugin
if getattr(PluginClass, 'extra_page_actions', False):
for key in plugin.extra_page_actions:
if key not in _extra_page_actions:
... | def register(PluginClass) | Register a plugin class. This function will call back your plugin's
constructor. | 1.948292 | 2.064886 | 0.943535 |
if 'crispy_forms' in settings.INSTALLED_APPS:
from crispy_forms.templatetags.crispy_forms_filters import as_crispy_form
return as_crispy_form(form)
template = get_template("bootstrap/form.html")
form = _preprocess_fields(form)
return template.render({"form": form}) | def render_form(form) | same than {{ form|crispy }} if crispy_forms is installed.
render using a bootstrap3 templating otherwise | 3.40788 | 3.008517 | 1.132744 |
from waliki.settings import WALIKI_USE_MATHJAX # NOQA
return {k: v for (k, v) in locals().items() if k.startswith('WALIKI')} | def settings(request) | inject few waliki's settings to the context to be used in templates | 5.857049 | 4.437412 | 1.319924 |
try:
utf16 = s.encode('utf_16_be')
except AttributeError: # ints and floats
utf16 = str(s).encode('utf_16_be')
safe = utf16.replace(b'\x00)', b'\x00\\)').replace(b'\x00(', b'\x00\\(')
return b''.join((codecs.BOM_UTF16_BE, safe)) | def smart_encode_str(s) | Create a UTF-16 encoded PDF string literal for `s`. | 3.135633 | 3.01847 | 1.038815 |
fdf = [b'%FDF-1.2\x0a%\xe2\xe3\xcf\xd3\x0d\x0a']
fdf.append(b'1 0 obj\x0a<</FDF')
fdf.append(b'<</Fields[')
fdf.append(b''.join(handle_data_strings(fdf_data_strings,
fields_hidden, fields_readonly,
checkbox_chec... | def forge_fdf(pdf_form_url=None, fdf_data_strings=[], fdf_data_names=[],
fields_hidden=[], fields_readonly=[],
checkbox_checked_name=b"Yes") | Generates fdf string from fields specified
* pdf_form_url (default: None): just the url for the form.
* fdf_data_strings (default: []): array of (string, value) tuples for the
form fields (or dicts). Value is passed as a UTF-16 encoded string,
unless True/False, in which case it is assumed to be a ... | 2.327713 | 2.440614 | 0.953741 |
# Task limit
if task_limit is not None and not task_limit > 0:
raise ValueError('The task limit must be None or greater than 0')
# Safe context
async with StreamerManager() as manager:
main_streamer = await manager.enter_and_create_task(source)
# Loop over events
... | async def base_combine(source, switch=False, ordered=False, task_limit=None) | Base operator for managing an asynchronous sequence of sequences.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
The ``switch`` argument enables the switch mecanism, which cause the
previous subsequence to be dis... | 3.633113 | 3.575224 | 1.016192 |
return base_combine.raw(
source, task_limit=task_limit, switch=False, ordered=True) | def concat(source, task_limit=None) | Given an asynchronous sequence of sequences, generate the elements
of the sequences in order.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
Errors raised in the source or an element sequence are propagated. | 16.762703 | 24.247648 | 0.691313 |
return base_combine.raw(
source, task_limit=task_limit, switch=False, ordered=False) | def flatten(source, task_limit=None) | Given an asynchronous sequence of sequences, generate the elements
of the sequences as soon as they're received.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
Errors raised in the source or an element sequence a... | 19.868174 | 27.504507 | 0.722361 |
return concat.raw(
combine.smap.raw(source, func, *more_sources), task_limit=task_limit) | def concatmap(source, func, *more_sources, task_limit=None) | Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences, and generate the elements of the created
sequences in order.
The function is applied as described in `map`, and must return an
asynchronous sequence. The returned sequences are awaited concurrentl... | 9.727205 | 12.739188 | 0.763566 |
return flatten.raw(
combine.smap.raw(source, func, *more_sources), task_limit=task_limit) | def flatmap(source, func, *more_sources, task_limit=None) | Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences, and generate the elements of the created
sequences as soon as they arrive.
The function is applied as described in `map`, and must return an
asynchronous sequence. The returned sequences are await... | 10.330174 | 17.769365 | 0.581347 |
return switch.raw(combine.smap.raw(source, func, *more_sources)) | def switchmap(source, func, *more_sources) | Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences and generate the elements of the most
recently created sequence.
The function is applied as described in `map`, and must return an
asynchronous sequence. Errors raised in a source or output sequenc... | 20.066463 | 32.905628 | 0.609819 |
iscorofunc = asyncio.iscoroutinefunction(func)
async with streamcontext(source) as streamer:
# Initialize
if initializer is None:
try:
value = await anext(streamer)
except StopAsyncIteration:
return
else:
value = in... | async def accumulate(source, func=op.add, initializer=None) | Generate a series of accumulated sums (or other binary function)
from an asynchronous sequence.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves as a default
when the sequence is empty. | 3.867696 | 4.635505 | 0.834363 |
acc = accumulate.raw(source, func, initializer)
return select.item.raw(acc, -1) | def reduce(source, func, initializer=None) | Apply a function of two arguments cumulatively to the items
of an asynchronous sequence, reducing the sequence to a single value.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty. | 15.808893 | 34.592117 | 0.457009 |
result = []
async with streamcontext(source) as streamer:
async for item in streamer:
result.append(item)
yield result | async def list(source) | Generate a single list from an asynchronous sequence. | 6.257992 | 4.702574 | 1.330759 |
async with streamcontext(aiterable) as streamer:
async for item in streamer:
item
try:
return item
except NameError:
raise StreamEmpty() | async def wait_stream(aiterable) | Wait for an asynchronous iterable to finish and return the last item.
The iterable is executed within a safe stream context.
A StreamEmpty exception is raised if the sequence is empty. | 7.378974 | 6.512679 | 1.133017 |
if asyncio.iscoroutinefunction(func):
async def innerfunc(arg):
await func(arg)
return arg
else:
def innerfunc(arg):
func(arg)
return arg
return map.raw(source, innerfunc) | def action(source, func) | Perform an action for each element of an asynchronous sequence
without modifying it.
The given function can be synchronous or asynchronous. | 3.971736 | 3.950197 | 1.005452 |
def func(value):
if template:
value = template.format(value)
builtins.print(value, **kwargs)
return action.raw(source, func) | def print(source, template=None, **kwargs) | Print each element of an asynchronous sequence without modifying it.
An optional template can be provided to be formatted with the elements.
All the keyword arguments are forwarded to the builtin function print. | 6.843581 | 8.333899 | 0.821174 |
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
return await fn(*args, **kwargs)
return wrapper | def async_(fn) | Wrap the given function into a coroutine function. | 1.87718 | 1.92819 | 0.973545 |
assert issubclass(cls, AsyncIteratorContext)
aiterator = aiter(aiterable)
if isinstance(aiterator, cls):
return aiterator
return cls(aiterator) | def aitercontext(aiterable, *, cls=AsyncIteratorContext) | Return an asynchronous context manager from an asynchronous iterable.
The context management makes sure the aclose asynchronous method
has run before it exits. It also issues warnings and RuntimeError
if it is used incorrectly.
It is safe to use with any asynchronous iterable and prevent
asynchron... | 3.342441 | 5.547912 | 0.602468 |
queue = collections.deque(maxlen=n if n > 0 else 0)
async with streamcontext(source) as streamer:
async for item in streamer:
queue.append(item)
for item in queue:
yield item | async def takelast(source, n) | Forward the last ``n`` elements from an asynchronous sequence.
If ``n`` is negative, it simply terminates after iterating the source.
Note: it is required to reach the end of the source before the first
element is generated. | 3.82403 | 4.749217 | 0.805192 |
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if i >= n:
yield item | async def skip(source, n) | Forward an asynchronous sequence, skipping the first ``n`` elements.
If ``n`` is negative, no elements are skipped. | 12.142706 | 10.696642 | 1.135189 |
queue = collections.deque(maxlen=n if n > 0 else 0)
async with streamcontext(source) as streamer:
async for item in streamer:
if n <= 0:
yield item
continue
if len(queue) == n:
yield queue[0]
queue.append(item) | async def skiplast(source, n) | Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated. | 3.844121 | 4.164516 | 0.923065 |
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if func(i):
yield item | async def filterindex(source, func) | Filter an asynchronous sequence using the index of the elements.
The given function is synchronous, takes the index as an argument,
and returns ``True`` if the corresponding should be forwarded,
``False`` otherwise. | 9.892514 | 9.948513 | 0.994371 |
s = builtins.slice(*args)
start, stop, step = s.start or 0, s.stop, s.step or 1
# Filter the first items
if start < 0:
source = takelast.raw(source, abs(start))
elif start > 0:
source = skip.raw(source, start)
# Filter the last items
if stop is not None:
if stop ... | def slice(source, *args) | Slice an asynchronous sequence.
The arguments are the same as the builtin type slice.
There are two limitations compare to regular slices:
- Positive stop index with negative start index is not supported
- Negative step is not supported | 2.930332 | 3.056498 | 0.958722 |
# Prepare
if index >= 0:
source = skip.raw(source, index)
else:
source = takelast(source, abs(index))
async with streamcontext(source) as streamer:
# Get first item
try:
result = await anext(streamer)
except StopAsyncIteration:
raise I... | async def item(source, index) | Forward the ``n``th element of an asynchronous sequence.
The index can be negative and works like regular indexing.
If the index is out of range, and ``IndexError`` is raised. | 4.18037 | 4.132962 | 1.011471 |
if isinstance(index, builtins.slice):
return slice.raw(source, index.start, index.stop, index.step)
if isinstance(index, int):
return item.raw(source, index)
raise TypeError("Not a valid index (int or slice)") | def getitem(source, index) | Forward one or several items from an asynchronous sequence.
The argument can either be a slice or an integer.
See the slice and item operators for more information. | 3.454866 | 3.639823 | 0.949185 |
iscorofunc = asyncio.iscoroutinefunction(func)
async with streamcontext(source) as streamer:
async for item in streamer:
result = func(item)
if iscorofunc:
result = await result
if not result:
return
yield item | async def takewhile(source, func) | Forward an asynchronous sequence while a condition is met.
The given function takes the item as an argument and returns a boolean
corresponding to the condition to meet. The function can either be
synchronous or asynchronous. | 3.792608 | 4.015685 | 0.944449 |
module_dir = __all__
operators = stream.__dict__
for key, value in operators.items():
if getattr(value, 'pipe', None):
globals()[key] = value.pipe
if key not in module_dir:
module_dir.append(key) | def update_pipe_module() | Populate the pipe module dynamically. | 5.625951 | 5.170109 | 1.088169 |
count = itertools.count(start, step)
async with streamcontext(source) as streamer:
async for item in streamer:
yield next(count), item | async def enumerate(source, start=0, step=1) | Generate ``(index, value)`` tuples from an asynchronous sequence.
This index is computed using a starting point and an increment,
respectively defaulting to ``0`` and ``1``. | 5.629621 | 6.729291 | 0.836584 |
if asyncio.iscoroutinefunction(func):
async def starfunc(args):
return await func(*args)
else:
def starfunc(args):
return func(*args)
return map.raw(source, starfunc, ordered=ordered, task_limit=task_limit) | def starmap(source, func, ordered=True, task_limit=None) | Apply a given function to the unpacked elements of
an asynchronous sequence.
Each element is unpacked before applying the function.
The given function can either be synchronous or asynchronous.
The results can either be returned in or out of order, depending on
the corresponding ``ordered`` argume... | 2.72524 | 3.403296 | 0.800765 |
while True:
async with streamcontext(source) as streamer:
async for item in streamer:
yield item
# Prevent blocking while loop if the stream is empty
await asyncio.sleep(0) | async def cycle(source) | Iterate indefinitely over an asynchronous sequence.
Note: it does not perform any buffering, but re-iterate over
the same given sequence instead. If the sequence is not
re-iterable, the generator might end up looping indefinitely
without yielding any item. | 8.108944 | 9.877162 | 0.820979 |
async with streamcontext(source) as streamer:
async for first in streamer:
xs = select.take(create.preserve(streamer), n-1)
yield [first] + await aggregate.list(xs) | async def chunks(source, n) | Generate chunks of size ``n`` from an asynchronous sequence.
The chunks are lists, and the last chunk might contain less than ``n``
elements. | 19.686268 | 22.202299 | 0.886677 |
while True:
await asyncio.sleep(interval)
yield offset + width * random_module.random() | async def random(offset=0., width=1., interval=0.1) | Generate a stream of random numbers. | 5.614445 | 5.968728 | 0.940643 |
async with streamcontext(source) as streamer:
async for item in streamer:
yield item ** exponent | async def power(source, exponent) | Raise the elements of an asynchronous sequence to the given power. | 7.062226 | 5.876719 | 1.201729 |
timeout = 0
loop = asyncio.get_event_loop()
async with streamcontext(source) as streamer:
async for item in streamer:
delta = timeout - loop.time()
delay = delta if delta > 0 else 0
await asyncio.sleep(delay)
yield item
timeout = loop.... | async def spaceout(source, interval) | Make sure the elements of an asynchronous sequence are separated
in time by the given interval. | 3.420299 | 3.269789 | 1.046031 |
async with streamcontext(source) as streamer:
while True:
try:
item = await wait_for(anext(streamer), timeout)
except StopAsyncIteration:
break
else:
yield item | async def timeout(source, timeout) | Raise a time-out if an element of the asynchronous sequence
takes too long to arrive.
Note: the timeout is not global but specific to each step of
the iteration. | 5.112751 | 6.586899 | 0.7762 |
await asyncio.sleep(delay)
async with streamcontext(source) as streamer:
async for item in streamer:
yield item | async def delay(source, delay) | Delay the iteration of an asynchronous sequence. | 5.531606 | 5.061666 | 1.092843 |
for source in sources:
async with streamcontext(source) as streamer:
async for item in streamer:
yield item | async def chain(*sources) | Chain asynchronous sequences together, in the order they are given.
Note: the sequences are not iterated until it is required,
so if the operation is interrupted, the remaining sequences
will be left untouched. | 5.988226 | 7.881842 | 0.75975 |
async with AsyncExitStack() as stack:
# Handle resources
streamers = [await stack.enter_async_context(streamcontext(source))
for source in sources]
# Loop over items
while True:
try:
coros = builtins.map(anext, streamers)
... | async def zip(*sources) | Combine and forward the elements of several asynchronous sequences.
Each generated value is a tuple of elements, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted.
Note: the different sequences are awaited in parrallel, so that their
... | 5.0337 | 5.579398 | 0.902194 |
if more_sources:
source = zip(source, *more_sources)
async with streamcontext(source) as streamer:
async for item in streamer:
yield func(*item) if more_sources else func(item) | async def smap(source, func, *more_sources) | Apply a given function to the elements of one or several
asynchronous sequences.
Each element is used as a positional argument, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted. The function is treated synchronously.
Note: if more ... | 4.494507 | 5.147287 | 0.87318 |
def func(*args):
return create.just(corofn(*args))
if ordered:
return advanced.concatmap.raw(
source, func, *more_sources, task_limit=task_limit)
return advanced.flatmap.raw(
source, func, *more_sources, task_limit=task_limit) | def amap(source, corofn, *more_sources, ordered=True, task_limit=None) | Apply a given coroutine function to the elements of one or several
asynchronous sequences.
Each element is used as a positional argument, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted.
The results can either be returned in or ou... | 4.11463 | 5.776571 | 0.712296 |
if asyncio.iscoroutinefunction(func):
return amap.raw(
source, func, *more_sources,
ordered=ordered, task_limit=task_limit)
return smap.raw(source, func, *more_sources) | def map(source, func, *more_sources, ordered=True, task_limit=None) | Apply a given function to the elements of one or several
asynchronous sequences.
Each element is used as a positional argument, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted. The function can either be synchronous or
asynchronous... | 3.825234 | 6.322645 | 0.605005 |
if is_async_iterable(it):
return from_async_iterable.raw(it)
if isinstance(it, Iterable):
return from_iterable.raw(it)
raise TypeError(
f"{type(it).__name__!r} object is not (async) iterable") | def iterate(it) | Generate values from a sychronous or asynchronous iterable. | 3.967711 | 3.65682 | 1.085017 |
args = () if times is None else (times,)
it = itertools.repeat(value, *args)
agen = from_iterable.raw(it)
return time.spaceout.raw(agen, interval) if interval else agen | def repeat(value, times=None, *, interval=0) | Generate the same value a given number of times.
If ``times`` is ``None``, the value is repeated indefinitely.
An optional interval can be given to space the values out. | 10.960748 | 12.539803 | 0.874077 |
agen = from_iterable.raw(builtins.range(*args))
return time.spaceout.raw(agen, interval) if interval else agen | def range(*args, interval=0) | Generate a given range of numbers.
It supports the same arguments as the builtin function.
An optional interval can be given to space the values out. | 30.865288 | 43.509941 | 0.709385 |
agen = from_iterable.raw(itertools.count(start, step))
return time.spaceout.raw(agen, interval) if interval else agen | def count(start=0, step=1, *, interval=0) | Generate consecutive numbers indefinitely.
Optional starting point and increment can be defined,
respectively defaulting to ``0`` and ``1``.
An optional interval can be given to space the values out. | 21.924417 | 31.338753 | 0.699594 |
params = {
"input": text,
"key": self.key,
"cs": self.cs,
"conversation_id": self.convo_id,
"wrapper": "CleverWrap.py"
}
reply = self._send(params)
self._process_reply(reply)
return self.output | def say(self, text) | Say something to www.cleverbot.com
:type text: string
Returns: string | 6.306431 | 5.367368 | 1.174958 |
# Get a response
try:
r = requests.get(self.url, params=params)
# catch errors, print then exit.
except requests.exceptions.RequestException as e:
print(e)
return r.json(strict=False) | def _send(self, params) | Make the request to www.cleverbot.com
:type params: dict
Returns: dict | 5.216327 | 4.986476 | 1.046095 |
self.cs = reply.get("cs", None)
self.count = int(reply.get("interaction_count", None))
self.output = reply.get("output", None)
self.convo_id = reply.get("conversation_id", None)
self.history = {key:value for key, value in reply.items() if key.startswith("interaction")}
... | def _process_reply(self, reply) | take the cleverbot.com response and populate properties. | 3.081259 | 2.753017 | 1.11923 |
'''Ends the tracer.
May be called in any state. Transitions the state to ended and releases
any SDK resources owned by this tracer (this includes only internal
resources, things like passed-in
:class:`oneagent.common.DbInfoHandle` need to be released manually).
Prefer u... | def end(self) | Ends the tracer.
May be called in any state. Transitions the state to ended and releases
any SDK resources owned by this tracer (this includes only internal
resources, things like passed-in
:class:`oneagent.common.DbInfoHandle` need to be released manually).
Prefer using the tr... | 11.59232 | 1.805158 | 6.421775 |
'''Marks the tracer as failed with the given exception class name
:code:`clsname` and message :code:`msg`.
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this does not end the tracer! Once a
tracer is marked as failed, a... | def mark_failed(self, clsname, msg) | Marks the tracer as failed with the given exception class name
:code:`clsname` and message :code:`msg`.
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this does not end the tracer! Once a
tracer is marked as failed, attempts to ... | 7.004141 | 1.552348 | 4.511964 |
'''Marks the tracer as failed with the given exception :code:`e_val` of
type :code:`e_ty` (defaults to the current exception).
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this does not end the tracer! Once a
tracer is... | def mark_failed_exc(self, e_val=None, e_ty=None) | Marks the tracer as failed with the given exception :code:`e_val` of
type :code:`e_ty` (defaults to the current exception).
May only be called in the started state and only if the tracer is not
already marked as failed. Note that this does not end the tracer! Once a
tracer is marked as ... | 4.045304 | 1.355147 | 2.985139 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.