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...
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-insensi...
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 t...
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)....
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: ...
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:...
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:`lis...
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, ...
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 ...
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...
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:`stravali...
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', ...
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 ...
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, ...
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, ...
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:`...
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=se...
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 segme...
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["sta...
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 ...
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) f...
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: (opti...
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...
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 diffe...
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...
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...
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 BatchedR...
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, ...
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: :cl...
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, ...
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...
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, ...
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 clien...
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...
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, obtai...
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 ...
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.en...
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') ...
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 straval...
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.c...
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 timeou...
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_lim...
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 ...
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 ...
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 = [] ...
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...
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 = [] r...
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(...
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.load...
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), ...
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...
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 gi...
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 ...
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.da...
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=Non...
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: Funct...
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): ...
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: Arbitrar...
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): ...
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 specif...
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.u...
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...
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.toke...
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 di...
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: #...
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') ...
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) # Preven...
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(timestam...
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 ...
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