Search is not available for this dataset
text
stringlengths
75
104k
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. "...
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) ...
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, ...
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. ...
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...
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...
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'])
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,...
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__']
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...
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...
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
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)
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') \ ...
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()
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 ...
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. ""...
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...
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...
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), ...
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...
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]
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...
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( ...
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)
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...
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...
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...
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...
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...
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...
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...
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. "...
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) ...
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...
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...
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' ...
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) ...
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 ...
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...
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_...
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. """ ...
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 ...
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...
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...
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:...
def init_with_keytab(self): """Initialize credential cache with keytab""" creds_opts = { 'usage': 'initiate', 'name': self._cleaned_options['principal'], } store = {} if self._cleaned_options['keytab'] != DEFAULT_KEYTAB: store['client_keytab']...
def init_with_password(self): """Initialize credential cache with password **Causion:** once you enter password from command line, or pass it to API directly, the given password is not encrypted always. Although getting credential with password works, from security point of view, it ...
def _prepare_context(self): """Prepare context Initialize credential cache with keytab or password according to ``using_keytab`` parameter. Then, ``KRB5CCNAME`` is set properly so that Kerberos library called in current context is able to get credential from correct cache. ...
def templates(self): """Generate a dictionary with template names and file paths.""" templates = {} result = [] if self.entry_point_group_templates: result = self.load_entry_point_group_templates( self.entry_point_group_templates) or [] for template i...
def register_mappings(self, alias, package_name): """Register mappings from a package under given alias. :param alias: The alias. :param package_name: The package name. """ # For backwards compatibility, we also allow for ES2 mappings to be # placed at the root level of ...
def register_templates(self, directory): """Register templates from the provided directory. :param directory: The templates directory. """ try: resource_listdir(directory, 'v{}'.format(ES_VERSION[0])) directory = '{}/v{}'.format(directory, ES_VERSION[0]) ...
def load_entry_point_group_mappings(self, entry_point_group_mappings): """Load actions from an entry point group.""" for ep in iter_entry_points(group=entry_point_group_mappings): self.register_mappings(ep.name, ep.module_name)
def load_entry_point_group_templates(self, entry_point_group_templates): """Load actions from an entry point group.""" result = [] for ep in iter_entry_points(group=entry_point_group_templates): with self.app.app_context(): for template_dir in ep.load()(): ...
def _client_builder(self): """Build Elasticsearch client.""" client_config = self.app.config.get('SEARCH_CLIENT_CONFIG') or {} client_config.setdefault( 'hosts', self.app.config.get('SEARCH_ELASTIC_HOSTS')) client_config.setdefault('connection_class', RequestsHttpConnection) ...
def client(self): """Return client for current application.""" if self._client is None: self._client = self._client_builder() return self._client
def flush_and_refresh(self, index): """Flush and refresh one or more indices. .. warning:: Do not call this method unless you know what you are doing. This method is only intended to be called during tests. """ self.client.indices.flush(wait_if_ongoing=True, index...
def cluster_version(self): """Get version of Elasticsearch running on the cluster.""" versionstr = self.client.info()['version']['number'] return [int(x) for x in versionstr.split('.')]
def active_aliases(self): """Get a filtered list of aliases based on configuration. Returns aliases and their mappings that are defined in the `SEARCH_MAPPINGS` config variable. If the `SEARCH_MAPPINGS` is set to `None` (the default), all aliases are included. """ whitel...
def create(self, ignore=None): """Yield tuple with created index name and responses from a client.""" ignore = ignore or [] def _create(tree_or_filename, alias=None): """Create indices and aliases by walking DFS.""" # Iterate over aliases: for name, value in ...
def put_templates(self, ignore=None): """Yield tuple with registered template and response from client.""" ignore = ignore or [] def _replace_prefix(template_path, body): """Replace index prefix in template request body.""" pattern = '__SEARCH_INDEX_PREFIX__' ...
def delete(self, ignore=None): """Yield tuple with deleted index name and responses from a client.""" ignore = ignore or [] def _delete(tree_or_filename, alias=None): """Delete indexes and aliases by walking DFS.""" if alias: yield alias, self.client.indi...
def init_app(self, app, entry_point_group_mappings='invenio_search.mappings', entry_point_group_templates='invenio_search.templates', **kwargs): """Flask application initialization. :param app: An instance of :class:`~flask.app.Flask`. """ ...
def main(): """Start the poor_consumer.""" try: opts, args = getopt.getopt(sys.argv[1:], "h:v", ["help", "nack=", "servers=", "queues="]) except getopt.GetoptError as err: print str(err) usage() sys.exit() # defaults nack = 0.0 ...
def connect(self): """ Connect to one of the Disque nodes. You can get current connection with connected_node property :returns: nothing """ self.connected_node = None for i, node in self.nodes.items(): host, port = i.split(':') port = i...
def execute_command(self, *args, **kwargs): """Execute a command on the connected server.""" try: return self.get_connection().execute_command(*args, **kwargs) except ConnectionError as e: logger.warn('trying to reconnect') self.connect() logger.wa...
def add_job(self, queue_name, job, timeout=200, replicate=None, delay=None, retry=None, ttl=None, maxlen=None, asynchronous=None): """ Add a job to a queue. ADDJOB queue_name job <ms-timeout> [REPLICATE <count>] [DELAY <sec>] [RETRY <sec>] [TTL <sec>] [MAXLEN <count>...
def get_job(self, queues, timeout=None, count=None, nohang=False, withcounters=False): """ Return some number of jobs from specified queues. GETJOB [NOHANG] [TIMEOUT <ms-timeout>] [COUNT <count>] [WITHCOUNTERS] FROM queue1 queue2 ... queueN :param queues: name of queues ...
def qstat(self, queue_name, return_dict=False): """ Return the status of the queue (currently unimplemented). Future support / testing of QSTAT support in Disque QSTAT <qname> Return produced ... consumed ... idle ... sources [...] ctime ... """ rtn = self.exec...
def show(self, job_id, return_dict=False): """ Describe the job. :param job_id: """ rtn = self.execute_command('SHOW', job_id) if return_dict: grouped = self._grouper(rtn, 2) rtn = dict((a, b) for a, b in grouped) return rtn
def pause(self, queue_name, kw_in=None, kw_out=None, kw_all=None, kw_none=None, kw_state=None, kw_bcast=None): """ Pause a queue. Unfortunately, the PAUSE keywords are mostly reserved words in Python, so I've been a little creative in the function variable names. Open ...
def qscan(self, cursor=0, count=None, busyloop=None, minlen=None, maxlen=None, importrate=None): """ Iterate all the existing queues in the local node. :param count: An hint about how much work to do per iteration. :param busyloop: Block and return all the elements in a bu...
def jscan(self, cursor=0, count=None, busyloop=None, queue=None, state=None, reply=None): """Iterate all the existing jobs in the local node. :param count: An hint about how much work to do per iteration. :param busyloop: Block and return all the elements in a busy loop. :...
def build_index_name(app, *parts): """Build an index name from parts. :param parts: Parts that should be combined to make an index name. """ base_index = os.path.splitext( '-'.join([part for part in parts if part]) )[0] return prefix_index(app=app, index=base_index)
def schema_to_index(schema, index_names=None): """Get index/doc_type given a schema URL. :param schema: The schema name :param index_names: A list of index name. :returns: A tuple containing (index, doc_type). """ parts = schema.split('/') doc_type = os.path.splitext(parts[-1]) if doc_...
def es_version_check(f): """Decorator to check Elasticsearch version.""" @wraps(f) def inner(*args, **kwargs): cluster_ver = current_search.cluster_version[0] client_ver = ES_VERSION[0] if cluster_ver != client_ver: raise click.ClickException( 'Elasticsear...
def init(force): """Initialize registered aliases and mappings.""" click.secho('Creating indexes...', fg='green', bold=True, file=sys.stderr) with click.progressbar( current_search.create(ignore=[400] if force else None), length=current_search.number_of_indexes) as bar: for n...
def destroy(force): """Destroy all indexes.""" click.secho('Destroying indexes...', fg='red', bold=True, file=sys.stderr) with click.progressbar( current_search.delete(ignore=[400, 404] if force else None), length=current_search.number_of_indexes) as bar: for name, response i...
def create(index_name, body, force, verbose): """Create a new index.""" result = current_search_client.indices.create( index=index_name, body=json.load(body), ignore=[400] if force else None, ) if verbose: click.echo(json.dumps(result))
def list_cmd(only_active, only_aliases, verbose): """List indices.""" def _tree_print(d, rec_list=None, verbose=False, indent=2): # Note that on every recursion rec_list is copied, # which might not be very effective for very deep dictionaries. rec_list = rec_list or [] for idx, ...
def delete(index_name, force, verbose): """Delete index by its name.""" result = current_search_client.indices.delete( index=index_name, ignore=[400, 404] if force else None, ) if verbose: click.echo(json.dumps(result))
def put(index_name, doc_type, identifier, body, force, verbose): """Index input data.""" result = current_search_client.index( index=index_name, doc_type=doc_type or index_name, id=identifier, body=json.load(body), op_type='index' if force or identifier is None else 'crea...
def get_records(self, ids): """Return records by their identifiers. :param ids: A list of record identifier. :returns: A list of records. """ return self.query(Ids(values=[str(id_) for id_ in ids]))
def faceted_search(cls, query=None, filters=None, search=None): """Return faceted search instance with defaults set. :param query: Elastic DSL query object (``Q``). :param filters: Dictionary with selected facet values. :param search: An instance of ``Search`` class. (default: ``cls()``...
def with_preference_param(self): """Add the preference param to the ES request and return a new Search. The preference param avoids the bouncing effect with multiple replicas, documented on ES documentation. See: https://www.elastic.co/guide/en/elasticsearch/guide/current /_sear...
def _get_user_agent(self): """Retrieve the request's User-Agent, if available. Taken from Flask Login utils.py. """ user_agent = request.headers.get('User-Agent') if user_agent: user_agent = user_agent.encode('utf-8') return user_agent or ''
def _get_user_hash(self): """Calculate a digest based on request's User-Agent and IP address.""" if request: user_hash = '{ip}-{ua}'.format(ip=request.remote_addr, ua=self._get_user_agent()) alg = hashlib.md5() alg.update(use...
def beautify(filename=None, json_str=None): """Beautify JSON string or file. Keyword arguments: :param filename: use its contents as json string instead of json_str param. :param json_str: json string to be beautified. """ if filename is not None: with open(filename) as json_file: ...
def replace(pretty, old_str, new_str): """ Replace strings giving some info on where the replacement was done """ out_str = '' line_number = 1 changes = 0 for line in pretty.splitlines(keepends=True): new_line = line.replace(old_str, new_str) if line.find(old_str) != -1: ...
def receive_connection(): """Wait for and then return a connected socket.. Opens a TCP connection on port 8080, and waits for a single client. """ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind(("localhost", 8...
def send_message(client, message): """Send message to client and close the connection.""" print(message) client.send("HTTP/1.1 200 OK\r\n\r\n{}".format(message).encode("utf-8")) client.close()
def main(): """Provide the program's entry point when directly executed.""" if len(sys.argv) < 2: print("Usage: {} SCOPE...".format(sys.argv[0])) return 1 authenticator = prawcore.TrustedAuthenticator( prawcore.Requestor("prawcore_refresh_token_example"), os.environ["PRAWCOR...
def watch(logger_name, level=DEBUG, out=stdout): """ Quick wrapper for using the Watcher. :param logger_name: name of logger to watch :param level: minimum log level to show (default INFO) :param out: where to send output (default stdout) :return: Watcher instance """ watcher = Watcher(logg...
def get_user_agent(): """ Obtain the default user agent string sent to the server after a successful handshake. """ from sys import platform, version_info template = "neobolt/{} Python/{}.{}.{}-{}-{} ({})" fields = (version,) + tuple(version_info) + (platform,) return template.format(*fields...
def import_best(c_module, py_module): """ Import the best available module, with C preferred to pure Python. """ from importlib import import_module from os import getenv pure_python = getenv("PURE_PYTHON", "") if pure_python: return import_module(py_module) else: try: ...
def hydrate(self, values): """ Convert PackStream values into native values. """ def hydrate_(obj): if isinstance(obj, Structure): try: f = self.hydration_functions[obj.tag] except KeyError: # If we don't recogn...
def authorize_url(self, duration, scopes, state, implicit=False): """Return the URL used out-of-band to grant access to your application. :param duration: Either ``permanent`` or ``temporary``. ``temporary`` authorizations generate access tokens that last only 1 hour. ``permanen...
def revoke_token(self, token, token_type=None): """Ask Reddit to revoke the provided token. :param token: The access or refresh token to revoke. :param token_type: (Optional) When provided, hint to Reddit what the token type is for a possible efficiency gain. The value can be ...
def revoke(self): """Revoke the current Authorization.""" if self.access_token is None: raise InvalidInvocation("no token available to revoke") self._authenticator.revoke_token(self.access_token, "access_token") self._clear_access_token()
def authorize(self, code): """Obtain and set authorization tokens based on ``code``. :param code: The code obtained by an out-of-band authorization request to Reddit. """ if self._authenticator.redirect_uri is None: raise InvalidInvocation("redirect URI not prov...