repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_iso3_country_code
python
def get_iso3_country_code(cls, country, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str] countriesdata = cls.countriesdata(use_live=use_live) countryupper = country.upper() len_countryupper = len(countryupper) if len_countryupper...
Get ISO3 code for cls. Only exact matches or None are returned. Args: country (str): Country for which to get ISO3 code use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L449-L483
[ "def countriesdata(cls, use_live=True):\n # type: (bool) -> List[Dict[Dict]]\n \"\"\"\n Read countries data from OCHA countries feed (falling back to file)\n\n Args:\n use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\n\n Returns:\n List...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_iso3_country_code_fuzzy
python
def get_iso3_country_code_fuzzy(cls, country, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Tuple[[Optional[str], bool]] countriesdata = cls.countriesdata(use_live=use_live) iso3 = cls.get_iso3_country_code(country, ...
Get ISO3 code for cls. A tuple is returned with the first value being the ISO3 code and the second showing if the match is exact or not. Args: country (str): Country for which to get ISO3 code use_live (bool): Try to get use latest data from web rather than file in package. Defa...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L486-L556
null
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_countries_in_region
python
def get_countries_in_region(cls, region, use_live=True, exception=None): # type: (Union[int,str], bool, Optional[ExceptionUpperBound]) -> List[str] countriesdata = cls.countriesdata(use_live=use_live) if isinstance(region, int): regioncode = region else: regionupp...
Get countries (ISO3 codes) in region Args: region (Union[int,str]): Three digit UNStats M49 region code or region name use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception ...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L559-L583
[ "def countriesdata(cls, use_live=True):\n # type: (bool) -> List[Dict[Dict]]\n \"\"\"\n Read countries data from OCHA countries feed (falling back to file)\n\n Args:\n use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\n\n Returns:\n List...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
paylogic/halogen
halogen/exceptions.py
ValidationError.to_dict
python
def to_dict(self): def exception_to_dict(e): try: return e.to_dict() except AttributeError: return { "type": e.__class__.__name__, "error": str(e), } result = { "errors": [excepti...
Return a dictionary representation of the error. :return: A dict with the keys: - attr: Attribute which contains the error, or "<root>" if it refers to the schema root. - errors: A list of dictionary representations of the errors.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/exceptions.py#L18-L41
null
class ValidationError(Exception): """Validation failed.""" def __init__(self, errors, attr=None, index=None): self.attr = attr self.index = index if isinstance(errors, list): self.errors = errors else: self.errors = [errors] def __str__(self): ...
paylogic/halogen
halogen/schema.py
_get_context
python
def _get_context(argspec, kwargs): if argspec.keywords is not None: return kwargs return dict((arg, kwargs[arg]) for arg in argspec.args if arg in kwargs)
Prepare a context for the serialization. :param argspec: The argspec of the serialization function. :param kwargs: Dict with context :return: Keywords arguments that function can accept.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L29-L38
null
"""Halogen schema primitives.""" import sys import inspect try: from collections import OrderedDict except ImportError: # pragma: no cover from ordereddict import OrderedDict # noqa from cached_property import cached_property from halogen import types from halogen import exceptions PY2 = sys.version_info...
paylogic/halogen
halogen/schema.py
Accessor.get
python
def get(self, obj, **kwargs): assert self.getter is not None, "Getter accessor is not specified." if callable(self.getter): return self.getter(obj, **_get_context(self._getter_argspec, kwargs)) assert isinstance(self.getter, string_types), "Accessor must be a function or a dot-separ...
Get an attribute from a value. :param obj: Object to get the attribute value from. :return: Value of object's attribute.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L54-L75
[ "def _get_context(argspec, kwargs):\n \"\"\"Prepare a context for the serialization.\n\n :param argspec: The argspec of the serialization function.\n :param kwargs: Dict with context\n :return: Keywords arguments that function can accept.\n \"\"\"\n if argspec.keywords is not None:\n return...
class Accessor(object): """Object that encapsulates the getter and the setter of the attribute.""" def __init__(self, getter=None, setter=None): """Initialize an Accessor object.""" self.getter = getter self.setter = setter @cached_property def _getter_argspec(self): r...
paylogic/halogen
halogen/schema.py
Accessor.set
python
def set(self, obj, value): assert self.setter is not None, "Setter accessor is not specified." if callable(self.setter): return self.setter(obj, value) assert isinstance(self.setter, string_types), "Accessor must be a function or a dot-separated string." def _set(obj, attr,...
Set value for obj's attribute. :param obj: Result object or dict to assign the attribute to. :param value: Value to be assigned.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L77-L100
[ "def basic_set_object(obj, value):\n \"\"\"Set the value of attribute \"value\" of \"obj\".\"\"\"\n obj.value = value\n", "def basic_set_dict(dic, value):\n \"\"\"Set the value of attribute \"value\" of \"obj\".\"\"\"\n dic[\"value\"] = value\n", "def _set(obj, attr, value):\n if isinstance(obj, ...
class Accessor(object): """Object that encapsulates the getter and the setter of the attribute.""" def __init__(self, getter=None, setter=None): """Initialize an Accessor object.""" self.getter = getter self.setter = setter @cached_property def _getter_argspec(self): r...
paylogic/halogen
halogen/schema.py
Attr.accessor
python
def accessor(self): if isinstance(self.attr, Accessor): return self.attr if callable(self.attr): return Accessor(getter=self.attr) attr = self.attr or self.name return Accessor(getter=attr, setter=attr)
Get an attribute's accessor with the getter and the setter. :return: `Accessor` instance.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L144-L156
null
class Attr(object): """Schema attribute.""" creation_counter = 0 def __init__(self, attr_type=None, attr=None, required=True, **kwargs): """Attribute constructor. :param attr_type: Type, Schema or constant that does the type conversion of the attribute. :param attr: Attribute name...
paylogic/halogen
halogen/schema.py
Attr.serialize
python
def serialize(self, value, **kwargs): if types.Type.is_type(self.attr_type): try: value = self.accessor.get(value, **kwargs) except (AttributeError, KeyError): if not hasattr(self, "default") and self.required: raise val...
Serialize the attribute of the input data. Gets the attribute value with accessor and converts it using the type serialization. Schema will place this serialized value into corresponding compartment of the HAL structure with the name of the attribute as a key. :param value: Val...
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L162-L183
[ "def _get_context(argspec, kwargs):\n \"\"\"Prepare a context for the serialization.\n\n :param argspec: The argspec of the serialization function.\n :param kwargs: Dict with context\n :return: Keywords arguments that function can accept.\n \"\"\"\n if argspec.keywords is not None:\n return...
class Attr(object): """Schema attribute.""" creation_counter = 0 def __init__(self, attr_type=None, attr=None, required=True, **kwargs): """Attribute constructor. :param attr_type: Type, Schema or constant that does the type conversion of the attribute. :param attr: Attribute name...
paylogic/halogen
halogen/schema.py
Attr.deserialize
python
def deserialize(self, value, **kwargs): compartment = value if self.compartment is not None: compartment = value[self.compartment] try: value = self.accessor.get(compartment, **kwargs) except (KeyError, AttributeError): if not hasattr(self, "default"...
Deserialize the attribute from a HAL structure. Get the value from the HAL structure from the attribute's compartment using the attribute's name as a key, convert it using the attribute's type. Schema will either return it to parent schema or will assign to the output value if specifie...
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L185-L209
null
class Attr(object): """Schema attribute.""" creation_counter = 0 def __init__(self, attr_type=None, attr=None, required=True, **kwargs): """Attribute constructor. :param attr_type: Type, Schema or constant that does the type conversion of the attribute. :param attr: Attribute name...
paylogic/halogen
halogen/schema.py
Embedded.key
python
def key(self): if self.curie is None: return self.name return ":".join((self.curie.name, self.name))
Embedded supports curies.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L376-L380
null
class Embedded(Attr): """Embedded attribute of schema.""" def __init__(self, attr_type=None, attr=None, curie=None, required=True): """Embedded constructor. :param attr_type: Type, Schema or constant that does the type conversion of the attribute. :param attr: Attribute name, dot-sepa...
paylogic/halogen
halogen/schema.py
_Schema.deserialize
python
def deserialize(cls, value, output=None, **kwargs): errors = [] result = {} for attr in cls.__attrs__.values(): try: result[attr.name] = attr.deserialize(value, **kwargs) except NotImplementedError: # Links don't support deserialization ...
Deserialize the HAL structure into the output value. :param value: Dict of already loaded json which will be deserialized by schema attributes. :param output: If present, the output object will be updated instead of returning the deserialized data. :returns: Dict of deserialized value for attr...
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L416-L450
null
class _Schema(types.Type): """Type for creating schema.""" def __new__(cls, **kwargs): """Create schema from keyword arguments.""" schema = type("Schema", (cls, ), {"__doc__": cls.__doc__}) schema.__class_attrs__ = OrderedDict() schema.__attrs__ = OrderedDict() for name...
paylogic/halogen
halogen/vnd/error.py
Error.from_validation_exception
python
def from_validation_exception(cls, exception, **kwargs): errors = [] def flatten(error, path=""): if isinstance(error, halogen.exceptions.ValidationError): if not path.endswith("/"): path += "/" if error.attr is not None: ...
Create an error from validation exception.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/vnd/error.py#L26-L53
[ "def flatten(error, path=\"\"):\n if isinstance(error, halogen.exceptions.ValidationError):\n if not path.endswith(\"/\"):\n path += \"/\"\n if error.attr is not None:\n path += error.attr\n elif error.index is not None:\n path += six.text_type(error.index)\n...
class Error(Exception): """Base exception.""" def __init__(self, message, path=None, errors=None): """Create an error. :param message: Error message. :param path: Optional JSON Pointer path. :param errors: Optional nested errors. """ self.message = message ...
paylogic/halogen
halogen/types.py
Type.deserialize
python
def deserialize(self, value, **kwargs): for validator in self.validators: validator.validate(value, **kwargs) return value
Deserialization of value. :return: Deserialized value. :raises: :class:`halogen.exception.ValidationError` exception if value is not valid.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L29-L38
null
class Type(object): """Base class for creating types.""" def __init__(self, validators=None, *args, **kwargs): """Type constructor. :param validators: A list of :class:`halogen.validators.Validator` objects that check the validity of the deserialized value. Validators raise :class:...
paylogic/halogen
halogen/types.py
Type.is_type
python
def is_type(value): if isinstance(value, type): return issubclass(value, Type) return isinstance(value, Type)
Determine if value is an instance or subclass of the class Type.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L41-L45
null
class Type(object): """Base class for creating types.""" def __init__(self, validators=None, *args, **kwargs): """Type constructor. :param validators: A list of :class:`halogen.validators.Validator` objects that check the validity of the deserialized value. Validators raise :class:...
paylogic/halogen
halogen/types.py
List.serialize
python
def serialize(self, value, **kwargs): return [self.item_type.serialize(val, **kwargs) for val in value]
Serialize every item of the list.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L61-L63
null
class List(Type): """List type for Halogen schema attribute.""" def __init__(self, item_type=None, allow_scalar=False, *args, **kwargs): """Create a new List. :param item_type: Item type or schema. :param allow_scalar: Automatically convert scalar value to the list. """ ...
paylogic/halogen
halogen/types.py
List.deserialize
python
def deserialize(self, value, **kwargs): if self.allow_scalar and not isinstance(value, (list, tuple)): value = [value] value = super(List, self).deserialize(value) result = [] errors = [] for index, val in enumerate(value): try: result.app...
Deserialize every item of the list.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L65-L81
[ "def deserialize(self, value, **kwargs):\n \"\"\"Deserialization of value.\n\n :return: Deserialized value.\n :raises: :class:`halogen.exception.ValidationError` exception if value is not valid.\n \"\"\"\n for validator in self.validators:\n validator.validate(value, **kwargs)\n\n return va...
class List(Type): """List type for Halogen schema attribute.""" def __init__(self, item_type=None, allow_scalar=False, *args, **kwargs): """Create a new List. :param item_type: Item type or schema. :param allow_scalar: Automatically convert scalar value to the list. """ ...
paylogic/halogen
halogen/types.py
ISOUTCDateTime.format_as_utc
python
def format_as_utc(self, value): if isinstance(value, datetime.datetime): if value.tzinfo is not None: value = value.astimezone(pytz.UTC) value = value.replace(microsecond=0) return value.isoformat().replace('+00:00', 'Z')
Format UTC times.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L110-L116
null
class ISOUTCDateTime(Type): """ISO-8601 datetime schema type in UTC timezone.""" type = "datetime" message = u"'{val}' is not a valid ISO-8601 datetime" def serialize(self, value, **kwargs): return self.format_as_utc(value) if value else None def deserialize(self, value, **kwargs): ...
paylogic/halogen
halogen/types.py
Amount.amount_object_to_dict
python
def amount_object_to_dict(self, amount): currency, amount = ( amount.as_quantized(digits=2).as_tuple() if not isinstance(amount, dict) else (amount["currency"], amount["amount"]) ) if currency not in self.currencies: raise ValueError(self.err_unkno...
Return the dictionary representation of an Amount object. Amount object must have amount and currency properties and as_tuple method which will return (currency, amount) and as_quantized method to quantize amount property. :param amount: instance of Amount object :return: dict with am...
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L205-L225
null
class Amount(Type): """Amount (money) schema type.""" err_unknown_currency = u"'{currency}' is not a valid currency." def __init__(self, currencies, amount_class, **kwargs): """Initialize new instance of Amount. :param currencies: list of all possible currency codes. :param amount...
paylogic/halogen
halogen/types.py
Amount.deserialize
python
def deserialize(self, value, **kwargs): if value is None: return None if isinstance(value, six.string_types): currency = value[:3] amount = value[3:] elif isinstance(value, dict): if set(value.keys()) != set(("currency", "amount")): ...
Deserialize the amount. :param value: Amount in CURRENCYAMOUNT or {"currency": CURRENCY, "amount": AMOUNT} format. For example EUR35.50 or {"currency": "EUR", "amount": "35.50"} :return: A paylogic Amount object. :raises ValidationError: when amount can"t be deserialzied :r...
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L238-L274
[ "def deserialize(self, value, **kwargs):\n \"\"\"Deserialization of value.\n\n :return: Deserialized value.\n :raises: :class:`halogen.exception.ValidationError` exception if value is not valid.\n \"\"\"\n for validator in self.validators:\n validator.validate(value, **kwargs)\n\n return va...
class Amount(Type): """Amount (money) schema type.""" err_unknown_currency = u"'{currency}' is not a valid currency." def __init__(self, currencies, amount_class, **kwargs): """Initialize new instance of Amount. :param currencies: list of all possible currency codes. :param amount...
paylogic/halogen
halogen/validators.py
Length.validate
python
def validate(self, value): try: length = len(value) except TypeError: length = 0 if self.min_length is not None: min_length = self.min_length() if callable(self.min_length) else self.min_length if length < min_length: raise excepti...
Validate the length of a list. :param value: List of values. :raises: :class:`halogen.exception.ValidationError` exception when length of the list is less than minimum or greater than maximum.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/validators.py#L92-L113
null
class Length(Validator): """Length validator that checks the length of a List-like type.""" min_err = "Length is less than {0}" max_err = "Length is greater than {0}" def __init__(self, min_length=None, max_length=None, min_err=None, max_err=None): """Length validator constructor. :p...
paylogic/halogen
halogen/validators.py
Range.validate
python
def validate(self, value): if self.min is not None: min_value = self.min() if callable(self.min) else self.min if value < min_value: raise exceptions.ValidationError(self.min_err.format(val=value, min=min_value)) if self.max is not None: max_value = s...
Validate value. :param value: Value which should be validated. :raises: :class:`halogen.exception.ValidationError` exception when either if value less than min in case when min is not None or if value greater than max in case when max is not None.
train
https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/validators.py#L143-L159
null
class Range(object): """Range validator. Validator which succeeds if the value it is passed is greater or equal to ``min`` and less than or equal to ``max``. If ``min`` is not specified, or is specified as ``None``, no lower bound exists. If ``max`` is not specified, or is specified as ``None``, no ...
visualfabriq/bquery
bquery/benchmarks/bench_groupby.py
ctime
python
def ctime(message=None): "Counts the time spent in some context" global t_elapsed t_elapsed = 0.0 print('\n') t = time.time() yield if message: print(message + ": ", end='') t_elapsed = time.time() - t print(round(t_elapsed, 4), "sec")
Counts the time spent in some context
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/benchmarks/bench_groupby.py#L29-L39
null
from __future__ import print_function # bench related imports import numpy as np import shutil import bquery import pandas as pd import itertools as itt import cytoolz import cytoolz.dicttoolz from toolz import valmap, compose from cytoolz.curried import pluck import blaze as blz # other imports import contextlib impor...
visualfabriq/bquery
bquery/ctable.py
rm_file_or_dir
python
def rm_file_or_dir(path, ignore_errors=True): if os.path.exists(path): if os.path.isdir(path): if os.path.islink(path): os.unlink(path) else: shutil.rmtree(path, ignore_errors=ignore_errors) else: if os.path.islink(path): ...
Helper function to clean a certain filepath Parameters ---------- path Returns -------
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L12-L34
null
import os import shutil import tempfile import uuid import bcolz import numpy as np from bquery import ctable_ext class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cach...
visualfabriq/bquery
bquery/ctable.py
ctable.cache_valid
python
def cache_valid(self, col): cache_valid = False if self.rootdir: col_org_file_check = self[col].rootdir + '/__attrs__' col_values_file_check = self[col].rootdir + '.values/__attrs__' cache_valid = os.path.exists(col_org_file_check) and os.path.exists(col_values_file_...
Checks whether the column has a factorization that exists and is not older than the source :param col: :return:
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L60-L74
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.group_cache_valid
python
def group_cache_valid(self, col_list): cache_valid = False if self.rootdir: col_values_file_check = os.path.join(self.rootdir, self.create_group_base_name(col_list)) + \ '.values/__attrs__' exists_group_index = os.path.exists(col_values_file_...
Checks whether the column has a factorization that exists and is not older than the source :param col: :return:
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L76-L93
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.cache_factor
python
def cache_factor(self, col_list, refresh=False): if not self.rootdir: raise TypeError('Only out-of-core ctables can have ' 'factorization caching at the moment') if not isinstance(col_list, list): col_list = [col_list] if refresh: ...
Existing todos here are: these should be hidden helper carrays As in: not normal columns that you would normally see as a user The factor (label index) carray is as long as the original carray (and the rest of the table therefore) But the (unique) values carray is not as long (as long a...
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L95-L152
[ "def rm_file_or_dir(path, ignore_errors=True):\n \"\"\"\n Helper function to clean a certain filepath\n\n Parameters\n ----------\n path\n\n Returns\n -------\n\n \"\"\"\n if os.path.exists(path):\n if os.path.isdir(path):\n if os.path.islink(path):\n os.u...
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.unique
python
def unique(self, col_or_col_list): if isinstance(col_or_col_list, list): col_is_list = True col_list = col_or_col_list else: col_is_list = False col_list = [col_or_col_list] output = [] for col in col_list: if self.auto_cach...
Return a list of unique values of a column or a list of lists of column list :param col_or_col_list: a column or a list of columns :return:
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L154-L192
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.aggregate_groups
python
def aggregate_groups(self, ct_agg, nr_groups, skip_key, carray_factor, groupby_cols, agg_ops, dtype_dict, bool_arr=None): '''Perform aggregation and place the result in the given ctable. Args: ct_agg (ctable): the table to hold the aggregati...
Perform aggregation and place the result in the given ctable. Args: ct_agg (ctable): the table to hold the aggregation nr_groups (int): the number of groups (number of rows in output table) skip_key (int): index of the output row to remove from results (used for filtering) ...
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L194-L260
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.factorize_groupby_cols
python
def factorize_groupby_cols(self, groupby_cols): # first check if the factorized arrays already exist # unless we need to refresh the cache factor_list = [] values_list = [] # factorize the groupby columns for col in groupby_cols: if self.auto_cache or self.c...
factorizes all columns that are used in the groupby it will use cache carrays if available if not yet auto_cache is valid, it will create cache carrays
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L318-L353
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable._int_array_hash
python
def _int_array_hash(input_list): list_len = len(input_list) arr_len = len(input_list[0]) mult_arr = np.full(arr_len, 1000003, dtype=np.long) value_arr = np.full(arr_len, 0x345678, dtype=np.long) for i, current_arr in enumerate(input_list): index = list_len - i - 1 ...
A function to calculate a hash value of multiple integer values, not used at the moment Parameters ---------- input_list Returns -------
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L356-L383
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.create_group_column_factor
python
def create_group_column_factor(self, factor_list, groupby_cols, cache=False): if not self.rootdir: # in-memory scenario input_rootdir = None col_rootdir = None col_factor_rootdir = None col_values_rootdir = None col_factor_rootdir_tmp = Non...
Create a unique, factorized column out of several individual columns Parameters ---------- factor_list groupby_cols cache Returns -------
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L385-L472
[ "def rm_file_or_dir(path, ignore_errors=True):\n \"\"\"\n Helper function to clean a certain filepath\n\n Parameters\n ----------\n path\n\n Returns\n -------\n\n \"\"\"\n if os.path.exists(path):\n if os.path.isdir(path):\n if os.path.islink(path):\n os.u...
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.make_group_index
python
def make_group_index(self, groupby_cols, bool_arr): '''Create unique groups for groupby loop Args: factor_list: values_list: groupby_cols: bool_arr: Returns: carray: (carray_factor) int: (nr...
Create unique groups for groupby loop Args: factor_list: values_list: groupby_cols: bool_arr: Returns: carray: (carray_factor) int: (nr_groups) the number of resulting groups int: (s...
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L474-L547
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.create_tmp_rootdir
python
def create_tmp_rootdir(self): if self.rootdir: tmp_rootdir = tempfile.mkdtemp(prefix='bcolz-') self._dir_clean_list.append(tmp_rootdir) else: tmp_rootdir = None return tmp_rootdir
create a rootdir that we can destroy later again Returns -------
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L549-L562
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.clean_tmp_rootdir
python
def clean_tmp_rootdir(self): for tmp_rootdir in list(self._dir_clean_list): rm_file_or_dir(tmp_rootdir) self._dir_clean_list.remove(tmp_rootdir)
clean up all used temporary rootdirs Returns -------
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L564-L574
[ "def rm_file_or_dir(path, ignore_errors=True):\n \"\"\"\n Helper function to clean a certain filepath\n\n Parameters\n ----------\n path\n\n Returns\n -------\n\n \"\"\"\n if os.path.exists(path):\n if os.path.isdir(path):\n if os.path.islink(path):\n os.u...
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.create_agg_ctable
python
def create_agg_ctable(self, groupby_cols, agg_list, expectedlen, rootdir): '''Create a container for the output table, a dictionary describing it's columns and a list of tuples describing aggregation operations to perform. Args: groupby_cols (list): a list of columns...
Create a container for the output table, a dictionary describing it's columns and a list of tuples describing aggregation operations to perform. Args: groupby_cols (list): a list of columns to groupby over agg_list (list): the aggregation operations (see groupby ...
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L576-L654
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.where_terms
python
def where_terms(self, term_list, cache=False): if type(term_list) not in [list, set, tuple]: raise ValueError("Only term lists are supported") col_list = [] op_list = [] value_list = [] for term in term_list: # get terms filter_col = term[0]...
Create a boolean array where `term_list` is true. A terms list has a [(col, operator, value), ..] construction. Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])] :param term_list: :param outcols: :param limit: :param skip: :return: :raise ValueError:
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L656-L740
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.where_terms_factorization_check
python
def where_terms_factorization_check(self, term_list): if type(term_list) not in [list, set, tuple]: raise ValueError("Only term lists are supported") valid = True for term in term_list: # get terms filter_col = term[0] filter_operator = term[1]....
check for where terms if they are applicable Create a boolean array where `term_list` is true. A terms list has a [(col, operator, value), ..] construction. Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])] :param term_list: :param outcols: :param limit: :pa...
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L742-L819
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/ctable.py
ctable.is_in_ordered_subgroups
python
def is_in_ordered_subgroups(self, basket_col=None, bool_arr=None, _max_len_subgroup=1000): assert basket_col is not None if bool_arr is None: return None if self.auto_cache and bool_arr.rootdir is not None: rootdir = self.create_tmp_rootd...
Expands the filter using a specified column Parameters ---------- basket_col bool_arr _max_len_subgroup Returns -------
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L821-L849
null
class ctable(bcolz.ctable): def __init__(self, *args, **kwargs): super(ctable, self).__init__(*args, **kwargs) # check autocaching if self.rootdir and kwargs.get('auto_cache') is True: # explicit auto_cache self.auto_cache = True elif self.rootdir and kwargs....
visualfabriq/bquery
bquery/toplevel.py
open
python
def open(rootdir, mode='a'): # ---------------------------------------------------------------------- # https://github.com/Blosc/bcolz/blob/master/bcolz/toplevel.py#L104-L132 # ---------------------------------------------------------------------- # First try with a carray rootsfile = os.path.join(r...
open(rootdir, mode='a') Open a disk-based carray/ctable. This function could be used to open bcolz objects as bquery objects to perform queries on them. Parameters ---------- rootdir : pathname (string) The directory hosting the carray/ctable object. mode : the open mode (string) ...
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/toplevel.py#L8-L41
null
import os from bcolz.ctable import ROOTDIRS import bquery
visualfabriq/bquery
bquery/benchmarks/bench_pos.py
ctime
python
def ctime(message=None): "Counts the time spent in some context" t = time.time() yield if message: print message + ":\t", print round(time.time() - t, 4), "sec"
Counts the time spent in some context
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/benchmarks/bench_pos.py#L14-L20
null
from contextlib import contextmanager import tempfile import os import random import shutil import time import bcolz as bz import bquery as bq @contextmanager @contextmanager def on_disk_data_cleaner(generator): rootdir = tempfile.mkdtemp(prefix='bcolz-') os.rmdir(rootdir) # folder should be emtpy c...
openregister/openregister-python
openregister/entry.py
Entry.timestamp
python
def timestamp(self, timestamp): if timestamp is None: self._timestamp = datetime.utcnow() elif isinstance(timestamp, datetime): self._timestamp = timestamp else: self._timestamp = datetime.strptime(timestamp, fmt)
Entry timestamp as datetime.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L27-L34
null
class Entry(object): """An Entry, an ordered instance of an item in a register.""" fields = ['entry-number', 'item-hash', 'timestamp'] def __init__(self, entry_number=None, item_hash=None, timestamp=None): if not (entry_number is None or isinstance(entry_number, numbers.Integral)):...
openregister/openregister-python
openregister/entry.py
Entry.primitive
python
def primitive(self): primitive = {} if self.entry_number is not None: primitive['entry-number'] = self.entry_number if self.item_hash is not None: primitive['item-hash'] = self.item_hash primitive['timestamp'] = self.timestamp.strftime(fmt) return primit...
Entry as Python primitive.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L37-L47
null
class Entry(object): """An Entry, an ordered instance of an item in a register.""" fields = ['entry-number', 'item-hash', 'timestamp'] def __init__(self, entry_number=None, item_hash=None, timestamp=None): if not (entry_number is None or isinstance(entry_number, numbers.Integral)):...
openregister/openregister-python
openregister/entry.py
Entry.primitive
python
def primitive(self, primitive): self.entry_number = primitive['entry-number'] self.item_hash = primitive['item-hash'] self.timestamp = primitive['timestamp']
Entry from Python primitive.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L50-L54
null
class Entry(object): """An Entry, an ordered instance of an item in a register.""" fields = ['entry-number', 'item-hash', 'timestamp'] def __init__(self, entry_number=None, item_hash=None, timestamp=None): if not (entry_number is None or isinstance(entry_number, numbers.Integral)):...
openregister/openregister-python
openregister/client.py
Client.config
python
def config(self, name, suffix): "Return config variable value, defaulting to environment" var = '%s_%s' % (name, suffix) var = var.upper().replace('-', '_') if var in self._config: return self._config[var] return os.environ[var]
Return config variable value, defaulting to environment
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/client.py#L16-L22
null
class Client(object): """ Access register items from an openregister server. """ def __init__(self, logger=None, config={}): self.logger = logger self._config = config def get(self, url, params=None): response = requests.get(url, params=params) if self.logger: ...
openregister/openregister-python
openregister/client.py
Client.index
python
def index(self, index, field, value): "Search for records matching a value in an index service" params = { "q": value, # search index has '_' instead of '-' in field names .. "q.options": "{fields:['%s']}" % (field.replace('-', '_')) } response = self...
Search for records matching a value in an index service
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/client.py#L41-L56
[ "def config(self, name, suffix):\n \"Return config variable value, defaulting to environment\"\n var = '%s_%s' % (name, suffix)\n var = var.upper().replace('-', '_')\n if var in self._config:\n return self._config[var]\n return os.environ[var]\n", "def get(self, url, params=None):\n respo...
class Client(object): """ Access register items from an openregister server. """ def __init__(self, logger=None, config={}): self.logger = logger self._config = config def config(self, name, suffix): "Return config variable value, defaulting to environment" var = '...
openregister/openregister-python
openregister/item.py
Item.primitive
python
def primitive(self): dict = {} for key, value in self.__dict__.items(): if not key.startswith('_'): dict[key] = copy(value) for key in dict: if isinstance(dict[key], (set)): dict[key] = sorted(list(dict[key])) return dict
Python primitive representation.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/item.py#L49-L60
null
class Item(object): """An Item, a content addressable set of attributes.""" def __init__(self, **kwds): self.__dict__.update(kwds) def __getitem__(self, key, default=None): try: return self.__dict__[key] except KeyError: return default def __setitem__(se...
openregister/openregister-python
openregister/item.py
Item.primitive
python
def primitive(self, dictionary): self.__dict__ = {k: v for k, v in dictionary.items() if v}
Item from Python primitive.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/item.py#L63-L65
null
class Item(object): """An Item, a content addressable set of attributes.""" def __init__(self, **kwds): self.__dict__.update(kwds) def __getitem__(self, key, default=None): try: return self.__dict__[key] except KeyError: return default def __setitem__(se...
openregister/openregister-python
openregister/record.py
Record.primitive
python
def primitive(self): primitive = copy(self.item.primitive) primitive.update(self.entry.primitive) return primitive
Record as Python primitive.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/record.py#L19-L23
null
class Record(object): """ A Record, the tuple of an entry and it's item Records are useful for representing the latest entry for a field value. Records are serialised as the merged entry and item """ def __init__(self, entry=None, item=None): self.entry = entry self.item = i...
openregister/openregister-python
openregister/record.py
Record.primitive
python
def primitive(self, primitive): self.entry = Entry() self.entry.primitive = primitive primitive = copy(primitive) for field in self.entry.fields: del primitive[field] self.item = Item() self.item.primitive = primitive
Record from Python primitive.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/record.py#L26-L36
null
class Record(object): """ A Record, the tuple of an entry and it's item Records are useful for representing the latest entry for a field value. Records are serialised as the merged entry and item """ def __init__(self, entry=None, item=None): self.entry = entry self.item = i...
openregister/openregister-python
openregister/representations/tsv.py
load
python
def load(self, text, fieldnames=None): lines = text.split('\n') fieldnames = load_line(lines[0]) values = load_line(lines[1]) self.__dict__ = dict(zip(fieldnames, values))
Item from TSV representation.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L43-L48
[ "def load_line(line):\n return [unescape(s) for s in line.rstrip('\\n').split('\\t')]\n" ]
from ..item import Item from ..writer import Writer content_type = 'text/tab-separated-values; charset=utf-8' escaped_chars = [('\t', '\\t'), ('\n', '\\n'), ('\r', '\\r'), ('', '\\')] def BadBackslash(): pass def escape(value): for a, b in escaped_chars: if a: value = value.replace(a, ...
openregister/openregister-python
openregister/representations/tsv.py
reader
python
def reader(stream, fieldnames=None): if not fieldnames: fieldnames = load_line(stream.readline()) for line in stream: values = load_line(line) item = Item() item.__dict__ = dict(zip(fieldnames, values)) yield item
Read Items from a stream containing TSV.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L51-L59
[ "def load_line(line):\n return [unescape(s) for s in line.rstrip('\\n').split('\\t')]\n" ]
from ..item import Item from ..writer import Writer content_type = 'text/tab-separated-values; charset=utf-8' escaped_chars = [('\t', '\\t'), ('\n', '\\n'), ('\r', '\\r'), ('', '\\')] def BadBackslash(): pass def escape(value): for a, b in escaped_chars: if a: value = value.replace(a, ...
openregister/openregister-python
openregister/representations/tsv.py
dump
python
def dump(self): dict = self.primitive if not dict: return '' return dump_line(self.keys) + dump_line(self.values)
TSV representation.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L66-L71
[ "def dump_line(values):\n return ('\\t'.join(escape(encode(value)) for value in values)) + '\\n'\n" ]
from ..item import Item from ..writer import Writer content_type = 'text/tab-separated-values; charset=utf-8' escaped_chars = [('\t', '\\t'), ('\n', '\\n'), ('\r', '\\r'), ('', '\\')] def BadBackslash(): pass def escape(value): for a, b in escaped_chars: if a: value = value.replace(a, ...
openregister/openregister-python
openregister/representations/csv.py
load
python
def load(self, text, lineterminator='\r\n', quotechar='"', delimiter=",", escapechar=escapechar, quoting=csv.QUOTE_MINIMAL): f = io.StringIO(text) if not quotechar: quoting = csv.QUOTE_NONE reader = csv.DictReader( f, delimiter=delimite...
Item from CSV representation.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/csv.py#L14-L40
null
import io import csv from ..item import Item from ..writer import Writer content_type = 'text/csv; charset=utf-8' escapechar = '\\' lineterminator = '\r\n' quotechar = '"' delimiter = "," class Writer(Writer): """Write CSV of items.""" def __init__(self, stream, fieldnames, delimiter=delim...
openregister/openregister-python
openregister/representations/csv.py
dump
python
def dump(self, **kwargs): f = io.StringIO() w = Writer(f, self.keys, **kwargs) w.write(self) text = f.getvalue().lstrip() f.close() return text
CSV representation of a item.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/csv.py#L70-L79
[ "def write(self, item):\n self.writer.writerow(item.primitive)\n" ]
import io import csv from ..item import Item from ..writer import Writer content_type = 'text/csv; charset=utf-8' escapechar = '\\' lineterminator = '\r\n' quotechar = '"' delimiter = "," def load(self, text, lineterminator='\r\n', quotechar='"', delimiter=",", escapechar=escapec...
openregister/openregister-python
openregister/datatypes/digest.py
git_hash
python
def git_hash(blob): head = str("blob " + str(len(blob)) + "\0").encode("utf-8") return sha1(head + blob).hexdigest()
Return git-hash compatible SHA-1 hexdigits for a blob of data.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/datatypes/digest.py#L5-L8
null
from hashlib import sha1 from base64 import b32encode def base32_encode(hexdigest): """Return SHA-1 hexdigits as lower-case RFC 3548 base 32 encoding.""" return b32encode(bytes.fromhex(hexdigest)).decode('utf-8').lower()
openregister/openregister-python
openregister/representations/json.py
dump
python
def dump(self): return json.dumps( self.primitive, sort_keys=True, ensure_ascii=False, separators=(',', ':'))
Item as a JSON representation.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/json.py#L17-L23
null
from ..item import Item from ..writer import Writer import json import re START = re.compile('[ \t\n\r\[]*', re.VERBOSE | re.MULTILINE | re.DOTALL) END = re.compile('[ \t\n\r,\]]*', re.VERBOSE | re.MULTILINE | re.DOTALL) content_type = 'application/json' def load(self, text): """Item from a JSON representation....
openregister/openregister-python
openregister/representations/json.py
reader
python
def reader(stream): string = stream.read() decoder = json.JSONDecoder().raw_decode index = START.match(string, 0).end() while index < len(string): obj, end = decoder(string, index) item = Item() item.primitive = obj yield item index = END.match(string, end).end()
Read Items from a stream containing a JSON array.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/json.py#L26-L37
null
from ..item import Item from ..writer import Writer import json import re START = re.compile('[ \t\n\r\[]*', re.VERBOSE | re.MULTILINE | re.DOTALL) END = re.compile('[ \t\n\r,\]]*', re.VERBOSE | re.MULTILINE | re.DOTALL) content_type = 'application/json' def load(self, text): """Item from a JSON representation....
openregister/openregister-python
openregister/representations/jsonl.py
reader
python
def reader(stream): for line in stream: item = Item() item.json = line yield item
Read Items from a stream containing lines of JSON.
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/jsonl.py#L8-L13
null
from ..item import Item from .json import load, dump, Writer content_type = 'application/json-l' class Writer(Writer): """Write items to a JSON log stream""" def __init__(self, stream, start="", sep="", eol="\n", end=""): super().__init__(stream, start, sep, eol, end) Item.jsonl = property(dump, ...
openregister/openregister-python
openregister/store.py
Store.meta
python
def meta(self, total, page=1, page_size=None): if page_size is None or page_size < 0: page_size = self.page_size meta = {} meta['total'] = total meta['page_size'] = page_size meta['pages'] = math.ceil(meta['total']/page_size) meta['page'] = page meta[...
Calculate statistics for a collection return: meta
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/store.py#L12-L26
null
class Store(object): page_size = 10000 """Interface for storage of Items.""" def __init__(self): pass def put(self, item): """ Store item returns: item """ raise NotImplementedError def add(self, item, timestamp=None): """ Add item...
ARMmbed/autoversion
src/auto_version/semver.py
get_current_semver
python
def get_current_semver(data): # get the not-none values from data known = { key: data.get(alias) for key, alias in config._forward_aliases.items() if data.get(alias) is not None } # prefer the strict field, if available potentials = [ known.pop(Constants.VERSION_STRI...
Given a dictionary of all version data available, determine the current version
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/semver.py#L15-L50
null
"""Functions for manipulating SemVer objects (Major.Minor.Patch)""" import logging import re from auto_version.config import AutoVersionConfig as config from auto_version.config import Constants from auto_version.definitions import SemVer from auto_version.definitions import SemVerSigFig _LOG = logging.getLogger(__fi...
ARMmbed/autoversion
src/auto_version/semver.py
make_new_semver
python
def make_new_semver(current_semver, all_triggers, **overrides): new_semver = {} bumped = False for sig_fig in SemVerSigFig: # iterate sig figs in order of significance value = getattr(current_semver, sig_fig) override = overrides.get(sig_fig) if override is not None: new...
Defines how to increment semver based on which significant figure is triggered
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/semver.py#L53-L71
null
"""Functions for manipulating SemVer objects (Major.Minor.Patch)""" import logging import re from auto_version.config import AutoVersionConfig as config from auto_version.config import Constants from auto_version.definitions import SemVer from auto_version.definitions import SemVerSigFig _LOG = logging.getLogger(__fi...
ARMmbed/autoversion
scripts/tag_and_release.py
main
python
def main(): # see: # https://packaging.python.org/tutorials/distributing-packages/#uploading-your-project-to-pypi twine_repo = os.getenv('TWINE_REPOSITORY_URL') or os.getenv('TWINE_REPOSITORY') print('tagging and releasing to %s as %s' % ( twine_repo, os.getenv('TWINE_USERNAME') )) ...
Tags the current repository and commits changes to news files
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/scripts/tag_and_release.py#L39-L86
null
# -------------------------------------------------------------------------- # Autoversion # (C) COPYRIGHT 2018 Arm Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apa...
ARMmbed/autoversion
src/auto_version/config.py
get_or_create_config
python
def get_or_create_config(path, config): if os.path.isfile(path): with open(path) as fh: _LOG.debug("loading config from %s", os.path.abspath(path)) config._inflate(toml.load(fh)) else: try: os.makedirs(os.path.dirname(path)) except OSError: ...
Using TOML format, load config from given path, or write out example based on defaults
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/config.py#L81-L93
[ "def _deflate(cls):\n \"\"\"Prepare for serialisation - returns a dictionary\"\"\"\n data = {k: v for k, v in vars(cls).items() if not k.startswith(\"_\")}\n return {Constants.CONFIG_KEY: data}\n", "def _inflate(cls, data):\n \"\"\"Update config by deserialising input dictionary\"\"\"\n for k, v in...
"""Configuration system for the auto_version tool""" import logging import os import toml from auto_version.definitions import SemVerSigFig _LOG = logging.getLogger(__name__) class Constants(object): """Internal - reused strings""" # regex groups KEY_GROUP = "KEY" VALUE_GROUP = "VALUE" # inte...
ARMmbed/autoversion
src/auto_version/config.py
AutoVersionConfig._deflate
python
def _deflate(cls): data = {k: v for k, v in vars(cls).items() if not k.startswith("_")} return {Constants.CONFIG_KEY: data}
Prepare for serialisation - returns a dictionary
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/config.py#L68-L71
null
class AutoVersionConfig(object): """Configuration - can be overridden using a toml config file""" CONFIG_NAME = "DEFAULT" RELEASED_VALUE = True VERSION_LOCK_VALUE = True VERSION_UNLOCK_VALUE = False key_aliases = { "__version__": Constants.VERSION_FIELD, "__strict_version__": Co...
ARMmbed/autoversion
src/auto_version/config.py
AutoVersionConfig._inflate
python
def _inflate(cls, data): for k, v in data[Constants.CONFIG_KEY].items(): setattr(cls, k, v) return cls._deflate()
Update config by deserialising input dictionary
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/config.py#L74-L78
null
class AutoVersionConfig(object): """Configuration - can be overridden using a toml config file""" CONFIG_NAME = "DEFAULT" RELEASED_VALUE = True VERSION_LOCK_VALUE = True VERSION_UNLOCK_VALUE = False key_aliases = { "__version__": Constants.VERSION_FIELD, "__strict_version__": Co...
ARMmbed/autoversion
src/auto_version/cli.py
get_cli
python
def get_cli(): parser = argparse.ArgumentParser( prog="auto_version", description="auto version v%s: a tool to control version numbers" % __version__, ) parser.add_argument( "--target", action="append", default=[], help="Files containing version info. " ...
Load cli options
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/cli.py#L9-L71
null
"""Load cli options""" import argparse from auto_version.config import AutoVersionConfig as config from auto_version.definitions import SemVerSigFig from auto_version import __version__
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
replace_lines
python
def replace_lines(regexer, handler, lines): result = [] for line in lines: content = line.strip() replaced = regexer.sub(handler, content) result.append(line.replace(content, replaced, 1)) return result
Uses replacement handler to perform replacements on lines of text First we strip off all whitespace We run the replacement on a clean 'content' string Finally we replace the original content with the replaced version This ensures that we retain the correct whitespace from the original line
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L37-L50
null
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
write_targets
python
def write_targets(targets, **params): handler = ReplacementHandler(**params) for target, regexer in regexer_for_targets(targets): with open(target) as fh: lines = fh.readlines() lines = replace_lines(regexer, handler, lines) with open(target, "w") as fh: fh.writel...
Writes version info into version file
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L53-L65
[ "def replace_lines(regexer, handler, lines):\n \"\"\"Uses replacement handler to perform replacements on lines of text\n\n First we strip off all whitespace\n We run the replacement on a clean 'content' string\n Finally we replace the original content with the replaced version\n This ensures that we ...
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
regexer_for_targets
python
def regexer_for_targets(targets): for target in targets: path, file_ext = os.path.splitext(target) regexer = config.regexers[file_ext] yield target, regexer
Pairs up target files with their correct regex
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L68-L73
null
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
extract_keypairs
python
def extract_keypairs(lines, regexer): updates = {} for line in lines: # for consistency we must match the replacer and strip whitespace / newlines match = regexer.match(line.strip()) if not match: continue k_v = match.groupdict() updates[k_v[Constants.KEY_GROU...
Given some lines of text, extract key-value pairs from them
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L76-L86
null
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
read_targets
python
def read_targets(targets): results = {} for target, regexer in regexer_for_targets(targets): with open(target) as fh: results.update(extract_keypairs(fh.readlines(), regexer)) return results
Reads generic key-value pairs from input files
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L89-L95
[ "def regexer_for_targets(targets):\n \"\"\"Pairs up target files with their correct regex\"\"\"\n for target in targets:\n path, file_ext = os.path.splitext(target)\n regexer = config.regexers[file_ext]\n yield target, regexer\n", "def extract_keypairs(lines, regexer):\n \"\"\"Given ...
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
detect_file_triggers
python
def detect_file_triggers(trigger_patterns): triggers = set() for trigger, pattern in trigger_patterns.items(): matches = glob.glob(pattern) if matches: _LOG.debug("trigger: %s bump from %r\n\t%s", trigger, pattern, matches) triggers.add(trigger) else: ...
The existence of files matching configured globs will trigger a version bump
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L98-L108
null
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
get_all_triggers
python
def get_all_triggers(bump, file_triggers): triggers = set() if file_triggers: triggers = triggers.union(detect_file_triggers(config.trigger_patterns)) if bump: _LOG.debug("trigger: %s bump requested", bump) triggers.add(bump) return triggers
Aggregated set of significant figures to bump
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L111-L119
[ "def detect_file_triggers(trigger_patterns):\n \"\"\"The existence of files matching configured globs will trigger a version bump\"\"\"\n triggers = set()\n for trigger, pattern in trigger_patterns.items():\n matches = glob.glob(pattern)\n if matches:\n _LOG.debug(\"trigger: %s bum...
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
get_lock_behaviour
python
def get_lock_behaviour(triggers, all_data, lock): updates = {} lock_key = config._forward_aliases.get(Constants.VERSION_LOCK_FIELD) # if we are explicitly setting or locking the version, then set the lock field True anyway if lock: updates[Constants.VERSION_LOCK_FIELD] = config.VERSION_LOCK_VALU...
Binary state lock protects from version increments if set
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L122-L136
null
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
get_final_version_string
python
def get_final_version_string(release_mode, semver, commit_count=0): version_string = ".".join(semver) maybe_dev_version_string = version_string updates = {} if release_mode: # in production, we have something like `1.2.3`, as well as a flag e.g. PRODUCTION=True updates[Constants.RELEASE_...
Generates update dictionary entries for the version string
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L139-L156
null
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
get_dvcs_info
python
def get_dvcs_info(): cmd = "git rev-list --count HEAD" commit_count = str( int(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip()) ) cmd = "git rev-parse HEAD" commit = str(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip()) return {Constants.COMMIT_FIELD: com...
Gets current repository info from git
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L159-L167
null
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
main
python
def main( set_to=None, set_patch_count=None, release=None, bump=None, lock=None, file_triggers=None, config_path=None, **extra_updates ): updates = {} if config_path: get_or_create_config(config_path, config) for k, v in config.regexers.items(): config.regex...
Main workflow. Load config from cli and file Detect "bump triggers" - things that cause a version increment Find the current version Create a new version Write out new version and any other requested variables :param set_to: explicitly set semver to this version string :param set_patch_cou...
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L170-L266
[ "def get_or_create_config(path, config):\n \"\"\"Using TOML format, load config from given path, or write out example based on defaults\"\"\"\n if os.path.isfile(path):\n with open(path) as fh:\n _LOG.debug(\"loading config from %s\", os.path.abspath(path))\n config._inflate(toml....
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
main_from_cli
python
def main_from_cli(): args, others = get_cli() if args.version: print(__version__) exit(0) log_level = logging.WARNING - 10 * args.verbosity logging.basicConfig(level=log_level, format="%(module)s %(levelname)8s %(message)s") command_line_updates = parse_other_args(others) old...
Main workflow. Load config from cli and file Detect "bump triggers" - things that cause a version increment Find the current version Create a new version Write out new version and any other requested variables
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L284-L320
[ "def main(\n set_to=None,\n set_patch_count=None,\n release=None,\n bump=None,\n lock=None,\n file_triggers=None,\n config_path=None,\n **extra_updates\n):\n \"\"\"Main workflow.\n\n Load config from cli and file\n Detect \"bump triggers\" - things that cause a version increment\n ...
"""Generates DVCS version information see also: https://git-scm.com/docs/git-shortlog https://www.python.org/dev/peps/pep-0440/ https://pypi.python.org/pypi/semver https://pypi.python.org/pypi/bumpversion https://github.com/warner/python-versioneer https://pypi.org/project/autoversion/ https://pypi.org/project/auto-ve...
contentful-labs/contentful.py
contentful/cda/resources.py
Array.resolve_links
python
def resolve_links(self): for resource in self.items_mapped['Entry'].values(): for dct in [getattr(resource, '_cf_cda', {}), resource.fields]: for k, v in dct.items(): if isinstance(v, ResourceLink): resolved = self._resolve_resource_link(v)...
Attempt to resolve all internal links (locally). In case the linked resources are found either as members of the array or within the `includes` element, those will be replaced and reference the actual resources. No network calls will be performed.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/resources.py#L90-L111
[ "def _resolve_resource_link(self, link):\n return self.items_mapped[link.link_type].get(link.resource_id)\n" ]
class Array(Resource): """Collection of multiple :class:`.Resource` instances. **Attributes**: - limit (int): `limit` parameter. - skip (int): `skip` parameter. - total (int): Total number of resources returned from the API. - items (list): Resources contained within the response. - items_...
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.from_json
python
def from_json(self, json): res_type = json['sys']['type'] if ResourceType.Array.value == res_type: return self.create_array(json) elif ResourceType.Entry.value == res_type: return self.create_entry(json) elif ResourceType.Asset.value == res_type: retu...
Create resource out of JSON data. :param json: JSON dict. :return: Resource with a type defined by the given JSON data.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L34-L51
[ "def create_entry(self, json):\n \"\"\"Create :class:`.resources.Entry` from JSON.\n\n :param json: JSON dict.\n :return: Entry instance.\n \"\"\"\n sys = json['sys']\n ct = sys['contentType']['sys']['id']\n fields = json['fields']\n raw_fields = copy.deepcopy(fields)\n\n # Replace links ...
class ResourceFactory(object): """Factory for generating :class:`.resources.Resource` subclasses out of JSON data. Attributes: entries_mapping (dict): Mapping of Content Type IDs to custom Entry subclasses. """ def __init__(self, custom_entries): """ResourceFactory constructor. :...
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.create_entry
python
def create_entry(self, json): sys = json['sys'] ct = sys['contentType']['sys']['id'] fields = json['fields'] raw_fields = copy.deepcopy(fields) # Replace links with :class:`.resources.ResourceLink` objects. for k, v in fields.items(): link = ResourceFactory._...
Create :class:`.resources.Entry` from JSON. :param json: JSON dict. :return: Entry instance.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L64-L101
[ "def _extract_link(obj):\n if not isinstance(obj, dict):\n return None\n\n sys = obj.get('sys')\n if isinstance(sys, dict) and sys.get('type') == ResourceType.Link.value:\n return ResourceLink(sys)\n\n return None\n", "def convert_value(value, field):\n \"\"\"Given a :class:`.fields.F...
class ResourceFactory(object): """Factory for generating :class:`.resources.Resource` subclasses out of JSON data. Attributes: entries_mapping (dict): Mapping of Content Type IDs to custom Entry subclasses. """ def __init__(self, custom_entries): """ResourceFactory constructor. :...
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.create_asset
python
def create_asset(json): result = Asset(json['sys']) file_dict = json['fields']['file'] result.fields = json['fields'] result.url = file_dict['url'] result.mimeType = file_dict['contentType'] return result
Create :class:`.resources.Asset` from JSON. :param json: JSON dict. :return: Asset instance.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L104-L115
null
class ResourceFactory(object): """Factory for generating :class:`.resources.Resource` subclasses out of JSON data. Attributes: entries_mapping (dict): Mapping of Content Type IDs to custom Entry subclasses. """ def __init__(self, custom_entries): """ResourceFactory constructor. :...
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.create_content_type
python
def create_content_type(json): result = ContentType(json['sys']) for field in json['fields']: field_id = field['id'] del field['id'] result.fields[field_id] = field result.name = json['name'] result.display_field = json.get('displayField') r...
Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L118-L134
null
class ResourceFactory(object): """Factory for generating :class:`.resources.Resource` subclasses out of JSON data. Attributes: entries_mapping (dict): Mapping of Content Type IDs to custom Entry subclasses. """ def __init__(self, custom_entries): """ResourceFactory constructor. :...
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.convert_value
python
def convert_value(value, field): clz = field.field_type if clz is Boolean: if not isinstance(value, bool): return bool(value) elif clz is Date: if not isinstance(value, str): value = str(value) return parser.parse(value) ...
Given a :class:`.fields.Field` and a value, ensure that the value matches the given type, otherwise attempt to convert it. :param value: field value. :param field: :class:`.fields.Field` instance. :return: Result value.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L148-L186
null
class ResourceFactory(object): """Factory for generating :class:`.resources.Resource` subclasses out of JSON data. Attributes: entries_mapping (dict): Mapping of Content Type IDs to custom Entry subclasses. """ def __init__(self, custom_entries): """ResourceFactory constructor. :...
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.process_array_items
python
def process_array_items(self, array, json): for item in json['items']: key = None processed = self.from_json(item) if isinstance(processed, Asset): key = 'Asset' elif isinstance(processed, Entry): key = 'Entry' if key ...
Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L189-L209
[ "def from_json(self, json):\n \"\"\"Create resource out of JSON data.\n\n :param json: JSON dict.\n :return: Resource with a type defined by the given JSON data.\n \"\"\"\n res_type = json['sys']['type']\n\n if ResourceType.Array.value == res_type:\n return self.create_array(json)\n elif...
class ResourceFactory(object): """Factory for generating :class:`.resources.Resource` subclasses out of JSON data. Attributes: entries_mapping (dict): Mapping of Content Type IDs to custom Entry subclasses. """ def __init__(self, custom_entries): """ResourceFactory constructor. :...
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.process_array_includes
python
def process_array_includes(self, array, json): includes = json.get('includes') or {} for key in array.items_mapped.keys(): if key in includes: for resource in includes[key]: processed = self.from_json(resource) array.items_mapped[key][p...
Iterate through all `includes` and create a resource for every item. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L211-L224
[ "def from_json(self, json):\n \"\"\"Create resource out of JSON data.\n\n :param json: JSON dict.\n :return: Resource with a type defined by the given JSON data.\n \"\"\"\n res_type = json['sys']['type']\n\n if ResourceType.Array.value == res_type:\n return self.create_array(json)\n elif...
class ResourceFactory(object): """Factory for generating :class:`.resources.Resource` subclasses out of JSON data. Attributes: entries_mapping (dict): Mapping of Content Type IDs to custom Entry subclasses. """ def __init__(self, custom_entries): """ResourceFactory constructor. :...
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.create_array
python
def create_array(self, json): result = Array(json['sys']) result.total = json['total'] result.skip = json['skip'] result.limit = json['limit'] result.items = [] result.items_mapped = {'Asset': {}, 'Entry': {}} self.process_array_items(result, json) self.p...
Create :class:`.resources.Array` from JSON. :param json: JSON dict. :return: Array instance.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L226-L242
[ "def process_array_items(self, array, json):\n \"\"\"Iterate through all `items` and create a resource for each.\n\n In addition map the resources under the `items_mapped` by the resource id and type.\n\n :param array: Array resource.\n :param json: Raw JSON dictionary.\n \"\"\"\n for item in json...
class ResourceFactory(object): """Factory for generating :class:`.resources.Resource` subclasses out of JSON data. Attributes: entries_mapping (dict): Mapping of Content Type IDs to custom Entry subclasses. """ def __init__(self, custom_entries): """ResourceFactory constructor. :...
contentful-labs/contentful.py
contentful/cda/client.py
Client.validate_config
python
def validate_config(config): non_null_params = ['space_id', 'access_token'] for param in non_null_params: if getattr(config, param) is None: raise Exception('Configuration for \"{0}\" must not be empty.'.format(param)) for clazz in config.custom_entries: ...
Verify sanity for a :class:`.Config` instance. This will raise an exception in case conditions are not met, otherwise will complete silently. :param config: (:class:`.Config`) Configuration container.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L52-L70
null
class Client(object): """Interface for retrieving resources from the Contentful Delivery API. **Attributes**: - dispatcher (:class:`.Dispatcher`): Dispatcher for invoking requests. - config (:class:`.Config`): Configuration container. """ def __init__(self, space_id, access_token, custom_entri...
contentful-labs/contentful.py
contentful/cda/client.py
Client.fetch
python
def fetch(self, resource_class): if issubclass(resource_class, Entry): params = None content_type = getattr(resource_class, '__content_type__', None) if content_type is not None: params = {'content_type': resource_class.__content_type__} return Req...
Construct a :class:`.Request` for the given resource type. Provided an :class:`.Entry` subclass, the Content Type ID will be inferred and requested explicitly. Examples:: client.fetch(Asset) client.fetch(Entry) client.fetch(ContentType) client.fetch(Cus...
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L72-L100
[ "def path_for_class(clz):\n if issubclass(clz, Asset):\n return const.PATH_ASSETS\n elif issubclass(clz, ContentType):\n return const.PATH_CONTENT_TYPES\n elif issubclass(clz, Entry):\n return const.PATH_ENTRIES\n" ]
class Client(object): """Interface for retrieving resources from the Contentful Delivery API. **Attributes**: - dispatcher (:class:`.Dispatcher`): Dispatcher for invoking requests. - config (:class:`.Config`): Configuration container. """ def __init__(self, space_id, access_token, custom_entri...
contentful-labs/contentful.py
contentful/cda/client.py
Client.resolve
python
def resolve(self, link_resource_type, resource_id, array=None): result = None if array is not None: container = array.items_mapped.get(link_resource_type) result = container.get(resource_id) if result is None: clz = utils.class_for_type(link_resource_type) ...
Resolve a link to a CDA resource. Provided an `array` argument, attempt to retrieve the resource from the `mapped_items` section of that array (containing both included and regular resources), in case the resource cannot be found in the array (or if no `array` was provided) - attempt to fetch ...
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L109-L132
[ "def class_for_type(resource_type):\n if resource_type == ResourceType.Asset.value:\n return Asset\n elif resource_type == ResourceType.ContentType.value:\n return ContentType\n elif resource_type == ResourceType.Entry.value:\n return Entry\n elif resource_type == ResourceType.Space...
class Client(object): """Interface for retrieving resources from the Contentful Delivery API. **Attributes**: - dispatcher (:class:`.Dispatcher`): Dispatcher for invoking requests. - config (:class:`.Config`): Configuration container. """ def __init__(self, space_id, access_token, custom_entri...
contentful-labs/contentful.py
contentful/cda/client.py
Client.resolve_resource_link
python
def resolve_resource_link(self, resource_link, array=None): return self.resolve(resource_link.link_type, resource_link.resource_id, array)
Convenience method for resolving links given a :class:`.resources.ResourceLink` object. Extract link values and pass to the :func:`.resolve` method of this class. :param resource_link: (:class:`.ResourceLink`) instance. :param array: (:class:`.Array`) Optional array resource. :return: ...
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L134-L143
[ "def resolve(self, link_resource_type, resource_id, array=None):\n \"\"\"Resolve a link to a CDA resource.\n\n Provided an `array` argument, attempt to retrieve the resource from the `mapped_items`\n section of that array (containing both included and regular resources), in case the\n resource cannot be...
class Client(object): """Interface for retrieving resources from the Contentful Delivery API. **Attributes**: - dispatcher (:class:`.Dispatcher`): Dispatcher for invoking requests. - config (:class:`.Config`): Configuration container. """ def __init__(self, space_id, access_token, custom_entri...
contentful-labs/contentful.py
contentful/cda/client.py
Client.resolve_dict_link
python
def resolve_dict_link(self, dct, array=None): sys = dct.get('sys') return self.resolve(sys['linkType'], sys['id'], array) if sys is not None else None
Convenience method for resolving links given a dict object. Extract link values and pass to the :func:`.resolve` method of this class. :param dct: (dict) Dictionary with the link data. :param array: (:class:`.Array`) Optional array resource. :return: :class:`.Resource` subclass, `None`...
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L145-L155
[ "def resolve(self, link_resource_type, resource_id, array=None):\n \"\"\"Resolve a link to a CDA resource.\n\n Provided an `array` argument, attempt to retrieve the resource from the `mapped_items`\n section of that array (containing both included and regular resources), in case the\n resource cannot be...
class Client(object): """Interface for retrieving resources from the Contentful Delivery API. **Attributes**: - dispatcher (:class:`.Dispatcher`): Dispatcher for invoking requests. - config (:class:`.Config`): Configuration container. """ def __init__(self, space_id, access_token, custom_entri...
contentful-labs/contentful.py
contentful/cda/client.py
Dispatcher.invoke
python
def invoke(self, request): url = '{0}/{1}'.format(self.base_url, request.remote_path) r = self.httpclient.get(url, params=request.params, headers=self.get_headers()) if 200 <= r.status_code < 300: return self.resource_factory.from_json(r.json()) else: if r.status_...
Invoke the given :class:`.Request` instance using the associated :class:`.Dispatcher`. :param request: :class:`.Request` instance to invoke. :return: :class:`.Resource` subclass.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L209-L223
[ "def get_headers(self):\n \"\"\"Create and return a base set of headers to be carried with all requests.\n\n :return: dict containing header values.\n \"\"\"\n return {'Authorization': 'Bearer {0}'.format(self.config.access_token), 'User-Agent': self.user_agent}\n" ]
class Dispatcher(object): """Responsible for invoking :class:`.Request` instances and delegating result processing. **Attributes**: - config (:class:`.Config`): Configuration settings. - resource_factory (:class:`.ResourceFactory`): Factory to use for generating resources out of JSON responses. - ...
contentful-labs/contentful.py
contentful/cda/client.py
RequestArray.all
python
def all(self): result = self.invoke() if self.resolve_links: result.resolve_links() return result
Attempt to retrieve all available resources matching this request. :return: Result instance as returned by the :class:`.Dispatcher`.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L263-L272
[ "def invoke(self):\n \"\"\"Invoke :class:`.Request` instance using the associated :class:`.Dispatcher`.\n\n :return: Result instance as returned by the :class:`.Dispatcher`.\n \"\"\"\n return self.dispatcher.invoke(self)\n" ]
class RequestArray(Request): """Represents a single request for retrieving multiple resources from the API.""" def __init__(self, dispatcher, remote_path, resolve_links, params=None): super(RequestArray, self).__init__(dispatcher, remote_path, params) self.resolve_links = resolve_links de...
contentful-labs/contentful.py
contentful/cda/client.py
RequestArray.first
python
def first(self): self.params['limit'] = 1 result = self.all() return result.items[0] if result.total > 0 else None
Attempt to retrieve only the first resource matching this request. :return: Result instance, or `None` if there are no matching resources.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L274-L281
[ "def all(self):\n \"\"\"Attempt to retrieve all available resources matching this request.\n\n :return: Result instance as returned by the :class:`.Dispatcher`.\n \"\"\"\n result = self.invoke()\n if self.resolve_links:\n result.resolve_links()\n\n return result\n" ]
class RequestArray(Request): """Represents a single request for retrieving multiple resources from the API.""" def __init__(self, dispatcher, remote_path, resolve_links, params=None): super(RequestArray, self).__init__(dispatcher, remote_path, params) self.resolve_links = resolve_links def...
contentful-labs/contentful.py
contentful/cda/client.py
RequestArray.where
python
def where(self, params): self.params = dict(self.params, **params) # params overrides self.params return self
Set a dict of parameters to be passed to the API when invoking this request. :param params: (dict) query parameters. :return: this :class:`.RequestArray` instance for convenience.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/client.py#L283-L290
null
class RequestArray(Request): """Represents a single request for retrieving multiple resources from the API.""" def __init__(self, dispatcher, remote_path, resolve_links, params=None): super(RequestArray, self).__init__(dispatcher, remote_path, params) self.resolve_links = resolve_links def...
contentful-labs/contentful.py
contentful/cda/errors.py
api_exception
python
def api_exception(http_code): def wrapper(*args): code = args[0] ErrorMapping.mapping[http_code] = code return code return wrapper
Convenience decorator to associate HTTP status codes with :class:`.ApiError` subclasses. :param http_code: (int) HTTP status code. :return: wrapper function.
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/errors.py#L23-L33
null
"""errors module.""" class ErrorMapping(object): """Holds a mapping of HTTP status codes and :class:`.ApiError` subclasses.""" mapping = {} class ApiError(Exception): """Class representing an error returned by the API.""" def __init__(self, result, message=None): """ApiError constructor. ...
shmir/PyTrafficGenerator
trafficgenerator/tgn_utils.py
new_log_file
python
def new_log_file(logger, suffix, file_type='tcl'): file_handler = None for handler in logger.handlers: if isinstance(handler, logging.FileHandler): file_handler = handler new_logger = logging.getLogger(file_type + suffix) if file_handler: logger_file_name = path.splitext(fil...
Create new logger and log file from existing logger. The new logger will be create in the same directory as the existing logger file and will be named as the existing log file with the requested suffix. :param logger: existing logger :param suffix: string to add to the existing log file name to create...
train
https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_utils.py#L81-L104
null
""" TGN projects utilities and errors. @author: yoram.shamir """ import logging from os import path from enum import Enum import collections class TgnType(Enum): ixexplorer = 1 ixnetwork = 2 testcenter = 3 class ApiType(Enum): tcl = 1 python = 2 rest = 3 socket = 4 def flatten(x): ...
shmir/PyTrafficGenerator
trafficgenerator/tgn_object.py
TgnObjectsDict.dumps
python
def dumps(self, indent=1): str_keys_dict = OrderedDict({str(k): v for k, v in self.items()}) for k, v in str_keys_dict.items(): if isinstance(v, dict): str_keys_dict[k] = OrderedDict({str(k1): v1 for k1, v1 in v.items()}) for k1, v1 in str_keys_dict[k].items(...
Returns nested string representation of the dictionary (like json.dumps). :param indent: indentation level.
train
https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L44-L57
null
class TgnObjectsDict(OrderedDict): """ Dictionary to map from TgnObjects to whatever data. Dictionary keys must be TgnObject but then it can be accessed by the object itself, the object reference or the object name. """ def __setitem__(self, key, value): if not isinstance(key, TgnObject): ...