repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
Crunch-io/crunch-cube | src/cr/cube/dimension.py | Dimension.inserted_hs_indices | def inserted_hs_indices(self):
"""list of int index of each inserted subtotal for the dimension.
Each value represents the position of a subtotal in the interleaved
sequence of elements and subtotals items.
"""
# ---don't do H&S insertions for CA and MR subvar dimensions---
... | python | def inserted_hs_indices(self):
"""list of int index of each inserted subtotal for the dimension.
Each value represents the position of a subtotal in the interleaved
sequence of elements and subtotals items.
"""
# ---don't do H&S insertions for CA and MR subvar dimensions---
... | [
"def",
"inserted_hs_indices",
"(",
"self",
")",
":",
"# ---don't do H&S insertions for CA and MR subvar dimensions---",
"if",
"self",
".",
"dimension_type",
"in",
"DT",
".",
"ARRAY_TYPES",
":",
"return",
"[",
"]",
"return",
"[",
"idx",
"for",
"idx",
",",
"item",
"... | list of int index of each inserted subtotal for the dimension.
Each value represents the position of a subtotal in the interleaved
sequence of elements and subtotals items. | [
"list",
"of",
"int",
"index",
"of",
"each",
"inserted",
"subtotal",
"for",
"the",
"dimension",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L299-L315 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | Dimension.is_marginable | def is_marginable(self):
"""True if adding counts across this dimension axis is meaningful."""
return self.dimension_type not in {DT.CA, DT.MR, DT.MR_CAT, DT.LOGICAL} | python | def is_marginable(self):
"""True if adding counts across this dimension axis is meaningful."""
return self.dimension_type not in {DT.CA, DT.MR, DT.MR_CAT, DT.LOGICAL} | [
"def",
"is_marginable",
"(",
"self",
")",
":",
"return",
"self",
".",
"dimension_type",
"not",
"in",
"{",
"DT",
".",
"CA",
",",
"DT",
".",
"MR",
",",
"DT",
".",
"MR_CAT",
",",
"DT",
".",
"LOGICAL",
"}"
] | True if adding counts across this dimension axis is meaningful. | [
"True",
"if",
"adding",
"counts",
"across",
"this",
"dimension",
"axis",
"is",
"meaningful",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L318-L320 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | Dimension.labels | def labels(
self, include_missing=False, include_transforms=False, include_cat_ids=False
):
"""Return list of str labels for the elements of this dimension.
Returns a list of (label, element_id) pairs if *include_cat_ids* is
True. The `element_id` value in the second position of the... | python | def labels(
self, include_missing=False, include_transforms=False, include_cat_ids=False
):
"""Return list of str labels for the elements of this dimension.
Returns a list of (label, element_id) pairs if *include_cat_ids* is
True. The `element_id` value in the second position of the... | [
"def",
"labels",
"(",
"self",
",",
"include_missing",
"=",
"False",
",",
"include_transforms",
"=",
"False",
",",
"include_cat_ids",
"=",
"False",
")",
":",
"# TODO: Having an alternate return type triggered by a flag-parameter",
"# (`include_cat_ids` in this case) is poor prac... | Return list of str labels for the elements of this dimension.
Returns a list of (label, element_id) pairs if *include_cat_ids* is
True. The `element_id` value in the second position of the pair is
None for subtotal items (which don't have an element-id). | [
"Return",
"list",
"of",
"str",
"labels",
"for",
"the",
"elements",
"of",
"this",
"dimension",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L322-L357 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | Dimension._iter_interleaved_items | def _iter_interleaved_items(self, elements):
"""Generate element or subtotal items in interleaved order.
This ordering corresponds to how value "rows" (or columns) are to
appear after subtotals have been inserted at their anchor locations.
Where more than one subtotal is anchored to the... | python | def _iter_interleaved_items(self, elements):
"""Generate element or subtotal items in interleaved order.
This ordering corresponds to how value "rows" (or columns) are to
appear after subtotals have been inserted at their anchor locations.
Where more than one subtotal is anchored to the... | [
"def",
"_iter_interleaved_items",
"(",
"self",
",",
"elements",
")",
":",
"subtotals",
"=",
"self",
".",
"_subtotals",
"for",
"subtotal",
"in",
"subtotals",
".",
"iter_for_anchor",
"(",
"\"top\"",
")",
":",
"yield",
"subtotal",
"for",
"element",
"in",
"element... | Generate element or subtotal items in interleaved order.
This ordering corresponds to how value "rows" (or columns) are to
appear after subtotals have been inserted at their anchor locations.
Where more than one subtotal is anchored to the same location, they
appear in their document or... | [
"Generate",
"element",
"or",
"subtotal",
"items",
"in",
"interleaved",
"order",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L391-L414 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | Dimension._subtotals | def _subtotals(self):
"""_Subtotals sequence object for this dimension.
The subtotals sequence provides access to any subtotal insertions
defined on this dimension.
"""
view = self._dimension_dict.get("references", {}).get("view", {})
# ---view can be both None and {}, t... | python | def _subtotals(self):
"""_Subtotals sequence object for this dimension.
The subtotals sequence provides access to any subtotal insertions
defined on this dimension.
"""
view = self._dimension_dict.get("references", {}).get("view", {})
# ---view can be both None and {}, t... | [
"def",
"_subtotals",
"(",
"self",
")",
":",
"view",
"=",
"self",
".",
"_dimension_dict",
".",
"get",
"(",
"\"references\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"view\"",
",",
"{",
"}",
")",
"# ---view can be both None and {}, thus the edge case.---",
"inser... | _Subtotals sequence object for this dimension.
The subtotals sequence provides access to any subtotal insertions
defined on this dimension. | [
"_Subtotals",
"sequence",
"object",
"for",
"this",
"dimension",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L417-L428 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _BaseElements._element_makings | def _element_makings(self):
"""(ElementCls, element_dicts) pair for this dimension's elements.
All the elements of a given dimension are the same type. This method
determines the type (class) and source dicts for the elements of this
dimension and provides them for the element factory.
... | python | def _element_makings(self):
"""(ElementCls, element_dicts) pair for this dimension's elements.
All the elements of a given dimension are the same type. This method
determines the type (class) and source dicts for the elements of this
dimension and provides them for the element factory.
... | [
"def",
"_element_makings",
"(",
"self",
")",
":",
"if",
"self",
".",
"_type_dict",
"[",
"\"class\"",
"]",
"==",
"\"categorical\"",
":",
"return",
"_Category",
",",
"self",
".",
"_type_dict",
"[",
"\"categories\"",
"]",
"return",
"_Element",
",",
"self",
".",... | (ElementCls, element_dicts) pair for this dimension's elements.
All the elements of a given dimension are the same type. This method
determines the type (class) and source dicts for the elements of this
dimension and provides them for the element factory. | [
"(",
"ElementCls",
"element_dicts",
")",
"pair",
"for",
"this",
"dimension",
"s",
"elements",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L495-L504 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _AllElements._elements | def _elements(self):
"""Composed tuple storing actual sequence of element objects."""
ElementCls, element_dicts = self._element_makings
return tuple(
ElementCls(element_dict, idx, element_dicts)
for idx, element_dict in enumerate(element_dicts)
) | python | def _elements(self):
"""Composed tuple storing actual sequence of element objects."""
ElementCls, element_dicts = self._element_makings
return tuple(
ElementCls(element_dict, idx, element_dicts)
for idx, element_dict in enumerate(element_dicts)
) | [
"def",
"_elements",
"(",
"self",
")",
":",
"ElementCls",
",",
"element_dicts",
"=",
"self",
".",
"_element_makings",
"return",
"tuple",
"(",
"ElementCls",
"(",
"element_dict",
",",
"idx",
",",
"element_dicts",
")",
"for",
"idx",
",",
"element_dict",
"in",
"e... | Composed tuple storing actual sequence of element objects. | [
"Composed",
"tuple",
"storing",
"actual",
"sequence",
"of",
"element",
"objects",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L524-L530 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _BaseElement.numeric_value | def numeric_value(self):
"""Numeric value assigned to element by user, np.nan if absent."""
numeric_value = self._element_dict.get("numeric_value")
return np.nan if numeric_value is None else numeric_value | python | def numeric_value(self):
"""Numeric value assigned to element by user, np.nan if absent."""
numeric_value = self._element_dict.get("numeric_value")
return np.nan if numeric_value is None else numeric_value | [
"def",
"numeric_value",
"(",
"self",
")",
":",
"numeric_value",
"=",
"self",
".",
"_element_dict",
".",
"get",
"(",
"\"numeric_value\"",
")",
"return",
"np",
".",
"nan",
"if",
"numeric_value",
"is",
"None",
"else",
"numeric_value"
] | Numeric value assigned to element by user, np.nan if absent. | [
"Numeric",
"value",
"assigned",
"to",
"element",
"by",
"user",
"np",
".",
"nan",
"if",
"absent",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L596-L599 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Element.label | def label(self):
"""str display-name for this element, '' when absent from cube response.
This property handles numeric, datetime and text variables, but also
subvar dimensions
"""
value = self._element_dict.get("value")
type_name = type(value).__name__
if type_... | python | def label(self):
"""str display-name for this element, '' when absent from cube response.
This property handles numeric, datetime and text variables, but also
subvar dimensions
"""
value = self._element_dict.get("value")
type_name = type(value).__name__
if type_... | [
"def",
"label",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"_element_dict",
".",
"get",
"(",
"\"value\"",
")",
"type_name",
"=",
"type",
"(",
"value",
")",
".",
"__name__",
"if",
"type_name",
"==",
"\"NoneType\"",
":",
"return",
"\"\"",
"if",
"t... | str display-name for this element, '' when absent from cube response.
This property handles numeric, datetime and text variables, but also
subvar dimensions | [
"str",
"display",
"-",
"name",
"for",
"this",
"element",
"when",
"absent",
"from",
"cube",
"response",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L620-L644 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotals.iter_for_anchor | def iter_for_anchor(self, anchor):
"""Generate each subtotal having matching *anchor*."""
return (subtotal for subtotal in self._subtotals if subtotal.anchor == anchor) | python | def iter_for_anchor(self, anchor):
"""Generate each subtotal having matching *anchor*."""
return (subtotal for subtotal in self._subtotals if subtotal.anchor == anchor) | [
"def",
"iter_for_anchor",
"(",
"self",
",",
"anchor",
")",
":",
"return",
"(",
"subtotal",
"for",
"subtotal",
"in",
"self",
".",
"_subtotals",
"if",
"subtotal",
".",
"anchor",
"==",
"anchor",
")"
] | Generate each subtotal having matching *anchor*. | [
"Generate",
"each",
"subtotal",
"having",
"matching",
"*",
"anchor",
"*",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L672-L674 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotals._iter_valid_subtotal_dicts | def _iter_valid_subtotal_dicts(self):
"""Generate each insertion dict that represents a valid subtotal."""
for insertion_dict in self._insertion_dicts:
# ---skip any non-dicts---
if not isinstance(insertion_dict, dict):
continue
# ---skip any non-subt... | python | def _iter_valid_subtotal_dicts(self):
"""Generate each insertion dict that represents a valid subtotal."""
for insertion_dict in self._insertion_dicts:
# ---skip any non-dicts---
if not isinstance(insertion_dict, dict):
continue
# ---skip any non-subt... | [
"def",
"_iter_valid_subtotal_dicts",
"(",
"self",
")",
":",
"for",
"insertion_dict",
"in",
"self",
".",
"_insertion_dicts",
":",
"# ---skip any non-dicts---",
"if",
"not",
"isinstance",
"(",
"insertion_dict",
",",
"dict",
")",
":",
"continue",
"# ---skip any non-subto... | Generate each insertion dict that represents a valid subtotal. | [
"Generate",
"each",
"insertion",
"dict",
"that",
"represents",
"a",
"valid",
"subtotal",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L681-L702 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotals._subtotals | def _subtotals(self):
"""Composed tuple storing actual sequence of _Subtotal objects."""
return tuple(
_Subtotal(subtotal_dict, self.valid_elements)
for subtotal_dict in self._iter_valid_subtotal_dicts()
) | python | def _subtotals(self):
"""Composed tuple storing actual sequence of _Subtotal objects."""
return tuple(
_Subtotal(subtotal_dict, self.valid_elements)
for subtotal_dict in self._iter_valid_subtotal_dicts()
) | [
"def",
"_subtotals",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"_Subtotal",
"(",
"subtotal_dict",
",",
"self",
".",
"valid_elements",
")",
"for",
"subtotal_dict",
"in",
"self",
".",
"_iter_valid_subtotal_dicts",
"(",
")",
")"
] | Composed tuple storing actual sequence of _Subtotal objects. | [
"Composed",
"tuple",
"storing",
"actual",
"sequence",
"of",
"_Subtotal",
"objects",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L705-L710 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotal.anchor | def anchor(self):
"""int or str indicating element under which to insert this subtotal.
An int anchor is the id of the dimension element (category or
subvariable) under which to place this subtotal. The return value can
also be one of 'top' or 'bottom'.
The return value default... | python | def anchor(self):
"""int or str indicating element under which to insert this subtotal.
An int anchor is the id of the dimension element (category or
subvariable) under which to place this subtotal. The return value can
also be one of 'top' or 'bottom'.
The return value default... | [
"def",
"anchor",
"(",
"self",
")",
":",
"anchor",
"=",
"self",
".",
"_subtotal_dict",
"[",
"\"anchor\"",
"]",
"try",
":",
"anchor",
"=",
"int",
"(",
"anchor",
")",
"if",
"anchor",
"not",
"in",
"self",
".",
"valid_elements",
".",
"element_ids",
":",
"re... | int or str indicating element under which to insert this subtotal.
An int anchor is the id of the dimension element (category or
subvariable) under which to place this subtotal. The return value can
also be one of 'top' or 'bottom'.
The return value defaults to 'bottom' for an anchor r... | [
"int",
"or",
"str",
"indicating",
"element",
"under",
"which",
"to",
"insert",
"this",
"subtotal",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L721-L739 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotal.anchor_idx | def anchor_idx(self):
"""int or str representing index of anchor element in dimension.
When the anchor is an operation, like 'top' or 'bottom'
"""
anchor = self.anchor
if anchor in ["top", "bottom"]:
return anchor
return self.valid_elements.get_by_id(anchor).... | python | def anchor_idx(self):
"""int or str representing index of anchor element in dimension.
When the anchor is an operation, like 'top' or 'bottom'
"""
anchor = self.anchor
if anchor in ["top", "bottom"]:
return anchor
return self.valid_elements.get_by_id(anchor).... | [
"def",
"anchor_idx",
"(",
"self",
")",
":",
"anchor",
"=",
"self",
".",
"anchor",
"if",
"anchor",
"in",
"[",
"\"top\"",
",",
"\"bottom\"",
"]",
":",
"return",
"anchor",
"return",
"self",
".",
"valid_elements",
".",
"get_by_id",
"(",
"anchor",
")",
".",
... | int or str representing index of anchor element in dimension.
When the anchor is an operation, like 'top' or 'bottom' | [
"int",
"or",
"str",
"representing",
"index",
"of",
"anchor",
"element",
"in",
"dimension",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L742-L750 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotal.addend_ids | def addend_ids(self):
"""tuple of int ids of elements contributing to this subtotal.
Any element id not present in the dimension or present but
representing missing data is excluded.
"""
return tuple(
arg
for arg in self._subtotal_dict.get("args", [])
... | python | def addend_ids(self):
"""tuple of int ids of elements contributing to this subtotal.
Any element id not present in the dimension or present but
representing missing data is excluded.
"""
return tuple(
arg
for arg in self._subtotal_dict.get("args", [])
... | [
"def",
"addend_ids",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"arg",
"for",
"arg",
"in",
"self",
".",
"_subtotal_dict",
".",
"get",
"(",
"\"args\"",
",",
"[",
"]",
")",
"if",
"arg",
"in",
"self",
".",
"valid_elements",
".",
"element_ids",
")"
] | tuple of int ids of elements contributing to this subtotal.
Any element id not present in the dimension or present but
representing missing data is excluded. | [
"tuple",
"of",
"int",
"ids",
"of",
"elements",
"contributing",
"to",
"this",
"subtotal",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L753-L763 |
Crunch-io/crunch-cube | src/cr/cube/dimension.py | _Subtotal.addend_idxs | def addend_idxs(self):
"""tuple of int index of each addend element for this subtotal.
The length of the tuple is the same as that for `.addend_ids`, but
each value repesents the offset of that element within the dimension,
rather than its element id.
"""
return tuple(
... | python | def addend_idxs(self):
"""tuple of int index of each addend element for this subtotal.
The length of the tuple is the same as that for `.addend_ids`, but
each value repesents the offset of that element within the dimension,
rather than its element id.
"""
return tuple(
... | [
"def",
"addend_idxs",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"valid_elements",
".",
"get_by_id",
"(",
"addend_id",
")",
".",
"index_in_valids",
"for",
"addend_id",
"in",
"self",
".",
"addend_ids",
")"
] | tuple of int index of each addend element for this subtotal.
The length of the tuple is the same as that for `.addend_ids`, but
each value repesents the offset of that element within the dimension,
rather than its element id. | [
"tuple",
"of",
"int",
"index",
"of",
"each",
"addend",
"element",
"for",
"this",
"subtotal",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/dimension.py#L766-L776 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scripts/build_collection.py | create_data_file_by_format | def create_data_file_by_format(directory_path = None):
"""
Browse subdirectories to extract stata and sas files
"""
stata_files = []
sas_files = []
for root, subdirs, files in os.walk(directory_path):
for file_name in files:
file_path = os.path.join(root, file_name)
... | python | def create_data_file_by_format(directory_path = None):
"""
Browse subdirectories to extract stata and sas files
"""
stata_files = []
sas_files = []
for root, subdirs, files in os.walk(directory_path):
for file_name in files:
file_path = os.path.join(root, file_name)
... | [
"def",
"create_data_file_by_format",
"(",
"directory_path",
"=",
"None",
")",
":",
"stata_files",
"=",
"[",
"]",
"sas_files",
"=",
"[",
"]",
"for",
"root",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory_path",
")",
":",
"for",
"fi... | Browse subdirectories to extract stata and sas files | [
"Browse",
"subdirectories",
"to",
"extract",
"stata",
"and",
"sas",
"files"
] | train | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scripts/build_collection.py#L55-L71 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.as_array | def as_array(
self,
include_missing=False,
weighted=True,
include_transforms_for_dims=None,
prune=False,
):
"""Return `ndarray` representing cube values.
Returns the tabular representation of the crunch cube. The returned
array has the same number of ... | python | def as_array(
self,
include_missing=False,
weighted=True,
include_transforms_for_dims=None,
prune=False,
):
"""Return `ndarray` representing cube values.
Returns the tabular representation of the crunch cube. The returned
array has the same number of ... | [
"def",
"as_array",
"(",
"self",
",",
"include_missing",
"=",
"False",
",",
"weighted",
"=",
"True",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"prune",
"=",
"False",
",",
")",
":",
"array",
"=",
"self",
".",
"_as_array",
"(",
"include_missing",
... | Return `ndarray` representing cube values.
Returns the tabular representation of the crunch cube. The returned
array has the same number of dimensions as the cube. E.g. for
a cross-tab representation of a categorical and numerical variable,
the resulting cube will have two dimensions.
... | [
"Return",
"ndarray",
"representing",
"cube",
"values",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L81-L126 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.count | def count(self, weighted=True):
"""Return numberic count of rows considered for cube response."""
return self._measures.weighted_n if weighted else self._measures.unweighted_n | python | def count(self, weighted=True):
"""Return numberic count of rows considered for cube response."""
return self._measures.weighted_n if weighted else self._measures.unweighted_n | [
"def",
"count",
"(",
"self",
",",
"weighted",
"=",
"True",
")",
":",
"return",
"self",
".",
"_measures",
".",
"weighted_n",
"if",
"weighted",
"else",
"self",
".",
"_measures",
".",
"unweighted_n"
] | Return numberic count of rows considered for cube response. | [
"Return",
"numberic",
"count",
"of",
"rows",
"considered",
"for",
"cube",
"response",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L132-L134 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.get_slices | def get_slices(self, ca_as_0th=False):
"""Return list of :class:`.CubeSlice` objects.
The number of slice objects in the returned list depends on the
dimensionality of this cube. A 1D or 2D cube will return a list
containing one slice object. A 3D cube will return a list of slices
... | python | def get_slices(self, ca_as_0th=False):
"""Return list of :class:`.CubeSlice` objects.
The number of slice objects in the returned list depends on the
dimensionality of this cube. A 1D or 2D cube will return a list
containing one slice object. A 3D cube will return a list of slices
... | [
"def",
"get_slices",
"(",
"self",
",",
"ca_as_0th",
"=",
"False",
")",
":",
"if",
"self",
".",
"ndim",
"<",
"3",
"and",
"not",
"ca_as_0th",
":",
"return",
"[",
"CubeSlice",
"(",
"self",
",",
"0",
")",
"]",
"return",
"[",
"CubeSlice",
"(",
"self",
"... | Return list of :class:`.CubeSlice` objects.
The number of slice objects in the returned list depends on the
dimensionality of this cube. A 1D or 2D cube will return a list
containing one slice object. A 3D cube will return a list of slices
the same length as the first dimension. | [
"Return",
"list",
"of",
":",
"class",
":",
".",
"CubeSlice",
"objects",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L166-L177 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.index | def index(self, weighted=True, prune=False):
"""Return cube index measurement.
This function is deprecated. Use index_table from CubeSlice.
"""
warnings.warn(
"CrunchCube.index() is deprecated. Use CubeSlice.index_table().",
DeprecationWarning,
)
... | python | def index(self, weighted=True, prune=False):
"""Return cube index measurement.
This function is deprecated. Use index_table from CubeSlice.
"""
warnings.warn(
"CrunchCube.index() is deprecated. Use CubeSlice.index_table().",
DeprecationWarning,
)
... | [
"def",
"index",
"(",
"self",
",",
"weighted",
"=",
"True",
",",
"prune",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"\"CrunchCube.index() is deprecated. Use CubeSlice.index_table().\"",
",",
"DeprecationWarning",
",",
")",
"return",
"Index",
".",
"data"... | Return cube index measurement.
This function is deprecated. Use index_table from CubeSlice. | [
"Return",
"cube",
"index",
"measurement",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L189-L198 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.inserted_hs_indices | def inserted_hs_indices(self, prune=False):
"""Get indices of the inserted H&S (for formatting purposes)."""
if self.ndim == 2 and prune:
# If pruning is applied, we need to subtract from the H&S indes
# the number of pruned rows (cols) that come before that index.
pr... | python | def inserted_hs_indices(self, prune=False):
"""Get indices of the inserted H&S (for formatting purposes)."""
if self.ndim == 2 and prune:
# If pruning is applied, we need to subtract from the H&S indes
# the number of pruned rows (cols) that come before that index.
pr... | [
"def",
"inserted_hs_indices",
"(",
"self",
",",
"prune",
"=",
"False",
")",
":",
"if",
"self",
".",
"ndim",
"==",
"2",
"and",
"prune",
":",
"# If pruning is applied, we need to subtract from the H&S indes",
"# the number of pruned rows (cols) that come before that index.",
... | Get indices of the inserted H&S (for formatting purposes). | [
"Get",
"indices",
"of",
"the",
"inserted",
"H&S",
"(",
"for",
"formatting",
"purposes",
")",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L200-L220 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.is_univariate_ca | def is_univariate_ca(self):
"""True if cube only contains a CA dimension-pair, in either order."""
return self.ndim == 2 and set(self.dim_types) == {DT.CA_SUBVAR, DT.CA_CAT} | python | def is_univariate_ca(self):
"""True if cube only contains a CA dimension-pair, in either order."""
return self.ndim == 2 and set(self.dim_types) == {DT.CA_SUBVAR, DT.CA_CAT} | [
"def",
"is_univariate_ca",
"(",
"self",
")",
":",
"return",
"self",
".",
"ndim",
"==",
"2",
"and",
"set",
"(",
"self",
".",
"dim_types",
")",
"==",
"{",
"DT",
".",
"CA_SUBVAR",
",",
"DT",
".",
"CA_CAT",
"}"
] | True if cube only contains a CA dimension-pair, in either order. | [
"True",
"if",
"cube",
"only",
"contains",
"a",
"CA",
"dimension",
"-",
"pair",
"in",
"either",
"order",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L228-L230 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.labels | def labels(self, include_missing=False, include_transforms_for_dims=False):
"""Gets labels for each cube's dimension.
Args
include_missing (bool): Include labels for missing values
Returns
labels (list of lists): Labels for each dimension
"""
return [
... | python | def labels(self, include_missing=False, include_transforms_for_dims=False):
"""Gets labels for each cube's dimension.
Args
include_missing (bool): Include labels for missing values
Returns
labels (list of lists): Labels for each dimension
"""
return [
... | [
"def",
"labels",
"(",
"self",
",",
"include_missing",
"=",
"False",
",",
"include_transforms_for_dims",
"=",
"False",
")",
":",
"return",
"[",
"dim",
".",
"labels",
"(",
"include_missing",
",",
"include_transforms_for_dims",
")",
"for",
"dim",
"in",
"self",
".... | Gets labels for each cube's dimension.
Args
include_missing (bool): Include labels for missing values
Returns
labels (list of lists): Labels for each dimension | [
"Gets",
"labels",
"for",
"each",
"cube",
"s",
"dimension",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L237-L249 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.margin | def margin(
self,
axis=None,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
include_mr_cat=False,
):
"""Get margin for the selected axis.
the selected axis. For MR variables, this is the sum of the selecte... | python | def margin(
self,
axis=None,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
include_mr_cat=False,
):
"""Get margin for the selected axis.
the selected axis. For MR variables, this is the sum of the selecte... | [
"def",
"margin",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"weighted",
"=",
"True",
",",
"include_missing",
"=",
"False",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"prune",
"=",
"False",
",",
"include_mr_cat",
"=",
"False",
",",
")",
":",
"... | Get margin for the selected axis.
the selected axis. For MR variables, this is the sum of the selected
and non-selected slices.
Args
axis (int): Axis across the margin is calculated. If no axis is
provided the margin is calculated across all axis.
... | [
"Get",
"margin",
"for",
"the",
"selected",
"axis",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L251-L379 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.mr_dim_ind | 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
... | python | 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
... | [
"def",
"mr_dim_ind",
"(",
"self",
")",
":",
"# 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"... | 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 ... | [
"Return",
"int",
"tuple",
"of",
"int",
"or",
"None",
"representing",
"MR",
"indices",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L387-L409 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.population_counts | 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... | python | 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... | [
"def",
"population_counts",
"(",
"self",
",",
"population_size",
",",
"weighted",
"=",
"True",
",",
"include_missing",
"=",
"False",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"prune",
"=",
"False",
",",
")",
":",
"population_counts",
"=",
"[",
"sli... | 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... | [
"Return",
"counts",
"scaled",
"in",
"proportion",
"to",
"overall",
"population",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L469-L512 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.proportions | 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
... | python | 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
... | [
"def",
"proportions",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"weighted",
"=",
"True",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"include_mr_cat",
"=",
"False",
",",
"prune",
"=",
"False",
",",
")",
":",
"# Calculate numerator from table (include... | 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... | [
"Return",
"percentage",
"values",
"for",
"cube",
"as",
"numpy",
".",
"ndarray",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L525-L613 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._denominator | 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 in... | python | 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 in... | [
"def",
"_denominator",
"(",
"self",
",",
"weighted",
",",
"include_transforms_for_dims",
",",
"axis",
")",
":",
"table",
"=",
"self",
".",
"_measure",
"(",
"weighted",
")",
".",
"raw_cube_array",
"new_axis",
"=",
"self",
".",
"_adjust_axis",
"(",
"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. | [
"Calculate",
"denominator",
"for",
"percentages",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L615-L630 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.scale_means | def scale_means(self, hs_dims=None, prune=False):
"""Get cube means."""
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... | python | def scale_means(self, hs_dims=None, prune=False):
"""Get cube means."""
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... | [
"def",
"scale_means",
"(",
"self",
",",
"hs_dims",
"=",
"None",
",",
"prune",
"=",
"False",
")",
":",
"slices_means",
"=",
"[",
"ScaleMeans",
"(",
"slice_",
")",
".",
"data",
"for",
"slice_",
"in",
"self",
".",
"slices",
"]",
"if",
"hs_dims",
"and",
... | Get cube means. | [
"Get",
"cube",
"means",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L658-L696 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.zscore | 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 ... | python | 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 ... | [
"def",
"zscore",
"(",
"self",
",",
"weighted",
"=",
"True",
",",
"prune",
"=",
"False",
",",
"hs_dims",
"=",
"None",
")",
":",
"res",
"=",
"[",
"s",
".",
"zscore",
"(",
"weighted",
",",
"prune",
",",
"hs_dims",
")",
"for",
"s",
"in",
"self",
".",... | 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... | [
"Return",
"ndarray",
"with",
"cube",
"s",
"zscore",
"measurements",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L707-L721 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.wishart_pairwise_pvals | 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 perf... | python | 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 perf... | [
"def",
"wishart_pairwise_pvals",
"(",
"self",
",",
"axis",
"=",
"0",
")",
":",
"return",
"[",
"slice_",
".",
"wishart_pairwise_pvals",
"(",
"axis",
"=",
"axis",
")",
"for",
"slice_",
"in",
"self",
".",
"slices",
"]"
] | 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... | [
"Return",
"matrices",
"of",
"column",
"-",
"comparison",
"p",
"-",
"values",
"as",
"list",
"of",
"numpy",
".",
"ndarrays",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L723-L732 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._adjust_axis | 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... | python | 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... | [
"def",
"_adjust_axis",
"(",
"self",
",",
"axis",
")",
":",
"if",
"not",
"self",
".",
"_is_axis_allowed",
"(",
"axis",
")",
":",
"ca_error_msg",
"=",
"\"Direction {} not allowed (items dimension)\"",
"raise",
"ValueError",
"(",
"ca_error_msg",
".",
"format",
"(",
... | 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 ... | [
"Return",
"raw",
"axis",
"/",
"axes",
"corresponding",
"to",
"apparent",
"axis",
"/",
"axes",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L748-L797 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._adjust_inserted_indices | def _adjust_inserted_indices(inserted_indices_list, prune_indices_list):
"""Adjust inserted indices, if there are pruned elements."""
# 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(p... | python | def _adjust_inserted_indices(inserted_indices_list, prune_indices_list):
"""Adjust inserted indices, if there are pruned elements."""
# 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(p... | [
"def",
"_adjust_inserted_indices",
"(",
"inserted_indices_list",
",",
"prune_indices_list",
")",
":",
"# Created a copy, to preserve cached property",
"updated_inserted",
"=",
"[",
"[",
"i",
"for",
"i",
"in",
"dim_inds",
"]",
"for",
"dim_inds",
"in",
"inserted_indices_lis... | Adjust inserted indices, if there are pruned elements. | [
"Adjust",
"inserted",
"indices",
"if",
"there",
"are",
"pruned",
"elements",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L800-L811 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._apply_missings | 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... | python | 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... | [
"def",
"_apply_missings",
"(",
"self",
",",
"res",
",",
"include_missing",
"=",
"False",
")",
":",
"# --element idxs that satisfy `include_missing` arg. Note this",
"# --includes MR_CAT elements so is essentially all-or-valid-elements",
"element_idxs",
"=",
"tuple",
"(",
"(",
"... | 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*
... | [
"Return",
"ndarray",
"with",
"missing",
"and",
"insertions",
"as",
"specified",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L826-L849 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._apply_subtotals | 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*.
"""
if not include_transforms_for_dims:
return res
... | python | 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*.
"""
if not include_transforms_for_dims:
return res
... | [
"def",
"_apply_subtotals",
"(",
"self",
",",
"res",
",",
"include_transforms_for_dims",
")",
":",
"if",
"not",
"include_transforms_for_dims",
":",
"return",
"res",
"suppressed_dim_count",
"=",
"0",
"for",
"(",
"dim_idx",
",",
"dim",
")",
"in",
"enumerate",
"(",
... | * Insert subtotals (and perhaps other insertions later) for
dimensions having their apparent dimension-idx in
*include_transforms_for_dims*. | [
"*",
"Insert",
"subtotals",
"(",
"and",
"perhaps",
"other",
"insertions",
"later",
")",
"for",
"dimensions",
"having",
"their",
"apparent",
"dimension",
"-",
"idx",
"in",
"*",
"include_transforms_for_dims",
"*",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L851-L876 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._as_array | 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... | python | 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... | [
"def",
"_as_array",
"(",
"self",
",",
"include_missing",
"=",
"False",
",",
"get_non_selected",
"=",
"False",
",",
"weighted",
"=",
"True",
",",
"include_transforms_for_dims",
"=",
"False",
",",
")",
":",
"return",
"self",
".",
"_apply_subtotals",
"(",
"self",... | 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... | [
"Get",
"crunch",
"cube",
"as",
"ndarray",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L878-L901 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._calculate_constraints_sum | 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 do... | python | 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 do... | [
"def",
"_calculate_constraints_sum",
"(",
"cls",
",",
"prop_table",
",",
"prop_margin",
",",
"axis",
")",
":",
"if",
"axis",
"not",
"in",
"[",
"0",
",",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"Unexpected value for `axis`: {}\"",
".",
"format",
"(",
"ax... | 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... | [
"Calculate",
"sum",
"of",
"constraints",
"(",
"part",
"of",
"the",
"standard",
"error",
"equation",
")",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L904-L926 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._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
... | python | 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
... | [
"def",
"_counts",
"(",
"self",
",",
"weighted",
")",
":",
"return",
"(",
"self",
".",
"_measures",
".",
"weighted_counts",
"if",
"weighted",
"else",
"self",
".",
"_measures",
".",
"unweighted_counts",
")"
] | 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... | [
"Return",
"_BaseMeasure",
"subclass",
"for",
"*",
"weighted",
"*",
"counts",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L932-L944 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._cube_dict | def _cube_dict(self):
"""dict containing raw cube response, parsed from JSON payload."""
try:
cube_response = self._cube_response_arg
# ---parse JSON to a dict when constructed with JSON---
cube_dict = (
cube_response
if isinstance(cube... | python | def _cube_dict(self):
"""dict containing raw cube response, parsed from JSON payload."""
try:
cube_response = self._cube_response_arg
# ---parse JSON to a dict when constructed with JSON---
cube_dict = (
cube_response
if isinstance(cube... | [
"def",
"_cube_dict",
"(",
"self",
")",
":",
"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",
"... | dict containing raw cube response, parsed from JSON payload. | [
"dict",
"containing",
"raw",
"cube",
"response",
"parsed",
"from",
"JSON",
"payload",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L953-L969 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._drop_mr_cat_dims | 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 ori... | python | 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 ori... | [
"def",
"_drop_mr_cat_dims",
"(",
"self",
",",
"array",
",",
"fix_valids",
"=",
"False",
")",
":",
"# 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... | 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
... | [
"Return",
"ndarray",
"reflecting",
"*",
"array",
"*",
"with",
"MR_CAT",
"dims",
"dropped",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L971-L1026 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._fix_valid_indices | def _fix_valid_indices(cls, valid_indices, insertion_index, dim):
"""Add indices for H&S inserted elements."""
# 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(sort... | python | def _fix_valid_indices(cls, valid_indices, insertion_index, dim):
"""Add indices for H&S inserted elements."""
# 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(sort... | [
"def",
"_fix_valid_indices",
"(",
"cls",
",",
"valid_indices",
",",
"insertion_index",
",",
"dim",
")",
":",
"# TODO: make this accept an immutable sequence for valid_indices",
"# (a tuple) and return an immutable sequence rather than mutating an",
"# argument.",
"indices",
"=",
"n... | Add indices for H&S inserted elements. | [
"Add",
"indices",
"for",
"H&S",
"inserted",
"elements",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1029-L1039 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._insertions | 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*.
"""
def iter_insertions():
for anchor_idx, addend_idxs in dimension.hs_ind... | python | 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*.
"""
def iter_insertions():
for anchor_idx, addend_idxs in dimension.hs_ind... | [
"def",
"_insertions",
"(",
"self",
",",
"result",
",",
"dimension",
",",
"dimension_index",
")",
":",
"def",
"iter_insertions",
"(",
")",
":",
"for",
"anchor_idx",
",",
"addend_idxs",
"in",
"dimension",
".",
"hs_indices",
":",
"insertion_idx",
"=",
"(",
"-",... | Return list of (idx, sum) pairs representing subtotals.
*idx* is the int offset at which to insert the ndarray subtotal
in *sum*. | [
"Return",
"list",
"of",
"(",
"idx",
"sum",
")",
"pairs",
"representing",
"subtotals",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1057-L1082 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._is_axis_allowed | 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.
"""
if axis is None:
# If table direction was requested, we must ensure that each slice
... | python | 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.
"""
if axis is None:
# If table direction was requested, we must ensure that each slice
... | [
"def",
"_is_axis_allowed",
"(",
"self",
",",
"axis",
")",
":",
"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 c... | 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. | [
"Check",
"if",
"axis",
"are",
"allowed",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1084-L1114 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._measure | 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 tha... | python | 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 tha... | [
"def",
"_measure",
"(",
"self",
",",
"weighted",
")",
":",
"return",
"(",
"self",
".",
"_measures",
".",
"means",
"if",
"self",
".",
"_measures",
".",
"means",
"is",
"not",
"None",
"else",
"self",
".",
"_measures",
".",
"weighted_counts",
"if",
"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-... | [
"_BaseMeasure",
"subclass",
"representing",
"primary",
"measure",
"for",
"this",
"cube",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1133-L1150 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._prune_3d_body | 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 ...
"""
mask = np.zeros(res.shape)
mr_dim_idxs = self.mr_dim_ind
for i, prune_inds in enumerate(self.prune_indi... | python | 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 ...
"""
mask = np.zeros(res.shape)
mr_dim_idxs = self.mr_dim_ind
for i, prune_inds in enumerate(self.prune_indi... | [
"def",
"_prune_3d_body",
"(",
"self",
",",
"res",
",",
"transforms",
")",
":",
"mask",
"=",
"np",
".",
"zeros",
"(",
"res",
".",
"shape",
")",
"mr_dim_idxs",
"=",
"self",
".",
"mr_dim_ind",
"for",
"i",
",",
"prune_inds",
"in",
"enumerate",
"(",
"self",... | Return masked array where mask indicates pruned vectors.
*res* is an ndarray (result). *transforms* is a list of ... | [
"Return",
"masked",
"array",
"where",
"mask",
"indicates",
"pruned",
"vectors",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1161-L1191 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._prune_body | 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).
... | python | 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).
... | [
"def",
"_prune_body",
"(",
"self",
",",
"res",
",",
"transforms",
"=",
"None",
")",
":",
"if",
"self",
".",
"ndim",
">",
"2",
":",
"return",
"self",
".",
"_prune_3d_body",
"(",
"res",
",",
"transforms",
")",
"res",
"=",
"self",
".",
"_drop_mr_cat_dims"... | 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). | [
"Return",
"a",
"masked",
"version",
"of",
"*",
"res",
"*",
"where",
"pruned",
"rows",
"/",
"cols",
"are",
"masked",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1205-L1254 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube.prune_indices | 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... | python | 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... | [
"def",
"prune_indices",
"(",
"self",
",",
"transforms",
"=",
"None",
")",
":",
"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",
"(",
"transform... | 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).
... | [
"Return",
"indices",
"of",
"pruned",
"rows",
"and",
"columns",
"as",
"list",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1256-L1305 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._pruning_base | 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) d... | python | 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) d... | [
"def",
"_pruning_base",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"hs_dims",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_is_axis_allowed",
"(",
"axis",
")",
":",
"# In case we encountered axis that would go across items dimension,",
"# we need to return at le... | 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... | [
"Gets",
"margin",
"if",
"across",
"CAT",
"dimension",
".",
"Gets",
"counts",
"if",
"across",
"items",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1322-L1342 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | CrunchCube._update_result | def _update_result(self, result, insertions, dimension_index):
"""Insert subtotals into resulting ndarray."""
for j, (ind_insertion, value) in enumerate(insertions):
result = np.insert(
result, ind_insertion + j + 1, value, axis=dimension_index
)
return re... | python | def _update_result(self, result, insertions, dimension_index):
"""Insert subtotals into resulting ndarray."""
for j, (ind_insertion, value) in enumerate(insertions):
result = np.insert(
result, ind_insertion + j + 1, value, axis=dimension_index
)
return re... | [
"def",
"_update_result",
"(",
"self",
",",
"result",
",",
"insertions",
",",
"dimension_index",
")",
":",
"for",
"j",
",",
"(",
"ind_insertion",
",",
"value",
")",
"in",
"enumerate",
"(",
"insertions",
")",
":",
"result",
"=",
"np",
".",
"insert",
"(",
... | Insert subtotals into resulting ndarray. | [
"Insert",
"subtotals",
"into",
"resulting",
"ndarray",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1344-L1350 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _Measures.is_weighted | 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.
"""
cube_dict = self._cube_dict
if cube_dict.get("query", {}).get("we... | python | 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.
"""
cube_dict = self._cube_dict
if cube_dict.get("query", {}).get("we... | [
"def",
"is_weighted",
"(",
"self",
")",
":",
"cube_dict",
"=",
"self",
".",
"_cube_dict",
"if",
"cube_dict",
".",
"get",
"(",
"\"query\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"weight\"",
")",
"is",
"not",
"None",
":",
"return",
"True",
"if",
"cube... | 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. | [
"True",
"if",
"weights",
"have",
"been",
"applied",
"to",
"the",
"measure",
"(",
"s",
")",
"for",
"this",
"cube",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1361-L1378 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _Measures.means | def means(self):
"""_MeanMeasure object providing access to means values.
None when the cube response does not contain a mean measure.
"""
mean_measure_dict = (
self._cube_dict.get("result", {}).get("measures", {}).get("mean")
)
if mean_measure_dict is None:
... | python | def means(self):
"""_MeanMeasure object providing access to means values.
None when the cube response does not contain a mean measure.
"""
mean_measure_dict = (
self._cube_dict.get("result", {}).get("measures", {}).get("mean")
)
if mean_measure_dict is None:
... | [
"def",
"means",
"(",
"self",
")",
":",
"mean_measure_dict",
"=",
"(",
"self",
".",
"_cube_dict",
".",
"get",
"(",
"\"result\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"measures\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"mean\"",
")",
")",
"if",
... | _MeanMeasure object providing access to means values.
None when the cube response does not contain a mean measure. | [
"_MeanMeasure",
"object",
"providing",
"access",
"to",
"means",
"values",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1381-L1391 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _Measures.missing_count | def missing_count(self):
"""numeric representing count of missing rows in cube response."""
if self.means:
return self.means.missing_count
return self._cube_dict["result"].get("missing", 0) | python | def missing_count(self):
"""numeric representing count of missing rows in cube response."""
if self.means:
return self.means.missing_count
return self._cube_dict["result"].get("missing", 0) | [
"def",
"missing_count",
"(",
"self",
")",
":",
"if",
"self",
".",
"means",
":",
"return",
"self",
".",
"means",
".",
"missing_count",
"return",
"self",
".",
"_cube_dict",
"[",
"\"result\"",
"]",
".",
"get",
"(",
"\"missing\"",
",",
"0",
")"
] | numeric representing count of missing rows in cube response. | [
"numeric",
"representing",
"count",
"of",
"missing",
"rows",
"in",
"cube",
"response",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1394-L1398 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _Measures.population_fraction | 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
... | python | 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
... | [
"def",
"population_fraction",
"(",
"self",
")",
":",
"numerator",
"=",
"self",
".",
"_cube_dict",
"[",
"\"result\"",
"]",
".",
"get",
"(",
"\"filtered\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"weighted_n\"",
")",
"denominator",
"=",
"self",
".",
"_cube... | 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... | [
"The",
"filtered",
"/",
"unfiltered",
"ratio",
"for",
"cube",
"response",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1401-L1416 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _Measures.weighted_counts | 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.
"""
if not self.is_we... | python | 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.
"""
if not self.is_we... | [
"def",
"weighted_counts",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_weighted",
":",
"return",
"self",
".",
"unweighted_counts",
"return",
"_WeightedCountMeasure",
"(",
"self",
".",
"_cube_dict",
",",
"self",
".",
"_all_dimensions",
")"
] | _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. | [
"_WeightedCountMeasure",
"object",
"for",
"this",
"cube",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1433-L1442 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _Measures.weighted_n | def weighted_n(self):
"""float count of returned rows adjusted for weighting."""
if not self.is_weighted:
return float(self.unweighted_n)
return float(sum(self._cube_dict["result"]["measures"]["count"]["data"])) | python | def weighted_n(self):
"""float count of returned rows adjusted for weighting."""
if not self.is_weighted:
return float(self.unweighted_n)
return float(sum(self._cube_dict["result"]["measures"]["count"]["data"])) | [
"def",
"weighted_n",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_weighted",
":",
"return",
"float",
"(",
"self",
".",
"unweighted_n",
")",
"return",
"float",
"(",
"sum",
"(",
"self",
".",
"_cube_dict",
"[",
"\"result\"",
"]",
"[",
"\"measures\""... | float count of returned rows adjusted for weighting. | [
"float",
"count",
"of",
"returned",
"rows",
"adjusted",
"for",
"weighting",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1445-L1449 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _BaseMeasure.raw_cube_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.
"""... | python | 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.
"""... | [
"def",
"raw_cube_array",
"(",
"self",
")",
":",
"array",
"=",
"np",
".",
"array",
"(",
"self",
".",
"_flat_values",
")",
".",
"reshape",
"(",
"self",
".",
"_all_dimensions",
".",
"shape",
")",
"# ---must be read-only to avoid hard-to-find bugs---",
"array",
".",... | 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. | [
"Return",
"read",
"-",
"only",
"ndarray",
"of",
"measure",
"values",
"from",
"cube",
"-",
"response",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1460-L1470 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | _MeanMeasure._flat_values | 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.
"""
return tuple(
np.nan if ty... | python | 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.
"""
return tuple(
np.nan if ty... | [
"def",
"_flat_values",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"np",
".",
"nan",
"if",
"type",
"(",
"x",
")",
"is",
"dict",
"else",
"x",
"for",
"x",
"in",
"self",
".",
"_cube_dict",
"[",
"\"result\"",
"]",
"[",
"\"measures\"",
"]",
"[",
"\"m... | 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. | [
"Return",
"tuple",
"of",
"mean",
"values",
"as",
"found",
"in",
"cube",
"response",
"."
] | train | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1490-L1500 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/input_dataframe_generator.py | make_input_dataframe_by_entity | 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 pe... | python | 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 pe... | [
"def",
"make_input_dataframe_by_entity",
"(",
"tax_benefit_system",
",",
"nb_persons",
",",
"nb_groups",
")",
":",
"input_dataframe_by_entity",
"=",
"dict",
"(",
")",
"person_entity",
"=",
"[",
"entity",
"for",
"entity",
"in",
"tax_benefit_system",
".",
"entities",
... | 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... | [
"Generate",
"a",
"dictionnary",
"of",
"dataframes",
"containing",
"nb_persons",
"persons",
"spread",
"in",
"nb_groups",
"groups",
"."
] | train | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/input_dataframe_generator.py#L25-L84 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/input_dataframe_generator.py | randomly_init_variable | 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 Tr... | python | 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 Tr... | [
"def",
"randomly_init_variable",
"(",
"tax_benefit_system",
",",
"input_dataframe_by_entity",
",",
"variable_name",
",",
"max_value",
",",
"condition",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"variable",
"=",
"tax_benefit_system",
".",
"variables",
"[",
"... | 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... | [
"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",... | train | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/input_dataframe_generator.py#L124-L167 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/surveys.py | Survey.get_value | 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... | python | 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... | [
"def",
"get_value",
"(",
"self",
",",
"variable",
"=",
"None",
",",
"table",
"=",
"None",
")",
":",
"assert",
"variable",
"is",
"not",
"None",
",",
"\"A variable is needed\"",
"if",
"table",
"not",
"in",
"self",
".",
"tables",
":",
"log",
".",
"error",
... | 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... | [
"Get",
"value"
] | train | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/surveys.py#L174-L193 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/surveys.py | Survey.get_values | 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, defaul... | python | 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, defaul... | [
"def",
"get_values",
"(",
"self",
",",
"variables",
"=",
"None",
",",
"table",
"=",
"None",
",",
"lowercase",
"=",
"False",
",",
"rename_ident",
"=",
"True",
")",
":",
"assert",
"self",
".",
"hdf5_file_path",
"is",
"not",
"None",
"assert",
"os",
".",
"... | 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
... | [
"Get",
"values"
] | train | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/surveys.py#L195-L246 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/surveys.py | Survey.insert_table | def insert_table(self, label = None, name = None, **kwargs):
"""
Insert a table in the Survey object
"""
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',... | python | def insert_table(self, label = None, name = None, **kwargs):
"""
Insert a table in the Survey object
"""
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',... | [
"def",
"insert_table",
"(",
"self",
",",
"label",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"data_frame",
"=",
"kwargs",
".",
"pop",
"(",
"'data_frame'",
",",
"None",
")",
"if",
"data_frame",
"is",
"None",
":",
"data_f... | Insert a table in the Survey object | [
"Insert",
"a",
"table",
"in",
"the",
"Survey",
"object"
] | train | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/surveys.py#L248-L272 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/variables.py | quantile | 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
"""
def formula(entity, period):
value = entity(variable, period)
if weight_variable is not None:
... | python | 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
"""
def formula(entity, period):
value = entity(variable, period)
if weight_variable is not None:
... | [
"def",
"quantile",
"(",
"q",
",",
"variable",
",",
"weight_variable",
"=",
"None",
",",
"filter_variable",
"=",
"None",
")",
":",
"def",
"formula",
"(",
"entity",
",",
"period",
")",
":",
"value",
"=",
"entity",
"(",
"variable",
",",
"period",
")",
"if... | Return quantile of a variable with weight provided by a specific wieght variable potentially filtered | [
"Return",
"quantile",
"of",
"a",
"variable",
"with",
"weight",
"provided",
"by",
"a",
"specific",
"wieght",
"variable",
"potentially",
"filtered"
] | train | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/variables.py#L12-L36 |
mgaitan/waliki | docs/conf.py | _get_version | def _get_version():
"""Get the version from package itself."""
with open("../waliki/__init__.py") as fh:
for line in fh:
if line.startswith("__version__ = "):
return line.split("=")[-1].strip().strip("'").strip('"') | python | def _get_version():
"""Get the version from package itself."""
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",
"(",
")",
":",
"with",
"open",
"(",
"\"../waliki/__init__.py\"",
")",
"as",
"fh",
":",
"for",
"line",
"in",
"fh",
":",
"if",
"line",
".",
"startswith",
"(",
"\"__version__ = \"",
")",
":",
"return",
"line",
".",
"split",
"(",
"\"=\... | Get the version from package itself. | [
"Get",
"the",
"version",
"from",
"package",
"itself",
"."
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/docs/conf.py#L27-L32 |
mgaitan/waliki | waliki/management/commands/moin_migration_cleanup.py | clean_meta | def clean_meta(rst_content):
"""remove moinmoin metada from the top of the file"""
rst = rst_content.split('\n')
for i, line in enumerate(rst):
if line.startswith('#'):
continue
break
return '\n'.join(rst[i:]) | python | def clean_meta(rst_content):
"""remove moinmoin metada from the top of the file"""
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",
")",
":",
"rst",
"=",
"rst_content",
".",
"split",
"(",
"'\\n'",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"rst",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue",
"break... | remove moinmoin metada from the top of the file | [
"remove",
"moinmoin",
"metada",
"from",
"the",
"top",
"of",
"the",
"file"
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/management/commands/moin_migration_cleanup.py#L21-L29 |
mgaitan/waliki | waliki/templatetags/waliki_tags.py | entry_point | 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 ... | python | 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 ... | [
"def",
"entry_point",
"(",
"context",
",",
"block_name",
")",
":",
"from",
"waliki",
".",
"plugins",
"import",
"get_plugins",
"includes",
"=",
"[",
"]",
"for",
"plugin",
"in",
"get_plugins",
"(",
")",
":",
"template_name",
"=",
"'waliki/%s_%s.html'",
"%",
"(... | 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 | [
"include",
"an",
"snippet",
"at",
"the",
"bottom",
"of",
"a",
"block",
"if",
"it",
"exists"
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/templatetags/waliki_tags.py#L30-L52 |
mgaitan/waliki | waliki/templatetags/waliki_tags.py | check_perms | 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
... | python | 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
... | [
"def",
"check_perms",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"format",
"=",
"'{% check_perms \"perm1[, perm2, ...]\" for user in slug as \"context_var\" %}'",
"if",
"len",
"(",
"bits",
")",
"!=",
"8",
"or",
"b... | 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... | [
"Returns",
"a",
"list",
"of",
"permissions",
"(",
"as",
"codename",
"strings",
")",
"for",
"a",
"given",
"user",
"/",
"group",
"and",
"obj",
"(",
"Model",
"instance",
")",
"."
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/templatetags/waliki_tags.py#L91-L134 |
mgaitan/waliki | waliki/templatetags/waliki_tags.py | waliki_box | 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
"""
request ... | python | 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
"""
request ... | [
"def",
"waliki_box",
"(",
"context",
",",
"slug",
",",
"show_edit",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"context",
"[",
"\"request\"",
"]",
"try",
":",
"page",
"=",
"Page",
".",
"objects",
".",
"get",
"... | 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 | [
"A",
"templatetag",
"to",
"render",
"a",
"wiki",
"page",
"content",
"as",
"a",
"box",
"in",
"any",
"webpage",
"and",
"allow",
"rapid",
"edition",
"if",
"you",
"have",
"permission",
"."
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/templatetags/waliki_tags.py#L138-L169 |
mgaitan/waliki | waliki/acl.py | check_perms | def check_perms(perms, user, slug, raise_exception=False):
"""a helper user to check if a user has the permissions
for a given slug"""
if isinstance(perms, string_types):
perms = {perms}
else:
perms = set(perms)
allowed_users = ACLRule.get_users_for(perms, slug)
if allowed_user... | python | def check_perms(perms, user, slug, raise_exception=False):
"""a helper user to check if a user has the permissions
for a given slug"""
if isinstance(perms, string_types):
perms = {perms}
else:
perms = set(perms)
allowed_users = ACLRule.get_users_for(perms, slug)
if allowed_user... | [
"def",
"check_perms",
"(",
"perms",
",",
"user",
",",
"slug",
",",
"raise_exception",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"perms",
",",
"string_types",
")",
":",
"perms",
"=",
"{",
"perms",
"}",
"else",
":",
"perms",
"=",
"set",
"(",
"pe... | a helper user to check if a user has the permissions
for a given slug | [
"a",
"helper",
"user",
"to",
"check",
"if",
"a",
"user",
"has",
"the",
"permissions",
"for",
"a",
"given",
"slug"
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/acl.py#L19-L45 |
mgaitan/waliki | waliki/acl.py | permission_required | 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 r... | python | 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 r... | [
"def",
"permission_required",
"(",
"perms",
",",
"login_url",
"=",
"None",
",",
"raise_exception",
"=",
"False",
",",
"redirect_field_name",
"=",
"REDIRECT_FIELD_NAME",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
"... | 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... | [
"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"
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/acl.py#L48-L87 |
mgaitan/waliki | waliki/plugins.py | get_module | 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.
"""
module_name = '%s.%s' % (app, modname)
try:
module = import_module(module_name)
except ImportError as e:
... | python | 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.
"""
module_name = '%s.%s' % (app, modname)
try:
module = import_module(module_name)
except ImportError as e:
... | [
"def",
"get_module",
"(",
"app",
",",
"modname",
",",
"verbose",
"=",
"False",
",",
"failfast",
"=",
"False",
")",
":",
"module_name",
"=",
"'%s.%s'",
"%",
"(",
"app",
",",
"modname",
")",
"try",
":",
"module",
"=",
"import_module",
"(",
"module_name",
... | Internal function to load a module from a single app.
taken from https://github.com/ojii/django-load. | [
"Internal",
"function",
"to",
"load",
"a",
"module",
"from",
"a",
"single",
"app",
"."
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/plugins.py#L28-L45 |
mgaitan/waliki | waliki/plugins.py | load | 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.
"""
for app in settings.INSTALLED_APPS:
get_mod... | python | 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.
"""
for app in settings.INSTALLED_APPS:
get_mod... | [
"def",
"load",
"(",
"modname",
",",
"verbose",
"=",
"False",
",",
"failfast",
"=",
"False",
")",
":",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"get_module",
"(",
"app",
",",
"modname",
",",
"verbose",
",",
"failfast",
")"
] | 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. | [
"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",
... | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/plugins.py#L48-L55 |
mgaitan/waliki | waliki/plugins.py | register | def register(PluginClass):
"""
Register a plugin class. This function will call back your plugin's
constructor.
"""
if PluginClass in _cache.keys():
raise Exception("Plugin class already registered")
plugin = PluginClass()
_cache[PluginClass] = plugin
if getattr(PluginClass, 'ex... | python | def register(PluginClass):
"""
Register a plugin class. This function will call back your plugin's
constructor.
"""
if PluginClass in _cache.keys():
raise Exception("Plugin class already registered")
plugin = PluginClass()
_cache[PluginClass] = plugin
if getattr(PluginClass, 'ex... | [
"def",
"register",
"(",
"PluginClass",
")",
":",
"if",
"PluginClass",
"in",
"_cache",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"Plugin class already registered\"",
")",
"plugin",
"=",
"PluginClass",
"(",
")",
"_cache",
"[",
"PluginClass",
"]",
... | Register a plugin class. This function will call back your plugin's
constructor. | [
"Register",
"a",
"plugin",
"class",
".",
"This",
"function",
"will",
"call",
"back",
"your",
"plugin",
"s",
"constructor",
"."
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/plugins.py#L62-L86 |
mgaitan/waliki | waliki/templatetags/bootstrap_tags.py | render_form | def render_form(form):
"""same than {{ form|crispy }} if crispy_forms is installed.
render using a bootstrap3 templating otherwise"""
if 'crispy_forms' in settings.INSTALLED_APPS:
from crispy_forms.templatetags.crispy_forms_filters import as_crispy_form
return as_crispy_form(form)
tem... | python | def render_form(form):
"""same than {{ form|crispy }} if crispy_forms is installed.
render using a bootstrap3 templating otherwise"""
if 'crispy_forms' in settings.INSTALLED_APPS:
from crispy_forms.templatetags.crispy_forms_filters import as_crispy_form
return as_crispy_form(form)
tem... | [
"def",
"render_form",
"(",
"form",
")",
":",
"if",
"'crispy_forms'",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"from",
"crispy_forms",
".",
"templatetags",
".",
"crispy_forms_filters",
"import",
"as_crispy_form",
"return",
"as_crispy_form",
"(",
"form",
")",
"... | same than {{ form|crispy }} if crispy_forms is installed.
render using a bootstrap3 templating otherwise | [
"same",
"than",
"{{",
"form|crispy",
"}}",
"if",
"crispy_forms",
"is",
"installed",
".",
"render",
"using",
"a",
"bootstrap3",
"templating",
"otherwise"
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/templatetags/bootstrap_tags.py#L25-L36 |
mgaitan/waliki | waliki/context_processors.py | settings | def settings(request):
"""inject few waliki's settings to the context to be used in templates"""
from waliki.settings import WALIKI_USE_MATHJAX # NOQA
return {k: v for (k, v) in locals().items() if k.startswith('WALIKI')} | python | def settings(request):
"""inject few waliki's settings to the context to be used in templates"""
from waliki.settings import WALIKI_USE_MATHJAX # NOQA
return {k: v for (k, v) in locals().items() if k.startswith('WALIKI')} | [
"def",
"settings",
"(",
"request",
")",
":",
"from",
"waliki",
".",
"settings",
"import",
"WALIKI_USE_MATHJAX",
"# NOQA",
"return",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"locals",
"(",
")",
".",
"items",
"(",
")",
"if",
"k",
"."... | inject few waliki's settings to the context to be used in templates | [
"inject",
"few",
"waliki",
"s",
"settings",
"to",
"the",
"context",
"to",
"be",
"used",
"in",
"templates"
] | train | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/context_processors.py#L2-L5 |
ccnmtl/fdfgen | fdfgen/__init__.py | smart_encode_str | def smart_encode_str(s):
"""Create a UTF-16 encoded PDF string literal for `s`."""
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(... | python | def smart_encode_str(s):
"""Create a UTF-16 encoded PDF string literal for `s`."""
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(... | [
"def",
"smart_encode_str",
"(",
"s",
")",
":",
"try",
":",
"utf16",
"=",
"s",
".",
"encode",
"(",
"'utf_16_be'",
")",
"except",
"AttributeError",
":",
"# ints and floats",
"utf16",
"=",
"str",
"(",
"s",
")",
".",
"encode",
"(",
"'utf_16_be'",
")",
"safe"... | Create a UTF-16 encoded PDF string literal for `s`. | [
"Create",
"a",
"UTF",
"-",
"16",
"encoded",
"PDF",
"string",
"literal",
"for",
"s",
"."
] | train | https://github.com/ccnmtl/fdfgen/blob/7db306b78e65058da408a76a3ff96ba917b70763/fdfgen/__init__.py#L23-L30 |
ccnmtl/fdfgen | fdfgen/__init__.py | forge_fdf | 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: [])... | python | 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: [])... | [
"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 ... | [
"Generates",
"fdf",
"string",
"from",
"fields",
"specified"
] | train | https://github.com/ccnmtl/fdfgen/blob/7db306b78e65058da408a76a3ff96ba917b70763/fdfgen/__init__.py#L109-L147 |
vxgmichel/aiostream | aiostream/stream/advanced.py | base_combine | 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`` arg... | python | 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`` arg... | [
"async",
"def",
"base_combine",
"(",
"source",
",",
"switch",
"=",
"False",
",",
"ordered",
"=",
"False",
",",
"task_limit",
"=",
"None",
")",
":",
"# Task limit",
"if",
"task_limit",
"is",
"not",
"None",
"and",
"not",
"task_limit",
">",
"0",
":",
"raise... | 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... | [
"Base",
"operator",
"for",
"managing",
"an",
"asynchronous",
"sequence",
"of",
"sequences",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L15-L96 |
vxgmichel/aiostream | aiostream/stream/advanced.py | concat | 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... | python | 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... | [
"def",
"concat",
"(",
"source",
",",
"task_limit",
"=",
"None",
")",
":",
"return",
"base_combine",
".",
"raw",
"(",
"source",
",",
"task_limit",
"=",
"task_limit",
",",
"switch",
"=",
"False",
",",
"ordered",
"=",
"True",
")"
] | 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. | [
"Given",
"an",
"asynchronous",
"sequence",
"of",
"sequences",
"generate",
"the",
"elements",
"of",
"the",
"sequences",
"in",
"order",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L102-L112 |
vxgmichel/aiostream | aiostream/stream/advanced.py | flatten | 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 ... | python | 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 ... | [
"def",
"flatten",
"(",
"source",
",",
"task_limit",
"=",
"None",
")",
":",
"return",
"base_combine",
".",
"raw",
"(",
"source",
",",
"task_limit",
"=",
"task_limit",
",",
"switch",
"=",
"False",
",",
"ordered",
"=",
"False",
")"
] | 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... | [
"Given",
"an",
"asynchronous",
"sequence",
"of",
"sequences",
"generate",
"the",
"elements",
"of",
"the",
"sequences",
"as",
"soon",
"as",
"they",
"re",
"received",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L116-L126 |
vxgmichel/aiostream | aiostream/stream/advanced.py | concatmap | 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
a... | python | 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
a... | [
"def",
"concatmap",
"(",
"source",
",",
"func",
",",
"*",
"more_sources",
",",
"task_limit",
"=",
"None",
")",
":",
"return",
"concat",
".",
"raw",
"(",
"combine",
".",
"smap",
".",
"raw",
"(",
"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 created
sequences in order.
The function is applied as described in `map`, and must return an
asynchronous sequence. The returned sequences are awaited concurrentl... | [
"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",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L147-L158 |
vxgmichel/aiostream | aiostream/stream/advanced.py | flatmap | 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 ret... | python | 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 ret... | [
"def",
"flatmap",
"(",
"source",
",",
"func",
",",
"*",
"more_sources",
",",
"task_limit",
"=",
"None",
")",
":",
"return",
"flatten",
".",
"raw",
"(",
"combine",
".",
"smap",
".",
"raw",
"(",
"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 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... | [
"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",
... | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L162-L175 |
vxgmichel/aiostream | aiostream/stream/advanced.py | switchmap | 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 se... | python | 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 se... | [
"def",
"switchmap",
"(",
"source",
",",
"func",
",",
"*",
"more_sources",
")",
":",
"return",
"switch",
".",
"raw",
"(",
"combine",
".",
"smap",
".",
"raw",
"(",
"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... | [
"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",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L179-L188 |
vxgmichel/aiostream | aiostream/stream/aggregate.py | accumulate | 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 ... | python | 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 ... | [
"async",
"def",
"accumulate",
"(",
"source",
",",
"func",
"=",
"op",
".",
"add",
",",
"initializer",
"=",
"None",
")",
":",
"iscorofunc",
"=",
"asyncio",
".",
"iscoroutinefunction",
"(",
"func",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
... | 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. | [
"Generate",
"a",
"series",
"of",
"accumulated",
"sums",
"(",
"or",
"other",
"binary",
"function",
")",
"from",
"an",
"asynchronous",
"sequence",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/aggregate.py#L14-L39 |
vxgmichel/aiostream | aiostream/stream/aggregate.py | reduce | 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 ... | python | 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 ... | [
"def",
"reduce",
"(",
"source",
",",
"func",
",",
"initializer",
"=",
"None",
")",
":",
"acc",
"=",
"accumulate",
".",
"raw",
"(",
"source",
",",
"func",
",",
"initializer",
")",
"return",
"select",
".",
"item",
".",
"raw",
"(",
"acc",
",",
"-",
"1... | 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. | [
"Apply",
"a",
"function",
"of",
"two",
"arguments",
"cumulatively",
"to",
"the",
"items",
"of",
"an",
"asynchronous",
"sequence",
"reducing",
"the",
"sequence",
"to",
"a",
"single",
"value",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/aggregate.py#L43-L52 |
vxgmichel/aiostream | aiostream/stream/aggregate.py | list | async def list(source):
"""Generate a single list from an asynchronous sequence."""
result = []
async with streamcontext(source) as streamer:
async for item in streamer:
result.append(item)
yield result | python | async def list(source):
"""Generate a single list from an asynchronous sequence."""
result = []
async with streamcontext(source) as streamer:
async for item in streamer:
result.append(item)
yield result | [
"async",
"def",
"list",
"(",
"source",
")",
":",
"result",
"=",
"[",
"]",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"streamer",
":",
"result",
".",
"append",
"(",
"item",
")",
"yield",
... | Generate a single list from an asynchronous sequence. | [
"Generate",
"a",
"single",
"list",
"from",
"an",
"asynchronous",
"sequence",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/aggregate.py#L56-L62 |
vxgmichel/aiostream | aiostream/core.py | wait_stream | 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.
"""
async with streamcontext(aiterable) as streamer:
async for item i... | python | 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.
"""
async with streamcontext(aiterable) as streamer:
async for item i... | [
"async",
"def",
"wait_stream",
"(",
"aiterable",
")",
":",
"async",
"with",
"streamcontext",
"(",
"aiterable",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"streamer",
":",
"item",
"try",
":",
"return",
"item",
"except",
"NameError",
":",
"rai... | 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. | [
"Wait",
"for",
"an",
"asynchronous",
"iterable",
"to",
"finish",
"and",
"return",
"the",
"last",
"item",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/core.py#L22-L34 |
vxgmichel/aiostream | aiostream/core.py | operator | def operator(func=None, *, pipable=False):
"""Create a stream operator from an asynchronous generator
(or any function returning an asynchronous iterable).
Decorator usage::
@operator
async def random(offset=0., width=1.):
while True:
yield offset + width * rand... | python | def operator(func=None, *, pipable=False):
"""Create a stream operator from an asynchronous generator
(or any function returning an asynchronous iterable).
Decorator usage::
@operator
async def random(offset=0., width=1.):
while True:
yield offset + width * rand... | [
"def",
"operator",
"(",
"func",
"=",
"None",
",",
"*",
",",
"pipable",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"Inner decorator for stream operator.\"\"\"",
"# Gather data",
"bases",
"=",
"(",
"Stream",
",",
")",
"name",
"=",... | Create a stream operator from an asynchronous generator
(or any function returning an asynchronous iterable).
Decorator usage::
@operator
async def random(offset=0., width=1.):
while True:
yield offset + width * random.random()
Decorator usage for pipable opera... | [
"Create",
"a",
"stream",
"operator",
"from",
"an",
"asynchronous",
"generator",
"(",
"or",
"any",
"function",
"returning",
"an",
"asynchronous",
"iterable",
")",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/core.py#L190-L339 |
vxgmichel/aiostream | aiostream/stream/misc.py | action | 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.
"""
if asyncio.iscoroutinefunction(func):
async def innerfunc(arg):
await func(arg)
return arg
... | python | 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.
"""
if asyncio.iscoroutinefunction(func):
async def innerfunc(arg):
await func(arg)
return arg
... | [
"def",
"action",
"(",
"source",
",",
"func",
")",
":",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"func",
")",
":",
"async",
"def",
"innerfunc",
"(",
"arg",
")",
":",
"await",
"func",
"(",
"arg",
")",
"return",
"arg",
"else",
":",
"def",
"inne... | Perform an action for each element of an asynchronous sequence
without modifying it.
The given function can be synchronous or asynchronous. | [
"Perform",
"an",
"action",
"for",
"each",
"element",
"of",
"an",
"asynchronous",
"sequence",
"without",
"modifying",
"it",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/misc.py#L12-L26 |
vxgmichel/aiostream | aiostream/stream/misc.py | print | 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.
"""
def func(value):
if template... | python | 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.
"""
def func(value):
if template... | [
"def",
"print",
"(",
"source",
",",
"template",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"func",
"(",
"value",
")",
":",
"if",
"template",
":",
"value",
"=",
"template",
".",
"format",
"(",
"value",
")",
"builtins",
".",
"print",
"(",... | 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. | [
"Print",
"each",
"element",
"of",
"an",
"asynchronous",
"sequence",
"without",
"modifying",
"it",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/misc.py#L30-L40 |
vxgmichel/aiostream | aiostream/aiter_utils.py | async_ | def async_(fn):
"""Wrap the given function into a coroutine function."""
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
return await fn(*args, **kwargs)
return wrapper | python | def async_(fn):
"""Wrap the given function into a coroutine function."""
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
return await fn(*args, **kwargs)
return wrapper | [
"def",
"async_",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"async",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"retu... | Wrap the given function into a coroutine function. | [
"Wrap",
"the",
"given",
"function",
"into",
"a",
"coroutine",
"function",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/aiter_utils.py#L40-L45 |
vxgmichel/aiostream | aiostream/aiter_utils.py | aitercontext | 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 saf... | python | 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 saf... | [
"def",
"aitercontext",
"(",
"aiterable",
",",
"*",
",",
"cls",
"=",
"AsyncIteratorContext",
")",
":",
"assert",
"issubclass",
"(",
"cls",
",",
"AsyncIteratorContext",
")",
"aiterator",
"=",
"aiter",
"(",
"aiterable",
")",
"if",
"isinstance",
"(",
"aiterator",
... | 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... | [
"Return",
"an",
"asynchronous",
"context",
"manager",
"from",
"an",
"asynchronous",
"iterable",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/aiter_utils.py#L180-L204 |
vxgmichel/aiostream | aiostream/stream/select.py | takelast | 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.
"""
queue = collections.deque(maxle... | python | 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.
"""
queue = collections.deque(maxle... | [
"async",
"def",
"takelast",
"(",
"source",
",",
"n",
")",
":",
"queue",
"=",
"collections",
".",
"deque",
"(",
"maxlen",
"=",
"n",
"if",
"n",
">",
"0",
"else",
"0",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"... | 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. | [
"Forward",
"the",
"last",
"n",
"elements",
"from",
"an",
"asynchronous",
"sequence",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L32-L45 |
vxgmichel/aiostream | aiostream/stream/select.py | skip | async def skip(source, n):
"""Forward an asynchronous sequence, skipping the first ``n`` elements.
If ``n`` is negative, no elements are skipped.
"""
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if i >= n:
... | python | async def skip(source, n):
"""Forward an asynchronous sequence, skipping the first ``n`` elements.
If ``n`` is negative, no elements are skipped.
"""
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if i >= n:
... | [
"async",
"def",
"skip",
"(",
"source",
",",
"n",
")",
":",
"source",
"=",
"transform",
".",
"enumerate",
".",
"raw",
"(",
"source",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"i",
",",
"item",
"i... | Forward an asynchronous sequence, skipping the first ``n`` elements.
If ``n`` is negative, no elements are skipped. | [
"Forward",
"an",
"asynchronous",
"sequence",
"skipping",
"the",
"first",
"n",
"elements",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L49-L58 |
vxgmichel/aiostream | aiostream/stream/select.py | skiplast | 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.
"""
queue = collections.deque(maxlen=n ... | python | 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.
"""
queue = collections.deque(maxlen=n ... | [
"async",
"def",
"skiplast",
"(",
"source",
",",
"n",
")",
":",
"queue",
"=",
"collections",
".",
"deque",
"(",
"maxlen",
"=",
"n",
"if",
"n",
">",
"0",
"else",
"0",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"... | 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. | [
"Forward",
"an",
"asynchronous",
"sequence",
"skipping",
"the",
"last",
"n",
"elements",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L62-L78 |
vxgmichel/aiostream | aiostream/stream/select.py | filterindex | 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.
"""
source = transform.enumerate.raw(so... | python | 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.
"""
source = transform.enumerate.raw(so... | [
"async",
"def",
"filterindex",
"(",
"source",
",",
"func",
")",
":",
"source",
"=",
"transform",
".",
"enumerate",
".",
"raw",
"(",
"source",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"i",
",",
"i... | 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. | [
"Filter",
"an",
"asynchronous",
"sequence",
"using",
"the",
"index",
"of",
"the",
"elements",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L82-L93 |
vxgmichel/aiostream | aiostream/stream/select.py | slice | 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
"""
s = builtins.slice(*... | python | 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
"""
s = builtins.slice(*... | [
"def",
"slice",
"(",
"source",
",",
"*",
"args",
")",
":",
"s",
"=",
"builtins",
".",
"slice",
"(",
"*",
"args",
")",
"start",
",",
"stop",
",",
"step",
"=",
"s",
".",
"start",
"or",
"0",
",",
"s",
".",
"stop",
",",
"s",
".",
"step",
"or",
... | 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 | [
"Slice",
"an",
"asynchronous",
"sequence",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L97-L129 |
vxgmichel/aiostream | aiostream/stream/select.py | item | 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.
"""
# Prepare
if index >= 0:
source = skip.raw(source, index)
else:
... | python | 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.
"""
# Prepare
if index >= 0:
source = skip.raw(source, index)
else:
... | [
"async",
"def",
"item",
"(",
"source",
",",
"index",
")",
":",
"# Prepare",
"if",
"index",
">=",
"0",
":",
"source",
"=",
"skip",
".",
"raw",
"(",
"source",
",",
"index",
")",
"else",
":",
"source",
"=",
"takelast",
"(",
"source",
",",
"abs",
"(",
... | 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. | [
"Forward",
"the",
"n",
"th",
"element",
"of",
"an",
"asynchronous",
"sequence",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L133-L158 |
vxgmichel/aiostream | aiostream/stream/select.py | getitem | 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.
"""
if isinstance(index, builtins.slice):
return slice.raw(source, index.start, index.stop, ind... | python | 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.
"""
if isinstance(index, builtins.slice):
return slice.raw(source, index.start, index.stop, ind... | [
"def",
"getitem",
"(",
"source",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"builtins",
".",
"slice",
")",
":",
"return",
"slice",
".",
"raw",
"(",
"source",
",",
"index",
".",
"start",
",",
"index",
".",
"stop",
",",
"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. | [
"Forward",
"one",
"or",
"several",
"items",
"from",
"an",
"asynchronous",
"sequence",
"."
] | train | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L162-L172 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.