INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Sort the items of this collection according to the optional callable * key *. If * reverse * is set then the sort order is reversed.
def sort(self, key=None, reverse=False): """ Sort the items of this collection according to the optional callable *key*. If *reverse* is set then the sort order is reversed. .. note:: This sort requires all items to be retrieved from Redis and stored in memory. ...
Add * value * to the right side of the collection.
def append(self, value): """Add *value* to the right side of the collection.""" def append_trans(pipe): self._append_helper(value, pipe) self._transaction(append_trans)
Add * value * to the left side of the collection.
def appendleft(self, value): """Add *value* to the left side of the collection.""" def appendleft_trans(pipe): self._appendleft_helper(value, pipe) self._transaction(appendleft_trans)
Return a new collection with the same items as this one. If * key * is specified create the new collection with the given Redis key.
def copy(self, key=None): """ Return a new collection with the same items as this one. If *key* is specified, create the new collection with the given Redis key. """ other = self.__class__( self.__iter__(), self.maxlen, redis=self.redis...
Extend the right side of the the collection by appending values from the iterable * other *.
def extend(self, other): """ Extend the right side of the the collection by appending values from the iterable *other*. """ def extend_trans(pipe): values = list(other.__iter__(pipe)) if use_redis else other for v in values: self._append_he...
Extend the left side of the the collection by appending values from the iterable * other *. Note that the appends will reverse the order of the given values.
def extendleft(self, other): """ Extend the left side of the the collection by appending values from the iterable *other*. Note that the appends will reverse the order of the given values. """ def extendleft_trans(pipe): values = list(other.__iter__(pipe)) if ...
Insert * value * into the collection at * index *. If the insertion would the collection to grow beyond maxlen raise IndexError.
def insert(self, index, value): """ Insert *value* into the collection at *index*. If the insertion would the collection to grow beyond ``maxlen``, raise ``IndexError``. """ def insert_trans(pipe): len_self = self.__len__(pipe) if (self.maxlen is n...
Rotate the deque n steps to the right. If n is negative rotate to the left.
def rotate(self, n=1): """ Rotate the deque n steps to the right. If n is negative, rotate to the left. """ # No work to do for a 0-step rotate if n == 0: return def rotate_trans(pipe): # Synchronize the cache before rotating i...
Builds a dict with keys of entity kinds if and values are another dict. Each of these dicts are keyed off of a super entity id and optional have an all key for any group that has a null super entity. Example structure: { entity_kind_id: { entity1_id: [ 1 2 3 ] entity2_id: [ 4 5 6 ] all: [ 1 2 3 4 5 6 ] } }
def get_entities_by_kind(membership_cache=None, is_active=True): """ Builds a dict with keys of entity kinds if and values are another dict. Each of these dicts are keyed off of a super entity id and optional have an 'all' key for any group that has a null super entity. Example structure: { ...
Given a list of super entities return the entities that have those as a subset of their super entities.
def is_sub_to_all(self, *super_entities): """ Given a list of super entities, return the entities that have those as a subset of their super entities. """ if super_entities: if len(super_entities) == 1: # Optimize for the case of just one super entity since th...
Given a list of super entities return the entities that have super entities that interset with those provided.
def is_sub_to_any(self, *super_entities): """ Given a list of super entities, return the entities that have super entities that interset with those provided. """ if super_entities: return self.filter(id__in=EntityRelationship.objects.filter( super_entity__in=s...
Each returned entity will have superentites whos combined entity_kinds included * super_entity_kinds
def is_sub_to_all_kinds(self, *super_entity_kinds): """ Each returned entity will have superentites whos combined entity_kinds included *super_entity_kinds """ if super_entity_kinds: if len(super_entity_kinds) == 1: # Optimize for the case of just one ...
Find all entities that have super_entities of any of the specified kinds
def is_sub_to_any_kind(self, *super_entity_kinds): """ Find all entities that have super_entities of any of the specified kinds """ if super_entity_kinds: # get the pks of the desired subs from the relationships table if len(super_entity_kinds) == 1: ...
Caches the super and sub relationships by doing a prefetch_related.
def cache_relationships(self, cache_super=True, cache_sub=True): """ Caches the super and sub relationships by doing a prefetch_related. """ relationships_to_cache = compress( ['super_relationships__super_entity', 'sub_relationships__sub_entity'], [cache_super, cache_sub]) ...
Given a saved entity model object return the associated entity.
def get_for_obj(self, entity_model_obj): """ Given a saved entity model object, return the associated entity. """ return self.get(entity_type=ContentType.objects.get_for_model( entity_model_obj, for_concrete_model=False), entity_id=entity_model_obj.id)
Delete the entities associated with a model object.
def delete_for_obj(self, entity_model_obj): """ Delete the entities associated with a model object. """ return self.filter( entity_type=ContentType.objects.get_for_model( entity_model_obj, for_concrete_model=False), entity_id=entity_model_obj.id).delete( ...
Caches the super and sub relationships by doing a prefetch_related.
def cache_relationships(self, cache_super=True, cache_sub=True): """ Caches the super and sub relationships by doing a prefetch_related. """ return self.get_queryset().cache_relationships(cache_super=cache_super, cache_sub=cache_sub)
Build a dict cache with the group membership info. Keyed off the group id and the values are a 2 element list of entity id and entity kind id ( same values as the membership model ). If no group ids are passed then all groups will be fetched
def get_membership_cache(self, group_ids=None, is_active=True): """ Build a dict cache with the group membership info. Keyed off the group id and the values are a 2 element list of entity id and entity kind id (same values as the membership model). If no group ids are passed, then all gr...
Return all the entities in the group.
def all_entities(self, is_active=True): """ Return all the entities in the group. Because groups can contain both individual entities, as well as whole groups of entities, this method acts as a convenient way to get a queryset of all the entities in the group. """ ...
Returns a list of all entity ids in this group or optionally returns a queryset for all entity models. In order to reduce queries for multiple group lookups it is expected that the membership_cache and entities_by_kind are built outside of this method and passed in as arguments.: param membership_cache: A group cache d...
def get_all_entities(self, membership_cache=None, entities_by_kind=None, return_models=False, is_active=True): """ Returns a list of all entity ids in this group or optionally returns a queryset for all entity models. In order to reduce queries for multiple group lookups, it is expected that the...
Add an entity or sub - entity group to this EntityGroup.
def add_entity(self, entity, sub_entity_kind=None): """ Add an entity, or sub-entity group to this EntityGroup. :type entity: Entity :param entity: The entity to add. :type sub_entity_kind: Optional EntityKind :param sub_entity_kind: If a sub_entity_kind is given, all ...
Add many entities and sub - entity groups to this EntityGroup.
def bulk_add_entities(self, entities_and_kinds): """ Add many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-kind pairs to add to the group. In the pairs th...
Remove an entity or sub - entity group to this EntityGroup.
def remove_entity(self, entity, sub_entity_kind=None): """ Remove an entity, or sub-entity group to this EntityGroup. :type entity: Entity :param entity: The entity to remove. :type sub_entity_kind: Optional EntityKind :param sub_entity_kind: If a sub_entity_kind is giv...
Remove many entities and sub - entity groups to this EntityGroup.
def bulk_remove_entities(self, entities_and_kinds): """ Remove many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-kind pairs to remove from the group. In t...
Update the group to the given entities and sub - entity groups.
def bulk_overwrite(self, entities_and_kinds): """ Update the group to the given entities and sub-entity groups. After this operation, the only members of this EntityGroup will be the given entities, and sub-entity groups. :type entities_and_kinds: List of (Entity, EntityKind) p...
A copy of spectator. core. models. SluggedModelMixin. _generate_slug ()
def generate_slug(value): "A copy of spectator.core.models.SluggedModelMixin._generate_slug()" alphabet = 'abcdefghijkmnopqrstuvwxyz23456789' salt = 'Django Spectator' if hasattr(settings, 'SPECTATOR_SLUG_ALPHABET'): alphabet = settings.SPECTATOR_SLUG_ALPHABET if hasattr(settings, 'SPECTAT...
Create a slug for each Work already in the DB.
def set_slug(apps, schema_editor, class_name): """ Create a slug for each Work already in the DB. """ Cls = apps.get_model('spectator_events', class_name) for obj in Cls.objects.all(): obj.slug = generate_slug(obj.pk) obj.save(update_fields=['slug'])
e. g. Gig or Movie.
def kind_name(self): "e.g. 'Gig' or 'Movie'." return {k:v for (k,v) in self.KIND_CHOICES}[self.kind]
e. g. Gigs or Movies.
def get_kind_name_plural(kind): "e.g. 'Gigs' or 'Movies'." if kind in ['comedy', 'cinema', 'dance', 'theatre']: return kind.title() elif kind == 'museum': return 'Galleries/Museums' else: return '{}s'.format(Event.get_kind_name(kind))
Returns a dict of all the data about the kinds keyed to the kind value. e. g: { gig: { name: Gig slug: gigs name_plural: Gigs } # etc }
def get_kinds_data(): """ Returns a dict of all the data about the kinds, keyed to the kind value. e.g: { 'gig': { 'name': 'Gig', 'slug': 'gigs', 'name_plural': 'Gigs', }, # et...
Get the list URL for this Work. You can also pass a kind_slug in ( e. g. movies ) and it will use that instead of the Work s kind_slug. ( Why? Useful in views. Or tests of views at least. )
def get_list_url(self, kind_slug=None): """ Get the list URL for this Work. You can also pass a kind_slug in (e.g. 'movies') and it will use that instead of the Work's kind_slug. (Why? Useful in views. Or tests of views, at least.) """ if kind_slug is None: ...
Convert descriptor and rows to Pandas
def convert_descriptor_and_rows(self, descriptor, rows): """Convert descriptor and rows to Pandas """ # Prepare primary_key = None schema = tableschema.Schema(descriptor) if len(schema.primary_key) == 1: primary_key = schema.primary_key[0] elif len(sc...
Convert type to Pandas
def convert_type(self, type): """Convert type to Pandas """ # Mapping mapping = { 'any': np.dtype('O'), 'array': np.dtype(list), 'boolean': np.dtype(bool), 'date': np.dtype('O'), 'datetime': np.dtype('datetime64[ns]'), ...
Restore descriptor from Pandas
def restore_descriptor(self, dataframe): """Restore descriptor from Pandas """ # Prepare fields = [] primary_key = None # Primary key if dataframe.index.name: field_type = self.restore_type(dataframe.index.dtype) field = { ...
Restore row from Pandas
def restore_row(self, row, schema, pk): """Restore row from Pandas """ result = [] for field in schema.fields: if schema.primary_key and schema.primary_key[0] == field.name: if field.type == 'number' and np.isnan(pk): pk = None ...
Restore type from Pandas
def restore_type(self, dtype, sample=None): """Restore type from Pandas """ # Pandas types if pdc.is_bool_dtype(dtype): return 'boolean' elif pdc.is_datetime64_any_dtype(dtype): return 'datetime' elif pdc.is_integer_dtype(dtype): retur...
If the user has permission to change obj show a link to its Admin page. obj -- An object like Movie Play ClassicalWork Publication etc. perms -- The perms object that it s the template.
def change_object_link_card(obj, perms): """ If the user has permission to change `obj`, show a link to its Admin page. obj -- An object like Movie, Play, ClassicalWork, Publication, etc. perms -- The `perms` object that it's the template. """ # eg: 'movie' or 'classicalwork': name = obj.__c...
Returns an HTML link to the supplied URL but only using the domain as the text. Strips www. from the start of the domain if present.
def domain_urlize(value): """ Returns an HTML link to the supplied URL, but only using the domain as the text. Strips 'www.' from the start of the domain, if present. e.g. if `my_url` is 'http://www.example.org/foo/' then: {{ my_url|domain_urlize }} returns: <a href="http://www.ex...
Returns the name of the current URL namespaced or False.
def current_url_name(context): """ Returns the name of the current URL, namespaced, or False. Example usage: {% current_url_name as url_name %} <a href="#"{% if url_name == 'myapp:home' %} class="active"{% endif %}">Home</a> """ url_name = False if context.request.resolver_ma...
For adding/ replacing a key = value pair to the GET string for a URL.
def query_string(context, key, value): """ For adding/replacing a key=value pair to the GET string for a URL. eg, if we're viewing ?p=3 and we do {% query_string order 'taken' %} then this returns "p=3&order=taken" And, if we're viewing ?p=3&order=uploaded and we do the same thing, we get the ...
Displays a card showing the Creators who have the most Readings associated with their Publications.
def most_read_creators_card(num=10): """ Displays a card showing the Creators who have the most Readings associated with their Publications. In spectator_core tags, rather than spectator_reading so it can still be used on core pages, even if spectator_reading isn't installed. """ if spectat...
Displays a card showing the Venues that have the most Events.
def most_visited_venues_card(num=10): """ Displays a card showing the Venues that have the most Events. In spectator_core tags, rather than spectator_events so it can still be used on core pages, even if spectator_events isn't installed. """ if spectator_apps.is_enabled('events'): obje...
Handy for templates.
def has_urls(self): "Handy for templates." if self.isbn_uk or self.isbn_us or self.official_url or self.notes_url: return True else: return False
eg get_entity ( spectator version ) returns __version__ value in __init__. py.
def get_entity(package, entity): """ eg, get_entity('spectator', 'version') returns `__version__` value in `__init__.py`. """ init_py = open(os.path.join(package, '__init__.py')).read() find = "__%s__ = ['\"]([^'\"]+)['\"]" % entity return re.search(find, init_py).group(1)
Reduce the number of queries and speed things up.
def get_queryset(self): "Reduce the number of queries and speed things up." qs = super().get_queryset() qs = qs.select_related('publication__series') \ .prefetch_related('publication__roles__creator') return qs
Create a slug for each Creator already in the DB.
def set_slug(apps, schema_editor): """ Create a slug for each Creator already in the DB. """ Creator = apps.get_model('spectator_core', 'Creator') for c in Creator.objects.all(): c.slug = generate_slug(c.pk) c.save(update_fields=['slug'])
Copy the ClassicalWork and DancePiece data to use the new through models.
def forwards(apps, schema_editor): """ Copy the ClassicalWork and DancePiece data to use the new through models. """ Event = apps.get_model('spectator_events', 'Event') ClassicalWorkSelection = apps.get_model( 'spectator_events', 'ClassicalWorkSelection') DancePie...
Set the venue_name field of all Events that have a Venue.
def forwards(apps, schema_editor): """ Set the venue_name field of all Events that have a Venue. """ Event = apps.get_model('spectator_events', 'Event') for event in Event.objects.all(): if event.venue is not None: event.venue_name = event.venue.name event.save()
Migrate all exhibition Events to the new museum Event kind.
def forwards(apps, schema_editor): """ Migrate all 'exhibition' Events to the new 'museum' Event kind. """ Event = apps.get_model('spectator_events', 'Event') for ev in Event.objects.filter(kind='exhibition'): ev.kind = 'museum' ev.save()
Truncate a string to a certain length removing line breaks and mutliple spaces optionally removing HTML and appending a truncate string.
def truncate_string(text, strip_html=True, chars=255, truncate='…', at_word_boundary=False): """Truncate a string to a certain length, removing line breaks and mutliple spaces, optionally removing HTML, and appending a 'truncate' string. Keyword arguments: strip_html -- boolean. chars -- Number of ...
Given a QuerySet it will go through and add a chart_position property to each object returning a list of the objects.
def chartify(qs, score_field, cutoff=0, ensure_chartiness=True): """ Given a QuerySet it will go through and add a `chart_position` property to each object returning a list of the objects. If adjacent objects have the same 'score' (based on `score_field`) then they will have the same `chart_positio...
Gets Venues in order of how many Events have been held there. Adds a num_visits field to each one.
def by_visits(self, event_kind=None): """ Gets Venues in order of how many Events have been held there. Adds a `num_visits` field to each one. event_kind filters by kind of Event, e.g. 'theatre', 'cinema', etc. """ qs = self.get_queryset() if event_kind is not N...
Gets Works in order of how many times they ve been attached to Events.
def by_views(self, kind=None): """ Gets Works in order of how many times they've been attached to Events. kind is the kind of Work, e.g. 'play', 'movie', etc. """ qs = self.get_queryset() if kind is not None: qs = qs.filter(kind=kind) qs = q...
Make a naturalized version of a general string not a person s name. e. g. title of a book a band s name etc.
def naturalize_thing(self, string): """ Make a naturalized version of a general string, not a person's name. e.g., title of a book, a band's name, etc. string -- a lowercase string. """ # Things we want to move to the back of the string: articles = [ ...
Attempt to make a version of the string that has the surname if any at the start.
def naturalize_person(self, string): """ Attempt to make a version of the string that has the surname, if any, at the start. 'John, Brown' to 'Brown, John' 'Sir John Brown Jr' to 'Brown, Sir John Jr' 'Prince' to 'Prince' string -- The string to change. "...
Makes any integers into very zero - padded numbers. e. g. 1 becomes 00000001.
def _naturalize_numbers(self, string): """ Makes any integers into very zero-padded numbers. e.g. '1' becomes '00000001'. """ def naturalize_int_match(match): return '%08d' % (int(match.group(0)),) string = re.sub(r'\d+', naturalize_int_match, string) ...
Returns a list of dicts one per year of reading. In year order. Each dict is like this ( if kind is all ):
def annual_reading_counts(kind='all'): """ Returns a list of dicts, one per year of reading. In year order. Each dict is like this (if kind is 'all'): {'year': datetime.date(2003, 1, 1), 'book': 12, # only included if kind is 'all' or 'book' 'periodical': 18, ...
Returns a list of tuples like:
def lookups(self, request, model_admin): """ Returns a list of tuples like: [ ('AU', 'Australia'), ('GB', 'UK'), ('US', 'USA'), ] One for each country that has at least one Venue. Sorted by the label names. ...
Returns the filtered queryset based on the value provided in the query string and retrievable via self. value ().
def queryset(self, request, queryset): """ Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`. """ if self.value(): return queryset.filter(country=self.value()) else: return quer...
Copying data from the old Event. movie and Event. play ForeignKey fields into the new Event. movies and Event. plays ManyToManyFields.
def forward(apps, schema_editor): """ Copying data from the old `Event.movie` and `Event.play` ForeignKey fields into the new `Event.movies` and `Event.plays` ManyToManyFields. """ Event = apps.get_model('spectator_events', 'Event') MovieSelection = apps.get_model('spectator_events', 'MovieSele...
Create a slug for each Event already in the DB.
def set_slug(apps, schema_editor): """ Create a slug for each Event already in the DB. """ Event = apps.get_model('spectator_events', 'Event') for e in Event.objects.all(): e.slug = generate_slug(e.pk) e.save(update_fields=['slug'])
Return a standard Page instance with custom digg - specific page ranges attached.
def page(self, number, *args, **kwargs): """Return a standard ``Page`` instance with custom, digg-specific page ranges attached. """ page = super().page(number, *args, **kwargs) number = int(number) # we know this will work # easier access num_pages, body, tail,...
Get the version number without importing the mrcfile package.
def version(): """Get the version number without importing the mrcfile package.""" namespace = {} with open(os.path.join('mrcfile', 'version.py')) as f: exec(f.read(), namespace) return namespace['__version__']
Returns a dict like: { counts: { all: 30 movie: 12 gig: 10 }}
def get_event_counts(self): """ Returns a dict like: {'counts': { 'all': 30, 'movie': 12, 'gig': 10, }} """ counts = {'all': Event.objects.count(),} for k,v in Event.KIND_CHOICES: # e.g. 'movie_c...
Unless we re on the front page we ll have a kind_slug like movies. We need to translate that into an event kind like movie.
def get_event_kind(self): """ Unless we're on the front page we'll have a kind_slug like 'movies'. We need to translate that into an event `kind` like 'movie'. """ slug = self.kwargs.get('kind_slug', None) if slug is None: return None # Front page; showing al...
Restrict to a single kind of event if any and include Venue data.
def get_queryset(self): "Restrict to a single kind of event, if any, and include Venue data." qs = super().get_queryset() kind = self.get_event_kind() if kind is not None: qs = qs.filter(kind=kind) qs = qs.select_related('venue') return qs
We ll have a kind_slug like movies. We need to translate that into a work kind like movie.
def get_work_kind(self): """ We'll have a kind_slug like 'movies'. We need to translate that into a work `kind` like 'movie'. """ slugs_to_kinds = {v:k for k,v in Work.KIND_SLUGS.items()} return slugs_to_kinds.get(self.kind_slug, None)
Returns a list of dicts one per country that has at least one Venue in it.
def get_countries(self): """ Returns a list of dicts, one per country that has at least one Venue in it. Each dict has 'code' and 'name' elements. The list is sorted by the country 'name's. """ qs = Venue.objects.values('country') \ ...
Re - save all the Works because something earlier didn t create their slugs.
def forwards(apps, schema_editor): """ Re-save all the Works because something earlier didn't create their slugs. """ Work = apps.get_model('spectator_events', 'Work') for work in Work.objects.all(): if not work.slug: work.slug = generate_slug(work.pk) work.save()
Returns a QuerySet of dicts each one with these keys:
def annual_event_counts(kind='all'): """ Returns a QuerySet of dicts, each one with these keys: * year - a date object representing the year * total - the number of events of `kind` that year kind - The Event `kind`, or 'all' for all kinds (default). """ qs = Event.objects if ...
Displays years and the number of events per year.
def annual_event_counts_card(kind='all', current_year=None): """ Displays years and the number of events per year. kind is an Event kind (like 'cinema', 'gig', etc.) or 'all' (default). current_year is an optional date object representing the year we're already showing information about. ""...
Render a date/ datetime ( d ) as a date using the SPECTATOR_DATE_FORMAT setting. Wrap the output in a <time > tag.
def display_date(d): """ Render a date/datetime (d) as a date, using the SPECTATOR_DATE_FORMAT setting. Wrap the output in a <time> tag. Time tags: http://www.brucelawson.co.uk/2012/best-of-time/ """ stamp = d.strftime('%Y-%m-%d') visible_date = d.strftime(app_settings.DATE_FORMAT) ret...
Displays the tabs to different event_list pages.
def event_list_tabs(counts, current_kind, page_number=1): """ Displays the tabs to different event_list pages. `counts` is a dict of number of events for each kind, like: {'all': 30, 'gig': 12, 'movie': 18,} `current_kind` is the event kind that's active, if any. e.g. 'gig', 'movie', e...
Displays Events that happened on the supplied date. date is a date object.
def day_events_card(date): """ Displays Events that happened on the supplied date. `date` is a date object. """ d = date.strftime(app_settings.DATE_FORMAT) card_title = 'Events on {}'.format(d) return { 'card_title': card_title, 'event_list': day_events(date=date), ...
Displays a card showing the Creators that are associated with the most Events.
def most_seen_creators_card(event_kind=None, num=10): """ Displays a card showing the Creators that are associated with the most Events. """ object_list = most_seen_creators(event_kind=event_kind, num=num) object_list = chartify(object_list, 'num_events', cutoff=1) return { 'card_title...
Returns a QuerySet of the Creators that are associated with the most Works.
def most_seen_creators_by_works(work_kind=None, role_name=None, num=10): """ Returns a QuerySet of the Creators that are associated with the most Works. """ return Creator.objects.by_works(kind=work_kind, role_name=role_name)[:num]
Displays a card showing the Creators that are associated with the most Works.
def most_seen_creators_by_works_card(work_kind=None, role_name=None, num=10): """ Displays a card showing the Creators that are associated with the most Works. e.g.: {% most_seen_creators_by_works_card work_kind='movie' role_name='Director' num=5 %} """ object_list = most_seen_creators_by_wo...
Displays a card showing the Works that are associated with the most Events.
def most_seen_works_card(kind=None, num=10): """ Displays a card showing the Works that are associated with the most Events. """ object_list = most_seen_works(kind=kind, num=num) object_list = chartify(object_list, 'num_views', cutoff=1) if kind: card_title = 'Most seen {}'.format( ...
Generates a slug using a Hashid of value.
def _generate_slug(self, value): """ Generates a slug using a Hashid of `value`. """ alphabet = app_settings.SLUG_ALPHABET salt = app_settings.SLUG_SALT hashids = Hashids(alphabet=alphabet, salt=salt, min_length=5) return hashids.encode(value)
https:// github. com/ frictionlessdata/ tableschema - pandas - py#storage
def create(self, bucket, descriptor, force=False): """https://github.com/frictionlessdata/tableschema-pandas-py#storage """ # Make lists buckets = bucket if isinstance(bucket, six.string_types): buckets = [bucket] descriptors = descriptor if isinstanc...
https:// github. com/ frictionlessdata/ tableschema - pandas - py#storage
def delete(self, bucket=None, ignore=False): """https://github.com/frictionlessdata/tableschema-pandas-py#storage """ # Make lists buckets = bucket if isinstance(bucket, six.string_types): buckets = [bucket] elif bucket is None: buckets = reversed...
https:// github. com/ frictionlessdata/ tableschema - pandas - py#storage
def describe(self, bucket, descriptor=None): """https://github.com/frictionlessdata/tableschema-pandas-py#storage """ # Set descriptor if descriptor is not None: self.__descriptors[bucket] = descriptor # Get descriptor else: descriptor = self.__d...
https:// github. com/ frictionlessdata/ tableschema - pandas - py#storage
def iter(self, bucket): """https://github.com/frictionlessdata/tableschema-pandas-py#storage """ # Check existense if bucket not in self.buckets: message = 'Bucket "%s" doesn\'t exist.' % bucket raise tableschema.exceptions.StorageError(message) # Prepar...
https:// github. com/ frictionlessdata/ tableschema - pandas - py#storage
def write(self, bucket, rows): """https://github.com/frictionlessdata/tableschema-pandas-py#storage """ # Prepare descriptor = self.describe(bucket) new_data_frame = self.__mapper.convert_descriptor_and_rows(descriptor, rows) # Just set new DataFrame if current is empty...
Change all Movie objects into Work objects and their associated data into WorkRole and WorkSelection models then delete the Movie.
def forwards(apps, schema_editor): """ Change all Movie objects into Work objects, and their associated data into WorkRole and WorkSelection models, then delete the Movie. """ Movie = apps.get_model('spectator_events', 'Movie') Work = apps.get_model('spectator_events', 'Work') WorkRole = app...
Paginate the queryset if needed.
def paginate_queryset(self, queryset, page_size): """ Paginate the queryset, if needed. This is EXACTLY the same as the standard ListView.paginate_queryset() except for this line: page = paginator.page(page_number, softlimit=True) Because we want to use the DiggPagin...
Displays years and the number of books/ periodicals read per year.
def annual_reading_counts_card(kind='all', current_year=None): """ Displays years and the number of books/periodicals read per year. kind is one of 'book', 'periodical', 'all' (default). current_year is an optional date object representing the year we're already showing information about. "...
Returns a QuerySet of Publications that were being read on date. date is a date tobject.
def day_publications(date): """ Returns a QuerySet of Publications that were being read on `date`. `date` is a date tobject. """ readings = Reading.objects \ .filter(start_date__lte=date) \ .filter( Q(end_date__gte=date) ...
Displays Publications that were being read on date. date is a date tobject.
def day_publications_card(date): """ Displays Publications that were being read on `date`. `date` is a date tobject. """ d = date.strftime(app_settings.DATE_FORMAT) card_title = 'Reading on {}'.format(d) return { 'card_title': card_title, 'publication_list': day_publi...
Given a Reading with start and end dates and granularities [ 1 ] it returns an HTML string representing that period. eg:
def reading_dates(reading): """ Given a Reading, with start and end dates and granularities[1] it returns an HTML string representing that period. eg: * '1–6 Feb 2017' * '1 Feb to 3 Mar 2017' * 'Feb 2017 to Mar 2018' * '2017–2018' etc. [1] https://www.flickr.com/ser...
Change Events with kind movie to cinema and Events with kind play to theatre.
def forwards(apps, schema_editor): """ Change Events with kind 'movie' to 'cinema' and Events with kind 'play' to 'theatre'. Purely for more consistency. """ Event = apps.get_model('spectator_events', 'Event') for ev in Event.objects.filter(kind='movie'): ev.kind = 'cinema' ...
Get the environment variable or return exception.
def get_env_variable(var_name, default=None): """Get the environment variable or return exception.""" try: return os.environ[var_name] except KeyError: if default is None: error_msg = "Set the %s environment variable" % var_name raise ImproperlyConfigured(error_msg) ...
Generates a slug using a Hashid of value.
def generate_slug(value): """ Generates a slug using a Hashid of `value`. COPIED from spectator.core.models.SluggedModelMixin() because migrations don't make this happen automatically and perhaps the least bad thing is to copy the method here, ugh. """ alphabet = app_settings.SLUG_ALPHABET ...
Having added the new exhibition Work type we re going to assume that every Event of type museum should actually have one Exhibition attached.
def forwards(apps, schema_editor): """ Having added the new 'exhibition' Work type, we're going to assume that every Event of type 'museum' should actually have one Exhibition attached. So, we'll add one, with the same title as the Event. And we'll move all Creators from the Event to the Exhibition...
The Creators who have been most - read ordered by number of read publications ( ignoring if any of those publicatinos have been read multiple times. )
def by_publications(self): """ The Creators who have been most-read, ordered by number of read publications (ignoring if any of those publicatinos have been read multiple times.) Each Creator will have a `num_publications` attribute. """ if not spectator_apps.is_...
The Creators who have been most - read ordered by number of readings.
def by_readings(self, role_names=['', 'Author']): """ The Creators who have been most-read, ordered by number of readings. By default it will only include Creators whose role was left empty, or is 'Author'. Each Creator will have a `num_readings` attribute. """ ...
Get the Creators involved in the most Events.
def by_events(self, kind=None): """ Get the Creators involved in the most Events. This only counts Creators directly involved in an Event. i.e. if a Creator is the director of a movie Work, and an Event was a viewing of that movie, that Event wouldn't count. Unless they were ...
Get the Creators involved in the most Works.
def by_works(self, kind=None, role_name=None): """ Get the Creators involved in the most Works. kind - If supplied, only Works with that `kind` value will be counted. role_name - If supplied, only Works on which the role is that will be counted. e.g. To get all 'movie' Works on...
Query Elasticsearch using Invenio query syntax.
def index(): """Query Elasticsearch using Invenio query syntax.""" page = request.values.get('page', 1, type=int) size = request.values.get('size', 2, type=int) search = ExampleSearch()[(page - 1) * size:page * size] if 'q' in request.values: search = search.query(QueryString(query=request.v...
Clean argument to related object
def clean_options(self, using_keytab=False, principal=None, keytab_file=None, ccache_file=None, password=None): """Clean argument to related object :param bool using_keytab: refer to ``krbContext.__init__``. :param str principal:...