How to use the stravalib.unithelper function in stravalib

To help you get started, weโ€™ve selected a few stravalib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github freezingsaddles / freezing-web / freezing / web / views / general.py View on Github external
uh.timedelta_to_seconds(timedelta(seconds=int(rain_res["moving_time"]))) / 3600
    )

    q = text(
        """
                select count(*) as num_rides, coalesce(sum(R.moving_time),0) as moving_time
                from rides R
                join ride_weather W on W.ride_id = R.id
                where W.ride_snow = 1
                ;
            """
    )

    snow_res = meta.scoped_session().execute(q).fetchone()  # @UndefinedVariable
    snow_hours = (
        uh.timedelta_to_seconds(timedelta(seconds=int(snow_res["moving_time"]))) / 3600
    )

    # Grab some recent photos
    photos = (
        meta.scoped_session()
        .query(RidePhoto)
        .join(Ride)
        .order_by(Ride.start_date.desc())
        .limit(11)
    )

    return render_template(
        "index.html",
        team_count=len(config.COMPETITION_TEAMS),
        contestant_count=contestant_count,
        total_rides=total_rides,
github hozn / stravalib / stravalib / client.py View on Github external
:type activity_type: str

        :param start_date_local: Local date/time of activity start. (TZ info will be ignored)
        :type start_date_local: :class:`datetime.datetime` or string in ISO8601 format.

        :param elapsed_time: The time in seconds or a :class:`datetime.timedelta` object.
        :type elapsed_time: :class:`datetime.timedelta` or int (seconds)

        :param description: The description for the activity.
        :type description: str

        :param distance: The distance in meters (float) or a :class:`units.quantity.Quantity` instance.
        :type distance: :class:`units.quantity.Quantity` or float (meters)
        """
        if isinstance(elapsed_time, timedelta):
            elapsed_time = unithelper.timedelta_to_seconds(elapsed_time)

        if isinstance(distance, Quantity):
            distance = float(unithelper.meters(distance))

        if isinstance(start_date_local, datetime):
            start_date_local = start_date_local.strftime("%Y-%m-%dT%H:%M:%SZ")

        if not activity_type.lower() in [t.lower() for t in model.Activity.TYPES]:
            raise ValueError("Invalid activity type: {0}.  Possible values: {1!r}".format(activity_type, model.Activity.TYPES))

        params = dict(name=name, type=activity_type, start_date_local=start_date_local,
                      elapsed_time=elapsed_time)

        if description is not None:
            params['description'] = description
github freezingsaddles / freezing-web / freezing / web / data.py View on Github external
:type ride: Ride
    """
    # Should apply to both new and preexisting rides ...
    # If there are multiple instagram photos, then request syncing of non-primary photos too.

    if strava_activity.photo_count > 1 and ride.photos_fetched is None:

        log.debug("Scheduling non-primary photos sync for {!r}".format(ride))
        ride.photos_fetched = False

    ride.private = bool(strava_activity.private)
    ride.name = strava_activity.name
    ride.start_date = strava_activity.start_date_local

    # We need to round so that "1.0" miles in strava is "1.0" miles when we convert back from meters.
    ride.distance = round(float(unithelper.miles(strava_activity.distance)), 3)

    ride.average_speed = float(unithelper.mph(strava_activity.average_speed))
    ride.maximum_speed = float(unithelper.mph(strava_activity.max_speed))
    ride.elapsed_time = timedelta_to_seconds(strava_activity.elapsed_time)
    ride.moving_time = timedelta_to_seconds(strava_activity.moving_time)

    location_parts = []
    if strava_activity.location_city:
        location_parts.append(strava_activity.location_city)
    if strava_activity.location_state:
        location_parts.append(strava_activity.location_state)
    location_str = ", ".join(location_parts)

    ride.location = location_str

    ride.commute = strava_activity.commute
github hozn / stravalib / stravalib / model.py View on Github external
start_date = TimestampAttribute((SUMMARY, DETAILED))
    start_date_local = TimestampAttribute((SUMMARY, DETAILED))
    is_kom = Attribute(bool, (SUMMARY, DETAILED))

class Segment(LoadableEntity):
    """
    Represents a single Strava segment.
    """
    _leaderboard = None

    name = Attribute(six.text_type, (SUMMARY, DETAILED))  #: Name of the segment.
    activity_type = Attribute(six.text_type, (SUMMARY, DETAILED))  #: Activity type of segment ('Ride' or 'Run')
    distance = Attribute(float, (SUMMARY, DETAILED), units=uh.meters)  #: Distance of segment
    average_grade = Attribute(float, (SUMMARY, DETAILED))  #: Average grade (%) for segment
    maximum_grade = Attribute(float, (SUMMARY, DETAILED))  #: Maximum grade (%) for segment
    elevation_high = Attribute(float, (SUMMARY, DETAILED), units=uh.meters)  #: The highest point of the segment.
    elevation_low = Attribute(float, (SUMMARY, DETAILED), units=uh.meters)  #: The lowest point of the segment.
    start_latlng = LocationAttribute((SUMMARY, DETAILED))  #: The start lat/lon (:class:`tuple`)
    end_latlng = LocationAttribute((SUMMARY, DETAILED))  #: The end lat/lon (:class:`tuple`)
    start_latitude = Attribute(float, (SUMMARY, DETAILED))  #: The start latitude (:class:`float`)
    end_latitude = Attribute(float, (SUMMARY, DETAILED))  #: The end latitude (:class:`float`)
    start_longitude = Attribute(float, (SUMMARY, DETAILED))  #: The start longitude (:class:`float`)

    end_longitude = Attribute(float, (SUMMARY, DETAILED))  #: The end longitude (:class:`float`)
    climb_category = Attribute(int, (SUMMARY, DETAILED))  # 0-5, lower is harder
    city = Attribute(six.text_type, (SUMMARY, DETAILED))  #: The city this segment is in.
    state = Attribute(six.text_type, (SUMMARY, DETAILED))  #: The state this segment is in.
    country = Attribute(six.text_type, (SUMMARY, DETAILED))  #: The country this segment is in.
    private = Attribute(bool, (SUMMARY, DETAILED))  #: Whether this is a private segment.
    starred = Attribute(bool, (SUMMARY, DETAILED))  #: Whether this segment is starred by authenticated athlete

    athlete_segment_stats = EntityAttribute(AthleteSegmentStats, (DETAILED,)) #: Undocumented attrib holding stats for current athlete.
github magsol / pybot / examples / artbot.py View on Github external
current = datetime.datetime.now()
        last_week = current + datetime.timedelta(weeks = -1)
        after = datetime.datetime(last_week.year, last_week.month, last_week.day)
        activities = self.client.get_activities(after = after)

        # Second, filter by activity type and time frame.
        lf = [a for a in activities if a.start_date_local.day != current.day]
        num_activities = len(lf)
        l = [a.id for a in lf if a.type == 'Run']

        # Third, tabulate up the stats for mileage and calories.
        mileage = 0.0
        calories = 0.0
        for activity_id in l:
            activity = self.client.get_activity(activity_id)
            distance = unithelper.miles(activity.distance)
            mileage += round(distance.num, 2)  # Rounds to 2 sig figs.
            calories += activity.calories
        calories = int(calories)

        # Finally, use the stats to craft a tweet. This can be any format
        # you want, but I'll use the example one from the start of the post.
        tweet = "My training last week: {:d} workouts for {:.2f} miles and {:d} calories burned.".format(num_activities, mileage, calories)
        self.update_status(tweet)
github freezingsaddles / freezing-web / freezing / web / views / api.py View on Github external
indiv_count_res = meta.scoped_session().execute(q).fetchone()  # @UndefinedVariable
    contestant_count = indiv_count_res["num_contestants"]

    q = text(
        """
                select count(*) as num_rides, coalesce(sum(R.moving_time),0) as moving_time,
                  coalesce(sum(R.distance),0) as distance
                from rides R
                ;
            """
    )

    all_res = meta.scoped_session().execute(q).fetchone()  # @UndefinedVariable
    total_miles = int(all_res["distance"])
    total_hours = (
        uh.timedelta_to_seconds(timedelta(seconds=int(all_res["moving_time"]))) / 3600
    )
    total_rides = all_res["num_rides"]

    q = text(
        """
                select count(*) as num_rides, coalesce(sum(R.moving_time),0) as moving_time
                from rides R
                join ride_weather W on W.ride_id = R.id
                where W.ride_temp_avg < 32
                ;
            """
    )

    sub32_res = meta.scoped_session().execute(q).fetchone()  # @UndefinedVariable
    sub_freezing_hours = (
        uh.timedelta_to_seconds(timedelta(seconds=int(sub32_res["moving_time"]))) / 3600
github freezingsaddles / freezing-web / freezing / web / data.py View on Github external
ride.elapsed_time = timedelta_to_seconds(strava_activity.elapsed_time)
    ride.moving_time = timedelta_to_seconds(strava_activity.moving_time)

    location_parts = []
    if strava_activity.location_city:
        location_parts.append(strava_activity.location_city)
    if strava_activity.location_state:
        location_parts.append(strava_activity.location_state)
    location_str = ", ".join(location_parts)

    ride.location = location_str

    ride.commute = strava_activity.commute
    ride.trainer = strava_activity.trainer
    ride.manual = strava_activity.manual
    ride.elevation_gain = float(unithelper.feet(strava_activity.total_elevation_gain))
    ride.timezone = str(strava_activity.timezone)

    # # Short-circuit things that might result in more obscure db errors later.
    if ride.elapsed_time is None:
        raise DataEntryError("Activities cannot have null elapsed time.")

    if ride.moving_time is None:
        raise DataEntryError("Activities cannot have null moving time.")

    if ride.distance is None:
        raise DataEntryError("Activities cannot have null distance.")

    log.debug(
        'Writing ride for {athlete!r}: "{ride!r}" on {date}'.format(
            athlete=ride.athlete.name,
            ride=ride.name,
github freezingsaddles / freezing-web / freezing / web / data.py View on Github external
# Should apply to both new and preexisting rides ...
    # If there are multiple instagram photos, then request syncing of non-primary photos too.

    if strava_activity.photo_count > 1 and ride.photos_fetched is None:

        log.debug("Scheduling non-primary photos sync for {!r}".format(ride))
        ride.photos_fetched = False

    ride.private = bool(strava_activity.private)
    ride.name = strava_activity.name
    ride.start_date = strava_activity.start_date_local

    # We need to round so that "1.0" miles in strava is "1.0" miles when we convert back from meters.
    ride.distance = round(float(unithelper.miles(strava_activity.distance)), 3)

    ride.average_speed = float(unithelper.mph(strava_activity.average_speed))
    ride.maximum_speed = float(unithelper.mph(strava_activity.max_speed))
    ride.elapsed_time = timedelta_to_seconds(strava_activity.elapsed_time)
    ride.moving_time = timedelta_to_seconds(strava_activity.moving_time)

    location_parts = []
    if strava_activity.location_city:
        location_parts.append(strava_activity.location_city)
    if strava_activity.location_state:
        location_parts.append(strava_activity.location_state)
    location_str = ", ".join(location_parts)

    ride.location = location_str

    ride.commute = strava_activity.commute
    ride.trainer = strava_activity.trainer
    ride.manual = strava_activity.manual
github freezingsaddles / freezing-web / freezing / web / views / api.py View on Github external
uh.timedelta_to_seconds(timedelta(seconds=int(rain_res["moving_time"]))) / 3600
    )

    q = text(
        """
                select count(*) as num_rides, coalesce(sum(R.moving_time),0) as moving_time
                from rides R
                join ride_weather W on W.ride_id = R.id
                where W.ride_snow = 1
                ;
            """
    )

    snow_res = meta.scoped_session().execute(q).fetchone()  # @UndefinedVariable
    snow_hours = (
        uh.timedelta_to_seconds(timedelta(seconds=int(snow_res["moving_time"]))) / 3600
    )

    return jsonify(
        team_count=len(config.COMPETITION_TEAMS),
        contestant_count=contestant_count,
        total_rides=total_rides,
        total_hours=total_hours,
        total_miles=total_miles,
        rain_hours=rain_hours,
        snow_hours=snow_hours,
        sub_freezing_hours=sub_freezing_hours,
    )
github hozn / stravalib / stravalib / model.py View on Github external
class PaceActivityZone(BaseActivityZone):
    """
    Activity zone for pace.
    """
    score = Attribute(int, (SUMMARY, DETAILED))  #: The score for this zone.
    sample_race_distance = Attribute(int, (SUMMARY, DETAILED), units=uh.meters)  #: (Not sure?)
    sample_race_time = TimeIntervalAttribute((SUMMARY, DETAILED))  #: (Not sure?)


class PowerActivityZone(BaseActivityZone):
    """
    Activity zone for power.
    """
    # these 2 below were removed according to June 3, 2014 update @
    #    http://strava.github.io/api/v3/changelog/
    bike_weight = Attribute(float, (SUMMARY, DETAILED), units=uh.kgs)  #: Weight of bike being used (factored into power calculations)
    athlete_weight = Attribute(float, (SUMMARY, DETAILED), units=uh.kgs)  #: Weight of athlete (factored into power calculations)


class Stream(LoadableEntity):
    """
    Stream of readings from the activity, effort or segment.
    """
    type = Attribute(six.text_type)
    data = Attribute(list)  #: array of values
    series_type = Attribute(six.text_type)  #: type of stream: time, latlng, distance, altitude, velocity_smooth, heartrate, cadence, watts, temp, moving, grade_smooth
    original_size = Attribute(int)  #: the size of the complete stream (when not reduced with resolution)
    resolution = Attribute(six.text_type)  #: (optional, default is 'all') the desired number of data points. 'low' (100), 'medium' (1000), 'high' (10000) or 'all'

    def __repr__(self):
        return ''.format(self.type,
                                                                        self.resolution,