Example #1
0
def test_valid_composed_to_basic():
    """Composed units should convert to basic equivalents."""
    metre = unit('m')
    
    hundred_cm_in_metres = metre(Quantity(100, unit('cm')))
    assert hundred_cm_in_metres == Quantity(1.0, metre)
    assert str(hundred_cm_in_metres) == '1.0 m'
Example #2
0
def test_multiply_named_scalar():
    """Named quantities * scalars"""
    m_per_s = NamedComposedUnit('vel',
                                unit('m') / unit('s'))

    assert (Quantity(8, m_per_s) * 2 ==
            Quantity(16, m_per_s))
Example #3
0
def index(request):
    primary_bike_id = ''
    bikes = request.user.gear_set.all()
    for bike in bikes:
        if bike.primary:
            primary_bike_id = bike.strava_id

    gear_id = request.POST.get('gear_id', primary_bike_id)
    before = request.POST.get('before')
    after = request.POST.get('after')
    if before and after:
        before = datetime.datetime.strptime(before, '%Y-%m-%d') + timedelta(hours=23, minutes=59, seconds=59)
        after = datetime.datetime.strptime(after, '%Y-%m-%d') + timedelta(hours=23, minutes=59, seconds=59)
    else:
        before = datetime.datetime.today().replace(hour=23, minute=59, second=59, microsecond=0)
        after = before - timedelta(days=7)

    stra = strava()
    filters = [
        {'field': 'athlete.id', 'query': request.user.strava_id},
        {'field': 'start_date', 'query': {'$lt': before, '$gte': after}},
        {'field': 'gear_id', 'query': gear_id},
    ]
    activities = stra.aggregate_activities_mongo(filters, {
        '_id': None,
        'distance': {'$sum': '$distance'},
        'elapsed_time': {'$sum': '$moving_time'},
        'elevation': {'$sum': '$total_elevation_gain'},
        'average_speed': {'$avg': '$average_speed'},
        'kilojoules': {'$sum': '$kilojoules'},
    })

    template_fields = {
        'bikes': bikes,
        'gear_id':gear_id,
        'before':before.strftime('%Y-%m-%d'),
        'after':after.strftime('%Y-%m-%d'),
        'distance': unithelper.miles(unit('m')(0)),
        'time': unithelper.hours(unit('s')(0)),
        'elevation': unithelper.meters(unit('m')(0)),
        'avg_speed': unithelper.mph(unit('m')(0)/unit('s')(1)),
        'kjs': 0,
    }
    activity = None
    for agg in activities:
        if not activity:
            activity = agg

    if activity:
        merge_dict = template_fields.copy()
        merge_dict.update({
            'distance': unithelper.miles(unit('m')(activity['distance'])),
            'time': unithelper.hours(unit('s')(activity['elapsed_time'])),
            'elevation': unithelper.meters(unit('m')(activity['elevation'])),
            'avg_speed': unithelper.mph(unit('m')(activity['average_speed'])/unit('s')(1)),
            'kjs': activity['kilojoules'],
        })
        template_fields = merge_dict

    return render_to_response('strava/templates/strava_index.html', template_fields, context_instance=RequestContext(request))
Example #4
0
def test_divide_named_scalar():
    """Named quantities / scalars"""
    m_per_s = NamedComposedUnit('vel',
                                unit('m') / unit('s'))

    assert (Quantity(8, m_per_s) / 2 ==
            Quantity(4, m_per_s))
Example #5
0
def test_valid_basic_to_composed():
    """Test conversion to composed units."""
    composed_cm = unit('cm').composed_unit

    one_m_in_cm = composed_cm(Quantity(1, unit('m')))

    assert one_m_in_cm == Quantity(1, unit('m'))
Example #6
0
def test_valid_basic_to_composed():
    """Test conversion to composed units."""
    composed_cm = unit('cm').composed_unit
    
    one_m_in_cm = composed_cm(Quantity(1, unit('m')))
    
    assert one_m_in_cm == Quantity(1, unit('m'))
def test_divide_named_scalar():
    """Named quantities / scalars"""
    m_per_s = NamedComposedUnit('vel', 
                                unit('m') / unit('s'))

    assert (Quantity(8, m_per_s) / 2 ==
            Quantity(4, m_per_s))
def test_multiply_named_scalar():
    """Named quantities * scalars"""
    m_per_s = NamedComposedUnit('vel', 
                                unit('m') / unit('s'))
    
    assert (Quantity(8, m_per_s) * 2 ==
            Quantity(16, m_per_s))
def test_rmultiply_named_scalar():
    """Scalars * Named quantities"""
    m_per_s = NamedComposedUnit('vel', 
                                unit('m') / unit('s'))

    assert (2 * Quantity(8, m_per_s) ==
            Quantity(16, m_per_s))
def test_rdivide_named_scalar():
    """Scalars / Named quantities"""
    m_per_s = NamedComposedUnit('vel', 
                                unit('m') / unit('s'))

    assert (4 / Quantity(2, m_per_s) ==
            Quantity(2, unit('s') / unit('m')))
Example #11
0
def test_valid_composed_to_basic():
    """Composed units should convert to basic equivalents."""
    metre = unit('m')

    hundred_cm_in_metres = metre(Quantity(100, unit('cm')))
    assert hundred_cm_in_metres == Quantity(1.0, metre)
    assert str(hundred_cm_in_metres) == '1.00 m'
Example #12
0
def test_rdivide_named_scalar():
    """Scalars / Named quantities"""
    m_per_s = NamedComposedUnit('vel',
                                unit('m') / unit('s'))

    assert (4 / Quantity(2, m_per_s) ==
            Quantity(2, unit('s') / unit('m')))
Example #13
0
def test_rmultiply_named_scalar():
    """Scalars * Named quantities"""
    m_per_s = NamedComposedUnit('vel',
                                unit('m') / unit('s'))

    assert (2 * Quantity(8, m_per_s) ==
            Quantity(16, m_per_s))
Example #14
0
def test_valid_basic_to_named():
    """Basic units should convert into named equivalents."""
    metre = unit('m')
    thousand_m_in_km = unit('km')(Quantity(1000, metre))
    
    assert thousand_m_in_km == Quantity(1, unit('km'))
    assert thousand_m_in_km.unit == unit('km')
    assert str(thousand_m_in_km) == '1 km'
Example #15
0
def test_valid_basic_to_named():
    """Basic units should convert into named equivalents."""
    metre = unit('m')
    thousand_m_in_km = unit('km')(Quantity(1000, metre))

    assert thousand_m_in_km == Quantity(1, unit('km'))
    assert thousand_m_in_km.unit == unit('km')
    assert str(thousand_m_in_km) == '1.00 km'
Example #16
0
def test_valid_named_to_basic():
    """Named units should convert to their basic equivalents"""
    
    kilometre = unit('km')
    one_km_in_m = unit('m')(Quantity(1, kilometre))
    
    assert one_km_in_m == Quantity(1000, unit('m'))
    assert one_km_in_m.unit == unit('m')
    assert str(one_km_in_m) == '1000 m'
Example #17
0
def test_valid_named_to_basic():
    """Named units should convert to their basic equivalents"""

    kilometre = unit('km')
    one_km_in_m = unit('m')(Quantity(1, kilometre))

    assert one_km_in_m == Quantity(1000, unit('m'))
    assert one_km_in_m.unit == unit('m')
    assert str(one_km_in_m) == '1000.00 m'
Example #18
0
def test_volume():
    """Volume units should interchange correctly with cubed area units."""
    litres = unit('L')
    millilitres = unit('mL')
    centimetres = unit('cm')
    cm_cubed = centimetres * centimetres * centimetres

    assert Quantity(1, litres) == Quantity(1000, millilitres)
    assert Quantity(1, millilitres) == Quantity(1, cm_cubed)
Example #19
0
def test_valid_named_to_named():
    """Named units should convert to named equivalents."""
    
    gray = unit('Gy')
    sievert = unit('Sv')
    
    one_gray_in_sievert = sievert(Quantity(1, gray))
    assert one_gray_in_sievert == Quantity(1, gray)
    assert str(one_gray_in_sievert) == '1 Sv'
Example #20
0
def test_valid_named_to_named():
    """Named units should convert to named equivalents."""

    gray = unit('Gy')
    sievert = unit('Sv')

    one_gray_in_sievert = sievert(Quantity(1, gray))
    assert one_gray_in_sievert == Quantity(1, gray)
    assert str(one_gray_in_sievert) == '1.00 Sv'
Example #21
0
def define_imperial_units():
    """Define some common imperial units."""

    assert unit("m").is_si()  # Ensure SI units already defined

    # scaled_unit measures
    scaled_unit("inch", "cm", 2.54, name="inch")
    scaled_unit("in", "cm", 2.54, name="inch")  # 'in' is a python keyword
    scaled_unit("ft", "inch", 12.0, name="foot")
    scaled_unit("yd", "ft", 3.0, name="yard")
    scaled_unit("fm", "ft", 6.0, name="fathom")
    scaled_unit("rd", "yd", 5.5, name="rod")
    scaled_unit("fur", "rd", 40.0, name="furlong")
    scaled_unit("mi", "fur", 8.0, name="mile")
    scaled_unit("lea", "mi", 3.0, name="leage")

    # nautical scaled_unit measures
    scaled_unit("NM", "m", 1852.0, name="nautical mile")
    scaled_unit("cable", "NM", 0.1, name="cable length")

    # chain measure
    scaled_unit("li", "inch", 7.92, name="link")
    scaled_unit("ch", "li", 100.0, name="chain")

    # area measure
    NamedComposedUnit("acre", ComposedUnit([unit("rd")] * 2, [], 160.0), name="acre")

    # liquid measures
    NamedComposedUnit("pt", ComposedUnit([unit("inch")] * 3, [], 28.875), name="pint")

    scaled_unit("gi", "pt", 0.25, name="gills")
    scaled_unit("qt", "pt", 2.0, name="quarts")
    scaled_unit("gal", "qt", 4.0, name="gallons")

    scaled_unit("fl oz", "pt", 1.0 / 16.0, name="fluid ounce")
    scaled_unit("fl dr", "fl oz", 1.0 / 8.0, name="fluid drachm")
    scaled_unit("minim", "fl dr", 1.0 / 60.0, name="minim")

    # weight
    scaled_unit("oz", "g", 28.375, name="ounce")
    scaled_unit("lb", "oz", 16.0, name="pound")
    scaled_unit("ton", "lb", 2000.0, name="ton")
    scaled_unit("grain", "lb", 1.0 / 7000.0, name="grain")
    scaled_unit("dr", "lb", 1.0 / 256.0, name="dram")
    scaled_unit("cwt", "lb", 100.0, name="hundredweight")

    scaled_unit("dwt", "grain", 24.0, name="pennyweight")
    scaled_unit("oz t", "dwt", 20.0, name="ounce troy")
    scaled_unit("lb t", "oz t", 12.0, name="pound troy")

    # power
    scaled_unit("hpl", "W", 746.9999, name="mechanical")
    scaled_unit("hpm", "W", 735.49875, name="metric horsepower")
    scaled_unit("hpe", "W", 746.0, name="electric horsepower")

    # energy
    scaled_unit("BTU", "J", 1055.056, name="ISO BTU", is_si=True)
Example #22
0
def test_volume():
    """Volume units should interchange correctly with cubed area units."""
    litres = unit('L')
    millilitres = unit('mL')
    centimetres = unit('cm')
    cm_cubed = centimetres * centimetres * centimetres
    
    assert Quantity(1, litres) == Quantity(1000, millilitres)
    assert Quantity(1, millilitres) == Quantity(1, cm_cubed)
Example #23
0
 def setUp(self):
     self.laminate = CathodeLaminate(mass_active_material=0.9,
                                     mass_carbon=0.05,
                                     mass_binder=0.05,
                                     name="LMO-NEI")
     self.electrode = CoinCellElectrode(total_mass=unit('mg')(15),
                                        substrate_mass=unit('mg')(5),
                                        laminate=self.laminate,
                                        name="DummyElectrode",
                                        diameter=unit('mm')(12.7))
Example #24
0
def test_composed_unit_repr():
    """Developer-friendly string representation of composed units."""
    
    test_repr = (repr(unit('m') * unit('g') / unit('s')))
    
    # non-deterministic
    assert test_repr in [
        "ComposedUnit([LeafUnit('g', True), " + "LeafUnit('m', True)], " + "[LeafUnit('s', True)], 1)",
        "ComposedUnit([LeafUnit('m', True), " + "LeafUnit('g', True)], " + "[LeafUnit('s', True)], 1)"
    ]
Example #25
0
def test_composed_unit_repr():
    """Developer-friendly string representation of composed units."""

    test_repr = (repr(unit('m') * unit('g') / unit('s')))

    # non-deterministic
    assert test_repr in [
        "ComposedUnit([LeafUnit('g', True), " + "LeafUnit('m', True)], " +
        "[LeafUnit('s', True)], 1)", "ComposedUnit([LeafUnit('m', True), " +
        "LeafUnit('g', True)], " + "[LeafUnit('s', True)], 1)"
    ]
def test_good_named_add_w_mult():
    """A quantity with a named composed unit that carries a multiplier 
    should add to a composed unit that has a multiplier"""
    
    mile = unit('mi').composed_unit
    kilometre = unit('km')
                                               
    assert within_epsilon(Quantity(1, mile) + Quantity(1, kilometre), 
                          Quantity(1, kilometre) + Quantity(1, mile))
    assert within_epsilon(Quantity(2609.344, unit('m')),
                          Quantity(1, kilometre) + Quantity(1, mile))
def test_good_named_add_w_mults():
    """Two quantities with compatible but differently-named and 
    differently-multiplied units should add together."""
    
    mile = unit('mi')
    kilometre = unit('km')
    
    assert within_epsilon(Quantity(1, mile) + Quantity(1, kilometre),
                          Quantity(1, kilometre) + Quantity(1, mile))
    assert within_epsilon(Quantity(2609.344, unit('m')),
                          Quantity(1, kilometre) + Quantity(1, mile))
Example #28
0
def test_good_named_add_w_mult():
    """A quantity with a named composed unit that carries a multiplier
    should add to a composed unit that has a multiplier"""

    mile = unit('mi').composed_unit
    kilometre = unit('km')

    assert within_epsilon(
        Quantity(1, mile) + Quantity(1, kilometre),
        Quantity(1, kilometre) + Quantity(1, mile))
    assert within_epsilon(Quantity(2609.344, unit('m')),
                          Quantity(1, kilometre) + Quantity(1, mile))
Example #29
0
def test_good_named_add_w_mults():
    """Two quantities with compatible but differently-named and
    differently-multiplied units should add together."""

    mile = unit('mi')
    kilometre = unit('km')

    assert within_epsilon(
        Quantity(1, mile) + Quantity(1, kilometre),
        Quantity(1, kilometre) + Quantity(1, mile))
    assert within_epsilon(Quantity(2609.344, unit('m')),
                          Quantity(1, kilometre) + Quantity(1, mile))
Example #30
0
def test_good_sub_w_mult():
    """Two quantities with same units should sub together when
    they have the same multiplier"""

    moon = ComposedUnit([unit('day')], [], multiplier=28)
    lunar_cycle = ComposedUnit([unit('day')], [], multiplier=28)

    assert (Quantity(2, moon) - Quantity(1, lunar_cycle) == Quantity(1, moon))

    assert (Quantity(2, lunar_cycle) - Quantity(1, moon) == Quantity(
        1, lunar_cycle))

    assert Quantity(1, moon) == Quantity(1, lunar_cycle)
Example #31
0
    def ConvertElectricFieldAtomicFromIntensitySI(self, intensity):
        """
        Intensity [W/cm**2] -> E-field strength [a.u.]

        Relation obtained from time-averaging over one cycle,

          E0 = sqrt( (2 <I>) / (eps0 * c) )

        """
        watt_per_squarecm = unit('W') / unit('cm')**2
        val = sqrt(2.0 * intensity / (self.electrostatic_constant.squeeze() /
                (4*pi) * self.lightspeed))
        return val * 100.0 / self.electric_field_strength.squeeze()
Example #32
0
def test_good_mixed_sub():
    """Two quantities with the same units should sub together
    even if one is named"""

    gray = unit('Gy')

    sievert = unit('Sv').composed_unit

    assert (Quantity(4, gray) - Quantity(2, sievert) == Quantity(2, gray))

    assert (Quantity(4, sievert) - Quantity(2, gray) == Quantity(2, sievert))

    assert Quantity(2, sievert) == Quantity(2, gray)
Example #33
0
 def test_read_current(self):
     run = GalvanostatRun(mptfile)
     # These are practically equal but assertEqual fails due to rounding in units package
     self.assertApproximatelyEqual(
         run.charge_current,
         unit('mA')(0.33570),
         tolerance=10**-15
     )
     self.assertApproximatelyEqual(
         run.discharge_current,
         unit('mA')(-335.70),
         tolerance=10**-15
     )
Example #34
0
def test_valid_composed_to_composed():
    """Valid composed units in terms of others."""
    metric_vel = unit('km') / unit('h')
    imp_vel = unit('mi') / unit('h')
    
    highway_kph = Quantity(100, metric_vel)
    highway_mph = Quantity(62.1371192237334, imp_vel)
    
    assert str(highway_kph) == '100 km / h'
    assert str(highway_mph) == '62.1371192237 mi / h'
    
    assert within_epsilon(imp_vel(highway_kph), highway_mph)
    
    assert str(imp_vel(highway_kph)) == '62.1371192237 mi / h'
Example #35
0
def test_valid_composed_to_composed():
    """Valid composed units in terms of others."""
    metric_vel = unit('km') / unit('h')
    imp_vel = unit('mi') / unit('h')

    highway_kph = Quantity(100, metric_vel)
    highway_mph = Quantity(62.1371192237334, imp_vel)

    assert str(highway_kph) == '100.00 km / h'
    assert str(highway_mph) == '62.14 mi / h'

    assert within_epsilon(imp_vel(highway_kph), highway_mph)

    assert str(imp_vel(highway_kph)) == '62.14 mi / h'
Example #36
0
def test_good_sub_w_mults():
    """Two quantities with compatible units should sub together
    even when they have different multipliers"""

    mile = unit('mi').composed_unit
    kilometre = unit('km').composed_unit

    m_on_left = Quantity(1, mile) - Quantity(1, kilometre)
    km_on_left = Quantity(1, kilometre) - Quantity(1, mile)
    m_on_left_diff = Quantity(609.344, unit('m'))
    km_on_left_diff = Quantity(-609.344, unit('m'))

    assert within_epsilon(m_on_left, m_on_left_diff)
    assert within_epsilon(km_on_left, km_on_left_diff)
    assert within_epsilon(m_on_left_diff, -km_on_left_diff)
def test_good_sub_w_mults():
    """Two quantities with compatible units should sub together 
    even when they have different multipliers"""
    
    mile = unit('mi').composed_unit
    kilometre = unit('km').composed_unit   
    
    m_on_left = Quantity(1, mile) - Quantity(1, kilometre)
    km_on_left = Quantity(1, kilometre) - Quantity(1, mile)
    m_on_left_diff = Quantity(609.344, unit('m'))
    km_on_left_diff = Quantity(-609.344, unit('m'))
            
    assert within_epsilon(m_on_left, m_on_left_diff)
    assert within_epsilon(km_on_left, km_on_left_diff)
    assert within_epsilon(m_on_left_diff, -km_on_left_diff)
Example #38
0
def test_pow():
    """Exponentiation of quantities."""
    REGISTRY.clear()
    define_units()
    
    m_unit = unit('m')
    m_quant = Quantity(2, m_unit)
    
    assert (m_quant ** 2 == m_quant * m_quant == pow(m_quant, 2))
    
    cm_unit = unit('cm')
    cm_quant = Quantity(2, cm_unit)
    
    assert within_epsilon(cm_quant ** 2, cm_quant * cm_quant)
    assert within_epsilon(cm_quant ** 2, pow(cm_quant, 2))
Example #39
0
def test_good_mixed_add():
    """Two quantities with the same units should add together
    even if one is named"""

    gray = NamedComposedUnit('gray',
                             ComposedUnit([unit('J'), unit('kg')], []),
                             is_si=True)

    sievert = ComposedUnit([unit('J'), unit('kg')], [])

    assert (Quantity(2, gray) + Quantity(2, sievert) == Quantity(4, gray))

    assert (Quantity(2, sievert) + Quantity(2, gray) == Quantity(4, sievert))

    assert Quantity(2, sievert) == Quantity(2, gray)
Example #40
0
def define_computer_units():
    """Define some units for technology.
    
    >>> define_units()
    >>> unit('GiB')(200) > unit('GB')(200) # bastard marketers
    True
    """

    NamedComposedUnit('flop', unit('operation') / unit('s'), is_si=True)
    scaled_unit('B', 'bit', 8, is_si=True)  # byte
    scaled_unit('KiB', 'B', 1024)
    scaled_unit('MiB', 'KiB', 1024)
    scaled_unit('GiB', 'MiB', 1024)
    scaled_unit('TiB', 'GiB', 1024)
    scaled_unit('PiB', 'TiB', 1024)
Example #41
0
def define_computer_units():
    """Define some units for technology.

    >>> define_units()
    >>> unit('GiB')(200) > unit('GB')(200) # bastard marketers
    True
    """

    NamedComposedUnit('flop', unit('operation') / unit('s'), is_si=True)
    scaled_unit('B', 'bit', 8, is_si=True)  # byte
    scaled_unit('KiB', 'B', 1024)
    scaled_unit('MiB', 'KiB', 1024)
    scaled_unit('GiB', 'MiB', 1024)
    scaled_unit('TiB', 'GiB', 1024)
    scaled_unit('PiB', 'TiB', 1024)
Example #42
0
def define_computer_units():
    """Define some units for technology.
    
    >>> define_units()
    >>> unit('GiB')(200) > unit('GB')(200) # bastard marketers
    True
    """

    NamedComposedUnit("flop", unit("operation") / unit("s"), name="flop", is_si=True)
    scaled_unit("B", "bit", 8.0, name="byte", is_si=True)
    scaled_unit("KiB", "B", 1024.0, name="kilobyte")
    scaled_unit("MiB", "KiB", 1024.0, name="megabyte")
    scaled_unit("GiB", "MiB", 1024.0, name="gigabyte")
    scaled_unit("TiB", "GiB", 1024.0, name="terabyte")
    scaled_unit("PiB", "TiB", 1024.0, name="petabyte")
Example #43
0
def define_time_units():
    """Define some common time units.
    
    >>> from units.compatibility import within_epsilon
    >>> define_base_si_units()
    >>> define_time_units()
    >>> hour = unit('h')
    >>> hour.is_si()
    False
    >>> from units.quantity import Quantity
    >>> half_hour = Quantity(0.5, hour)
    >>> few_secs = Quantity(60.0, unit('s'))
    >>> sum = half_hour + few_secs
    
    >>> mins = unit('min')
    >>> thirty_one = Quantity(31, mins)
    >>> within_epsilon(thirty_one, sum)
    True
    """
    assert unit('s').is_si() # Ensure SI units already defined.
    
    scaled_unit('min', 's', 60.)
    scaled_unit('h', 'min', 60.)
    scaled_unit('day', 'h', 24.)
    scaled_unit('wk', 'day', 7.)
Example #44
0
def define_time_units():
    """Define some common time units.

    >>> from units.compatibility import within_epsilon
    >>> define_base_si_units()
    >>> define_time_units()
    >>> hour = unit('h')
    >>> hour.is_si()
    False
    >>> from units.quantity import Quantity
    >>> half_hour = Quantity(0.5, hour)
    >>> few_secs = Quantity(60.0, unit('s'))
    >>> sum = half_hour + few_secs

    >>> mins = unit('min')
    >>> thirty_one = Quantity(31, mins)
    >>> within_epsilon(thirty_one, sum)
    True
    """
    assert unit('s').is_si() # Ensure SI units already defined.

    scaled_unit('min', 's', 60.)
    scaled_unit('h', 'min', 60.)
    scaled_unit('day', 'h', 24.)
    scaled_unit('wk', 'day', 7.)
Example #45
0
def test_composed_pickle():
    """Pickling is reversible on quantities backed by composed units"""
    arbitrary = unit('arbitrary')
    arbitrary_quantity = arbitrary(3.0) * arbitrary(3.0)
    pickled = dumps(arbitrary_quantity)
    unpickled = loads(pickled)
    assert within_epsilon(arbitrary_quantity, unpickled)
Example #46
0
def test_good_named_sub():
    """Two quantities with the same named complex units should sub together"""

    furlong = unit('fur')

    assert (Quantity(4, furlong) - Quantity(2, furlong) == Quantity(
        2, furlong))
Example #47
0
def strava_pick(ctx, limit, before, after):
    """Getting GPX file by picked activity and upload to Strava"""
    new_time = ctx.obj['new_time']
    client = ctx.obj['client']

    define_units()
    kilometers = unit('km')

    activities = []
    Activity = collections.namedtuple('Activity', [
        'id', 'start_date_local', 'name', 'moving_time', 'distance',
        'total_elevation_gain'
    ])

    with Halo(text='Fetch activities from Strava', spinner='dots'):
        fetched_activities = client.get_activities(before, after, limit)

    for activity in fetched_activities:
        activities.append(
            Activity(id=activity.id,
                     start_date_local=activity.start_date_local,
                     name=activity.name,
                     moving_time=activity.moving_time,
                     distance=kilometers(activity.distance),
                     total_elevation_gain=activity.total_elevation_gain))

    title = 'Please choose your activity'
    option, index = pick(options=activities,
                         title=title,
                         options_map_func=get_label)

    update_activity(client, option.id, new_time)
Example #48
0
def define_time_units():
    """Define some common time units.
    
    >>> from units.compatibility import within_epsilon
    >>> define_base_si_units()
    >>> define_time_units()
    >>> hour = unit('h')
    >>> hour.is_si()
    False
    >>> from units.quantity import Quantity
    >>> half_hour = Quantity(0.5, hour)
    >>> few_secs = Quantity(60.0, unit('s'))
    >>> sum = half_hour + few_secs
    
    >>> mins = unit('min')
    >>> thirty_one = Quantity(31, mins)
    >>> within_epsilon(thirty_one, sum)
    True
    """
    assert unit("s").is_si()  # Ensure SI units already defined.

    scaled_unit("min", "s", 60.0, name="minute")
    scaled_unit("h", "min", 60.0, name="hour")
    scaled_unit("day", "h", 24.0, symbal="d", name="day")
    scaled_unit("wk", "day", 7.0, name="week")
def test_simple_multiply_quantity():
    """Simple multiplication of quantities"""
    assert (Quantity(2, unit('m')) * 
            Quantity(2, unit('s')) ==
            Quantity(4, unit('m') * unit('s')))
            
    assert (Quantity(2, unit('s')) * 
            Quantity(2, unit('m')) ==
            Quantity(4, unit('m') * unit('s')))
Example #50
0
def test_simple_multiply_quantity():
    """Simple multiplication of quantities"""
    assert (Quantity(2, unit('m')) *
            Quantity(2, unit('s')) ==
            Quantity(4, unit('m') * unit('s')))

    assert (Quantity(2, unit('s')) *
            Quantity(2, unit('m')) ==
            Quantity(4, unit('m') * unit('s')))
Example #51
0
def stats_localize(athlete, stats):

    if athlete.measurement_preference != 'feet':
        ath_units = {
            'dist': unithelper.kilometers,
            'time': unithelper.seconds,
            'elevation': unithelper.meters,
            'speed': unithelper.kph,
            'pace': units.unit('min') / unithelper.kilometers,
        }
    else:
        ath_units = {
            'dist': unithelper.miles,
            'time': unithelper.seconds,
            'elevation': unithelper.feet,
            'speed': unithelper.mph,
            'pace': units.unit('min') / unithelper.miles
        }

    sdict = {}

    sdict_total = {}
    sdict_total['dist'] = str(ath_units['dist'](stats['total']['dist']))
    sdict_total['elevation'] = str(ath_units['elevation'](
        stats['total']['elevation']))
    sdict_total['time'] = _seconds_to_timestr(stats['total']['time'])
    sdict['total'] = sdict_total

    sdict_per_activity = {}
    sdict_per_activity['dist'] = str(ath_units['dist'](
        stats['per_activity']['dist']))
    sdict_per_activity['elevation'] = str(ath_units['elevation'](
        stats['per_activity']['elevation']))
    sdict_per_activity['time'] = _seconds_to_timestr(
        stats['per_activity']['time'])
    sdict['per_activity'] = sdict_per_activity

    sdict_per_time = {}
    sdict_per_time['speed'] = str(ath_units['speed'](
        stats['per_time']['dist']))
    sdict['per_time'] = sdict_per_time

    sdict_per_dist = {}
    sdict_per_dist['pace'] = str(ath_units['pace'](stats['per_dist']['time']))
    sdict['per_dist'] = sdict_per_dist

    return sdict
Example #52
0
def calculate(name, value, givenUnit):
	conversionDict = eval(name + '_dict')
	results = []
	for newUnit in conversionDict.values():
		convertedValue = eval(newUnit)(unit(givenUnit)(value))
		results.append(convertedValue)

	return results
Example #53
0
def test_pow():
    """Exponentiation of quantities."""
    REGISTRY.clear()
    define_units()

    m_unit = unit('m')
    m_quant = Quantity(2, m_unit)

    assert (m_quant ** 2 ==
            m_quant * m_quant ==
            pow(m_quant, 2))

    cm_unit = unit('cm')
    cm_quant = Quantity(2, cm_unit)

    assert within_epsilon(cm_quant ** 2, cm_quant * cm_quant)
    assert within_epsilon(cm_quant ** 2, pow(cm_quant, 2))
def test_good_named_sub():
    """Two quantities with the same named complex units should sub together"""
    
    furlong = unit('fur')
                
    assert (Quantity(4, furlong) -
            Quantity(2, furlong) ==
            Quantity(2, furlong))
def test_good_mixed_sub():
    """Two quantities with the same units should sub together 
    even if one is named"""
    
    gray = unit('Gy')
            
    sievert = unit('Sv').composed_unit
    
    assert(Quantity(4, gray) - 
           Quantity(2, sievert) ==
           Quantity(2, gray))
           
    assert(Quantity(4, sievert) -
           Quantity(2, gray) ==
           Quantity(2, sievert))
            
    assert(Quantity(2, sievert) == Quantity(2, gray))
Example #56
0
def test_valid_named_to_composed():
    """Named units should convert to the composed equivalents."""

    hertz = unit('Hz')
    one_hz_in_per_second = hertz.composed_unit(Quantity(1, hertz))

    assert one_hz_in_per_second == Quantity(1, hertz)
    assert str(one_hz_in_per_second) == '1.00 1 / s'
Example #57
0
def test_valid_named_to_composed():
    """Named units should convert to the composed equivalents."""
    
    hertz = unit('Hz')
    one_hz_in_per_second = hertz.composed_unit(Quantity(1, hertz))
    
    assert one_hz_in_per_second == Quantity(1, hertz)
    assert str(one_hz_in_per_second) == '1 1 / s'
Example #58
0
def test_good_add_w_mults():
    """Two quantities with compatible units should add together
    even when they have different multipliers"""

    mile = ComposedUnit([unit('m')], [], multiplier=1609.344)
    kilometre = ComposedUnit([unit('m')], [], multiplier=1000)

    m_on_left = Quantity(1, mile) + Quantity(1, kilometre)
    km_on_left = Quantity(1, kilometre) + Quantity(1, mile)
    manual_sum = Quantity(2609.344, unit('m'))

    assert within_epsilon(m_on_left, km_on_left)
    assert within_epsilon(km_on_left, m_on_left)
    assert within_epsilon(manual_sum, m_on_left)
    assert within_epsilon(manual_sum, km_on_left)
    assert within_epsilon(m_on_left, manual_sum)
    assert within_epsilon(km_on_left, manual_sum)
Example #59
0
def test_valid_composed_to_named():
    """Composed units should convert to named equivalents."""
    hertz = unit('Hz')
    per_second = hertz.composed_unit

    one_hz = hertz(Quantity(1, per_second))

    assert one_hz == Quantity(1, hertz)
    assert str(one_hz) == '1.00 Hz'