code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
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
if distance is not None:
params['distance'] = distance
raw_activity = self.protocol.post('/activities', **params)
return model.Activity.deserialize(raw_activity, bind_client=self) | def create_activity(self, name, activity_type, start_date_local, elapsed_time,
description=None, distance=None) | Create a new manual activity.
If you would like to create an activity from an uploaded GPS file, see the
:meth:`stravalib.client.Client.upload_activity` method instead.
:param name: The name of the activity.
:type name: str
:param activity_type: The activity type (case-insensitive).
Possible values: ride, run, swim, workout, hike, walk, nordicski,
alpineski, backcountryski, iceskate, inlineskate, kitesurf, rollerski,
windsurf, workout, snowboard, snowshoe
: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) | 2.419645 | 2.395284 | 1.01017 |
# Convert the kwargs into a params dict
params = {}
if name is not None:
params['name'] = name
if activity_type is not None:
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['type'] = activity_type
if private is not None:
params['private'] = int(private)
if commute is not None:
params['commute'] = int(commute)
if trainer is not None:
params['trainer'] = int(trainer)
if gear_id is not None:
params['gear_id'] = gear_id
if description is not None:
params['description'] = description
if device_name is not None:
params['device_name'] = device_name
raw_activity = self.protocol.put('/activities/{activity_id}', activity_id=activity_id, **params)
return model.Activity.deserialize(raw_activity, bind_client=self) | def update_activity(self, activity_id, name=None, activity_type=None,
private=None, commute=None, trainer=None, gear_id=None,
description=None,device_name=None) | Updates the properties of a specific activity.
http://strava.github.io/api/v3/activities/#put-updates
:param activity_id: The ID of the activity to update.
:type activity_id: int
:param name: The name of the activity.
:param activity_type: The activity type (case-insensitive).
Possible values: ride, run, swim, workout, hike,
walk, nordicski, alpineski, backcountryski,
iceskate, inlineskate, kitesurf, rollerski,
windsurf, workout, snowboard, snowshoe
:param private: Whether the activity is private.
:param commute: Whether the activity is a commute.
:param trainer: Whether this is a trainer activity.
:param gear_id: Alpha-numeric ID of gear (bike, shoes) used on this activity.
:param description: Description for the activity.
:param device_name: Device name for the activity
:return: The updated activity.
:rtype: :class:`stravalib.model.Activity` | 2.07509 | 1.937626 | 1.070945 |
if not hasattr(activity_file, 'read'):
if isinstance(activity_file, six.string_types):
activity_file = BytesIO(activity_file.encode('utf-8'))
elif isinstance(activity_file, str):
activity_file = BytesIO(activity_file)
else:
raise TypeError("Invalid type specified for activity_file: {0}".format(type(activity_file)))
valid_data_types = ('fit', 'fit.gz', 'tcx', 'tcx.gz', 'gpx', 'gpx.gz')
if not data_type in valid_data_types:
raise ValueError("Invalid data type {0}. Possible values {1!r}".format(data_type, valid_data_types))
params = {'data_type': data_type}
if name is not None:
params['name'] = name
if description is not None:
params['description'] = description
if activity_type is not None:
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['activity_type'] = activity_type
if private is not None:
params['private'] = int(private)
if external_id is not None:
params['external_id'] = external_id
initial_response = self.protocol.post('/uploads',
files={'file': activity_file},
check_for_errors=False,
**params)
return ActivityUploader(self, response=initial_response) | def upload_activity(self, activity_file, data_type, name=None, description=None,
activity_type=None, private=None, external_id=None) | Uploads a GPS file (tcx, gpx) to create a new activity for current athlete.
http://strava.github.io/api/v3/athlete/#get-details
:param activity_file: The file object to upload or file contents.
:type activity_file: file or str
:param data_type: File format for upload. Possible values: fit, fit.gz, tcx, tcx.gz, gpx, gpx.gz
:type data_type: str
:param name: (optional) if not provided, will be populated using start date and location, if available
:type name: str
:param description: (optional) The description for the activity
:type name: str
:param activity_type: (optional) case-insensitive type of activity.
possible values: ride, run, swim, workout, hike, walk,
nordicski, alpineski, backcountryski, iceskate, inlineskate,
kitesurf, rollerski, windsurf, workout, snowboard, snowshoe
Type detected from file overrides, uses athlete's default type if not specified
:type activity_type: str
:param private: (optional) set to True to mark the resulting activity as private, 'view_private' permissions will be necessary to view the activity
:type private: bool
:param external_id: (optional) An arbitrary unique identifier may be specified which will be included in status responses.
:type external_id: str | 2.122998 | 1.995545 | 1.063869 |
zones = self.protocol.get('/activities/{id}/zones', id=activity_id)
# We use a factory to give us the correct zone based on type.
return [model.BaseActivityZone.deserialize(z, bind_client=self) for z in zones] | def get_activity_zones(self, activity_id) | Gets zones for activity.
Requires premium account.
http://strava.github.io/api/v3/activities/#zones
:param activity_id: The activity for which to zones.
:type activity_id: int
:return: An list of :class:`stravalib.model.ActivityComment` objects.
:rtype: :py:class:`list` | 10.064012 | 12.072384 | 0.833639 |
result_fetcher = functools.partial(self.protocol.get, '/activities/{id}/comments',
id=activity_id, markdown=int(markdown))
return BatchedResultsIterator(entity=model.ActivityComment,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | def get_activity_comments(self, activity_id, markdown=False, limit=None) | Gets the comments for an activity.
http://strava.github.io/api/v3/comments/#list
:param activity_id: The activity for which to fetch comments.
:type activity_id: int
:param markdown: Whether to include markdown in comments (default is false/filterout).
:type markdown: bool
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.ActivityComment` objects.
:rtype: :class:`BatchedResultsIterator` | 7.464018 | 6.533318 | 1.142454 |
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/kudos',
id=activity_id)
return BatchedResultsIterator(entity=model.ActivityKudos,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | def get_activity_kudos(self, activity_id, limit=None) | Gets the kudos for an activity.
http://strava.github.io/api/v3/kudos/#list
:param activity_id: The activity for which to fetch kudos.
:type activity_id: int
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.ActivityKudos` objects.
:rtype: :class:`BatchedResultsIterator` | 6.191192 | 5.229209 | 1.183963 |
params = {}
if not only_instagram:
params['photo_sources'] = 'true'
if size is not None:
params['size'] = size
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/photos',
id=activity_id, **params)
return BatchedResultsIterator(entity=model.ActivityPhoto,
bind_client=self,
result_fetcher=result_fetcher) | def get_activity_photos(self, activity_id, size=None, only_instagram=False) | Gets the photos from an activity.
http://strava.github.io/api/v3/photos/
:param activity_id: The activity for which to fetch kudos.
:type activity_id: int
:param size: the requested size of the activity's photos. URLs for the photos will be returned that best match
the requested size. If not included, the smallest size is returned
:type size: int
:param only_instagram: Parameter to preserve legacy behavior of only returning Instagram photos.
:type only_instagram: bool
:return: An iterator of :class:`stravalib.model.ActivityPhoto` objects.
:rtype: :class:`BatchedResultsIterator` | 5.52205 | 5.057427 | 1.091869 |
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/laps',
id=activity_id)
return BatchedResultsIterator(entity=model.ActivityLap,
bind_client=self,
result_fetcher=result_fetcher) | def get_activity_laps(self, activity_id) | Gets the laps from an activity.
http://strava.github.io/api/v3/activities/#laps
:param activity_id: The activity for which to fetch laps.
:type activity_id: int
:return: An iterator of :class:`stravalib.model.ActivityLaps` objects.
:rtype: :class:`BatchedResultsIterator` | 8.405441 | 6.773012 | 1.24102 |
return model.Gear.deserialize(self.protocol.get('/gear/{id}', id=gear_id)) | def get_gear(self, gear_id) | Get details for an item of gear.
http://strava.github.io/api/v3/gear/#show
:param gear_id: The gear id.
:type gear_id: str
:return: The Bike or Shoe subclass object.
:rtype: :class:`stravalib.model.Gear` | 12.279832 | 11.971224 | 1.025779 |
return model.SegmentEffort.deserialize(self.protocol.get('/segment_efforts/{id}',
id=effort_id)) | def get_segment_effort(self, effort_id) | Return a specific segment effort by ID.
http://strava.github.io/api/v3/efforts/#retrieve
:param effort_id: The id of associated effort to fetch.
:type effort_id: int
:return: The specified effort on a segment.
:rtype: :class:`stravalib.model.SegmentEffort` | 7.990736 | 8.046786 | 0.993034 |
return model.Segment.deserialize(self.protocol.get('/segments/{id}',
id=segment_id), bind_client=self) | def get_segment(self, segment_id) | Gets a specific segment by ID.
http://strava.github.io/api/v3/segments/#retrieve
:param segment_id: The segment to fetch.
:type segment_id: int
:return: A segment object.
:rtype: :class:`stravalib.model.Segment` | 17.291857 | 16.76302 | 1.031548 |
params = {}
if limit is not None:
params["limit"] = limit
result_fetcher = functools.partial(self.protocol.get,
'/segments/starred')
return BatchedResultsIterator(entity=model.Segment,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | def get_starred_segments(self, limit=None) | Returns a summary representation of the segments starred by the
authenticated user. Pagination is supported.
http://strava.github.io/api/v3/segments/#starred
:param limit: (optional), limit number of starred segments returned.
:type limit: int
:return: An iterator of :class:`stravalib.model.Segment` starred by authenticated user.
:rtype: :class:`BatchedResultsIterator` | 6.545248 | 5.903955 | 1.108621 |
result_fetcher = functools.partial(self.protocol.get,
'/athletes/{id}/segments/starred',
id=athlete_id)
return BatchedResultsIterator(entity=model.Segment,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | def get_athlete_starred_segments(self, athlete_id, limit=None) | Returns a summary representation of the segments starred by the
specified athlete. Pagination is supported.
http://strava.github.io/api/v3/segments/#starred
:param athlete_id: The ID of the athlete.
:type athlete_id: int
:param limit: (optional), limit number of starred segments returned.
:type limit: int
:return: An iterator of :class:`stravalib.model.Segment` starred by authenticated user.
:rtype: :class:`BatchedResultsIterator` | 6.581481 | 5.621348 | 1.170801 |
params = {"segment_id": segment_id}
if athlete_id is not None:
params['athlete_id'] = athlete_id
if start_date_local:
if isinstance(start_date_local, six.string_types):
start_date_local = arrow.get(start_date_local).naive
params["start_date_local"] = start_date_local.strftime("%Y-%m-%dT%H:%M:%SZ")
if end_date_local:
if isinstance(end_date_local, six.string_types):
end_date_local = arrow.get(end_date_local).naive
params["end_date_local"] = end_date_local.strftime("%Y-%m-%dT%H:%M:%SZ")
if limit is not None:
params["limit"] = limit
result_fetcher = functools.partial(self.protocol.get,
'/segments/{segment_id}/all_efforts',
**params)
return BatchedResultsIterator(entity=model.BaseEffort, bind_client=self,
result_fetcher=result_fetcher, limit=limit) | def get_segment_efforts(self, segment_id, athlete_id=None,
start_date_local=None, end_date_local=None,
limit=None) | Gets all efforts on a particular segment sorted by start_date_local
Returns an array of segment effort summary representations sorted by
start_date_local ascending or by elapsed_time if an athlete_id is
provided.
If no filtering parameters is provided all efforts for the segment
will be returned.
Date range filtering is accomplished using an inclusive start and end time,
thus start_date_local and end_date_local must be sent together. For open
ended ranges pick dates significantly in the past or future. The
filtering is done over local time for the segment, so there is no need
for timezone conversion. For example, all efforts on Jan. 1st, 2014
for a segment in San Francisco, CA can be fetched using
2014-01-01T00:00:00Z and 2014-01-01T23:59:59Z.
http://strava.github.io/api/v3/segments/#all_efforts
:param segment_id: ID of the segment.
:type segment_id: param
:int athlete_id: (optional) ID of athlete.
:type athlete_id: int
:param start_date_local: (optional) efforts before this date will be excluded.
Either as ISO8601 or datetime object
:type start_date_local: datetime.datetime or str
:param end_date_local: (optional) efforts after this date will be excluded.
Either as ISO8601 or datetime object
:type end_date_local: datetime.datetime or str
:param limit: (optional), limit number of efforts.
:type limit: int
:return: An iterator of :class:`stravalib.model.SegmentEffort` efforts on a segment.
:rtype: :class:`BatchedResultsIterator` | 2.079779 | 1.996057 | 1.041944 |
if len(bounds) == 2:
bounds = (bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1])
elif len(bounds) != 4:
raise ValueError("Invalid bounds specified: {0!r}. Must be list of 4 float values or list of 2 (lat,lon) tuples.")
params = {'bounds': ','.join(str(b) for b in bounds)}
valid_activity_types = ('riding', 'running')
if activity_type is not None:
if activity_type not in ('riding', 'running'):
raise ValueError('Invalid activity type: {0}. Possible values: {1!r}'.format(activity_type, valid_activity_types))
params['activity_type'] = activity_type
if min_cat is not None:
params['min_cat'] = min_cat
if max_cat is not None:
params['max_cat'] = max_cat
raw = self.protocol.get('/segments/explore', **params)
return [model.SegmentExplorerResult.deserialize(v, bind_client=self)
for v in raw['segments']] | def explore_segments(self, bounds, activity_type=None, min_cat=None, max_cat=None) | Returns an array of up to 10 segments.
http://strava.github.io/api/v3/segments/#explore
:param bounds: list of bounding box corners lat/lon [sw.lat, sw.lng, ne.lat, ne.lng] (south,west,north,east)
:type bounds: list of 4 floats or list of 2 (lat,lon) tuples
:param activity_type: (optional, default is riding) 'running' or 'riding'
:type activity_type: str
:param min_cat: (optional) Minimum climb category filter
:type min_cat: int
:param max_cat: (optional) Maximum climb category filter
:type max_cat: int
:return: An list of :class:`stravalib.model.Segment`.
:rtype: :py:class:`list` | 2.690504 | 2.521873 | 1.066868 |
# stream are comma seperated list
if types is not None:
types = ",".join(types)
params = {}
if resolution is not None:
params["resolution"] = resolution
if series_type is not None:
params["series_type"] = series_type
result_fetcher = functools.partial(self.protocol.get,
'/activities/{id}/streams/{types}'.format(id=activity_id, types=types),
**params)
streams = BatchedResultsIterator(entity=model.Stream,
bind_client=self,
result_fetcher=result_fetcher)
# Pack streams into dictionary
try:
return {i.type: i for i in streams}
except exc.ObjectNotFound:
return None | def get_activity_streams(self, activity_id, types=None,
resolution=None, series_type=None) | Returns an streams for an activity.
http://strava.github.io/api/v3/streams/#activity
Streams represent the raw data of the uploaded file. External
applications may only access this information for activities owned
by the authenticated athlete.
Streams are available in 11 different types. If the stream is not
available for a particular activity it will be left out of the request
results.
Streams types are: time, latlng, distance, altitude, velocity_smooth,
heartrate, cadence, watts, temp, moving, grade_smooth
http://strava.github.io/api/v3/streams/#activity
:param activity_id: The ID of activity.
:type activity_id: int
:param types: (optional) A list of the the types of streams to fetch.
:type types: list
:param resolution: (optional, default is 'all') indicates desired number
of data points. 'low' (100), 'medium' (1000),
'high' (10000) or 'all'.
:type resolution: str
:param series_type: (optional, default is 'distance'. Relevant only if
using resolution either 'time' or 'distance'.
Used to index the streams if the stream is being
reduced.
:type series_type: str
:return: An dictionary of :class:`stravalib.model.Stream` from the activity or None if there are no streams.
:rtype: :py:class:`dict` | 4.134935 | 4.404527 | 0.938792 |
# stream are comma seperated list
if types is not None:
types = ",".join(types)
params = {}
if resolution is not None:
params["resolution"] = resolution
if series_type is not None:
params["series_type"] = series_type
result_fetcher = functools.partial(self.protocol.get,
'/segment_efforts/{id}/streams/{types}'.format(id=effort_id, types=types),
**params)
streams = BatchedResultsIterator(entity=model.Stream,
bind_client=self,
result_fetcher=result_fetcher)
# Pack streams into dictionary
return {i.type: i for i in streams} | def get_effort_streams(self, effort_id, types=None, resolution=None,
series_type=None) | Returns an streams for an effort.
http://strava.github.io/api/v3/streams/#effort
Streams represent the raw data of the uploaded file. External
applications may only access this information for activities owned
by the authenticated athlete.
Streams are available in 11 different types. If the stream is not
available for a particular activity it will be left out of the request
results.
Streams types are: time, latlng, distance, altitude, velocity_smooth,
heartrate, cadence, watts, temp, moving, grade_smooth
http://strava.github.io/api/v3/streams/#effort
:param effort_id: The ID of effort.
:type effort_id: int
:param types: (optional) A list of the the types of streams to fetch.
:type types: list
:param resolution: (optional, default is 'all') indicates desired number
of data points. 'low' (100), 'medium' (1000),
'high' (10000) or 'all'.
:type resolution: str
:param series_type: (optional, default is 'distance'. Relevant only if
using resolution either 'time' or 'distance'.
Used to index the streams if the stream is being
reduced.
:type series_type: str
:return: An dictionary of :class:`stravalib.model.Stream` from the effort.
:rtype: :py:class:`dict` | 4.214985 | 4.531703 | 0.930111 |
raw = self.protocol.get('/running_races/{id}', id=race_id)
return model.RunningRace.deserialize(raw, bind_client=self) | def get_running_race(self, race_id) | Gets a running race for a given identifier.t
http://strava.github.io/api/v3/running_races/#list
:param race_id: id for the race
:rtype: :class:`stravalib.model.RunningRace` | 8.886401 | 7.839909 | 1.133483 |
if year is None:
year = datetime.datetime.now().year
params = {"year": year}
result_fetcher = functools.partial(self.protocol.get,
'/running_races',
**params)
return BatchedResultsIterator(entity=model.RunningRace, bind_client=self,
result_fetcher=result_fetcher) | def get_running_races(self, year=None) | Gets a running races for a given year.
http://strava.github.io/api/v3/running_races/#list
:param year: year for the races (default current)
:return: An iterator of :class:`stravalib.model.RunningRace` objects.
:rtype: :class:`BatchedResultsIterator` | 6.989241 | 5.351981 | 1.305917 |
if athlete_id is None:
athlete_id = self.get_athlete().id
result_fetcher = functools.partial(self.protocol.get,
'/athletes/{id}/routes'.format(id=athlete_id))
return BatchedResultsIterator(entity=model.Route,
bind_client=self,
result_fetcher=result_fetcher,
limit=limit) | def get_routes(self, athlete_id=None, limit=None) | Gets the routes list for an authenticated user.
http://strava.github.io/api/v3/routes/#list
:param athlete_id: id for the
:param limit: Max rows to return (default unlimited).
:type limit: int
:return: An iterator of :class:`stravalib.model.Route` objects.
:rtype: :class:`BatchedResultsIterator` | 4.421844 | 4.110026 | 1.075868 |
raw = self.protocol.get('/routes/{id}', id=route_id)
return model.Route.deserialize(raw, bind_client=self) | def get_route(self, route_id) | Gets specified route.
Will be detail-level if owned by authenticated user; otherwise summary-level.
https://strava.github.io/api/v3/routes/#retreive
:param route_id: The ID of route to fetch.
:type route_id: int
:rtype: :class:`stravalib.model.Route` | 9.152076 | 9.446809 | 0.968801 |
result_fetcher = functools.partial(self.protocol.get,
'/routes/{id}/streams/'.format(id=route_id))
streams = BatchedResultsIterator(entity=model.Stream,
bind_client=self,
result_fetcher=result_fetcher)
# Pack streams into dictionary
return {i.type: i for i in streams} | def get_route_streams(self, route_id) | Returns streams for a route.
http://strava.github.io/api/v3/streams/#routes
Streams represent the raw data of the saved route. External
applications may access this information for all public routes and for
the private routes of the authenticated athlete.
The 3 available route stream types `distance`, `altitude` and `latlng`
are always returned.
http://strava.github.io/api/v3/streams/#routes
:param activity_id: The ID of activity.
:type activity_id: int
:return: A dictionary of :class:`stravalib.model.Stream`from the route.
:rtype: :py:class:`dict` | 8.429484 | 8.187093 | 1.029607 |
params = dict(client_id=client_id, client_secret=client_secret,
object_type=object_type, aspect_type=aspect_type,
callback_url=callback_url, verify_token=verify_token)
raw = self.protocol.post('/push_subscriptions', use_webhook_server=True,
**params)
return model.Subscription.deserialize(raw, bind_client=self) | def create_subscription(self, client_id, client_secret, callback_url,
object_type=model.Subscription.OBJECT_TYPE_ACTIVITY,
aspect_type=model.Subscription.ASPECT_TYPE_CREATE,
verify_token=model.Subscription.VERIFY_TOKEN_DEFAULT) | Creates a webhook event subscription.
http://strava.github.io/api/partner/v3/events/#create-a-subscription
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str
:param callback_url: callback URL where Strava will first send a GET request to validate, then subsequently send POST requests with updates
:type callback_url: str
:param object_type: object_type (currently only `activity` is supported)
:type object_type: str
:param aspect_type: object_type (currently only `create` is supported)
:type aspect_type: str
:param verify_token: a token you can use to verify Strava's GET callback request
:type verify_token: str
:return: An instance of :class:`stravalib.model.Subscription`.
:rtype: :class:`stravalib.model.Subscription`
Notes:
`object_type` and `aspect_type` are given defaults because there is currently only one valid value for each.
`verify_token` is set to a default in the event that the author doesn't want to specify one.
The appliction must have permission to make use of the webhook API. Access can be requested by contacting developers -at- strava.com. | 3.361273 | 3.87216 | 0.868062 |
callback = model.SubscriptionCallback.deserialize(raw)
callback.validate(verify_token)
response_raw = {'hub.challenge': callback.hub_challenge}
return response_raw | def handle_subscription_callback(self, raw,
verify_token=model.Subscription.VERIFY_TOKEN_DEFAULT) | Validate callback request and return valid response with challenge.
:return: The JSON response expected by Strava to the challenge request.
:rtype: Dict[str, str] | 5.222439 | 5.817089 | 0.897775 |
result_fetcher = functools.partial(self.protocol.get, '/push_subscriptions', client_id=client_id,
client_secret=client_secret, use_webhook_server=True)
return BatchedResultsIterator(entity=model.Subscription,
bind_client=self,
result_fetcher=result_fetcher) | def list_subscriptions(self, client_id, client_secret) | List current webhook event subscriptions in place for the current application.
http://strava.github.io/api/partner/v3/events/#list-push-subscriptions
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str
:return: An iterator of :class:`stravalib.model.Subscription` objects.
:rtype: :class:`BatchedResultsIterator` | 8.618741 | 6.61716 | 1.302483 |
self.protocol.delete('/push_subscriptions/{id}', id=subscription_id,
client_id=client_id, client_secret=client_secret, use_webhook_server=True) | def delete_subscription(self, subscription_id, client_id, client_secret) | Unsubscribe from webhook events for an existing subscription.
http://strava.github.io/api/partner/v3/events/#delete-a-subscription
:param subscription_id: ID of subscription to remove.
:type subscription_id: int
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtained during registration
:type client_secret: str | 7.003993 | 7.232459 | 0.968411 |
# If we cannot fetch anymore from the server then we're done here.
if self._all_results_fetched:
self._eof()
raw_results = self.result_fetcher(page=self._page, per_page=self.per_page)
entities = []
for raw in raw_results:
entities.append(self.entity.deserialize(raw, bind_client=self.bind_client))
self._buffer = collections.deque(entities)
self.log.debug("Requested page {0} (got: {1} items)".format(self._page,
len(self._buffer)))
if len(self._buffer) < self.per_page:
self._all_results_fetched = True
self._page += 1 | def _fill_buffer(self) | Fills the internal size-50 buffer from Strava API. | 4.427713 | 4.299631 | 1.029789 |
self.upload_id = response.get('id')
self.external_id = response.get('external_id')
self.activity_id = response.get('activity_id')
self.status = response.get('status') or response.get('message')
if response.get('error'):
self.error = response.get('error')
elif response.get('errors'):
# This appears to be an undocumented API; ths is a bit of a hack for now.
self.error = str(response.get('errors'))
else:
self.error = None
if raise_exc:
self.raise_for_error() | def update_from_response(self, response, raise_exc=True) | Updates internal state of object.
:param response: The response object (dict).
:type response: :py:class:`dict`
:param raise_exc: Whether to raise an exception if the response
indicates an error state. (default True)
:type raise_exc: bool
:raise stravalib.exc.ActivityUploadFailed: If the response indicates an error and raise_exc is True. | 3.030301 | 2.886174 | 1.049937 |
response = self.client.protocol.get('/uploads/{upload_id}',
upload_id=self.upload_id,
check_for_errors=False)
self.update_from_response(response) | def poll(self) | Update internal state from polling strava.com.
:raise stravalib.exc.ActivityUploadFailed: If the poll returns an error. | 7.087687 | 5.301383 | 1.336951 |
start = time.time()
while self.activity_id is None:
self.poll()
time.sleep(poll_interval)
if timeout and (time.time() - start) > timeout:
raise exc.TimeoutExceeded()
# If we got this far, we must have an activity!
return self.client.get_activity(self.activity_id) | def wait(self, timeout=None, poll_interval=1.0) | Wait for the upload to complete or to err out.
Will return the resulting Activity or raise an exception if the upload fails.
:param timeout: The max seconds to wait. Will raise TimeoutExceeded
exception if this time passes without success or error response.
:type timeout: float
:param poll_interval: How long to wait between upload checks. Strava
recommends 1s minimum. (default 1.0s)
:type poll_interval: float
:return: The uploaded Activity object (fetched from server)
:rtype: :class:`stravalib.model.Activity`
:raise stravalib.exc.TimeoutExceeded: If a timeout was specified and
activity is still processing after
timeout has elapsed.
:raise stravalib.exc.ActivityUploadFailed: If the poll returns an error. | 3.553714 | 3.148791 | 1.128597 |
try:
usage_rates = [int(v) for v in headers['X-RateLimit-Usage'].split(',')]
limit_rates = [int(v) for v in headers['X-RateLimit-Limit'].split(',')]
return RequestRate(short_usage=usage_rates[0], long_usage=usage_rates[1],
short_limit=limit_rates[0], long_limit=limit_rates[1])
except KeyError:
return None | def get_rates_from_response_headers(headers) | Returns a namedtuple with values for short - and long usage and limit rates found in provided HTTP response headers
:param headers: HTTP response headers
:type headers: dict
:return: namedtuple with request rates or None if no rate-limit headers present in response.
:rtype: Optional[RequestRate] | 2.405303 | 1.880854 | 1.278835 |
if now is None:
now = arrow.utcnow()
return 899 - (now - now.replace(minute=(now.minute // 15) * 15, second=0, microsecond=0)).seconds | def get_seconds_until_next_quarter(now=None) | Returns the number of seconds until the next quarter of an hour. This is the short-term rate limit used by Strava.
:param now: A (utc) timestamp
:type now: arrow.arrow.Arrow
:return: the number of seconds until the next quarter, as int | 3.433654 | 3.482043 | 0.986103 |
if now is None:
now = arrow.utcnow()
return (now.ceil('day') - now).seconds | def get_seconds_until_next_day(now=None) | Returns the number of seconds until the next day (utc midnight). This is the long-term rate limit used by Strava.
:param now: A (utc) timestamp
:type now: arrow.arrow.Arrow
:return: the number of seconds until next day, as int | 3.786581 | 3.867019 | 0.979199 |
if v is None:
return None
o = cls(bind_client=bind_client)
o.from_dict(v)
return o | def deserialize(cls, v, bind_client=None) | Creates a new object based on serialized (dict) struct. | 3.10192 | 2.679616 | 1.157599 |
if self._members is None:
self.assert_bind_client()
self._members = self.bind_client.get_club_members(self.id)
return self._members | def members(self) | An iterator of :class:`stravalib.model.Athlete` members of this club. | 5.435192 | 3.634064 | 1.495624 |
if self._activities is None:
self.assert_bind_client()
self._activities = self.bind_client.get_club_activities(self.id)
return self._activities | def activities(self) | An iterator of reverse-chronological :class:`stravalib.model.Activity` activities for this club. | 5.380942 | 3.692949 | 1.457086 |
if v is None:
return None
if cls == Gear and v.get('resource_state') == 3:
if 'frame_type' in v:
o = Bike()
else:
o = Shoe()
else:
o = cls()
o.from_dict(v)
return o | def deserialize(cls, v) | Creates a new object based on serialized (dict) struct. | 5.392874 | 4.945109 | 1.090547 |
if self._is_authenticated is None:
if self.resource_state == DETAILED:
# If the athlete is in detailed state it must be the authenticated athlete
self._is_authenticated = True
else:
# We need to check this athlete's id matches the authenticated athlete's id
self.assert_bind_client()
authenticated_athlete = self.bind_client.get_athlete()
self._is_authenticated = authenticated_athlete.id == self.id
return self._is_authenticated | def is_authenticated_athlete(self) | :return: Boolean as to whether the athlete is the authenticated athlete. | 4.370085 | 3.892509 | 1.122691 |
if self._friends is None:
self.assert_bind_client()
if self.friend_count > 0:
self._friends = self.bind_client.get_athlete_friends(self.id)
else:
# Shortcut if we know there aren't any
self._friends = []
return self._friends | def friends(self) | :return: Iterator of :class:`stravalib.model.Athlete` friend objects for this athlete. | 5.240615 | 3.788292 | 1.383371 |
if self._followers is None:
self.assert_bind_client()
if self.follower_count > 0:
self._followers = self.bind_client.get_athlete_followers(self.id)
else:
# Shortcut if we know there aren't any
self._followers = []
return self._followers | def followers(self) | :return: Iterator of :class:`stravalib.model.Athlete` followers objects for this athlete. | 5.054235 | 3.703151 | 1.364847 |
if not self.is_authenticated_athlete():
raise exc.NotAuthenticatedAthlete("Statistics are only available for the authenticated athlete")
if self._stats is None:
self.assert_bind_client()
self._stats = self.bind_client.get_athlete_stats(self.id)
return self._stats | def stats(self) | :return: Associated :class:`stravalib.model.AthleteStats` | 5.920742 | 4.244499 | 1.394921 |
if self._segment is None:
self.assert_bind_client()
if self.id is not None:
self._segment = self.bind_client.get_segment(self.id)
return self._segment | def segment(self) | Associated (full) :class:`stravalib.model.Segment` object. | 4.120099 | 3.282878 | 1.255027 |
if self._leaderboard is None:
self.assert_bind_client()
if self.id is not None:
self._leaderboard = self.bind_client.get_segment_leaderboard(self.id)
return self._leaderboard | def leaderboard(self) | The :class:`stravalib.model.SegmentLeaderboard` object for this segment. | 4.740958 | 2.920479 | 1.623349 |
if self._comments is None:
self.assert_bind_client()
if self.comment_count > 0:
self._comments = self.bind_client.get_activity_comments(self.id)
else:
# Shortcut if we know there aren't any
self._comments = []
return self._comments | def comments(self) | Iterator of :class:`stravalib.model.ActivityComment` objects for this activity. | 4.714332 | 3.592322 | 1.312336 |
if self._zones is None:
self.assert_bind_client()
self._zones = self.bind_client.get_activity_zones(self.id)
return self._zones | def zones(self) | :class:`list` of :class:`stravalib.model.ActivityZone` objects for this activity. | 5.715449 | 3.527222 | 1.620383 |
if self._kudos is None:
self.assert_bind_client()
self._kudos = self.bind_client.get_activity_kudos(self.id)
return self._kudos | def kudos(self) | :class:`list` of :class:`stravalib.model.ActivityKudos` objects for this activity. | 4.026 | 2.867346 | 1.404086 |
if self._photos is None:
if self.total_photo_count > 0:
self.assert_bind_client()
self._photos = self.bind_client.get_activity_photos(self.id, only_instagram=False)
else:
self._photos = []
return self._photos | def full_photos(self) | Gets a list of photos using default options.
:class:`list` of :class:`stravalib.model.ActivityPhoto` objects for this activity. | 5.0937 | 3.920494 | 1.299249 |
if self._related is None:
if self.athlete_count - 1 > 0:
self.assert_bind_client()
self._related = self.bind_client.get_related_activities(self.id)
else:
self._related = []
return self._related | def related(self) | Iterator of :class:`stravalib.model.Activty` objects for activities matched as
with this activity. | 4.618784 | 3.923967 | 1.17707 |
if v is None:
return None
az_classes = {'heartrate': HeartrateActivityZone,
'power': PowerActivityZone,
'pace': PaceActivityZone}
try:
clazz = az_classes[v['type']]
except KeyError:
raise ValueError("Unsupported activity zone type: {0}".format(v['type']))
else:
o = clazz(bind_client=bind_client)
o.from_dict(v)
return o | def deserialize(cls, v, bind_client=None) | Creates a new object based on serialized (dict) struct. | 3.367313 | 3.384277 | 0.994987 |
key = self.make_key(key)
if self.debug:
return default
try:
value = self.database[key]
except KeyError:
self.metrics['misses'] += 1
return default
else:
self.metrics['hits'] += 1
return pickle.loads(value) | def get(self, key, default=None) | Retreive a value from the cache. In the event the value
does not exist, return the ``default``. | 3.168453 | 3.073276 | 1.030969 |
key = self.make_key(key)
if timeout is None:
timeout = self.default_timeout
if self.debug:
return True
pickled_value = pickle.dumps(value)
self.metrics['writes'] += 1
if timeout:
return self.database.setex(key, int(timeout), pickled_value)
else:
return self.database.set(key, pickled_value) | def set(self, key, value, timeout=None) | Cache the given ``value`` in the specified ``key``. If no
timeout is specified, the default timeout will be used. | 2.953779 | 3.043469 | 0.97053 |
if not self.debug:
self.database.delete(self.make_key(key)) | def delete(self, key) | Remove the given key from the cache. | 7.059404 | 6.093403 | 1.158532 |
keys = list(self.keys())
if keys:
return self.database.delete(*keys) | def flush(self) | Remove all cached objects from the database. | 8.384835 | 6.723493 | 1.247095 |
def decorator(fn):
def make_key(args, kwargs):
return '%s:%s' % (fn.__name__, key_fn(args, kwargs))
def bust(*args, **kwargs):
return self.delete(make_key(args, kwargs))
_metrics = {
'hits': 0,
'misses': 0,
'avg_hit_time': 0,
'avg_miss_time': 0}
@wraps(fn)
def inner(*args, **kwargs):
start = time.time()
is_cache_hit = True
key = make_key(args, kwargs)
res = self.get(key)
if res is None:
res = fn(*args, **kwargs)
self.set(key, res, timeout)
is_cache_hit = False
if metrics:
dur = time.time() - start
if is_cache_hit:
_metrics['hits'] += 1
_metrics['avg_hit_time'] += (dur / _metrics['hits'])
else:
_metrics['misses'] += 1
_metrics['avg_miss_time'] += (dur / _metrics['misses'])
return res
inner.bust = bust
inner.make_key = make_key
if metrics:
inner.metrics = _metrics
return inner
return decorator | def cached(self, key_fn=_key_fn, timeout=None, metrics=False) | Decorator that will transparently cache calls to the
wrapped function. By default, the cache key will be made
up of the arguments passed in (like memoize), but you can
override this by specifying a custom ``key_fn``.
:param key_fn: Function used to generate a key from the
given args and kwargs.
:param timeout: Time to cache return values.
:param metrics: Keep stats on cache utilization and timing.
:returns: Return the result of the decorated function
call with the given args and kwargs.
Usage::
cache = Cache(my_database)
@cache.cached(timeout=60)
def add_numbers(a, b):
return a + b
print add_numbers(3, 4) # Function is called.
print add_numbers(3, 4) # Not called, value is cached.
add_numbers.bust(3, 4) # Clear cache for (3, 4).
print add_numbers(3, 4) # Function is called.
The decorated function also gains a new attribute named
``bust`` which will clear the cache for the given args. | 1.77044 | 1.869456 | 0.947035 |
this = self
class _cached_property(object):
def __init__(self, fn):
self._fn = this.cached(key_fn, timeout)(fn)
def __get__(self, instance, instance_type=None):
if instance is None:
return self
return self._fn(instance)
def __delete__(self, obj):
self._fn.bust(obj)
def __set__(self, instance, value):
raise ValueError('Cannot set value of a cached property.')
def decorator(fn):
return _cached_property(fn)
return decorator | def cached_property(self, key_fn=_key_fn, timeout=None) | Decorator that will transparently cache calls to the wrapped
method. The method will be exposed as a property.
Usage::
cache = Cache(my_database)
class Clock(object):
@cache.cached_property()
def now(self):
return datetime.datetime.now()
clock = Clock()
print clock.now | 2.743067 | 3.595673 | 0.76288 |
def decorator(fn):
wrapped = self.cached(key_fn, timeout)(fn)
@wraps(fn)
def inner(*args, **kwargs):
q = Queue()
def _sub_fn():
q.put(wrapped(*args, **kwargs))
def _get_value(block=True, timeout=None):
if not hasattr(_get_value, '_return_value'):
result = q.get(block=block, timeout=timeout)
_get_value._return_value = result
return _get_value._return_value
thread = threading.Thread(target=_sub_fn)
thread.start()
return _get_value
return inner
return decorator | def cache_async(self, key_fn=_key_fn, timeout=3600) | Decorator that will execute the cached function in a separate
thread. The function will immediately return, returning a
callable to the user. This callable can be used to check for
a return value.
For details, see the :ref:`cache-async` section of the docs.
:param key_fn: Function used to generate cache key.
:param int timeout: Cache timeout in seconds.
:returns: A new function which can be called to retrieve the
return value of the decorated function. | 2.547853 | 2.799237 | 0.910196 |
if title is None:
title = obj_id
if data is None:
data = title
obj_type = obj_type or ''
if self._use_json:
data = json.dumps(data)
combined_id = self.object_key(obj_id, obj_type)
if self.exists(obj_id, obj_type):
stored_title = self._title_data[combined_id]
if stored_title == title:
self._data[combined_id] = data
return
else:
self.remove(obj_id, obj_type)
self._data[combined_id] = data
self._title_data[combined_id] = title
clean_title = ' '.join(self.tokenize_title(title))
title_score = self.score_token(clean_title)
for idx, word in enumerate(self.tokenize_title(title)):
word_score = self.score_token(word)
position_score = word_score + (self._offset * idx)
key_score = position_score + title_score
for substring in self.substrings(word):
self.database.zadd(self.word_key(substring),
{combined_id: key_score})
return True | def store(self, obj_id, title=None, data=None, obj_type=None) | Store data in the autocomplete index.
:param obj_id: Either a unique identifier for the object
being indexed or the word/phrase to be indexed.
:param title: The word or phrase to be indexed. If not
provided, the ``obj_id`` will be used as the title.
:param data: Arbitrary data to index, which will be
returned when searching for results. If not provided,
this value will default to the title being indexed.
:param obj_type: Optional object type. Since results can be
boosted by type, you might find it useful to specify this
when storing multiple types of objects.
You have the option of storing several types of data as
defined by the parameters. At the minimum, you can specify
an ``obj_id``, which will be the word or phrase you wish to
index. Alternatively, if for instance you were indexing blog
posts, you might specify all parameters. | 3.003971 | 2.99651 | 1.00249 |
if not self.exists(obj_id, obj_type):
raise KeyError('Object not found.')
combined_id = self.object_key(obj_id, obj_type)
title = self._title_data[combined_id]
for word in self.tokenize_title(title):
for substring in self.substrings(word):
key = self.word_key(substring)
if not self.database.zrange(key, 1, 2):
self.database.delete(key)
else:
self.database.zrem(key, combined_id)
del self._data[combined_id]
del self._title_data[combined_id]
del self._boosts[combined_id] | def remove(self, obj_id, obj_type=None) | Remove an object identified by the given ``obj_id`` (and
optionally ``obj_type``) from the search index.
:param obj_id: The object's unique identifier.
:param obj_type: The object's type. | 3.479975 | 3.534642 | 0.984534 |
return self.object_key(obj_id, obj_type) in self._data | def exists(self, obj_id, obj_type=None) | Return whether the given object exists in the search index.
:param obj_id: The object's unique identifier.
:param obj_type: The object's type. | 6.284723 | 11.329367 | 0.554729 |
combined_id = self.object_key(obj_id or '', obj_type or '')
if relative:
current = float(self._boosts[combined_id] or 1.0)
self._boosts[combined_id] = current * multiplier
else:
self._boosts[combined_id] = multiplier | def boost_object(self, obj_id=None, obj_type=None, multiplier=1.1,
relative=True) | Boost search results for the given object or type by the
amount specified. When the ``multiplier`` is greater than
1, the results will percolate to the top. Values between
0 and 1 will percolate results to the bottom.
Either an ``obj_id`` or ``obj_type`` (or both) must be
specified.
:param obj_id: An object's unique identifier (optional).
:param obj_type: The object's type (optional).
:param multiplier: A positive floating-point number.
:param relative: If ``True``, then any pre-existing saved
boost will be updated using the given multiplier.
Examples:
.. code-block:: python
# Make all objects of type=photos percolate to top.
ac.boost_object(obj_type='photo', multiplier=2.0)
# Boost a particularly popular blog entry.
ac.boost_object(
popular_entry.id,
'entry',
multipler=5.0,
relative=False) | 3.06595 | 4.122432 | 0.743724 |
cleaned = self.tokenize_title(phrase, stopwords=False)
if not cleaned:
return
all_boosts = self._load_saved_boosts()
if PY3 and boosts:
for key in boosts:
all_boosts[encode(key)] = boosts[key]
elif boosts:
all_boosts.update(boosts)
if len(cleaned) == 1 and not all_boosts:
result_key = self.word_key(cleaned[0])
else:
result_key = self.get_cache_key(cleaned, all_boosts)
if result_key not in self.database:
self.database.zinterstore(
result_key,
list(map(self.word_key, cleaned)))
self.database.expire(result_key, self._cache_timeout)
results = self.database.ZSet(result_key)
if all_boosts:
for raw_id, score in results[0:0, True]:
orig_score = score
for identifier in raw_id.split(encode('\x01'), 1):
if identifier and identifier in all_boosts:
score *= 1 / all_boosts[identifier]
if orig_score != score:
results[raw_id] = score
for result in self._load_objects(results, limit, chunk_size):
yield result | def search(self, phrase, limit=None, boosts=None, chunk_size=1000) | Perform a search for the given phrase. Objects whose title
matches the search will be returned. The values returned
will be whatever you specified as the ``data`` parameter
when you called :py:meth:`~Autocomplete.store`.
:param phrase: One or more words or substrings.
:param int limit: Limit size of the result set.
:param dict boosts: A mapping of object id/object type to
floating point multipliers.
:returns: A list containing the object data for objects
matching the search phrase. | 3.96351 | 4.001085 | 0.990609 |
fn = (lambda v: json.loads(decode(v))) if self._use_json else decode
return map(fn, self._data.values()) | def list_data(self) | Return all the data stored in the autocomplete index. If the data was
stored as serialized JSON, then it will be de-serialized before being
returned.
:rtype: list | 8.94228 | 8.674795 | 1.030835 |
keys = self.database.keys(self.namespace + ':*')
for i in range(0, len(keys), batch_size):
self.database.delete(*keys[i:i + batch_size]) | def flush(self, batch_size=1000) | Delete all autocomplete indexes and metadata. | 3.21373 | 2.858917 | 1.124108 |
key = 'doc.%s.%s' % (self.name, decode(document_id))
return decode_dict(self.db.hgetall(key)) | def get_document(self, document_id) | :param document_id: Document unique identifier.
:returns: a dictionary containing the document content and
any associated metadata. | 6.15591 | 8.358623 | 0.736474 |
self.members.add(key)
document_hash = self._get_hash(key)
document_hash.update(content=content, **metadata)
for word, score in self.tokenizer.tokenize(content).items():
word_key = self.get_key(word)
word_key[key] = -score | def add(self, key, content, **metadata) | :param key: Document unique identifier.
:param str content: Content to store and index for search.
:param metadata: Arbitrary key/value pairs to store for document.
Add a document to the search index. | 6.536847 | 6.930731 | 0.943168 |
if self.members.remove(key) != 1:
raise KeyError('Document with key "%s" not found.' % key)
document_hash = self._get_hash(key)
content = decode(document_hash['content'])
if not preserve_data:
document_hash.clear()
for word in self.tokenizer.tokenize(content):
word_key = self.get_key(word)
del word_key[key]
if len(word_key) == 0:
word_key.clear() | def remove(self, key, preserve_data=False) | :param key: Document unique identifier.
Remove the document from the search index. | 4.197263 | 3.9526 | 1.061899 |
self.remove(key, preserve_data=True)
self.add(key, content, **metadata) | def update(self, key, content, **metadata) | :param key: Document unique identifier.
:param str content: Content to store and index for search.
:param metadata: Arbitrary key/value pairs to store for document.
Update the given document. Existing metadata will be preserved and,
optionally, updated with the provided metadata. | 5.208948 | 6.952234 | 0.749248 |
self.remove(key)
self.add(key, content, **metadata) | def replace(self, key, content, **metadata) | :param key: Document unique identifier.
:param str content: Content to store and index for search.
:param metadata: Arbitrary key/value pairs to store for document.
Update the given document. Existing metadata will not be removed and
replaced with the provided metadata. | 4.212604 | 4.851114 | 0.868379 |
return [self.get_document(key) for key, _ in self._search(query)] | def search(self, query) | :param str query: Search query. May contain boolean/set operations
and parentheses.
:returns: a list of document hashes corresponding to matching
documents.
Search the index. The return value is a list of dictionaries
corresponding to the documents that matched. These dictionaries contain
a ``content`` key with the original indexed content, along with any
additional metadata that was specified. | 6.721484 | 8.58967 | 0.782508 |
stemmer = PorterStemmer()
_stem = stemmer.stem
for word in words:
yield _stem(word, 0, len(word) - 1) | def stem(self, words) | Use the porter stemmer to generate consistent forms of
words, e.g.::
from walrus.search.utils import PorterStemmer
stemmer = PorterStemmer()
for word in ['faith', 'faiths', 'faithful']:
print s.stem(word, 0, len(word) - 1)
# Prints:
# faith
# faith
# faith | 3.159904 | 2.647381 | 1.193596 |
for word in words:
r = 0
for w in double_metaphone(word):
if w:
w = w.strip()
if w:
r += 1
yield w
if not r:
yield word | def metaphone(self, words) | Apply the double metaphone algorithm to the given words.
Using metaphone allows the search index to tolerate
misspellings and small typos.
Example::
>>> from walrus.search.metaphone import dm as metaphone
>>> print metaphone('walrus')
('ALRS', 'FLRS')
>>> print metaphone('python')
('P0N', 'PTN')
>>> print metaphone('pithonn')
('P0N', 'PTN') | 4.336816 | 4.95193 | 0.875783 |
words = self.split_phrase(decode(value).lower())
if self._stopwords:
words = [w for w in words if w not in self._stopwords]
if self._min_word_length:
words = [w for w in words if len(w) >= self._min_word_length]
fraction = 1. / (len(words) + 1) # Prevent division by zero.
# Apply optional transformations.
if self._use_stemmer:
words = self.stem(words)
if self._use_metaphone:
words = self.metaphone(words)
scores = {}
for word in words:
scores.setdefault(word, 0)
scores[word] += fraction
return scores | def tokenize(self, value) | Split the incoming value into tokens and process each token,
optionally stemming or running metaphone.
:returns: A ``dict`` mapping token to score. The score is
based on the relative frequency of the word in the
document. | 2.887065 | 2.683195 | 1.07598 |
if search_query:
expr = Entry.content.search(search_query)
else:
expr = None
query = Entry.query(expr, order_by=Entry.timestamp.desc())
for entry in query:
timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p')
print(timestamp)
print('=' * len(timestamp))
print(entry.content)
print('n) next entry')
print('d) delete entry')
print('q) return to main menu')
choice = raw_input('Choice? (Ndq) ').lower().strip()
if choice == 'q':
break
elif choice == 'd':
entry.delete()
print('Entry deleted successfully.')
break | def view_entries(search_query=None) | View previous entries | 3.088771 | 3.117307 | 0.990846 |
if ttl is not None:
self.database.expire(self.key, ttl)
else:
self.database.persist(self.key) | def expire(self, ttl=None) | Expire the given key in the given number of seconds.
If ``ttl`` is ``None``, then any expiry will be cleared
and key will be persisted. | 2.865896 | 3.208265 | 0.893285 |
if ttl is not None:
self.database.pexpire(self.key, ttl)
else:
self.database.persist(self.key) | def pexpire(self, ttl=None) | Expire the given key in the given number of milliseconds.
If ``ttl`` is ``None``, then any expiry will be cleared
and key will be persisted. | 2.952317 | 3.519322 | 0.838888 |
return self._scan(match=pattern, count=count) | def search(self, pattern, count=None) | Search the keys of the given hash using the specified pattern.
:param str pattern: Pattern used to match keys.
:param int count: Limit number of results returned.
:returns: An iterator yielding matching key/value pairs. | 14.308758 | 15.963847 | 0.896323 |
if args:
self.database.hmset(self.key, *args)
else:
self.database.hmset(self.key, kwargs) | def update(self, *args, **kwargs) | Update the hash using the given dictionary or key/value pairs. | 3.996363 | 3.008665 | 1.328284 |
return self.database.hincrby(self.key, key, incr_by) | def incr(self, key, incr_by=1) | Increment the key by the given amount. | 4.506447 | 4.488548 | 1.003988 |
return self.database.hincrbyfloat(self.key, key, incr_by) | def incr_float(self, key, incr_by=1.) | Increment the key by the given amount. | 4.736065 | 4.379116 | 1.081512 |
res = self.database.hgetall(self.key)
return decode_dict(res) if decode else res | def as_dict(self, decode=False) | Return a dictionary containing all the key/value pairs in the
hash. | 6.242192 | 5.161972 | 1.209265 |
hsh = cls(database, key)
if clear:
hsh.clear()
hsh.update(data)
return hsh | def from_dict(cls, database, key, data, clear=False) | Create and populate a Hash object from a data dictionary. | 3.442043 | 2.739794 | 1.256315 |
ret = self.database.blpop(self.key, timeout)
if ret is not None:
return ret[1] | def bpopleft(self, timeout=0) | Remove the first item from the list, blocking until an item becomes
available or timeout is reached (0 for no timeout, default). | 4.614307 | 4.190265 | 1.101197 |
ret = self.database.blpop(self.key, timeout)
if ret is not None:
return ret[1] | def bpopright(self, timeout=0) | Remove the last item from the list, blocking until an item becomes
available or timeout is reached (0 for no timeout, default). | 4.53592 | 4.213148 | 1.076611 |
items = self.database.lrange(self.key, 0, -1)
return [_decode(item) for item in items] if decode else items | def as_list(self, decode=False) | Return a list containing all the items in the list. | 4.491571 | 3.80861 | 1.17932 |
lst = cls(database, key)
if clear:
lst.clear()
lst.extend(data)
return lst | def from_list(cls, database, key, data, clear=False) | Create and populate a List object from a data list. | 3.222316 | 2.979189 | 1.081608 |
keys = [self.key]
keys.extend([other.key for other in others])
self.database.sdiffstore(dest, keys)
return self.database.Set(dest) | def diffstore(self, dest, *others) | Store the set difference of the current set and one or more
others in a new key.
:param dest: the name of the key to store set difference
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``. | 5.10078 | 5.885095 | 0.866729 |
keys = [self.key]
keys.extend([other.key for other in others])
self.database.sinterstore(dest, keys)
return self.database.Set(dest) | def interstore(self, dest, *others) | Store the intersection of the current set and one or more
others in a new key.
:param dest: the name of the key to store intersection
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``. | 4.951336 | 5.835682 | 0.848459 |
keys = [self.key]
keys.extend([other.key for other in others])
self.database.sunionstore(dest, keys)
return self.database.Set(dest) | def unionstore(self, dest, *others) | Store the union of the current set and one or more
others in a new key.
:param dest: the name of the key to store union
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``. | 5.140438 | 6.050323 | 0.849614 |
items = self.database.smembers(self.key)
return set(_decode(item) for item in items) if decode else items | def as_set(self, decode=False) | Return a Python set containing all the items in the collection. | 5.943567 | 4.857215 | 1.223657 |
s = cls(database, key)
if clear:
s.clear()
s.add(*data)
return s | def from_set(cls, database, key, data, clear=False) | Create and populate a Set object from a data set. | 3.342077 | 3.005019 | 1.112165 |
if _mapping is not None:
_mapping.update(kwargs)
mapping = _mapping
else:
mapping = _mapping
return self.database.zadd(self.key, mapping) | def add(self, _mapping=None, **kwargs) | Add the given item/score pairs to the ZSet. Arguments are
specified as ``item1, score1, item2, score2...``. | 3.806282 | 3.594431 | 1.058939 |
fn = reverse and self.database.zrevrank or self.database.zrank
return fn(self.key, item) | def rank(self, item, reverse=False) | Return the rank of the given item. | 6.156884 | 5.617603 | 1.095998 |
if high is None:
high = low
return self.database.zcount(self.key, low, high) | def count(self, low, high=None) | Return the number of items between the given bounds. | 4.414515 | 3.677171 | 1.200519 |
return self.database.zlexcount(self.key, low, high) | def lex_count(self, low, high) | Count the number of members in a sorted set between a given
lexicographical range. | 7.138125 | 5.998083 | 1.190068 |
if reverse:
return self.database.zrevrange(self.key, low, high, with_scores)
else:
return self.database.zrange(self.key, low, high, desc, with_scores) | def range(self, low, high, with_scores=False, desc=False, reverse=False) | Return a range of items between ``low`` and ``high``. By
default scores will not be included, but this can be controlled
via the ``with_scores`` parameter.
:param low: Lower bound.
:param high: Upper bound.
:param bool with_scores: Whether the range should include the
scores along with the items.
:param bool desc: Whether to sort the results descendingly.
:param bool reverse: Whether to select the range in reverse. | 2.380279 | 2.929911 | 0.812406 |
if reverse:
fn = self.database.zrevrangebylex
low, high = high, low
else:
fn = self.database.zrangebylex
return fn(self.key, low, high, start, num) | def range_by_lex(self, low, high, start=None, num=None, reverse=False) | Return a range of members in a sorted set, by lexicographical range. | 3.048012 | 2.685772 | 1.134874 |
if high is None:
high = low
return self.database.zremrangebyrank(self.key, low, high) | def remove_by_rank(self, low, high=None) | Remove elements from the ZSet by their rank (relative position).
:param low: Lower bound.
:param high: Upper bound. | 3.895818 | 4.148646 | 0.939058 |
if high is None:
high = low
return self.database.zremrangebyscore(self.key, low, high) | def remove_by_score(self, low, high=None) | Remove elements from the ZSet by their score.
:param low: Lower bound.
:param high: Upper bound. | 3.890885 | 4.489084 | 0.866744 |
return self.database.zincrby(self.key, incr_by, key) | def incr(self, key, incr_by=1.) | Increment the score of an item in the ZSet.
:param key: Item to increment.
:param incr_by: Amount to increment item's score. | 6.573302 | 8.370766 | 0.785269 |
keys = [self.key]
keys.extend([other.key for other in others])
self.database.zinterstore(dest, keys, **kwargs)
return self.database.ZSet(dest) | def interstore(self, dest, *others, **kwargs) | Store the intersection of the current zset and one or more
others in a new key.
:param dest: the name of the key to store intersection
:param others: One or more :py:class:`ZSet` instances
:returns: A :py:class:`ZSet` referencing ``dest``. | 3.617196 | 4.243474 | 0.852414 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.