code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if html:
text = _tag_re.sub(' ', text)
text = _strip_re.sub('', text)
text = _punctuation_re.sub(' ', text)
return len(text.split()) | def word_count(text, html=True) | Return the count of words in the given text. If the text is HTML (default True),
tags are stripped before counting. Handles punctuation and bad formatting like.this
when counting words, but assumes conventions for Latin script languages. May not
be reliable for other languages. | 2.773529 | 2.792231 | 0.993302 |
text = unescape(text)
# Find the "dot"
text = _deobfuscate_dot1_re.sub('.', text)
text = _deobfuscate_dot2_re.sub(r'\1.\2', text)
text = _deobfuscate_dot3_re.sub(r'\1.\2', text)
# Find the "at"
text = _deobfuscate_at1_re.sub('@', text)
text = _deobfuscate_at2_re.sub(r'\1@\2', text)
... | def deobfuscate_email(text) | Deobfuscate email addresses in provided text | 1.973893 | 2.014992 | 0.979603 |
if isinstance(text, six.text_type):
if six.PY3: # pragma: no cover
text = text.translate(text.maketrans("", "", string.punctuation)).lower()
else: # pragma: no cover
text = six.text_type(text.encode('utf-8').translate(string.maketrans("", ""), string.punctuation).lower... | def simplify_text(text) | Simplify text to allow comparison.
>>> simplify_text("Awesome Coder wanted at Awesome Company")
'awesome coder wanted at awesome company'
>>> simplify_text("Awesome Coder, wanted at Awesome Company! ")
'awesome coder wanted at awesome company'
>>> simplify_text(u"Awesome Coder, wanted at Awesome ... | 2.385149 | 2.495042 | 0.955956 |
sentences = []
for text in text_blocks:
sentences.extend(nltk.sent_tokenize(text))
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
chunked_sentences = nltk.ne_chunk_sents(tagg... | def extract_named_entities(text_blocks) | Return a list of named entities extracted from provided text blocks (list of text strings). | 1.617779 | 1.612203 | 1.003459 |
config = Config()
try:
config.set_main_option("script_location", path or "migrations")
script = ScriptDirectory.from_config(config)
head = script.get_current_head()
# create alembic table
metadata, alembic_version = alembic_table_metadata()
metadata.create_al... | def set_alembic_revision(path=None) | Create/Update alembic table to latest revision number | 2.849393 | 2.801376 | 1.01714 |
manager.db.engine.echo = True
if prompt_bool("Are you sure you want to lose all your data"):
manager.db.drop_all()
metadata, alembic_version = alembic_table_metadata()
alembic_version.drop()
manager.db.session.commit() | def dropdb() | Drop database tables | 5.545073 | 5.710923 | 0.970959 |
manager.db.engine.echo = True
manager.db.create_all()
set_alembic_revision() | def createdb() | Create database tables from sqlalchemy models | 7.480009 | 7.322297 | 1.021539 |
print("Syncing resources with Lastuser...")
resources = manager.app.lastuser.sync_resources()['results']
for rname, resource in six.iteritems(resources):
if resource['status'] == 'error':
print("Error for %s: %s" % (rname, resource['error']))
else:
print("Resour... | def sync_resources() | Sync the client's resources with the Lastuser server | 2.883702 | 2.620923 | 1.100262 |
manager.app = app
manager.db = db
manager.context = kwargs
manager.add_command('db', MigrateCommand)
manager.add_command('clean', Clean())
manager.add_command('showurls', ShowUrls())
manager.add_command('shell', Shell(make_context=shell_context))
manager.add_command('plainshell', Sh... | def init_manager(app, db, **kwargs) | Initialise Manager
:param app: Flask app object
:parm db: db instance
:param kwargs: Additional keyword arguments to be made available as shell context | 2.951478 | 3.483786 | 0.847204 |
# Make current_auth available to app templates
app.jinja_env.globals['current_auth'] = current_auth
# Make the current view available to app templates
app.jinja_env.globals['current_view'] = current_view
# Disable Flask-SQLAlchemy events.
# Apps that want it can turn it back on in their con... | def init_app(app, env=None) | Configure an app depending on the environment. Loads settings from a file
named ``settings.py`` in the instance folder, followed by additional
settings from one of ``development.py``, ``production.py`` or
``testing.py``. Typical usage::
from flask import Flask
import coaster.app
ap... | 4.446163 | 4.316846 | 1.029956 |
try:
app.config.from_pyfile(filepath)
return True
except IOError:
# TODO: Can we print to sys.stderr in production? Should this go to
# logs instead?
print("Did not find settings file %s for additional settings, skipping it" % filepath, file=sys.stderr)
retur... | def load_config_from_file(app, filepath) | Helper function to load config from a specified file | 6.769448 | 6.982987 | 0.96942 |
options = dict(self.jinja_options)
if 'autoescape' not in options:
options['autoescape'] = self.select_jinja_autoescape
rv = SandboxedEnvironment(self, **options)
rv.globals.update(
url_for=url_for,
get_flashed_messages=get_flashed_messages,
... | def create_jinja_environment(self) | Creates the Jinja2 environment based on :attr:`jinja_options`
and :meth:`select_jinja_autoescape`. Since 0.7 this also adds
the Jinja2 globals and filters after initialization. Override
this function to customize the behavior. | 7.131316 | 6.117064 | 1.165807 |
if cls.__uuid_primary_key__:
return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False))
else:
return immutable(Column(Integer, primary_key=True, nullable=False)) | def id(cls) | Database identity for this model, used for foreign key references from other models | 4.869601 | 4.07018 | 1.196409 |
if cls.__uuid_primary_key__:
def url_id_func(self):
return self.id.hex
def url_id_is(cls):
return SqlHexUuidComparator(cls.id)
url_id_func.__name__ = 'url_id'
url_id_property = hybrid_property(url_id_func... | def url_id(cls) | The URL id | 2.655386 | 2.690797 | 0.98684 |
if hasattr(cls, '__uuid_primary_key__') and cls.__uuid_primary_key__:
return synonym('id')
else:
return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, unique=True, nullable=False)) | def uuid(cls) | UUID column, or synonym to existing :attr:`id` column if that is a UUID | 5.488538 | 4.365532 | 1.257244 |
app = current_app._get_current_object() if current_app else None
if app is not None and action in self.url_for_endpoints.get(app, {}):
endpoint, paramattrs, _external = self.url_for_endpoints[app][action]
else:
try:
endpoint, paramattrs, _external... | def url_for(self, action='view', **kwargs) | Return public URL to this instance for a given action (default 'view') | 3.108453 | 3.08979 | 1.00604 |
def decorator(f):
if 'url_for_endpoints' not in cls.__dict__:
cls.url_for_endpoints = {None: {}} # Stick it into the class with the first endpoint
cls.url_for_endpoints.setdefault(_app, {})
for keyword in paramattrs:
if isinstance(pa... | def is_url_for(cls, _action, _endpoint=None, _app=None, _external=None, **paramattrs) | View decorator that registers the view as a :meth:`url_for` target. | 3.201713 | 3.132145 | 1.022211 |
if 'view_for_endpoints' not in cls.__dict__:
cls.view_for_endpoints = {}
cls.view_for_endpoints.setdefault(app, {})[action] = (classview, attr) | def register_view_for(cls, app, action, classview, attr) | Register a classview and viewhandler for a given app and action | 2.563018 | 2.608813 | 0.982446 |
app = current_app._get_current_object()
view, attr = self.view_for_endpoints[app][action]
return getattr(view(self), attr) | def view_for(self, action='view') | Return the classview viewhandler that handles the specified action | 6.676606 | 6.248316 | 1.068545 |
app = current_app._get_current_object()
return self.view_for_endpoints[app][action][0](self) | def classview_for(self, action='view') | Return the classview that contains the viewhandler for the specified action | 9.392295 | 8.327181 | 1.127908 |
for f in fields:
if hasattr(self, f):
setattr(self, f, fields[f])
else:
raise TypeError("'{arg}' is an invalid argument for {instance_type}".format(arg=f, instance_type=self.__class__.__name__)) | def _set_fields(self, fields) | Helper method for :meth:`upsert` in the various subclasses | 3.184088 | 3.000539 | 1.061172 |
if cls.__name_length__ is None:
column_type = UnicodeText()
else:
column_type = Unicode(cls.__name_length__)
if cls.__name_blank_allowed__:
return Column(column_type, nullable=False, unique=True)
else:
return Column(column_type, Ch... | def name(cls) | The URL name of this object, unique across all instances of this model | 3.706893 | 3.480841 | 1.064942 |
if cls.__title_length__ is None:
column_type = UnicodeText()
else:
column_type = Unicode(cls.__title_length__)
return Column(column_type, nullable=False) | def title(cls) | The title of this object | 4.853666 | 5.12363 | 0.94731 |
instance = cls.get(name)
if instance:
instance._set_fields(fields)
else:
instance = cls(name=name, **fields)
instance = failsafe_add(cls.query.session, instance, name=name)
return instance | def upsert(cls, name, **fields) | Insert or update an instance | 4.433874 | 4.282513 | 1.035344 |
if self.title:
if inspect(self).has_identity:
def checkused(c):
return bool(c in reserved or c in self.reserved_names
or self.__class__.query.filter(self.__class__.id != self.id).filter_by(name=c).notempty())
else:
... | def make_name(self, reserved=[]) | Autogenerates a :attr:`name` from the :attr:`title`. If the auto-generated name is already
in use in this model, :meth:`make_name` tries again by suffixing numbers starting with 2
until an available name is found.
:param reserved: List or set of reserved names unavailable for use | 4.113009 | 4.1867 | 0.982399 |
return cls.query.filter_by(parent=parent, name=name).one_or_none() | def get(cls, parent, name) | Get an instance matching the parent and name | 2.865816 | 2.70541 | 1.059291 |
if self.title and self.parent is not None and hasattr(self.parent, 'title') and self.parent.title:
if self.title.startswith(self.parent.title):
short = self.title[len(self.parent.title):].strip()
match = _punctuation_re.match(short)
if match:
... | def short_title(self) | Generates an abbreviated title by subtracting the parent's title from this instance's title. | 2.638506 | 2.359515 | 1.118241 |
if inherited is not None:
return inherited | super(BaseScopedNameMixin, self).permissions(actor)
elif self.parent is not None and isinstance(self.parent, PermissionMixin):
return self.parent.permissions(actor) | super(BaseScopedNameMixin, self).permissions(actor)
... | def permissions(self, actor, inherited=None) | Permissions for this model, plus permissions inherited from the parent. | 2.686325 | 2.393143 | 1.122509 |
if self.title:
self.name = six.text_type(make_name(self.title_for_name, maxlength=self.__name_length__)) | def make_name(self) | Autogenerates a :attr:`name` from :attr:`title_for_name` | 11.419167 | 5.828464 | 1.959207 |
return cls.query.filter_by(parent=parent, url_id=url_id).one_or_none() | def get(cls, parent, url_id) | Get an instance matching the parent and url_id | 2.346487 | 2.076021 | 1.130281 |
if self.url_id is None: # Set id only if empty
self.url_id = select([func.coalesce(func.max(self.__class__.url_id + 1), 1)],
self.__class__.parent == self.parent) | def make_id(self) | Create a new URL id that is unique to the parent container | 7.639987 | 5.549291 | 1.37675 |
return (
Column('created_at', DateTime, default=func.utcnow(), nullable=False),
Column('updated_at', DateTime, default=func.utcnow(), onupdate=func.utcnow(), nullable=False),
) | def make_timestamp_columns() | Return two columns, created_at and updated_at, with appropriate defaults | 2.201124 | 1.729359 | 1.272798 |
if _instance in _session:
# This instance is already in the session, most likely due to a
# save-update cascade. SQLAlchemy will flush before beginning a
# nested transaction, which defeats the purpose of nesting, so
# remove it for now and add it back inside the SAVEPOINT.
... | def failsafe_add(_session, _instance, **filters) | Add and commit a new instance in a nested transaction (using SQL SAVEPOINT),
gracefully handling failure in case a conflicting entry is already in the
database (which may occur due to parallel requests causing race conditions
in a production environment with multiple workers).
Returns the instance save... | 5.223291 | 5.182709 | 1.00783 |
if isinstance(column, ColumnProperty):
default = column.columns[0].default
else:
default = column.default
@event.listens_for(column, 'init_scalar', retval=True, propagate=True)
def init_scalar(target, value, dict_):
# A subclass may override the column and not provide a def... | def auto_init_default(column) | Set the default value for a column when it's first accessed rather than
first committed to the database. | 5.314609 | 5.197159 | 1.022599 |
if config and list(config.keys()) != ['source']:
raise TypeError("Unrecognised parameters: %s" % repr(config.keys()))
def inner(f):
namefilt = [(name[:-2], filt, True) if name.endswith('[]') else (name, filt, False)
for name, filt in
[(v[0], v[1]) if isinstance(... | def requestargs(*vars, **config) | Decorator that loads parameters from request.values if not specified in the
function's keyword arguments. Usage::
@requestargs('param1', ('param2', int), 'param3[]', ...)
def function(param1, param2=0, param3=None):
...
requestargs takes a list of parameters to pass to the wrapped ... | 2.88035 | 2.978963 | 0.966897 |
return load_models((model, attributes, parameter),
kwargs=kwargs, permission=permission, addlperms=addlperms, urlcheck=urlcheck) | def load_model(model, attributes=None, parameter=None,
kwargs=False, permission=None, addlperms=None, urlcheck=[]) | Decorator to load a model given a query parameter.
Typical usage::
@app.route('/<profile>')
@load_model(Profile, {'name': 'profile'}, 'profileob')
def profile_view(profileob):
# 'profileob' is now a Profile model instance. The load_model decorator replaced this:
# p... | 2.962371 | 5.869337 | 0.50472 |
if not isinstance(param, dict):
param = dict(param)
return jsonify(param) | def dict_jsonify(param) | Convert the parameter into a dictionary before calling jsonify, if it's not already one | 3.672094 | 2.288848 | 1.604341 |
if not isinstance(param, dict):
param = dict(param)
return jsonp(param) | def dict_jsonp(param) | Convert the parameter into a dictionary before calling jsonp, if it's not already one | 3.614106 | 2.752073 | 1.31323 |
def inner(f):
@wraps(f)
def wrapper(*args, **kwargs):
origin = request.headers.get('Origin')
if request.method not in methods:
abort(405)
if origins == '*':
pass
elif is_collection(origins) and origin in origins:
... | def cors(origins,
methods=['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
headers=['Accept', 'Accept-Language', 'Content-Language', 'Content-Type', 'X-Requested-With'],
max_age=None) | Adds CORS headers to the decorated view function.
:param origins: Allowed origins (see below)
:param methods: A list of allowed HTTP methods
:param headers: A list of allowed HTTP headers
:param max_age: Duration in seconds for which the CORS response may be cached
The :obj:`origins` parameter may... | 2.03099 | 2.046797 | 0.992277 |
def inner(f):
def is_available_here():
if not hasattr(current_auth, 'permissions'):
return False
elif is_collection(permission):
return bool(current_auth.permissions.intersection(permission))
else:
return permission in ... | def requires_permission(permission) | View decorator that requires a certain permission to be present in
``current_auth.permissions`` before the view is allowed to proceed.
Aborts with ``403 Forbidden`` if the permission is not present.
The decorated view will have an ``is_available`` method that can be called
to perform the same test.
... | 3.499117 | 3.359447 | 1.041575 |
return not isinstance(item, six.string_types) and isinstance(item, (collections.Set, collections.Sequence)) | def is_collection(item) | Returns True if the item is a collection class: list, tuple, set, frozenset
or any other class that resembles one of these (using abstract base classes).
>>> is_collection(0)
False
>>> is_collection(0.1)
False
>>> is_collection('')
False
>>> is_collection({})
False
>>> is_collec... | 4.486109 | 7.141439 | 0.62818 |
if six.PY3: # pragma: no cover
return urlsafe_b64encode(uuid.uuid4().bytes).decode('utf-8').rstrip('=')
else: # pragma: no cover
return six.text_type(urlsafe_b64encode(uuid.uuid4().bytes).rstrip('=')) | def buid() | Return a new random id that is exactly 22 characters long,
by encoding a UUID4 in URL-safe Base64. See
http://en.wikipedia.org/wiki/Base64#Variants_summary_table
>>> len(buid())
22
>>> buid() == buid()
False
>>> isinstance(buid(), six.text_type)
True | 2.398249 | 2.263492 | 1.059535 |
fields = list(uuid1mc().fields)
if isinstance(dt, datetime):
timeval = time.mktime(dt.timetuple()) + dt.microsecond / 1e6
else:
# Assume we got an actual timestamp
timeval = dt
# The following code is borrowed from the UUID module source:
nanoseconds = int(timeval * 1e9... | def uuid1mc_from_datetime(dt) | Return a UUID1 with a random multicast MAC id and with a timestamp
matching the given datetime object or timestamp value.
.. warning::
This function does not consider the timezone, and is not guaranteed to
return a unique UUID. Use under controlled conditions only.
>>> dt = datetime.now()
... | 2.117967 | 2.291817 | 0.924143 |
if six.PY3: # pragma: no cover
return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=')
else:
return six.text_type(urlsafe_b64encode(value.bytes).rstrip('=')) | def uuid2buid(value) | Convert a UUID object to a 22-char BUID string
>>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089')
>>> uuid2buid(u)
'MyA90vLvQi-usAWNb19wiQ' | 2.639111 | 3.202799 | 0.824001 |
randnum = randint(0, 10 ** digits)
while len(str(randnum)) > digits:
randnum = randint(0, 10 ** digits)
return (u'%%0%dd' % digits) % randnum | def newpin(digits=4) | Return a random numeric string with the specified number of digits,
default 4.
>>> len(newpin())
4
>>> len(newpin(5))
5
>>> newpin().isdigit()
True | 2.952576 | 3.655383 | 0.807734 |
if encoding not in ['PLAIN', 'SSHA', 'BCRYPT']:
raise ValueError("Unknown encoding %s" % encoding)
if encoding == 'PLAIN':
if isinstance(password, str) and six.PY2:
password = six.text_type(password, 'utf-8')
return '{PLAIN}%s' % password
elif encoding == 'SSHA':
... | def make_password(password, encoding='BCRYPT') | Make a password with PLAIN, SSHA or BCRYPT (default) encoding.
>>> make_password('foo', encoding='PLAIN')
'{PLAIN}foo'
>>> make_password(u're-foo', encoding='SSHA')[:6]
'{SSHA}'
>>> make_password(u're-foo')[:8]
'{BCRYPT}'
>>> make_password('foo') == make_password('foo')
False | 3.002518 | 2.891279 | 1.038474 |
if reference.startswith(u'{PLAIN}'):
if reference[7:] == attempt:
return True
elif reference.startswith(u'{SSHA}'):
# In python3 b64decode takes inputtype as bytes as opposed to str in python 2, and returns
# binascii.Error as opposed to TypeError
if six.PY3: # ... | def check_password(reference, attempt) | Compare a reference password with the user attempt.
>>> check_password('{PLAIN}foo', 'foo')
True
>>> check_password(u'{PLAIN}bar', 'bar')
True
>>> check_password(u'{UNKNOWN}baz', 'baz')
False
>>> check_password(u'no-encoding', u'no-encoding')
False
>>> check_password(u'{SSHA}q/uVU8r... | 2.550243 | 2.477404 | 1.029401 |
number, decimal = ((u'%%.%df' % decimals) % value).split(u'.')
parts = []
while len(number) > 3:
part, number = number[-3:], number[:-3]
parts.append(part)
parts.append(number)
parts.reverse()
if int(decimal) == 0:
return u','.join(parts)
else:
return u',... | def format_currency(value, decimals=2) | Return a number suitably formatted for display as currency, with
thousands separated by commas and up to two decimal points.
>>> format_currency(1000)
'1,000'
>>> format_currency(100)
'100'
>>> format_currency(999.95)
'999.95'
>>> format_currency(99.95)
'99.95'
>>> format_curren... | 2.428779 | 2.819771 | 0.861339 |
if six.PY3: # pragma: no cover
return hashlib.md5(data.encode('utf-8')).hexdigest()
else: # pragma: no cover
return hashlib.md5(data).hexdigest() | def md5sum(data) | Return md5sum of data as a 32-character string.
>>> md5sum('random text')
'd9b9bec3f4cc5482e7c5ef43143e563a'
>>> md5sum(u'random text')
'd9b9bec3f4cc5482e7c5ef43143e563a'
>>> len(md5sum('random text'))
32 | 1.926434 | 2.54655 | 0.756488 |
naivedt = datetime.combine(isoweek.Week(year, week).day(0), datetime.min.time())
if isinstance(timezone, six.string_types):
tz = pytz.timezone(timezone)
else:
tz = timezone
dt = tz.localize(naivedt).astimezone(pytz.UTC)
if naive:
return dt.replace(tzinfo=None)
else:
... | def isoweek_datetime(year, week, timezone='UTC', naive=False) | Returns a datetime matching the starting point of a specified ISO week
in the specified timezone (default UTC). Returns a naive datetime in
UTC if requested (default False).
>>> isoweek_datetime(2017, 1)
datetime.datetime(2017, 1, 2, 0, 0, tzinfo=<UTC>)
>>> isoweek_datetime(2017, 1, 'Asia/Kolkata')... | 2.334225 | 3.416525 | 0.683216 |
if timezone:
if isinstance(timezone, six.string_types):
tz = pytz.timezone(timezone)
else:
tz = timezone
elif isinstance(dt, datetime) and dt.tzinfo:
tz = dt.tzinfo
else:
tz = pytz.UTC
utc_dt = tz.localize(datetime.combine(dt, datetime.min.ti... | def midnight_to_utc(dt, timezone=None, naive=False) | Returns a UTC datetime matching the midnight for the given date or datetime.
>>> from datetime import date
>>> midnight_to_utc(datetime(2017, 1, 1))
datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>)
>>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)))
datetime.datetime(... | 1.739809 | 2.211954 | 0.786549 |
value = str(value).lower()
if value in ['1', 't', 'true', 'y', 'yes']:
return True
elif value in ['0', 'f', 'false', 'n', 'no']:
return False
return None | def getbool(value) | Returns a boolean from any of a range of values. Returns None for
unrecognized values. Numbers other than 0 and 1 are considered
unrecognized.
>>> getbool(True)
True
>>> getbool(1)
True
>>> getbool('1')
True
>>> getbool('t')
True
>>> getbool(2)
>>> getbool(0)
False
... | 1.87451 | 2.349326 | 0.797893 |
# Two ways to count number of non-None parameters:
#
# 1. sum([1 if v is not None else 0 for v in kwargs.values()])
#
# Using a list comprehension instead of a generator comprehension as the
# parameter to `sum` is faster on both Python 2 and 3.
#
# 2. len(kwargs) - kwargs.va... | def require_one_of(_return=False, **kwargs) | Validator that raises :exc:`TypeError` unless one and only one parameter is
not ``None``. Use this inside functions that take multiple parameters, but
allow only one of them to be specified::
def my_func(this=None, that=None, other=None):
# Require one and only one of `this` or `that`
... | 3.756746 | 3.684079 | 1.019725 |
r
if six.PY3: # pragma: no cover
# email.header.decode_header expects strings, not bytes. Your input data may be in bytes.
# Since these bytes are almost always ASCII, calling `.decode()` on it without specifying
# a charset should work fine.
if isinstance(value, six.binary_type... | def unicode_http_header(value) | r"""
Convert an ASCII HTTP header string into a unicode string with the
appropriate encoding applied. Expects headers to be RFC 2047 compliant.
>>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal'
True
>>> unicode_http_header(b'=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal'
True
... | 6.021856 | 6.225986 | 0.967213 |
realname, address = email.utils.parseaddr(emailaddr)
try:
username, domain = address.split('@')
if not username:
return None
return domain or None
except ValueError:
return None | def get_email_domain(emailaddr) | Return the domain component of an email address. Returns None if the
provided string cannot be parsed as an email address.
>>> get_email_domain('test@example.com')
'example.com'
>>> get_email_domain('test+trailing@example.com')
'example.com'
>>> get_email_domain('Example Address <test@example.c... | 3.915631 | 5.261959 | 0.744139 |
def hourmin(delta):
if delta.days < 0:
hours, remaining = divmod(86400 - delta.seconds, 3600)
else:
hours, remaining = divmod(delta.seconds, 3600)
minutes, remaining = divmod(remaining, 60)
return hours, minutes
now = datetime.utcnow()
# Make a l... | def sorted_timezones() | Return a list of timezones sorted by offset from UTC. | 3.227013 | 3.128444 | 1.031507 |
parsed = urlparse(url)
if parsed.hostname is None or parsed.hostname in ['localhost', 'localhost.localdomain'] or (
_ipv4_re.search(parsed.hostname)):
return None
namespace = parsed.hostname.split('.')
namespace.reverse()
if namespace and not namespace[0]:
namespace... | def namespace_from_url(url) | Construct a dotted namespace string from a URL. | 3.354635 | 3.28251 | 1.021972 |
r1 = tldextract.extract(d1)
r2 = tldextract.extract(d2)
# r1 and r2 contain subdomain, domain and suffix.
# We want to confirm that domain and suffix match.
return r1.domain == r2.domain and r1.suffix == r2.suffix | def base_domain_matches(d1, d2) | Check if two domains have the same base domain, using the Public Suffix List.
>>> base_domain_matches('https://hasjob.co', 'hasjob.co')
True
>>> base_domain_matches('hasgeek.hasjob.co', 'hasjob.co')
True
>>> base_domain_matches('hasgeek.com', 'hasjob.co')
False
>>> base_domain_matches('stat... | 3.16405 | 3.693691 | 0.856609 |
return composite(MarkdownComposite,
Column(name + '_text', UnicodeText, **kwargs),
Column(name + '_html', UnicodeText, **kwargs),
deferred=deferred, group=group or name
) | def MarkdownColumn(name, deferred=False, group=None, **kwargs) | Create a composite column that autogenerates HTML from Markdown text,
storing data in db columns named with ``_html`` and ``_text`` prefixes. | 5.087738 | 3.808099 | 1.336031 |
if not isinstance(value, MutableDict):
if isinstance(value, dict):
return MutableDict(value)
elif isinstance(value, six.string_types):
# Assume JSON string
if value:
return MutableDict(simplejson.loads(value, u... | def coerce(cls, key, value) | Convert plain dictionaries to MutableDict. | 4.368638 | 3.441278 | 1.269481 |
blacklist = set([n[1:] for n in namespecs if n.startswith('!')])
not_blacklist = [n for n in namespecs if not n.startswith('!')]
return Bundle(*[bundle for name, version, bundle
in self._require_recursive(*not_blacklist) if name not in blacklist]) | def require(self, *namespecs) | Return a bundle of the requested assets and their dependencies. | 5.637578 | 4.78127 | 1.179097 |
for statemanager, conditions in self.statetransition.transitions.items():
current_state = getattr(self.obj, statemanager.propname)
if conditions['from'] is None:
state_valid = True
else:
mstate = conditions['from'].get(current_state)
... | def _state_invalid(self) | If the state is invalid for the transition, return details on what didn't match
:return: Tuple of (state manager, current state, label for current state) | 4.784698 | 4.429417 | 1.080209 |
if value not in self.lenum:
raise ValueError("Not a valid value: %s" % value)
type(obj).__dict__[self.propname].__set__(obj, value) | def _set(self, obj, value) | Internal method to set state, called by meth:`StateTransition.__call__` | 6.885401 | 6.323578 | 1.088846 |
# See `_add_state_internal` for explanation of the following
if hasattr(self, name):
raise AttributeError(
"State group name %s conflicts with existing attribute in the state manager" % name)
mstate = ManagedStateGroup(name, self, states)
self.states[... | def add_state_group(self, name, *states) | Add a group of managed states. Groups can be specified directly in the
:class:`~coaster.utils.classes.LabeledEnum`. This method is only useful
for grouping a conditional state with existing states. It cannot be
used to form a group of groups.
:param str name: Name of this group
... | 5.133136 | 5.886859 | 0.871965 |
# We'll accept a ManagedState with grouped values, but not a ManagedStateGroup
if not isinstance(state, ManagedState):
raise TypeError("Not a managed state: %s" % repr(state))
elif state.statemanager != self:
raise ValueError("State %s is not associated with this... | def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None) | Add a conditional state that combines an existing state with a validator
that must also pass. The validator receives the object on which the property
is present as a parameter.
:param str name: Name of the new state
:param ManagedState state: Existing state that this is based on
... | 4.249356 | 4.474283 | 0.949729 |
def decorator(f):
if isinstance(f, StateTransition):
f.add_transition(self, from_, to, if_, data)
st = f
else:
st = StateTransition(f, self, from_, to, if_, data)
self.transitions.append(st.name)
return st
... | def transition(self, from_, to, if_=None, **data) | Decorates a method to transition from one state to another. The
decorated method can accept any necessary parameters and perform
additional processing, or raise an exception to abort the transition.
If it returns without an error, the state value is updated
automatically. Transitions may... | 3.623134 | 3.975598 | 0.911343 |
return self.transition(from_, None, if_, **data) | def requires(self, from_, if_=None, **data) | Decorates a method that may be called if the given state is currently active.
Registers a transition internally, but does not change the state.
:param from_: Required state to allow this call (can be a state group)
:param if_: Validator(s) that, given the object, must all return True for the ca... | 9.028352 | 11.684745 | 0.772661 |
if obj is not None:
return getattr(obj, self.propname)
else:
return getattr(cls, self.propname) | def _value(self, obj, cls=None) | The state value (called from the wrapper) | 3.678539 | 3.269275 | 1.125185 |
return CheckConstraint(
str(column_constructor(column).in_(lenum.keys()).compile(compile_kwargs={'literal_binds': True})),
**kwargs) | def check_constraint(column, lenum, **kwargs) | Returns a SQL CHECK constraint string given a column name and a
:class:`~coaster.utils.classes.LabeledEnum`.
Alembic may not detect the CHECK constraint when autogenerating
migrations, so you may need to do this manually using the Python
console to extract the SQL string::
... | 6.43736 | 8.26925 | 0.77847 |
if self.obj is not None:
for mstate in self.statemanager.all_states_by_value[self.value]:
msw = mstate(self.obj, self.cls) # This returns a wrapper
if msw: # If the wrapper evaluates to True, it's our best match
return msw | def bestmatch(self) | Best matching current scalar state (direct or conditional), only
applicable when accessed via an instance. | 9.698454 | 8.638727 | 1.122672 |
if self.obj is not None:
return {name: mstate(self.obj, self.cls)
for name, mstate in self.statemanager.states.items()
if mstate(self.obj, self.cls)} | def current(self) | All states and state groups that are currently active. | 6.820048 | 5.865564 | 1.162727 |
if current and isinstance(self.obj, RoleMixin):
proxy = self.obj.current_access()
else:
proxy = {}
current = False # In case the host object is not a RoleMixin
return OrderedDict((name, transition) for name, transition in
# Retrieve trans... | def transitions(self, current=True) | Returns available transitions for the current state, as a dictionary of
name: :class:`StateTransitionWrapper`.
:param bool current: Limit to transitions available in ``obj.``
:meth:`~coaster.sqlalchemy.mixins.RoleMixin.current_access` | 8.873592 | 7.081093 | 1.253139 |
proxy = self.obj.access_for(roles, actor, anchors)
return {name: transition for name, transition in self.transitions(current=False).items()
if name in proxy} | def transitions_for(self, roles=None, actor=None, anchors=[]) | For use on :class:`~coaster.sqlalchemy.mixins.RoleMixin` classes:
returns currently available transitions for the specified
roles or actor as a dictionary of name: :class:`StateTransitionWrapper`. | 7.969698 | 7.099466 | 1.122577 |
cls = self.cls if self.cls is not None else type(self.obj) # Class of the item being managed
groups = OrderedDict()
for mstate in self.statemanager.states_by_value.values():
# Ensure we sort groups using the order of states in the source LabeledEnum.
# We'll dis... | def group(self, items, keep_empty=False) | Given an iterable of instances, groups them by state using :class:`ManagedState` instances
as dictionary keys. Returns an `OrderedDict` that preserves the order of states from
the source :class:`~coaster.utils.classes.LabeledEnum`.
:param bool keep_empty: If ``True``, empty states are included ... | 4.859067 | 4.12167 | 1.178907 |
def indent_code(matchobj):
syntax = matchobj.group(1)
code = matchobj.group(2)
if syntax:
result = ' :::' + syntax + '\n'
else:
result = ''
# The last line will be blank since it had the closing "```". Discard it
# when indenting the li... | def gfm(text) | Prepare text for rendering by a regular Markdown processor. | 4.021921 | 3.977104 | 1.011269 |
if text is None:
return None
if html:
return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid_tags=valid_tags))
else:
return Markup(markdown_convert_text(gfm(text))) | def markdown(text, html=False, valid_tags=GFM_TAGS) | Return Markdown rendered text using GitHub Flavoured Markdown,
with HTML escaped and syntax-highlighting enabled. | 3.058632 | 2.979169 | 1.026673 |
if method_rule.startswith('/'):
return method_rule
else:
return class_rule + ('' if class_rule.endswith('/') or not method_rule else '/') + method_rule | def rulejoin(class_rule, method_rule) | Join class and method rules. Used internally by :class:`ClassView` to
combine rules from the :func:`route` decorators on the class and on the
individual view handler methods::
>>> rulejoin('/', '')
'/'
>>> rulejoin('/', 'first')
'/first'
>>> rulejoin('/first', '/second')... | 3.646801 | 4.352709 | 0.837823 |
def inner(f):
def is_available_here(context):
return bool(roles.intersection(context.obj.current_roles))
def is_available(context):
result = is_available_here(context)
if result and hasattr(f, 'is_available'):
# We passed, but we're wrapping ... | def requires_roles(roles) | Decorator for :class:`ModelView` views that limits access to the specified
roles. | 3.657922 | 3.7312 | 0.980361 |
@wraps(f)
def wrapper(self, *args, **kwargs):
if request.method == 'GET' and self.obj is not None:
correct_url = self.obj.url_for(f.__name__, _external=True)
if correct_url != request.base_url:
if request.query_string:
correct_url = correc... | def url_change_check(f) | View method decorator that checks the URL of the loaded object in
``self.obj`` against the URL in the request (using
``self.obj.url_for(__name__)``). If the URLs do not match,
and the request is a ``GET``, it issues a redirect to the correct URL.
Usage::
@route('/doc/<document>')
class ... | 2.562593 | 2.345701 | 1.092464 |
def view_func(**view_args):
# view_func does not make any reference to variables from init_app to avoid creating
# a closure. Instead, the code further below sticks all relevant variables into
# view_func's namespace.
# Instantiate the view class. We dep... | def init_app(self, app, cls, callback=None) | Register routes for a given app and :class:`ClassView` class. At the
time of this call, we will always be in the view class even if we were
originally defined in a base class. :meth:`ClassView.init_app`
ensures this. :meth:`init_app` therefore takes the liberty of adding
additional attri... | 5.250796 | 5.173685 | 1.014904 |
if hasattr(self._viewh.wrapped_func, 'is_available'):
return self._viewh.wrapped_func.is_available(self._obj)
return True | def is_available(self) | Indicates whether this view is available in the current context | 6.468046 | 5.321447 | 1.215467 |
# Call the :meth:`before_request` method
resp = self.before_request()
if resp:
return self.after_request(make_response(resp))
# Call the view handler method, then pass the response to :meth:`after_response`
return self.after_request(make_response(view(self, *... | def dispatch_request(self, view, view_args) | View dispatcher that calls before_request, the view, and then after_request.
Subclasses may override this to provide a custom flow. :class:`ModelView`
does this to insert a model loading phase.
:param view: View method wrapped in specified decorators. The dispatcher
must call this
... | 4.243517 | 4.110312 | 1.032407 |
if self.is_always_available:
return True
for viewname in self.__views__:
if getattr(self, viewname).is_available():
return True
return False | def is_available(self) | Returns `True` if *any* view handler in the class is currently
available via its `is_available` method. | 5.016894 | 3.536884 | 1.41845 |
setattr(cls, _name, route(rule, **options)(cls.__get_raw_attr(_name))) | def add_route_for(cls, _name, rule, **options) | Add a route for an existing method or view. Useful for modifying routes
that a subclass inherits from a base class::
class BaseView(ClassView):
def latent_view(self):
return 'latent-view'
@route('other')
def other_view(self):
... | 9.58443 | 15.831733 | 0.605394 |
processed = set()
cls.__views__ = set()
cls.is_always_available = False
for base in cls.__mro__:
for name, attr in base.__dict__.items():
if name in processed:
continue
processed.add(name)
if isinsta... | def init_app(cls, app, callback=None) | Register views on an app. If :attr:`callback` is specified, it will
be called after ``app.``:meth:`~flask.Flask.add_url_rule`, with the same
parameters. | 4.269023 | 4.244739 | 1.005721 |
# Call the :meth:`before_request` method
resp = self.before_request()
if resp:
return self.after_request(make_response(resp))
# Load the database model
self.obj = self.loader(**view_args)
# Trigger pre-view processing of the loaded object
resp... | def dispatch_request(self, view, view_args) | View dispatcher that calls :meth:`before_request`, :meth:`loader`,
:meth:`after_loader`, the view, and then :meth:`after_request`.
:param view: View method wrapped in specified decorators.
:param dict view_args: View arguments, to be passed on to the view method | 4.653306 | 3.951389 | 1.177638 |
# Convert lists and None values to sets
rw = set(rw) if rw else set()
call = set(call) if call else set()
read = set(read) if read else set()
write = set(write) if write else set()
# `rw` is shorthand for read+write
read.update(rw)
write.update(rw)
def inner(attr):
__ca... | def with_roles(obj=None, rw=None, call=None, read=None, write=None) | Convenience function and decorator to define roles on an attribute. Only
works with :class:`RoleMixin`, which reads the annotations made by this
function and populates :attr:`~RoleMixin.__roles__`.
Examples::
id = db.Column(Integer, primary_key=True)
with_roles(id, read={'all'})
@... | 5.483829 | 5.808249 | 0.944145 |
def inner(f):
@wraps(f)
def attr(cls):
# Pass f(cls) as a parameter to with_roles.inner to avoid the test for
# iterables within with_roles. We have no idea about the use cases for
# declared_attr in downstream code. There could be a declared_attr
... | def declared_attr_roles(rw=None, call=None, read=None, write=None) | Equivalent of :func:`with_roles` for use with ``@declared_attr``::
@declared_attr
@declared_attr_roles(read={'all'})
def my_column(cls):
return Column(Integer)
While :func:`with_roles` is always the outermost decorator on properties
and functions, :func:`declared_attr_roles... | 7.80649 | 7.481693 | 1.043412 |
# Don't mutate ``__roles__`` in the base class.
# The subclass must have its own.
# Since classes may specify ``__roles__`` directly without
# using :func:`with_roles`, we must preserve existing content.
if '__roles__' not in cls.__dict__:
# If the following line is confusing, it's beca... | def __configure_roles(mapper, cls) | Run through attributes of the class looking for role decorations from
:func:`with_roles` and add them to :attr:`cls.__roles__` | 3.939518 | 3.788303 | 1.039916 |
return InspectableSet(self.roles_for(actor=current_auth.actor, anchors=current_auth.anchors)) | def current_roles(self) | :class:`~coaster.utils.classes.InspectableSet` containing currently
available roles on this object, using
:obj:`~coaster.auth.current_auth`. Use in the view layer to inspect
for a role being present:
if obj.current_roles.editor:
pass
{% if obj.current_ro... | 20.461571 | 10.844199 | 1.886868 |
if roles is None:
roles = self.roles_for(actor=actor, anchors=anchors)
elif actor is not None or anchors:
raise TypeError('If roles are specified, actor/anchors must not be specified')
return RoleAccessProxy(self, roles=roles) | def access_for(self, roles=None, actor=None, anchors=[]) | Return a proxy object that limits read and write access to attributes
based on the actor's roles. If the ``roles`` parameter isn't
provided, :meth:`roles_for` is called with the other parameters::
# This typical call:
obj.access_for(actor=current_auth.actor)
# Is sho... | 3.844693 | 3.359956 | 1.144269 |
return self.access_for(actor=current_auth.actor, anchors=current_auth.anchors) | def current_access(self) | Wraps :meth:`access_for` with :obj:`~coaster.auth.current_auth` to
return a proxy for the currently authenticated user. | 17.94174 | 8.278926 | 2.167158 |
if current_app.config.get('SERVER_NAME') and (
# Check current hostname against server name, ignoring port numbers, if any (split on ':')
request.environ['HTTP_HOST'].split(':', 1)[0] != current_app.config['SERVER_NAME'].split(':', 1)[0]):
return request.url
url = url_for(r... | def get_current_url() | Return the current URL including the query string as a relative path. If the app uses
subdomains, return an absolute path | 3.534254 | 3.419292 | 1.033622 |
if session:
next_url = request_session.pop('next', None) or request.args.get('next', '')
else:
next_url = request.args.get('next', '')
if next_url and not external:
next_url = __clean_external_url(next_url)
if next_url:
return next_url
if default is __marker:
... | def get_next_url(referrer=False, external=False, session=False, default=__marker) | Get the next URL to redirect to. Don't return external URLs unless
explicitly asked for. This is to protect the site from being an unwitting
redirector to external URLs. Subdomains are okay, however.
This function looks for a ``next`` parameter in the request or in the session
(depending on whether par... | 2.666718 | 2.629724 | 1.014068 |
data = json.dumps(dict(*args, **kw), indent=2)
callback = request.args.get('callback', request.args.get('jsonp'))
if callback and __jsoncallback_re.search(callback) is not None:
data = callback + u'(' + data + u');'
mimetype = 'application/javascript'
else:
mimetype = 'appli... | def jsonp(*args, **kw) | Returns a JSON response with a callback wrapper, if asked for.
Consider using CORS instead, as JSONP makes the client app insecure.
See the :func:`~coaster.views.decorators.cors` decorator. | 2.538811 | 2.55396 | 0.994069 |
parsed_url = urlsplit(url)
if not parsed_url.netloc:
# We require an absolute URL
return None, {}
# Take the current runtime environment...
environ = dict(request.environ)
# ...but replace the HTTP host with the URL's host...
environ['HTTP_HOST'] = parsed_url.netloc
# .... | def endpoint_for(url, method=None, return_rule=False, follow_redirects=True) | Given an absolute URL, retrieve the matching endpoint name (or rule) and
view arguments. Requires a current request context to determine runtime
environment.
:param str method: HTTP method to use (defaults to GET)
:param bool return_rule: Return the URL rule instead of the endpoint name
:param bool... | 4.51112 | 4.317631 | 1.044814 |
perms = set(super(DocumentWorkflow, self).permissions())
if g:
if hasattr(g, 'permissions'):
perms.update(g.permissions or [])
if hasattr(self.document, 'permissions'):
perms = self.document.permissions(current_auth.actor, perms)
r... | def permissions(self) | Permissions for this workflow. Plays nice with
:meth:`coaster.views.load_models` and
:class:`coaster.sqlalchemy.PermissionMixin` to determine the available
permissions to the current user. | 6.968427 | 6.457468 | 1.079127 |
annotations = {}
annotations_by_attr = {}
# An attribute may be defined more than once in base classes. Only handle the first
processed = set()
# Loop through all attributes in the class and its base classes, looking for annotations
for base in cls.__mro__:
for name, attr in base.... | def __configure_annotations(mapper, cls) | Run through attributes of the class looking for annotations from
:func:`annotation_wrapper` and add them to :attr:`cls.__annotations__`
and :attr:`cls.__annotations_by_attr__` | 3.55573 | 3.521393 | 1.009751 |
def decorator(attr):
__cache__.setdefault(attr, []).append(annotation)
# Also mark the annotation on the object itself. This will
# fail if the object has a restrictive __slots__, but it's
# required for some objects like Column because SQLAlchemy copies
# them in subcla... | def annotation_wrapper(annotation, doc=None) | Defines an annotation, which can be applied to attributes in a database model. | 7.391641 | 7.181705 | 1.029232 |
if attr in ('actor', 'anchors', 'is_anonymous', 'not_anonymous', 'is_authenticated', 'not_authenticated'):
raise AttributeError("Attribute name %s is reserved by current_auth" % attr)
# Invoking current_auth will also create it on the local stack. We can
# then proceed to set attributes on it.... | def add_auth_attribute(attr, value, actor=False) | Helper function for login managers. Adds authorization attributes
to :obj:`current_auth` for the duration of the request.
:param str attr: Name of the attribute
:param value: Value of the attribute
:param bool actor: Whether this attribute is an actor
(user or client app accessing own data)
... | 6.290623 | 5.564731 | 1.130445 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.