示例#1
0
    def test_repr_doesnt_get_called_when_not_necessary(self):
        class Something(object):
            def __repr__(self):
                assert False, "__repr__ called when not necessary"

        foreach(Something())
        unless(Exception, Something())
示例#2
0
    def test_repr_doesnt_get_called_when_not_necessary(self):

        class Something(object):

            def __repr__(self):
                assert False, "__repr__ called when not necessary"

        foreach(Something())
        unless(Exception, Something())
示例#3
0
def authenticate(data):
    """
    Checks for a valid combination of ``unit_id`` and ``secret_key`` values in
    `data`.

    Also removes the ``secret_key`` for enhanced security.
    """
    invalid = pipe | 'Authentication failed ({0}).' | InvalidRequest

    valid, error = validate(
        required('unit_id', valid_int),
        required('secret_key', valid_string),
    )(data)

    if not valid:
        raise invalid(error)

    unit = unless(CarUnit.DoesNotExist, CarUnit.objects.get)(
        unit_id=data['unit_id'],
        secret_key=data['secret_key'],
    )

    if not unit:
        raise invalid('wrong "unit_id" and/or "secret_key"')

    if not unit.enabled:
        raise invalid('unit is disabled')

    return data.iteritems() > where(KEY != 'secret_key') | dict
示例#4
0
def entry_from_torque(data):
    """
    Convert an item from Torque-app [1] CSV to a valid Geotrack entry.

    TODO: convert timestamp, just did it manually in the csv for now...

    [1] http://torque-bhp.com/
    """
    cleaned_data = dict((k.strip(), v) for k, v in data.iteritems())

    get = lambda T, k: k > maybe | cleaned_data.get | unless(ValueError, T)

    return (
        ('altitude',
            get(float, 'Altitude')),
        ('consumption',
            get(float, 'Fuel flow rate/hour(l/hr)')),
        ('engine_temp',
            get(float, 'Engine Coolant Temperature(C)')),
        ('engine_rpm',
            get(float, 'Engine RPM(rpm)')),
        ('fuel_remaining',
            get(float, 'Fuel Remaining (Calculated from vehicle profile)(%)')),
        ('location', (
            get(float, 'Longitude'), get(float, 'Latitude'))),
        ('throttle',
            get(float, 'Absolute Throttle Position B(%)')),
        ('timestamp',
            get(str, 'GPS Time')),
        ('velocity',
            (get(float, 'GPS Speed (Meters/second)') or 0) * 3.6),
    ) > where(VALUE) | dict
示例#5
0
def journey_splitter(journeys, entry, split_by):
    """
    A reducer function for splitting a sequence of (timestamp-ordered) entries
    into "journeys" using `split_by` function.

    Entries should be dictionaries containing:
    - timestamp
    - location
    - event (optional)

    Journeys are dictionaries containing:
    - entries = sequence of entries
    - events = sequence of events from entries (without None values)

    The `split_by` function should take a journey and an entry and return
    whether the journey should be split at that point (True) or that the entry
    still belongs to it (False).
    """
    last_journey = journeys > unless(IndexError, X[-1])
    event = entry.get('event')

    if (not last_journey) or split_by(last_journey, entry):
        # create new journey
        journeys.append({
            'entries': [entry],
            'events': [event] if event else [],
        })
    else:
        # append entry to last journey
        last_journey['entries'].append(entry)
        if event:
            last_journey['events'].append(event)

    return journeys
示例#6
0
def authenticate(data):
    """
    Checks for a valid combination of ``unit_id`` and ``secret_key`` values in
    `data`.

    Also removes the ``secret_key`` for enhanced security.
    """
    invalid = pipe | 'Authentication failed ({0}).' | InvalidRequest

    valid, error = validate(
        required('unit_id', valid_int),
        required('secret_key', valid_string),
    )(data)

    if not valid:
        raise invalid(error)

    unit = unless(CarUnit.DoesNotExist, CarUnit.objects.get)(
        unit_id=data['unit_id'],
        secret_key=data['secret_key'],
    )

    if not unit:
        raise invalid('wrong "unit_id" and/or "secret_key"')

    if not unit.enabled:
        raise invalid('unit is disabled')

    return data.iteritems() > where(KEY != 'secret_key') | dict
示例#7
0
def import_query(potential_module_names):
    query_module = first_of(potential_module_names >
        foreach(unless(ImportError, import_module)))
    try:
        return query_module and query_module.execute
    except AttributeError:
        raise NotImplementedError('The "%s" module does not provide the '
            'execute method.' % query_module)
示例#8
0
    def get_for(self, car):
        """
        Returns a CarUnit installed in `car` or None if no such unit exists.

        Raises an exception if there are more CarUnits in the `car`, but that
        probably shouldn't happen.
        """
        return unless(CarUnit.DoesNotExist, self.get_query_set().get)(car=car)
示例#9
0
 def last_address(self):
     if not self._last_address:
         self._last_address = (self._last_position > maybe
             | X.coords
             | unless(Exception, NominatimQuerier().resolve_address)
             | X['display_name']
             ) or _('Unknown')
         self.save()
     return self._last_address
示例#10
0
def create_or_get_custom_permission(modelname, name, codename):
    modelname = modelname.lower()
    ct = unless(ContentType.DoesNotExist,
        ContentType.objects.get)(model=modelname)

    if not ct:
        # happens in the initial syncdb when creating the default Subsidiary,
        # but since it's going to have to be edited and .save()d anyway,
        # it doesn't matter
        # TODO: refactoring
        return None

    perm, created = Permission.objects.get_or_create(
        codename=codename,
        content_type__pk=ct.id,
        defaults={
            'name': name[:50],  # permission name can be at most 50 chars long!
            'content_type': ct,
        })
    if(created == True):
        get_logger().info("Created new permission: " + unicode(perm))
    return perm
示例#11
0
def create_or_get_custom_permission(modelname, name, codename):
    modelname = modelname.lower()
    ct = unless(ContentType.DoesNotExist,
                ContentType.objects.get)(model=modelname)

    if not ct:
        # happens in the initial syncdb when creating the default Subsidiary,
        # but since it's going to have to be edited and .save()d anyway,
        # it doesn't matter
        # TODO: refactoring
        return None

    perm, created = Permission.objects.get_or_create(
        codename=codename,
        content_type__pk=ct.id,
        defaults={
            'name': name[:50],  # permission name can be at most 50 chars long!
            'content_type': ct,
        })
    if (created == True):
        get_logger().info("Created new permission: " + unicode(perm))
    return perm
示例#12
0
def process_docstring(app, what, name, obj, options, lines):
    """
    Appends Model's fields to it's docstring together with help_texts.
    """
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model class
    if unless(TypeError, issubclass)(obj, models.Model):

        # Grab the field list from the meta class
        fields = obj._meta._fields()

        for field in fields > where(type | (X != models.AutoField)):

            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_unicode(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_unicode(field.verbose_name).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.name, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.name, verbose_name))

            # Add the field's type to the docstring
            lines.append(u':type %s: %s' % (field.name, type(field).__name__))

    # Return the extended docstring
    return lines
示例#13
0
def process_docstring(app, what, name, obj, options, lines):
    """
    Appends Model's fields to it's docstring together with help_texts.
    """
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model class
    if unless(TypeError, issubclass)(obj, models.Model):

        # Grab the field list from the meta class
        fields = obj._meta._fields()

        for field in fields > where(type | (X != models.AutoField)):

            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_unicode(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_unicode(field.verbose_name).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.name, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.name, verbose_name))

            # Add the field's type to the docstring
            lines.append(u':type %s: %s' % (field.name, type(field).__name__))

    # Return the extended docstring
    return lines
示例#14
0
 def test_with_exception_in_foreach(self):
     f = foreach(unless(AttributeError, X.lower())) | list
     assert f(['A', 'B', 37]) == ['a', 'b', None]
示例#15
0
 def test_with_exception(self):
     f = unless(AttributeError, foreach(X.lower()) | list)
     assert f(['A', 'B', 37]) is None
示例#16
0
 def test_ok(self):
     f = unless(AttributeError, foreach(X.lower())) | list
     assert f("ABC") == ['a', 'b', 'c']
示例#17
0
 def test_X_exception(self):
     f = unless(TypeError, X * 'x')
     assert f('x') is None
示例#18
0
 def test_X_ok(self):
     f = unless(TypeError, X * 'x')
     assert f(3) == 'xxx'
示例#19
0
 def test_partial_exc(self):
     f = unless(TypeError, enumerate, start=3)
     assert f(42) is None
示例#20
0
 def get_for(self, journey):
     """
     Returns a datafile for particular journey.
     Relation is 1-to-1, exception is raised when more than one datafile is found.
     """
     return unless(JourneyDataFile.DoesNotExist, self.get_query_set().get)(journey=journey)
示例#21
0
 def test_with_exception(self):
     f = unless(AttributeError, foreach(X.lower()) | list)
     assert f(['A', 'B', 37]) is None
示例#22
0
 def test_ok(self):
     f = unless(AttributeError, foreach(X.lower())) | list
     assert f("ABC") == ['a', 'b', 'c']
示例#23
0

commit_readme = """

git add README.rst
git commit -m "(readme update)"

"""

update_gh_pages = """

git checkout gh-pages
git merge master

git rm -rf doc
sphinx-build -b html docs/source/ doc

git add doc
git commit -m "doc update"
git checkout master

"""

runscript = X.split('\n') | where(X) | unless(BuildFailure, foreach_do(sh))

if __name__ == '__main__':

    create_readme()
    runscript(commit_readme)
    runscript(update_gh_pages)
示例#24
0
 def test_partial_ok(self):
     f = unless(TypeError, enumerate, start=3) | list
     assert f('abc') == [(3, 'a'), (4, 'b'), (5, 'c')]
示例#25
0
 def test_partial_ok(self):
     f = unless(TypeError, enumerate, start=3) | list
     assert f('abc') == [(3, 'a'), (4, 'b'), (5, 'c')]
示例#26
0
 def test_with_exception_in_foreach(self):
     f = foreach(unless(AttributeError, X.lower())) | list
     assert f(['A', 'B', 37]) == ['a', 'b', None]
示例#27
0
commit_readme = """

git add README.rst
git commit -m "(readme update)"

"""


update_gh_pages = """

git checkout gh-pages
git merge master

git rm -rf doc
sphinx-build -b html docs/source/ doc

git add doc
git commit -m "doc update"
git checkout master

"""

runscript = X.split('\n') | where(X) | unless(BuildFailure, foreach_do(sh))


if __name__ == '__main__':

    create_readme()
    runscript(commit_readme)
    runscript(update_gh_pages)
示例#28
0
 def test_X_ok(self):
     f = unless(TypeError, X * 'x')
     assert f(3) == 'xxx'
示例#29
0
 def test_X_exception(self):
     f = unless(TypeError, X * 'x')
     assert f('x') is None
示例#30
0
 def test_partial_exc(self):
     f = unless(TypeError, enumerate, start=3)
     assert f(42) is None
示例#31
0
def convertible_to(typ):
    return unless((TypeError, ValueError), typ) | (X != None)