INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return a client with same settings of the batch client
def unit_client(self): # type: () -> Client """Return a client with same settings of the batch client""" client = Client(self.host, self.port, self.prefix) self._configure_client(client) return client
Send buffered metrics in batch requests
def flush(self): # type: () -> BatchClient """Send buffered metrics in batch requests""" address = self.remote_address while len(self._batches) > 0: self._socket.sendto(self._batches[0], address) self._batches.popleft() return self
My permission factory.
def my_permission_factory(record, *args, **kwargs): """My permission factory.""" def can(self): rec = Record.get_record(record.id) return rec.get('access', '') == 'open' return type('MyPermissionChecker', (), {'can': can})()
Return a TCP batch client with same settings of the TCP client
def batch_client(self, size=512): # type: (int) -> TCPBatchClient """Return a TCP batch client with same settings of the TCP client""" batch_client = TCPBatchClient(self.host, self.port, self.prefix, size) self._configure_client(batch_client) return batch_client
Send buffered metrics in batch requests over TCP
def flush(self): """Send buffered metrics in batch requests over TCP""" # type: () -> TCPBatchClient while len(self._batches) > 0: self._socket.sendall(self._batches[0]) self._batches.popleft() return self
Return a TCPClient with same settings of the batch TCP client
def unit_client(self): # type: () -> TCPClient """Return a TCPClient with same settings of the batch TCP client""" client = TCPClient(self.host, self.port, self.prefix) self._configure_client(client) return client
Supposes that choices is sequence of two elements items where first one is the probability and second is the result object or callable >>> result = weighted_choice ( [ ( 20 x ) ( 100 y ) ] ) >>> result in [ x y ] True
def weighted_choice(choices): """ Supposes that choices is sequence of two elements items, where first one is the probability and second is the result object or callable >>> result = weighted_choice([(20,'x'), (100, 'y')]) >>> result in ['x', 'y'] True """ total = sum([wei...
Returns random float >>> result = any_float ( min_value = 0 max_value = 100 precision = 2 ) >>> type ( result ) <type float > >>> result > = 0 and result < = 100 True
def any_float(min_value=0, max_value=100, precision=2): """ Returns random float >>> result = any_float(min_value=0, max_value=100, precision=2) >>> type(result) <type 'float'> >>> result >=0 and result <= 100 True """ return round(random.uniform(min_value, max_value...
Return string with random content >>> result = any_string ( letters = ascii_letters min_length = 3 max_length = 100 ) >>> type ( result ) <type str > >>> len ( result ) in range ( 3 101 ) True >>> any ( [ c in ascii_letters for c in result ] ) True
def any_string(letters = ascii_letters, min_length=3, max_length=100): """ Return string with random content >>> result = any_string(letters = ascii_letters, min_length=3, max_length=100) >>> type(result) <type 'str'> >>> len(result) in range(3,101) True >>> any([c in ascii_let...
Return random date from the [ from_date to_date ] interval >>> result = any_date ( from_date = date ( 1990 1 1 ) to_date = date ( 1990 1 3 )) >>> type ( result ) <type datetime. date > >>> result > = date ( 1990 1 1 ) and result < = date ( 1990 1 3 ) True
def any_date(from_date=date(1990, 1, 1), to_date=date.today()): """ Return random date from the [from_date, to_date] interval >>> result = any_date(from_date=date(1990,1,1), to_date=date(1990,1,3)) >>> type(result) <type 'datetime.date'> >>> result >= date(1990,1,1) and result <= date(19...
Return random datetime from the [ from_date to_date ] interval >>> result = any_datetime ( from_date = datetime ( 1990 1 1 ) to_date = datetime ( 1990 1 3 )) >>> type ( result ) <type datetime. datetime > >>> result > = datetime ( 1990 1 1 ) and result < = datetime ( 1990 1 3 ) True
def any_datetime(from_date=datetime(1990, 1, 1), to_date=datetime.now()): """ Return random datetime from the [from_date, to_date] interval >>> result = any_datetime(from_date=datetime(1990,1,1), to_date=datetime(1990,1,3)) >>> type(result) <type 'datetime.datetime'> >>> result >= dateti...
Return random decimal from the [ min_value max_value ] interval >>> result = any_decimal ( min_value = 0. 999 max_value = 3 decimal_places = 3 ) >>> type ( result ) <class decimal. Decimal > >>> result > = Decimal ( 0. 999 ) and result < = Decimal ( 3 ) True
def any_decimal(min_value=Decimal(0), max_value=Decimal('99.99'), decimal_places=2): """ Return random decimal from the [min_value, max_value] interval >>> result = any_decimal(min_value=0.999, max_value=3, decimal_places=3) >>> type(result) <class 'decimal.Decimal'> >>> result >= Decima...
Shortcut for creating Users
def any_user(password=None, permissions=[], groups=[], **kwargs): """ Shortcut for creating Users Permissions could be a list of permission names If not specified, creates active, non superuser and non staff user """ is_active = kwargs.pop('is_active', True) is_superuser = kwargs.pop...
tries to convert a Python object into an OpenMath object this is not a replacement for using a Converter for exporting Python objects instead it is used conveniently building OM objects in DSL embedded in Python inparticular it converts Python functions into OMBinding objects using lambdaOM as the binder
def interpretAsOpenMath(x): """tries to convert a Python object into an OpenMath object this is not a replacement for using a Converter for exporting Python objects instead, it is used conveniently building OM objects in DSL embedded in Python inparticular, it converts Python functions into OMBinding ob...
Converts a term into OpenMath using either a converter or the interpretAsOpenMath method
def convertAsOpenMath(term, converter): """ Converts a term into OpenMath, using either a converter or the interpretAsOpenMath method """ # if we already have openmath, or have some of our magic helpers, use interpretAsOpenMath if hasattr(term, "_ishelper") and term._ishelper or isinstance(term, om.OMA...
Convert OpenMath object to Python
def to_python(self, omobj): """ Convert OpenMath object to Python """ # general overrides if omobj.__class__ in self._omclass_to_py: return self._omclass_to_py[omobj.__class__](omobj) # oms elif isinstance(omobj, om.OMSymbol): return self._lookup_to_python...
Convert Python object to OpenMath
def to_openmath(self, obj): """ Convert Python object to OpenMath """ for cl, conv in reversed(self._conv_to_om): if cl is None or isinstance(obj, cl): try: return conv(obj) except CannotConvertError: continue i...
Register a conversion from Python to OpenMath
def register_to_openmath(self, py_class, converter): """Register a conversion from Python to OpenMath :param py_class: A Python class the conversion is attached to, or None :type py_class: None, type :param converter: A conversion function or an OpenMath object :type converter:...
Register a conversion from OpenMath to Python
def _deprecated_register_to_python(self, cd, name, converter=None): """Register a conversion from OpenMath to Python This function has two forms. A three-arguments one: :param cd: A content dictionary name :type cd: str :param name: A symbol name :type name: str ...
This is a shorthand for:
def _deprecated_register(self, py_class, to_om, om_cd, om_name, to_py=None): """ This is a shorthand for: ``self.register_to_python(om_cd, om_name, to_py)`` ``self.register_to_openmath(py_class, to_om)`` """ self.register_to_python(om_cd, om_name, to_py) se...
Used to initialize redis with app object
def init_app(self, app): """ Used to initialize redis with app object """ app.config.setdefault('REDIS_URLS', { 'main': 'redis://localhost:6379/0', 'admin': 'redis://localhost:6379/1', }) app.before_request(self.before_request) self.app ...
Return list of choices s keys
def valid_choices(choices): """ Return list of choices's keys """ for key, value in choices: if isinstance(value, (list, tuple)): for key, _ in value: yield key else: yield key
django_any birds language parser
def split_model_kwargs(kw): """ django_any birds language parser """ from collections import defaultdict model_fields = {} fields_agrs = defaultdict(lambda : {}) for key in kw.keys(): if '__' in key: field, _, subfield = key.partition('__') fields_ag...
Register form field data function. Could be used as decorator
def register(self, field_type, impl=None): """ Register form field data function. Could be used as decorator """ def _wrapper(func): self.registry[field_type] = func return func if impl: return _wrapper(impl) return _w...
Lowest value generator.
def _create_value(self, *args, **kwargs): """ Lowest value generator. Separated from __call__, because it seems that python cache __call__ reference on module import """ if not len(args): raise TypeError('Object instance is not provided') if self.by_...
Returns tuple with form data and files
def any_form_default(form_cls, **kwargs): """ Returns tuple with form data and files """ form_data = {} form_files = {} form_fields, fields_args = split_model_kwargs(kwargs) for name, field in form_cls.base_fields.iteritems(): if name in form_fields: form_data[name] = k...
Sometimes return None if field is not required
def field_required_attribute(function): """ Sometimes return None if field is not required >>> result = any_form_field(forms.BooleanField(required=False)) >>> result in ['', 'True', 'False'] True """ def _wrapper(field, **kwargs): if not field.required and random.random < 0.1: ...
Selection from field. choices
def field_choices_attibute(function): """ Selection from field.choices """ def _wrapper(field, **kwargs): if hasattr(field.widget, 'choices'): return random.choice(list(valid_choices(field.widget.choices))) return function(field, **kwargs) return _wrapper
Return random value for CharField >>> result = any_form_field ( forms. CharField ( min_length = 3 max_length = 10 )) >>> type ( result ) <type str >
def char_field_data(field, **kwargs): """ Return random value for CharField >>> result = any_form_field(forms.CharField(min_length=3, max_length=10)) >>> type(result) <type 'str'> """ min_length = kwargs.get('min_length', 1) max_length = kwargs.get('max_length', field.max_length or 255) ...
Return random value for DecimalField
def decimal_field_data(field, **kwargs): """ Return random value for DecimalField >>> result = any_form_field(forms.DecimalField(max_value=100, min_value=11, max_digits=4, decimal_places = 2)) >>> type(result) <type 'str'> >>> from decimal import Decimal >>> Decimal(result) >= 11, Decimal(r...
Return random value for EmailField
def email_field_data(field, **kwargs): """ Return random value for EmailField >>> result = any_form_field(forms.EmailField(min_length=10, max_length=30)) >>> type(result) <type 'str'> >>> len(result) <= 30, len(result) >= 10 (True, True) """ max_length = 10 if field.max_length: ...
Return random value for DateField
def date_field_data(field, **kwargs): """ Return random value for DateField >>> result = any_form_field(forms.DateField()) >>> type(result) <type 'str'> """ from_date = kwargs.get('from_date', date(1990, 1, 1)) to_date = kwargs.get('to_date', date.today()) date_format = random....
Return random value for DateTimeField
def datetime_field_data(field, **kwargs): """ Return random value for DateTimeField >>> result = any_form_field(forms.DateTimeField()) >>> type(result) <type 'str'> """ from_date = kwargs.get('from_date', datetime(1990, 1, 1)) to_date = kwargs.get('to_date', datetime.today()) date_f...
Return random value for FloatField
def float_field_data(field, **kwargs): """ Return random value for FloatField >>> result = any_form_field(forms.FloatField(max_value=200, min_value=100)) >>> type(result) <type 'str'> >>> float(result) >=100, float(result) <=200 (True, True) """ min_value = 0 max_value = 100 ...
Return random value for IntegerField
def integer_field_data(field, **kwargs): """ Return random value for IntegerField >>> result = any_form_field(forms.IntegerField(max_value=200, min_value=100)) >>> type(result) <type 'str'> >>> int(result) >=100, int(result) <=200 (True, True) """ min_value = 0 max_value = 100 ...
Return random value for IPAddressField >>> result = any_form_field ( forms. IPAddressField () ) >>> type ( result ) <type str > >>> from django. core. validators import ipv4_re >>> import re >>> re. match ( ipv4_re result ) is not None True
def ipaddress_field_data(field, **kwargs): """ Return random value for IPAddressField >>> result = any_form_field(forms.IPAddressField()) >>> type(result) <type 'str'> >>> from django.core.validators import ipv4_re >>> import re >>> re.match(ipv4_re, result) is not None True ...
Return random value for SlugField >>> result = any_form_field ( forms. SlugField () ) >>> type ( result ) <type str > >>> from django. core. validators import slug_re >>> import re >>> re. match ( slug_re result ) is not None True
def slug_field_data(field, **kwargs): """ Return random value for SlugField >>> result = any_form_field(forms.SlugField()) >>> type(result) <type 'str'> >>> from django.core.validators import slug_re >>> import re >>> re.match(slug_re, result) is not None True """ min_le...
Return random value for TimeField
def time_field_data(field, **kwargs): """ Return random value for TimeField >>> result = any_form_field(forms.TimeField()) >>> type(result) <type 'str'> """ time_format = random.choice(field.input_formats or formats.get_format('TIME_INPUT_FORMATS')) return time(xunit.any_int(min_value=...
Return random value for ChoiceField
def choice_field_data(field, **kwargs): """ Return random value for ChoiceField >>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')] >>> result = any_form_field(forms.ChoiceField(choices=CHOICES)) >>> type(result) <type 'str'> >>> result in ['YNG', 'OLD'] True >>> typed_result = any_...
Return random value for MultipleChoiceField
def multiple_choice_field_data(field, **kwargs): """ Return random value for MultipleChoiceField >>> CHOICES = [('YNG', 'Child'), ('MIDDLE', 'Parent') ,('OLD', 'GrandParent')] >>> result = any_form_field(forms.MultipleChoiceField(choices=CHOICES)) >>> type(result) <type 'str'> """ if fi...
Return one of first ten items for field queryset
def model_choice_field_data(field, **kwargs): """ Return one of first ten items for field queryset """ data = list(field.queryset[:10]) if data: return random.choice(data) else: raise TypeError('No %s available in queryset' % field.queryset.model)
Encodes an OpenMath object as an XML node.
def encode_xml(obj, E=None): """ Encodes an OpenMath object as an XML node. :param obj: OpenMath object (or related item) to encode as XML. :type obj: OMAny :param ns: Namespace prefix to use for http://www.openmath.org/OpenMath", or None if default namespace. :type ns: str, None :ret...
Encodes an OpenMath element into a string.
def encode_bytes(obj, nsprefix=None): """ Encodes an OpenMath element into a string. :param obj: Object to encode as string. :type obj: OMAny :rtype: bytes """ node = encode_xml(obj, nsprefix) return etree.tostring(node)
Decodes a stream into an OpenMath object.
def decode_bytes(xml, validator=None, snippet=False): """ Decodes a stream into an OpenMath object. :param xml: XML to decode. :type xml: bytes :param validator: Validator to use. :param snippet: Is this an OpenMath snippet, or a full object? :type snippet: Bool :rtype: OMAny """ ...
Decodes a stream into an OpenMath object.
def decode_stream(stream, validator=None, snippet=False): """ Decodes a stream into an OpenMath object. :param stream: Stream to decode. :type stream: Any :param validator: Validator to use. :param snippet: Is this an OpenMath snippet, or a full object? :type snippet: Bool :rtype: OMAny ...
Decodes an XML element into an OpenMath object.
def decode_xml(elem, _in_bind = False): """ Decodes an XML element into an OpenMath object. :param elem: Element to decode. :type elem: etree._Element :param _in_bind: Internal flag used to indicate if we should decode within an OMBind. :type _in_bind: bool :rtype: OMAny """ obj ...
Deploy the app to PYPI.
def publish(msg="checkpoint: publish package"): """Deploy the app to PYPI. Args: msg (str, optional): Description """ test = check() if test.succeeded: # clean() # push(msg) sdist = local("python setup.py sdist") if sdist.succeeded: build = local(...
Deploy a version tag.
def tag(version=__version__): """Deploy a version tag.""" build = local("git tag {0}".format(version)) if build.succeeded: local("git push --tags")
Sometimes return None if field could be blank
def any_field_blank(function): """ Sometimes return None if field could be blank """ def wrapper(field, **kwargs): if kwargs.get('isnull', False): return None if field.blank and random.random < 0.1: return None return function(field, **kwarg...
Selection from field. choices >>> CHOICES = [ ( YNG Child ) ( OLD Parent ) ] >>> result = any_field ( models. CharField ( max_length = 3 choices = CHOICES )) >>> result in [ YNG OLD ] True
def any_field_choices(function): """ Selection from field.choices >>> CHOICES = [('YNG', 'Child'), ('OLD', 'Parent')] >>> result = any_field(models.CharField(max_length=3, choices=CHOICES)) >>> result in ['YNG', 'OLD'] True """ def wrapper(field, **kwargs): if field.ch...
Return random value for BigIntegerField >>> result = any_field ( models. BigIntegerField () ) >>> type ( result ) <type long >
def any_biginteger_field(field, **kwargs): """ Return random value for BigIntegerField >>> result = any_field(models.BigIntegerField()) >>> type(result) <type 'long'> """ min_value = kwargs.get('min_value', 1) max_value = kwargs.get('max_value', 10**10) return long(xunit.a...
An positive integer >>> result = any_field ( models. PositiveIntegerField () ) >>> type ( result ) <type int > >>> result > 0 True
def any_positiveinteger_field(field, **kwargs): """ An positive integer >>> result = any_field(models.PositiveIntegerField()) >>> type(result) <type 'int'> >>> result > 0 True """ min_value = kwargs.get('min_value', 1) max_value = kwargs.get('max_value', 9999) re...
Return random value for CharField >>> result = any_field ( models. CharField ( max_length = 10 )) >>> type ( result ) <type str >
def any_char_field(field, **kwargs): """ Return random value for CharField >>> result = any_field(models.CharField(max_length=10)) >>> type(result) <type 'str'> """ min_length = kwargs.get('min_length', 1) max_length = kwargs.get('max_length', field.max_length) return xuni...
Return random value for CharField >>> result = any_field ( models. CommaSeparatedIntegerField ( max_length = 10 )) >>> type ( result ) <type str > >>> [ int ( num ) for num in result. split ( ) ] and OK OK
def any_commaseparatedinteger_field(field, **kwargs): """ Return random value for CharField >>> result = any_field(models.CommaSeparatedIntegerField(max_length=10)) >>> type(result) <type 'str'> >>> [int(num) for num in result.split(',')] and 'OK' 'OK' """ nums_count = fie...
Return random value for DateField skips auto_now and auto_now_add fields >>> result = any_field ( models. DateField () ) >>> type ( result ) <type datetime. date >
def any_date_field(field, **kwargs): """ Return random value for DateField, skips auto_now and auto_now_add fields >>> result = any_field(models.DateField()) >>> type(result) <type 'datetime.date'> """ if field.auto_now or field.auto_now_add: return None from_date...
Return random value for DateTimeField skips auto_now and auto_now_add fields >>> result = any_field ( models. DateTimeField () ) >>> type ( result ) <type datetime. datetime >
def any_datetime_field(field, **kwargs): """ Return random value for DateTimeField, skips auto_now and auto_now_add fields >>> result = any_field(models.DateTimeField()) >>> type(result) <type 'datetime.datetime'> """ from_date = kwargs.get('from_date', datetime(1990, 1, 1)) ...
Return random value for DecimalField >>> result = any_field ( models. DecimalField ( max_digits = 5 decimal_places = 2 )) >>> type ( result ) <class decimal. Decimal >
def any_decimal_field(field, **kwargs): """ Return random value for DecimalField >>> result = any_field(models.DecimalField(max_digits=5, decimal_places=2)) >>> type(result) <class 'decimal.Decimal'> """ min_value = kwargs.get('min_value', 0) max_value = kwargs.get('max_value',...
Return random value for EmailField >>> result = any_field ( models. EmailField () ) >>> type ( result ) <type str > >>> re. match ( r ( ?: ^| \ s ) [ - a - z0 - 9_. ] +
def any_email_field(field, **kwargs): """ Return random value for EmailField >>> result = any_field(models.EmailField()) >>> type(result) <type 'str'> >>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None True """ retu...
Return random value for FloatField >>> result = any_field ( models. FloatField () ) >>> type ( result ) <type float >
def any_float_field(field, **kwargs): """ Return random value for FloatField >>> result = any_field(models.FloatField()) >>> type(result) <type 'float'> """ min_value = kwargs.get('min_value', 1) max_value = kwargs.get('max_value', 100) precision = kwargs.get('precision', ...
Lookup for nearest existing file
def any_file_field(field, **kwargs): """ Lookup for nearest existing file """ def get_some_file(path): subdirs, files = field.storage.listdir(path) if files: result_file = random.choice(files) instance = field.storage.open("%s/%s" % (path, result_file)...
Lookup for nearest existing file
def any_filepath_field(field, **kwargs): """ Lookup for nearest existing file """ def get_some_file(path): subdirs, files = [], [] for entry in os.listdir(path): entry_path = os.path.join(path, entry) if os.path.isdir(entry_path): subdir...
Return random value for IPAddressField >>> result = any_field ( models. IPAddressField () ) >>> type ( result ) <type str > >>> from django. core. validators import ipv4_re >>> re. match ( ipv4_re result ) is not None True
def any_ipaddress_field(field, **kwargs): """ Return random value for IPAddressField >>> result = any_field(models.IPAddressField()) >>> type(result) <type 'str'> >>> from django.core.validators import ipv4_re >>> re.match(ipv4_re, result) is not None True """ nums = [s...
Return random value for PositiveSmallIntegerField >>> result = any_field ( models. PositiveSmallIntegerField () ) >>> type ( result ) <type int > >>> result < 256 result > 0 ( True True )
def any_positivesmallinteger_field(field, **kwargs): """ Return random value for PositiveSmallIntegerField >>> result = any_field(models.PositiveSmallIntegerField()) >>> type(result) <type 'int'> >>> result < 256, result > 0 (True, True) """ min_value = kwargs.get('min_value...
Return random value for SlugField >>> result = any_field ( models. SlugField () ) >>> type ( result ) <type str > >>> from django. core. validators import slug_re >>> re. match ( slug_re result ) is not None True
def any_slug_field(field, **kwargs): """ Return random value for SlugField >>> result = any_field(models.SlugField()) >>> type(result) <type 'str'> >>> from django.core.validators import slug_re >>> re.match(slug_re, result) is not None True """ letters = ascii_letters ...
Return random value for SmallIntegerValue >>> result = any_field ( models. SmallIntegerField () ) >>> type ( result ) <type int > >>> result > - 256 result < 256 ( True True )
def any_smallinteger_field(field, **kwargs): """ Return random value for SmallIntegerValue >>> result = any_field(models.SmallIntegerField()) >>> type(result) <type 'int'> >>> result > -256, result < 256 (True, True) """ min_value = kwargs.get('min_value', -255) max_val...
Return random value for IntegerField >>> result = any_field ( models. IntegerField () ) >>> type ( result ) <type int >
def any_integer_field(field, **kwargs): """ Return random value for IntegerField >>> result = any_field(models.IntegerField()) >>> type(result) <type 'int'> """ min_value = kwargs.get('min_value', -10000) max_value = kwargs.get('max_value', 10000) return xunit.any_int(min_va...
Return random value for URLField >>> result = any_field ( models. URLField () ) >>> from django. core. validators import URLValidator >>> re. match ( URLValidator. regex result ) is not None True
def any_url_field(field, **kwargs): """ Return random value for URLField >>> result = any_field(models.URLField()) >>> from django.core.validators import URLValidator >>> re.match(URLValidator.regex, result) is not None True """ url = kwargs.get('url') if not url: ...
Return random value for TimeField >>> result = any_field ( models. TimeField () ) >>> type ( result ) <type datetime. time >
def any_time_field(field, **kwargs): """ Return random value for TimeField >>> result = any_field(models.TimeField()) >>> type(result) <type 'datetime.time'> """ return time( xunit.any_int(min_value=0, max_value=23), xunit.any_int(min_value=0, max_value=59), ...
Evaluate an OpenMath symbol describing a global Python object
def load_python_global(module, name): """ Evaluate an OpenMath symbol describing a global Python object EXAMPLES:: >>> from openmath.convert_pickle import to_python >>> from openmath.convert_pickle import load_python_global >>> load_python_global('math', 'sin') <built-in f...
Apply the setstate protocol to initialize inst from state.
def cls_build(inst, state): """ Apply the setstate protocol to initialize `inst` from `state`. INPUT: - ``inst`` -- a raw instance of a class - ``state`` -- the state to restore; typically a dictionary mapping attribute names to their values EXAMPLES:: >>> from openmath.convert_pickl...
r Helper function to build an OMS object EXAMPLES::
def OMSymbol(self, module, name): r""" Helper function to build an OMS object EXAMPLES:: >>> from openmath.convert_pickle import PickleConverter >>> converter = PickleConverter() >>> o = converter.OMSymbol(module="foo.bar", name="baz"); o ...
Convert a list of OM objects into an OM object
def OMList(self, l): """ Convert a list of OM objects into an OM object EXAMPLES:: >>> from openmath import openmath as om >>> from openmath.convert_pickle import PickleConverter >>> converter = PickleConverter() >>> o = converter.OMList([om.OMI...
Convert a tuple of OM objects into an OM object
def OMTuple(self, l): """ Convert a tuple of OM objects into an OM object EXAMPLES:: >>> from openmath import openmath as om >>> from openmath.convert_pickle import PickleConverter >>> converter = PickleConverter() >>> o = converter.OMTuple([om....
Convert a dictionary ( or list of items thereof ) of OM objects into an OM object
def OMDict(self, items): """ Convert a dictionary (or list of items thereof) of OM objects into an OM object EXAMPLES:: >>> from openmath import openmath as om >>> from openmath.convert_pickle import PickleConverter >>> converter = PickleConverter() ...
Decodes a PackBit encoded data.
def decode(data): """ Decodes a PackBit encoded data. """ data = bytearray(data) # <- python 2/3 compatibility fix result = bytearray() pos = 0 while pos < len(data): header_byte = data[pos] if header_byte > 127: header_byte -= 256 pos += 1 if 0 <...
Encodes data using PackBits encoding.
def encode(data): """ Encodes data using PackBits encoding. """ if len(data) == 0: return data if len(data) == 1: return b'\x00' + data data = bytearray(data) result = bytearray() buf = bytearray() pos = 0 repeat_count = 0 MAX_LENGTH = 127 # we can saf...
Summary.
def _check_currency_format(self, format=None): """ Summary. Args: format (TYPE, optional): Description Returns: name (TYPE): Description """ defaults = self.settings['currency']['format'] if hasattr(format, '__call__'): format...
Check and normalise the value of precision ( must be positive integer ).
def _change_precision(self, val, base=0): """ Check and normalise the value of precision (must be positive integer). Args: val (INT): must be positive integer base (INT): Description Returns: VAL (INT): Description """ if not isinstan...
Summary.
def parse(self, value, decimal=None): """ Summary. Takes a string/array of strings, removes all formatting/cruft and returns the raw float value Decimal must be included in the regular expression to match floats (defaults to Accounting.settings.number.decimal), ...
Implementation that treats floats more like decimals.
def to_fixed(self, value, precision): """Implementation that treats floats more like decimals. Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61") that present problems for accounting and finance-related software. """ precision = self._change_precision( ...
Format a given number.
def format(self, number, **kwargs): """Format a given number. Format a number, with comma-separated thousands and custom precision/decimal places Localise by overriding the precision and thousand / decimal separators 2nd parameter `precision` can be an object matching `settings...
Format a number into currency.
def as_money(self, number, **options): """Format a number into currency. Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format) defaults: (0, "$", 2, ",", ".", "%s%v") Localise by overriding the symbol, precision,...
Import a blosc array into a numpy array.
def to_array(data): """ Import a blosc array into a numpy array. Arguments: data: A blosc packed numpy array Returns: A numpy array with data from a blosc compressed array """ try: numpy_data = blosc.unpack_array(data) except Exception as e: raise ValueError...
Export a numpy array to a blosc array.
def from_array(array): """ Export a numpy array to a blosc array. Arguments: array: The numpy array to compress to blosc array Returns: Bytes/String. A blosc compressed array """ try: raw_data = blosc.pack_array(array) except Exception as e: raise ValueError...
Add a workspace entry in user config file.
def add(self, name, path): """Add a workspace entry in user config file.""" if not (os.path.exists(path)): raise ValueError("Workspace path `%s` doesn't exists." % path) if (self.exists(name)): raise ValueError("Workspace `%s` already exists." % name) self.confi...
Remove workspace from config file.
def remove(self, name): """Remove workspace from config file.""" if not (self.exists(name)): raise ValueError("Workspace `%s` doesn't exists." % name) self.config["workspaces"].pop(name, 0) self.config.write()
List all available workspaces.
def list(self): """List all available workspaces.""" ws_list = {} for key, value in self.config["workspaces"].items(): ws_list[key] = dict({"name": key}, **value) return ws_list
Get workspace infos from name. Return None if workspace doesn t exists.
def get(self, name): """ Get workspace infos from name. Return None if workspace doesn't exists. """ ws_list = self.list() return ws_list[name] if name in ws_list else None
Return True if workspace contains repository name.
def repository_exists(self, workspace, repo): """Return True if workspace contains repository name.""" if not self.exists(workspace): return False workspaces = self.list() return repo in workspaces[workspace]["repositories"]
Synchronise workspace s repositories.
def sync(self, ws_name): """Synchronise workspace's repositories.""" path = self.config["workspaces"][ws_name]["path"] repositories = self.config["workspaces"][ws_name]["repositories"] logger = logging.getLogger(__name__) color = Color() for r in os.listdir(path): ...
Clone a repository.
def clone(url, path): """Clone a repository.""" adapter = None if url[:4] == "git@" or url[-4:] == ".git": adapter = Git(path) if url[:6] == "svn://": adapter = Svn(path) if url[:6] == "bzr://": adapter = Bzr(path) if url[:9] == "ssh://hg@": adapter = Hg(path) ...
Tells you if you have an old version of ndio.
def check_version(): """ Tells you if you have an old version of ndio. """ import requests r = requests.get('https://pypi.python.org/pypi/ndio/json').json() r = r['info']['version'] if r != version: print("A newer version of ndio is available. " + "'pip install -U ndio'...
Converts an array to its voxel list.
def to_voxels(array): """ Converts an array to its voxel list. Arguments: array (numpy.ndarray): A numpy nd array. This must be boolean! Returns: A list of n-tuples """ if type(array) is not numpy.ndarray: raise ValueError("array argument must be of type numpy.ndarray")...
Converts a voxel list to an ndarray.
def from_voxels(voxels): """ Converts a voxel list to an ndarray. Arguments: voxels (tuple[]): A list of coordinates indicating coordinates of populated voxels in an ndarray. Returns: numpy.ndarray The result of the transformation. """ dimensions = len(voxels[0]) ...
Execute update subcommand.
def execute(self, args): """Execute update subcommand.""" if args.name is not None: self.print_workspace(args.name) elif args.all is not None: self.print_all()
Print repository update.
def print_update(self, repo_name, repo_path): """Print repository update.""" color = Color() self.logger.info(color.colored( "=> [%s] %s" % (repo_name, repo_path), "green")) try: repo = Repository(repo_path) repo.update() except RepositoryError...
Set FileHandler
def set_file_handler(self, logfile): """Set FileHandler""" handler = logging.FileHandler(logfile) handler.setLevel(logging.NOTSET) handler.setFormatter(Formatter(FORMAT)) self.addHandler(handler)
Set Console handler.
def set_console_handler(self, debug=False): """Set Console handler.""" console = logging.StreamHandler() console.setFormatter(Formatter(LFORMAT)) if not debug: console.setLevel(logging.INFO) self.addHandler(console)
Execute command with os. popen and return output.
def execute(self, command, path=None): """Execute command with os.popen and return output.""" logger = logging.getLogger(__name__) self.check_executable() logger.debug("Executing command `%s` (cwd: %s)" % (command, path)) process = subprocess.Popen( command, ...
Import a png file into a numpy array.
def load(png_filename): """ Import a png file into a numpy array. Arguments: png_filename (str): A string filename of a png datafile Returns: A numpy array with data from the png file """ # Expand filename to be absolute png_filename = os.path.expanduser(png_filename) ...