text stringlengths 81 112k |
|---|
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 %}
def most_seen_creators_by_works_card(work_kind=None, role_name=None, num=10):
"""
Displays a card showing the Creators that are ass... |
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_vi... |
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)
re... |
ERROR: type should be string, got "https://github.com/frictionlessdata/tableschema-pandas-py#storage\n\ndef create(self, bucket, descriptor, force=False):\n \"\"\"https://github.com/frictionlessdata/tableschema-pandas-py#storage\n \"\"\"\n\n # Make lists\n buckets = bucket\n if isinstance(bucket, six.string_types):\n buckets = [bucket]\n descriptors = descriptor\n if isinstance(descriptor, dict):\n descriptors = [descriptor]\n\n # Check buckets for existence\n for bucket in buckets:\n if bucket in self.buckets:\n if not force:\n message = 'Bucket \"%s\" already exists' % bucket\n raise tableschema.exceptions.StorageError(message)\n self.delete(bucket)\n\n # Define dataframes\n for bucket, descriptor in zip(buckets, descriptors):\n tableschema.validate(descriptor)\n self.__descriptors[bucket] = descriptor\n self.__dataframes[bucket] = pd.DataFrame()" |
ERROR: type should be string, got "https://github.com/frictionlessdata/tableschema-pandas-py#storage\n\ndef delete(self, bucket=None, ignore=False):\n \"\"\"https://github.com/frictionlessdata/tableschema-pandas-py#storage\n \"\"\"\n\n # Make lists\n buckets = bucket\n if isinstance(bucket, six.string_types):\n buckets = [bucket]\n elif bucket is None:\n buckets = reversed(self.buckets)\n\n # Iterate over buckets\n for bucket in buckets:\n\n # Non existent bucket\n if bucket not in self.buckets:\n if not ignore:\n message = 'Bucket \"%s\" doesn\\'t exist' % bucket\n raise tableschema.exceptions.StorageError(message)\n return\n\n # Remove from descriptors\n if bucket in self.__descriptors:\n del self.__descriptors[bucket]\n\n # Remove from dataframes\n if bucket in self.__dataframes:\n del self.__dataframes[bucket]" |
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
... |
ERROR: type should be string, got "https://github.com/frictionlessdata/tableschema-pandas-py#storage\n\ndef iter(self, bucket):\n \"\"\"https://github.com/frictionlessdata/tableschema-pandas-py#storage\n \"\"\"\n\n # Check existense\n if bucket not in self.buckets:\n message = 'Bucket \"%s\" doesn\\'t exist.' % bucket\n raise tableschema.exceptions.StorageError(message)\n\n # Prepare\n descriptor = self.describe(bucket)\n schema = tableschema.Schema(descriptor)\n\n # Yield rows\n for pk, row in self.__dataframes[bucket].iterrows():\n row = self.__mapper.restore_row(row, schema=schema, pk=pk)\n yield row" |
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(desc... |
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... |
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 DiggPaginator's softlimit option.
So that if you're viewing a page of, ... |
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 annual_reading_counts_card(kind='all', current_year=None):
"""
Disp... |
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__... |
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)
ret... |
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/services/api/misc.dates.html
def reading_d... |
Change Events with kind 'movie' to 'cinema'
and Events with kind 'play' to 'theatre'.
Purely for more consistency.
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 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
... |
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.
def generate_slug(value):
"""
Generates a slug using a Hashid of `value`.
... |
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 forwards(apps, schema_editor):
"""
... |
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.
def by_publications(self):
"""
The Creators who have been most-read, ordere... |
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_readings(self, role_names=['', 'Author']):
"""
The Creators who ha... |
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
also directly involved in the Event (e.g. speak... |
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 which the Creators had the role 'Director':
Creator.o... |
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:
... |
Clean argument to related object
:param bool using_keytab: refer to ``krbContext.__init__``.
:param str principal: refer to ``krbContext.__init__``.
:param str keytab_file: refer to ``krbContext.__init__``.
:param str ccache_file: refer to ``krbContext.__init__``.
:param str pas... |
Initialize credential cache with keytab
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_K... |
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
is strongly recommended **NOT** use ... |
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.
Internal use only.
def _prepare_co... |
Generate a dictionary with template names and file paths.
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... |
Register mappings from a package under given alias.
:param alias: The alias.
:param package_name: The package name.
def register_mappings(self, alias, package_name):
"""Register mappings from a package under given alias.
:param alias: The alias.
:param package_name: The packag... |
Register templates from the provided directory.
:param directory: The templates directory.
def register_templates(self, directory):
"""Register templates from the provided directory.
:param directory: The templates directory.
"""
try:
resource_listdir(directory, 'v... |
Load actions from an entry point group.
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) |
Load actions from an entry point group.
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... |
Build Elasticsearch client.
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_cla... |
Return client for current application.
def client(self):
"""Return client for current application."""
if self._client is None:
self._client = self._client_builder()
return self._client |
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.
def flush_and_refresh(self, index):
"""Flush and refresh one or more indices.
.. warning::
... |
Get version of Elasticsearch running on the cluster.
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('.')] |
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.
def active_aliases(self):
"""Get a filtered list of al... |
Yield tuple with created index name and responses from a client.
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."""
... |
Yield tuple with registered template and response from client.
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... |
Yield tuple with deleted index name and responses from a client.
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."""
... |
Flask application initialization.
:param app: An instance of :class:`~flask.app.Flask`.
def init_app(self, app,
entry_point_group_mappings='invenio_search.mappings',
entry_point_group_templates='invenio_search.templates',
**kwargs):
"""Flask applicati... |
Start the poor_consumer.
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()
# de... |
Connect to one of the Disque nodes.
You can get current connection with connected_node property
:returns: nothing
def connect(self):
"""
Connect to one of the Disque nodes.
You can get current connection with connected_node property
:returns: nothing
"""
... |
Execute a command on the connected server.
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')
... |
Add a job to a queue.
ADDJOB queue_name job <ms-timeout> [REPLICATE <count>] [DELAY <sec>]
[RETRY <sec>] [TTL <sec>] [MAXLEN <count>] [ASYNC]
:param queue_name: is the name of the queue, any string, basically.
:param job: is a string representing the job.
:param timeout: is... |
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
:returns: list of tuple(job_id, queue_name, job), tuple(job_id, queue_name, job, nacks, additional_de... |
Return the status of the queue (currently unimplemented).
Future support / testing of QSTAT support in Disque
QSTAT <qname>
Return produced ... consumed ... idle ... sources [...] ctime ...
def qstat(self, queue_name, return_dict=False):
"""
Return the status of the queue (cu... |
Describe the job.
:param job_id:
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 ... |
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
to suggestions to change it (canardleteer)
:param queue_name: The job queue we are modifying.
:param kw_in: pause the queue ... |
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 busy loop.
:param minlen: Don't return elements with less than count jobs queued.
:param maxlen: Don't return element... |
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.
:param queue: Return only jobs in the specified queue.
:param state: Must be a list - Return jobs in the spe... |
Build an index name from parts.
:param parts: Parts that should be combined to make an index name.
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... |
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).
def schema_to_index(schema, index_names=None):
"""Get index/doc_type given a schema URL.
:param schema: The schema name
:param index_... |
Decorator to check Elasticsearch version.
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.C... |
Initialize registered aliases and mappings.
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_se... |
Destroy all indexes.
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:
... |
Create a new index.
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)) |
List indices.
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 []
... |
Delete index by its name.
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)) |
Index input data.
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... |
Return records by their identifiers.
:param ids: A list of record identifier.
:returns: A list of records.
def get_records(self, ids):
"""Return records by their identifiers.
:param ids: A list of record identifier.
:returns: A list of records.
"""
return self.... |
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 faceted_search(cls, query=None, filters=None, search=None):
... |
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
/_search_options.html#_preference for more informa... |
Retrieve the request's User-Agent, if available.
Taken from Flask Login utils.py.
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:
... |
Calculate a digest based on request's User-Agent and IP address.
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_a... |
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.
def beautify(filename=None, json_str=None):
"""Beautify JSON string or file.
Keyword arguments:
:param filename: use ... |
Replace strings giving some info on where
the replacement was done
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 = ... |
Wait for and then return a connected socket..
Opens a TCP connection on port 8080, and waits for a single client.
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_IN... |
Send message to client and close the connection.
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() |
Provide the program's entry point when directly executed.
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("pr... |
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
def watch(logger_name, level=DEBUG, out=stdout):
""" Quick wrapper for using the Watch... |
Obtain the default user agent string sent to the server after
a successful handshake.
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/{}.{}.{}-{}-{} ({})"
... |
Import the best available module,
with C preferred to pure Python.
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_p... |
Convert PackStream values into native values.
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 Key... |
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. ``permanent`` authorizations additionally generate a refresh
token that can... |
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
either ``access_token`` or ``refresh_token``.
def re... |
Revoke the current Authorization.
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() |
Obtain and set authorization tokens based on ``code``.
:param code: The code obtained by an out-of-band authorization request
to Reddit.
def authorize(self, code):
"""Obtain and set authorization tokens based on ``code``.
:param code: The code obtained by an out-of-band authorizat... |
Obtain a new access token from the refresh_token.
def refresh(self):
"""Obtain a new access token from the refresh_token."""
if self.refresh_token is None:
raise InvalidInvocation("refresh token not provided")
self._request_token(
grant_type="refresh_token", refresh_toke... |
Revoke the current Authorization.
:param only_access: (Optional) When explicitly set to True, do not
evict the refresh token if one is set.
Revoking a refresh token will in-turn revoke all access tokens
associated with that authorization.
def revoke(self, only_access=False):
... |
Obtain a new access token.
def refresh(self):
"""Obtain a new access token."""
grant_type = "https://oauth.reddit.com/grants/installed_client"
self._request_token(grant_type=grant_type, device_id=self._device_id) |
Obtain a new personal-use script type access token.
def refresh(self):
"""Obtain a new personal-use script type access token."""
self._request_token(
grant_type="password",
username=self._username,
password=self._password,
) |
Issue the HTTP request capturing any errors that may occur.
def request(self, *args, **kwargs):
"""Issue the HTTP request capturing any errors that may occur."""
try:
return self._http.request(*args, timeout=TIMEOUT, **kwargs)
except Exception as exc:
raise RequestExcept... |
Return a 3-tuple of lead, vowel, and tail jamo characters.
Note: Non-Hangul characters are echoed back.
def _hangul_char_to_jamo(syllable):
"""Return a 3-tuple of lead, vowel, and tail jamo characters.
Note: Non-Hangul characters are echoed back.
"""
if is_hangul_char(syllable):
rem = ord(s... |
Return the Hangul character for the given jamo characters.
def _jamo_to_hangul_char(lead, vowel, tail=0):
"""Return the Hangul character for the given jamo characters.
"""
lead = ord(lead) - _JAMO_LEAD_OFFSET
vowel = ord(vowel) - _JAMO_VOWEL_OFFSET
tail = ord(tail) - _JAMO_TAIL_OFFSET if tail else ... |
Fetch the unicode name for jamo characters.
def _get_unicode_name(char):
"""Fetch the unicode name for jamo characters.
"""
if char not in _JAMO_TO_NAME.keys() and char not in _HCJ_TO_NAME.keys():
raise InvalidJamoError("Not jamo or nameless jamo character", char)
else:
if is_hcj(char):... |
Test if a single character is a jamo character.
Valid jamo includes all modern and archaic jamo, as well as all HCJ.
Non-assigned code points are invalid.
def is_jamo(character):
"""Test if a single character is a jamo character.
Valid jamo includes all modern and archaic jamo, as well as all HCJ.
... |
Test if a single character is a modern jamo character.
Modern jamo includes all U+11xx jamo in addition to HCJ in modern usage,
as defined in Unicode 7.0.
WARNING: U+1160 is NOT considered a modern jamo character, but it is listed
under 'Medial Vowels' in the Unicode 7.0 spec.
def is_jamo_modern(charac... |
Test if a single character is a compound, i.e., a consonant
cluster, double consonant, or dipthong.
def is_jamo_compound(character):
"""Test if a single character is a compound, i.e., a consonant
cluster, double consonant, or dipthong.
"""
if len(character) != 1:
return False
# Cons... |
Determine if a jamo character is a lead, vowel, or tail.
Integers and U+11xx characters are valid arguments. HCJ consonants are not
valid here.
get_jamo_class should return the class ["lead" | "vowel" | "tail"] of a
given character or integer.
Note: jamo class directly corresponds to the Unicode 7... |
Convert a HCJ character to a jamo character.
Arguments may be single characters along with the desired jamo class
(lead, vowel, tail). Non-mappable input will raise an InvalidJamoError.
def hcj_to_jamo(hcj_char, position="vowel"):
"""Convert a HCJ character to a jamo character.
Arguments may be single ... |
Convert a string of Hangul to jamo.
Arguments may be iterables of characters.
hangul_to_jamo should split every Hangul character into U+11xx jamo
characters for any given string. Non-hangul characters are not changed.
hangul_to_jamo is the generator version of h2j, the string version.
def hangul_to_j... |
Return the Hangul character for the given jamo input.
Integers corresponding to U+11xx jamo codepoints, U+11xx jamo characters,
or HCJ are valid inputs.
Outputs a one-character Hangul string.
This function is identical to j2h.
def jamo_to_hangul(lead, vowel, tail=''):
"""Return the Hangul charact... |
Return a tuple of jamo character constituents of a compound.
Note: Non-compound characters are echoed back.
WARNING: Archaic jamo compounds will raise NotImplementedError.
def decompose_jamo(compound):
"""Return a tuple of jamo character constituents of a compound.
Note: Non-compound characters are ec... |
Return the compound jamo for the given jamo input.
Integers corresponding to U+11xx jamo codepoints, U+11xx jamo
characters, or HCJ are valid inputs.
Outputs a one-character jamo string.
def compose_jamo(*parts):
"""Return the compound jamo for the given jamo input.
Integers corresponding to U+11x... |
Convert jamo characters in a string into hcj as much as possible.
def synth_hangul(string):
"""Convert jamo characters in a string into hcj as much as possible."""
raise NotImplementedError
return ''.join([''.join(''.join(jamo_to_hcj(_)) for _ in string)]) |
Return an exception instance that maps to the OAuth Error.
:param response: The HTTP response containing a www-authenticate error.
def authorization_error_class(response):
"""Return an exception instance that maps to the OAuth Error.
:param response: The HTTP response containing a www-authenticate error.... |
Return the latest of two bookmarks by looking for the maximum
integer value following the last colon in the bookmark string.
def _last_bookmark(b0, b1):
""" Return the latest of two bookmarks by looking for the maximum
integer value following the last colon in the bookmark string.
"""
n = [None, No... |
The bookmark returned by the last :class:`.Transaction`.
def last_bookmark(bookmarks):
""" The bookmark returned by the last :class:`.Transaction`.
"""
last = None
for bookmark in bookmarks:
if last is None:
last = bookmark
else:
last = _last_bookmark(last, bookm... |
Connect and perform a handshake and return a valid Connection object, assuming
a protocol version can be agreed.
def connect(address, **config):
""" Connect and perform a handshake and return a valid Connection object, assuming
a protocol version can be agreed.
"""
ssl_context = make_ssl_context(**... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.