Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def timid_relpath(arg):
# TODO-TEST: unit tests
from os.path import isabs, relpath, sep
if isabs(arg):
result = relpath(arg)
if result.count(sep) + 1 < arg.count(sep):
return result
return arg | [
"convert an argument to a relative path, carefully"
] |
Please provide a description of the function:def exec_(argv): # never returns
# info('EXEC' + colorize(argv)) # TODO: debug logging by environment variable
# in python3, sys.exitfunc has gone away, and atexit._run_exitfuncs seems to be the only pubic-ish interface
# https://hg.python.org/cpython/f... | [
"Wrapper to os.execv which shows the command and runs any atexit handlers (for coverage's sake).\n Like os.execv, this function never returns.\n "
] |
Please provide a description of the function:def exec_scratch_virtualenv(args):
scratch = Scratch()
if not exists(scratch.python):
run(('virtualenv', scratch.venv))
if not exists(join(scratch.src, 'virtualenv.py')):
scratch_python = venv_python(scratch.venv)
# TODO: do we allow... | [
"\n goals:\n - get any random site-packages off of the pythonpath\n - ensure we can import virtualenv\n - ensure that we're not using the interpreter that we may need to delete\n - idempotency: do nothing if the above goals are already met\n "
] |
Please provide a description of the function:def ensure_virtualenv(args, return_values):
def adjust_options(options, args):
# TODO-TEST: proper error message with no arguments
venv_path = return_values.venv_path = args[0]
if venv_path == DEFAULT_VIRTUALENV_PATH or options.prompt == '<d... | [
"Ensure we have a valid virtualenv."
] |
Please provide a description of the function:def touch(filename, timestamp):
if timestamp is not None:
timestamp = (timestamp, timestamp) # atime, mtime
from os import utime
utime(filename, timestamp) | [
"set the mtime of a file"
] |
Please provide a description of the function:def venv_update(
venv=DEFAULT_OPTION_VALUES['venv='],
install=DEFAULT_OPTION_VALUES['install='],
pip_command=DEFAULT_OPTION_VALUES['pip-command='],
bootstrap_deps=DEFAULT_OPTION_VALUES['bootstrap-deps='],
):
# SMELL: mutable argument... | [
"we have an arbitrary python interpreter active, (possibly) outside the virtualenv we want.\n\n make a fresh venv at the right spot, make sure it has pip-faster, and use it\n "
] |
Please provide a description of the function:def pip_faster(venv_path, pip_command, install, bootstrap_deps):
# activate the virtualenv
execfile_(venv_executable(venv_path, 'activate_this.py'))
# disable a useless warning
# FIXME: ensure a "true SSLContext" is available
from os import environ
... | [
"install and run pip-faster"
] |
Please provide a description of the function:def raise_on_failure(mainfunc):
try:
errors = mainfunc()
if errors:
exit(errors)
except CalledProcessError as error:
exit(error.returncode)
except SystemExit as error:
if error.code:
raise
except Ke... | [
"raise if and only if mainfunc fails"
] |
Please provide a description of the function:def cache_installed_wheels(index_url, installed_packages):
for installed_package in installed_packages:
if not _can_be_cached(installed_package):
continue
_store_wheel_in_cache(installed_package.link.path, index_url) | [
"After installation, pip tells us what it installed and from where.\n\n We build a structure that looks like\n\n .cache/pip-faster/wheelhouse/$index_url/$wheel\n "
] |
Please provide a description of the function:def pip(args):
from sys import stdout
stdout.write(colorize(('pip',) + args))
stdout.write('\n')
stdout.flush()
return pipmodule._internal.main(list(args)) | [
"Run pip, in-process."
] |
Please provide a description of the function:def dist_to_req(dist):
try: # :pragma:nocover: (pip>=10)
from pip._internal.operations.freeze import FrozenRequirement
except ImportError: # :pragma:nocover: (pip<10)
from pip import FrozenRequirement
# normalize the casing, dashes in the ... | [
"Make a pip.FrozenRequirement from a pkg_resources distribution object"
] |
Please provide a description of the function:def pip_get_installed():
from pip._internal.utils.misc import dist_is_local
return tuple(
dist_to_req(dist)
for dist in fresh_working_set()
if dist_is_local(dist)
if dist.key != 'python' # See #220
) | [
"Code extracted from the middle of the pip freeze command.\n FIXME: does not list anything installed via -e\n "
] |
Please provide a description of the function:def fresh_working_set():
class WorkingSetPlusEditableInstalls(pkg_resources.WorkingSet):
def __init__(self, *args, **kwargs):
self._normalized_name_mapping = {}
super(WorkingSetPlusEditableInstalls, self).__init__(*args, **kwargs)
... | [
"return a pkg_resources \"working set\", representing the *currently* installed packages",
"Same as the original .add_entry, but sets only=False, so that egg-links are honored."
] |
Please provide a description of the function:def req_cycle(req):
cls = req.__class__
seen = {req.name}
while isinstance(req.comes_from, cls):
req = req.comes_from
if req.name in seen:
return True
else:
seen.add(req.name)
return False | [
"is this requirement cyclic?"
] |
Please provide a description of the function:def pretty_req(req):
from copy import copy
req = copy(req)
req.link = None
req.satisfied_by = None
return req | [
"\n return a copy of a pip requirement that is a bit more readable,\n at the expense of removing some of its data\n "
] |
Please provide a description of the function:def trace_requirements(requirements):
requirements = tuple(pretty_req(r) for r in requirements)
working_set = fresh_working_set()
# breadth-first traversal:
from collections import deque
queue = deque(requirements)
queued = {_package_req_to_pkg_... | [
"given an iterable of pip InstallRequirements,\n return the set of required packages, given their transitive requirements.\n "
] |
Please provide a description of the function:def patch(attrs, updates):
orig = {}
for attr, value in updates:
orig[attr] = attrs[attr]
attrs[attr] = value
return orig | [
"Perform a set of updates to a attribute dictionary, return the original values."
] |
Please provide a description of the function:def patched(attrs, updates):
orig = patch(attrs, updates.items())
try:
yield orig
finally:
patch(attrs, orig.items()) | [
"A context in which some attributes temporarily have a modified value."
] |
Please provide a description of the function:def pipfaster_packagefinder():
# A poor man's dependency injection: monkeypatch :(
try: # :pragma:nocover: pip>=18.1
from pip._internal.cli import base_command
except ImportError: # :pragma:nocover: pip<18.1
from pip._internal import baseco... | [
"Provide a short-circuited search when the requirement is pinned and appears on disk.\n\n Suggested upstream at: https://github.com/pypa/pip/pull/2114\n "
] |
Please provide a description of the function:def pipfaster_download_cacher(index_urls):
from pip._internal import download
orig = download._download_http_url
patched_fn = get_patched_download_http_url(orig, index_urls)
return patched(vars(download), {'_download_http_url': patched_fn}) | [
"vanilla pip stores a cache of the http session in its cache and not the\n wheel files. We intercept the download and save those files into our\n cache\n "
] |
Please provide a description of the function:def run(self, options, args):
if options.prune:
previously_installed = pip_get_installed()
index_urls = [options.index_url] + options.extra_index_urls
with pipfaster_download_cacher(index_urls):
requirement_set = supe... | [
"update install options with caching values"
] |
Please provide a description of the function:def bulk_of_jsons(d):
"Replace serialized JSON values with objects in a bulk array response (list)"
def _f(b):
for index, item in enumerate(b):
if item is not None:
b[index] = d(item)
return b
return _f | [] |
Please provide a description of the function:def setEncoder(self, encoder):
if not encoder:
self._encoder = json.JSONEncoder()
else:
self._encoder = encoder
self._encode = self._encoder.encode | [
"\n Sets the client's encoder\n ``encoder`` should be an instance of a ``json.JSONEncoder`` class\n "
] |
Please provide a description of the function:def setDecoder(self, decoder):
if not decoder:
self._decoder = json.JSONDecoder()
else:
self._decoder = decoder
self._decode = self._decoder.decode | [
"\n Sets the client's decoder\n ``decoder`` should be an instance of a ``json.JSONDecoder`` class\n "
] |
Please provide a description of the function:def jsondel(self, name, path=Path.rootPath()):
return self.execute_command('JSON.DEL', name, str_path(path)) | [
"\n Deletes the JSON value stored at key ``name`` under ``path``\n "
] |
Please provide a description of the function:def jsonget(self, name, *args):
pieces = [name]
if len(args) == 0:
pieces.append(Path.rootPath())
else:
for p in args:
pieces.append(str_path(p))
# Handle case where key doesn't exist. The ... | [
"\n Get the object stored as a JSON value at key ``name``\n ``args`` is zero or more paths, and defaults to root path\n "
] |
Please provide a description of the function:def jsonmget(self, path, *args):
pieces = []
pieces.extend(args)
pieces.append(str_path(path))
return self.execute_command('JSON.MGET', *pieces) | [
"\n Gets the objects stored as a JSON values under ``path`` from \n keys ``args``\n "
] |
Please provide a description of the function:def jsonset(self, name, path, obj, nx=False, xx=False):
pieces = [name, str_path(path), self._encode(obj)]
# Handle existential modifiers
if nx and xx:
raise Exception('nx and xx are mutually exclusive: use one, the '
... | [
"\n Set the JSON value at key ``name`` under the ``path`` to ``obj``\n ``nx`` if set to True, set ``value`` only if it does not exist\n ``xx`` if set to True, set ``value`` only if it exists\n "
] |
Please provide a description of the function:def jsontype(self, name, path=Path.rootPath()):
return self.execute_command('JSON.TYPE', name, str_path(path)) | [
"\n Gets the type of the JSON value under ``path`` from key ``name``\n "
] |
Please provide a description of the function:def jsonnumincrby(self, name, path, number):
return self.execute_command('JSON.NUMINCRBY', name, str_path(path), self._encode(number)) | [
"\n Increments the numeric (integer or floating point) JSON value under\n ``path`` at key ``name`` by the provided ``number``\n "
] |
Please provide a description of the function:def jsonnummultby(self, name, path, number):
return self.execute_command('JSON.NUMMULTBY', name, str_path(path), self._encode(number)) | [
"\n Multiplies the numeric (integer or floating point) JSON value under\n ``path`` at key ``name`` with the provided ``number``\n "
] |
Please provide a description of the function:def jsonstrappend(self, name, string, path=Path.rootPath()):
return self.execute_command('JSON.STRAPPEND', name, str_path(path), self._encode(string)) | [
"\n Appends to the string JSON value under ``path`` at key ``name`` the\n provided ``string``\n "
] |
Please provide a description of the function:def jsonstrlen(self, name, path=Path.rootPath()):
return self.execute_command('JSON.STRLEN', name, str_path(path)) | [
"\n Returns the length of the string JSON value under ``path`` at key\n ``name``\n "
] |
Please provide a description of the function:def jsonarrappend(self, name, path=Path.rootPath(), *args):
pieces = [name, str_path(path)]
for o in args:
pieces.append(self._encode(o))
return self.execute_command('JSON.ARRAPPEND', *pieces) | [
"\n Appends the objects ``args`` to the array under the ``path` in key\n ``name``\n "
] |
Please provide a description of the function:def jsonarrindex(self, name, path, scalar, start=0, stop=-1):
return self.execute_command('JSON.ARRINDEX', name, str_path(path), self._encode(scalar), start, stop) | [
"\n Returns the index of ``scalar`` in the JSON array under ``path`` at key\n ``name``. The search can be limited using the optional inclusive\n ``start`` and exclusive ``stop`` indices.\n "
] |
Please provide a description of the function:def jsonarrinsert(self, name, path, index, *args):
pieces = [name, str_path(path), index]
for o in args:
pieces.append(self._encode(o))
return self.execute_command('JSON.ARRINSERT', *pieces) | [
"\n Inserts the objects ``args`` to the array at index ``index`` under the\n ``path` in key ``name``\n "
] |
Please provide a description of the function:def jsonarrlen(self, name, path=Path.rootPath()):
return self.execute_command('JSON.ARRLEN', name, str_path(path)) | [
"\n Returns the length of the array JSON value under ``path`` at key\n ``name``\n "
] |
Please provide a description of the function:def jsonarrpop(self, name, path=Path.rootPath(), index=-1):
return self.execute_command('JSON.ARRPOP', name, str_path(path), index) | [
"\n Pops the element at ``index`` in the array JSON value under ``path`` at\n key ``name``\n "
] |
Please provide a description of the function:def jsonarrtrim(self, name, path, start, stop):
return self.execute_command('JSON.ARRTRIM', name, str_path(path), start, stop) | [
"\n Trim the array JSON value under ``path`` at key ``name`` to the \n inclusive range given by ``start`` and ``stop``\n "
] |
Please provide a description of the function:def jsonobjkeys(self, name, path=Path.rootPath()):
return self.execute_command('JSON.OBJKEYS', name, str_path(path)) | [
"\n Returns the key names in the dictionary JSON value under ``path`` at key\n ``name``\n "
] |
Please provide a description of the function:def jsonobjlen(self, name, path=Path.rootPath()):
return self.execute_command('JSON.OBJLEN', name, str_path(path)) | [
"\n Returns the length of the dictionary JSON value under ``path`` at key\n ``name``\n "
] |
Please provide a description of the function:def pipeline(self, transaction=True, shard_hint=None):
p = Pipeline(
connection_pool=self.connection_pool,
response_callbacks=self.response_callbacks,
transaction=transaction,
shard_hint=shard_hint)
p.s... | [
"\n Return a new pipeline object that can queue multiple commands for\n later execution. ``transaction`` indicates whether all commands\n should be executed atomically. Apart from making a group of operations\n atomic, pipelines are useful for reducing the back-and-forth overhead\n ... |
Please provide a description of the function:def get_pg_info():
from psycopg2 import connect, OperationalError
log.debug("entered get_pg_info")
try:
conf = settings.DATABASES['default']
database = conf["NAME"]
user = conf["USER"]
host = conf["HOST"]
port = conf["... | [
"Check PostgreSQL connection."
] |
Please provide a description of the function:def get_redis_info():
from kombu.utils.url import _parse_url as parse_redis_url
from redis import (
StrictRedis,
ConnectionError as RedisConnectionError,
ResponseError as RedisResponseError,
)
for conf_name in ('REDIS_URL', 'BROKE... | [
"Check Redis connection."
] |
Please provide a description of the function:def get_elasticsearch_info():
from elasticsearch import (
Elasticsearch,
ConnectionError as ESConnectionError
)
if hasattr(settings, 'ELASTICSEARCH_URL'):
url = settings.ELASTICSEARCH_URL
else:
return {"status": NO_CONFIG}... | [
"Check Elasticsearch connection."
] |
Please provide a description of the function:def get_celery_info():
import celery
if not getattr(settings, 'USE_CELERY', False):
log.error("No celery config found. Set USE_CELERY in settings to enable.")
return {"status": NO_CONFIG}
start = datetime.now()
try:
# pylint: disa... | [
"\n Check celery availability\n "
] |
Please provide a description of the function:def get_certificate_info():
if hasattr(settings, 'MIT_WS_CERTIFICATE') and settings.MIT_WS_CERTIFICATE:
mit_ws_certificate = settings.MIT_WS_CERTIFICATE
else:
return {"status": NO_CONFIG}
app_cert = OpenSSL.crypto.load_certificate(
O... | [
"\n checks app certificate expiry status\n "
] |
Please provide a description of the function:def status(request): # pylint: disable=unused-argument
token = request.GET.get("token", "")
if not token or token != settings.STATUS_TOKEN:
raise Http404()
info = {}
check_mapping = {
'REDIS': (get_redis_info, 'redis'),
'ELASTIC... | [
"Status"
] |
Please provide a description of the function:def process_response(self, request, response):
# A higher middleware layer may return a request which does not contain
# messages storage, so make no assumption that it will be there.
if hasattr(request, '_messages'):
unstored_mes... | [
"\n Update the storage backend (i.e., save the messages).\n\n Raise ValueError if not all messages could be stored and DEBUG is True.\n "
] |
Please provide a description of the function:def route(self, rule, **options):
def decorator(f):
endpoint = options.pop('endpoint', None)
self.add_update_rule(rule, endpoint, f, **options)
return f
return decorator | [
"A decorator that is used to register a view function for a\n given URL rule. This does the same thing as :meth:`add_url_rule`\n but is intended for decorator usage::\n @app.route('/')\n def index():\n return 'Hello World'\n For more information refer to :r... |
Please provide a description of the function:def _start(self):
'''Requests bot information based on current api_key, and sets
self.whoami to dictionary with username, first_name, and id of the
configured bot.
'''
if self.whoami is None:
me = self.get_me()
... | [] |
Please provide a description of the function:def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False):
'''These should also be in the config section, but some here for
overrides
'''
if self.config['api_key'] is None:
raise ValueError('config api_key is undefin... | [] |
Please provide a description of the function:def get_value(self, var, cast=None, default=environ.Env.NOTSET, # noqa: C901
parse_default=False, raw=False):
if raw:
env_var = var
else:
env_var = f'{self.prefix}{var}'
# logger.debug(f"get '{env_... | [
"Return value for given environment variable.\n\n :param var: Name of variable.\n :param cast: Type to cast return value as.\n :param default: If var not present in environ, return this instead.\n :param parse_default: force to parse default..\n\n ... |
Please provide a description of the function:def fqn(o):
parts = []
if isinstance(o, (str, bytes)):
return o
if not hasattr(o, '__module__'):
raise ValueError('Invalid argument `%s`' % o)
parts.append(o.__module__)
if isclass(o):
parts.append(o.__name__)
elif isinsta... | [
"Returns the fully qualified class name of an object or a class\n\n :param o: object or class\n :return: class name\n "
] |
Please provide a description of the function:def get_otp(self, message_list):
if isinstance(message_list, six.string_types):
message_list = [message_list, ]
for x in message_list:
if self.separator in x:
raise ValueError('Messages cannot contain separator... | [
"\n Generates a url-safe base64 encoded encypted message together with current timestamp (to the second).\n Throws in some random number of characters to prenvent ecryption chill exploit\n Args:\n message_list: the message to be encrypted\n\n Returns:\n\n "
] |
Please provide a description of the function:def validate(self, cipher_text, max_timedelta=None):
if isinstance(cipher_text, six.string_types):
cipher_text.encode()
cipher_text = base64.urlsafe_b64decode(cipher_text)
decrypted = self.encryption_suite.decrypt(cipher_text).dec... | [
"\n Will decrypt the url safe base64 encoded crypted str or bytes array.\n Args:\n cipher_text: the encrypted text\n max_timedelta: maximum timedelta in seconds\n\n Returns:\n the original message list\n "
] |
Please provide a description of the function:def get_attr(obj, attr, default=None):
if '.' not in attr:
return getattr(obj, attr, default)
else:
L = attr.split('.')
return get_attr(getattr(obj, L[0], default), '.'.join(L[1:]), default) | [
"Recursive get object's attribute. May use dot notation.\n\n >>> class C(object): pass\n >>> a = C()\n >>> a.b = C()\n >>> a.b.c = 4\n >>> get_attr(a, 'b.c')\n 4\n\n >>> get_attr(a, 'b.c.y', None)\n\n >>> get_attr(a, 'b.c.y', 1)\n 1\n "
] |
Please provide a description of the function:def asset(path):
commit = bitcaster.get_full_version()
return mark_safe('{0}?{1}'.format(_static(path), commit)) | [
"\n Join the given path with the STATIC_URL setting.\n\n Usage::\n\n {% static path [as varname] %}\n\n Examples::\n\n {% static \"myapp/css/base.css\" %}\n {% static variable_with_path %}\n {% static \"myapp/css/base.css\" as admin_base_css %}\n {% static variable_with_p... |
Please provide a description of the function:def get_client_ip(request):
try:
return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
except (KeyError, IndexError):
return request.META.get('REMOTE_ADDR') | [
"\n Naively yank the first IP address in an X-Forwarded-For header\n and assume this is correct.\n\n Note: Don't use this in security sensitive situations since this\n value may be forged from a client.\n "
] |
Please provide a description of the function:def rows(thelist, n):
try:
n = int(n)
thelist = list(thelist)
except (ValueError, TypeError):
return [thelist]
list_len = len(thelist)
split = list_len // n
if list_len % n != 0:
split += 1
return [thelist[split *... | [
"\n Break a list into ``n`` rows, filling up each row to the maximum equal\n length possible. For example::\n\n >>> l = range(10)\n\n >>> rows(l, 2)\n [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]\n\n >>> rows(l, 3)\n [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]\n\n >>> rows(l, 4)\n ... |
Please provide a description of the function:def rows_distributed(thelist, n):
try:
n = int(n)
thelist = list(thelist)
except (ValueError, TypeError):
return [thelist]
list_len = len(thelist)
split = list_len // n
remainder = list_len % n
offset = 0
rows = []
... | [
"\n Break a list into ``n`` rows, distributing columns as evenly as possible\n across the rows. For example::\n\n >>> l = range(10)\n\n >>> rows_distributed(l, 2)\n [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]\n\n >>> rows_distributed(l, 3)\n [[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]\n\n ... |
Please provide a description of the function:def update_status(self, *args, **kwargs):
post_data = {}
media_ids = kwargs.pop('media_ids', None)
if media_ids is not None:
post_data['media_ids'] = list_to_csv(media_ids)
return bind_api(
api=self,
... | [
" :reference: https://dev.twitter.com/rest/reference/post/statuses/update\n :allowed_param:'status', 'in_reply_to_status_id', 'in_reply_to_status_id_str', 'auto_populate_reply_metadata', 'lat', 'long', 'source', 'place_id', 'display_coordinates', 'media_ids'\n "
] |
Please provide a description of the function:def send_direct_message_new(self, messageobject):
headers, post_data = API._buildmessageobject(messageobject)
return bind_api(
api=self,
path='/direct_messages/events/new.json',
method='POST',
require_a... | [
" :reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html\n "
] |
Please provide a description of the function:def update_profile_banner(self, filename, **kargs):
f = kargs.pop('file', None)
headers, post_data = API._pack_image(filename, 700, form_field='banner', f=f)
bind_api(
api=self,
path='/account/update_profile_banner.jso... | [
" :reference: https://dev.twitter.com/rest/reference/post/account/update_profile_banner\n :allowed_param:'width', 'height', 'offset_left', 'offset_right'\n "
] |
Please provide a description of the function:def _pack_image(filename, max_size, form_field='image', f=None):
# image must be less than 700kb in size
if f is None:
try:
if os.path.getsize(filename) > (max_size * 1024):
raise TweepError('File is to... | [
"Pack image from file into multipart-formdata post body"
] |
Please provide a description of the function:def channel_submit_row(context):
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
show_save = context.get('show_save', True)
show_save_and_continue = context.get('show_save_and_continue', True)
can_delete = ... | [
"\n Display the row of buttons for delete and save.\n "
] |
Please provide a description of the function:def get_setting(self, name):
notfound = object()
"get configuration from 'constance.config' first "
value = getattr(config, name, notfound)
if name.endswith('_WHITELISTED_DOMAINS'):
if value:
return value.split(',')... | [] |
Please provide a description of the function:def user_data(self, access_token, *args, **kwargs):
try:
user_data = super().user_data(access_token, *args, **kwargs)
if not user_data.get('email'):
raise AuthFailed(self, _('You must have a public email configured in ... | [
"Loads user data from service"
] |
Please provide a description of the function:def debug(self, request, message, extra_tags='', fail_silently=False):
add(self.target_name, request, constants.DEBUG, message, extra_tags=extra_tags,
fail_silently=fail_silently) | [
"Add a message with the ``DEBUG`` level."
] |
Please provide a description of the function:def info(self, request, message, extra_tags='', fail_silently=False):
add(self.target_name,
request, constants.INFO, message, extra_tags=extra_tags,
fail_silently=fail_silently) | [
"Add a message with the ``INFO`` level."
] |
Please provide a description of the function:def success(self, request, message, extra_tags='', fail_silently=False):
add(self.target_name, request, constants.SUCCESS, message, extra_tags=extra_tags,
fail_silently=fail_silently) | [
"Add a message with the ``SUCCESS`` level."
] |
Please provide a description of the function:def warning(self, request, message, extra_tags='', fail_silently=False):
add(self.target_name, request, constants.WARNING, message, extra_tags=extra_tags,
fail_silently=fail_silently) | [
"Add a message with the ``WARNING`` level."
] |
Please provide a description of the function:def error(self, request, message, extra_tags='', fail_silently=False):
add(self.target_name, request, constants.ERROR, message, extra_tags=extra_tags,
fail_silently=fail_silently) | [
"Add a message with the ``ERROR`` level."
] |
Please provide a description of the function:def createuser(ctx, email, password, superuser, no_password, prompt):
'Create a new user.'
if prompt:
if not email:
email = click.prompt('Email')
if not (password or no_password):
password = click.prompt('Password')
... | [] |
Please provide a description of the function:def signup(request, signup_form=SignupForm,
template_name='userena/signup_form.html', success_url=None,
extra_context=None):
# If signup is disabled, return 403
if userena_settings.USERENA_DISABLE_SIGNUP:
raise PermissionDenied
... | [
"\n Signup of an account.\n\n Signup requiring a username, email and password. After signup a user gets\n an email with an activation link used to activate their account. After\n successful signup redirects to ``success_url``.\n\n :param signup_form:\n Form that will be used to sign a user. De... |
Please provide a description of the function:def signout(request, next_page=userena_settings.USERENA_REDIRECT_ON_SIGNOUT,
template_name='userena/signout.html', *args, **kwargs):
if request.user.is_authenticated() and userena_settings.USERENA_USE_MESSAGES: # pragma: no cover
messages.success... | [
"\n Signs out the user and adds a success message ``You have been signed\n out.`` If next_page is defined you will be redirected to the URI. If\n not the template in template_name is used.\n\n :param next_page:\n A string which specifies the URI to redirect to.\n\n :param template_name:\n ... |
Please provide a description of the function:def extend(self, other):
overlap = [key for key in other.defaults if key in self.defaults]
if overlap:
raise ValueError(
"Duplicate hyperparameter(s): %s" % " ".join(overlap))
new = dict(self.defaults)
new.... | [
"\n Return a new HyperparameterDefaults instance containing the\n hyperparameters from the current instance combined with\n those from other.\n\n It is an error if self and other have any hyperparameters in\n common.\n "
] |
Please provide a description of the function:def with_defaults(self, obj):
self.check_valid_keys(obj)
obj = dict(obj)
for (key, value) in self.defaults.items():
if key not in obj:
obj[key] = value
return obj | [
"\n Given a dict of hyperparameter settings, return a dict containing\n those settings augmented by the defaults for any keys missing from\n the dict.\n "
] |
Please provide a description of the function:def subselect(self, obj):
return dict(
(key, value) for (key, value)
in obj.items()
if key in self.defaults) | [
"\n Filter a dict of hyperparameter settings to only those keys defined\n in this HyperparameterDefaults .\n "
] |
Please provide a description of the function:def check_valid_keys(self, obj):
invalid_keys = [
x for x in obj if x not in self.defaults
]
if invalid_keys:
raise ValueError(
"No such model parameters: %s. Valid parameters are: %s"
%... | [
"\n Given a dict of hyperparameter settings, throw an exception if any\n keys are not defined in this HyperparameterDefaults instance.\n "
] |
Please provide a description of the function:def models_grid(self, **kwargs):
'''
Make a grid of models by taking the cartesian product of all specified
model parameter lists.
Parameters
-----------
The valid kwarg parameters are the entries of this
Hyperparamete... | [] |
Please provide a description of the function:def fixed_length_vector_encoded_sequences(self, vector_encoding_name):
cache_key = (
"fixed_length_vector_encoding",
vector_encoding_name)
if cache_key not in self.encoding_cache:
index_encoded_matrix = amino_acid.... | [
"\n Encode alleles.\n\n Parameters\n ----------\n vector_encoding_name : string\n How to represent amino acids.\n One of \"BLOSUM62\", \"one-hot\", etc. Full list of supported vector\n encodings is given by available_vector_encodings() in amino_acid.\n\n ... |
Please provide a description of the function:def fixed_vectors_encoding(index_encoded_sequences, letter_to_vector_df):
(num_sequences, sequence_length) = index_encoded_sequences.shape
target_shape = (
num_sequences, sequence_length, letter_to_vector_df.shape[0])
result = letter_to_vector_df.ilo... | [
"\n Given a `n` x `k` matrix of integers such as that returned by `index_encoding()` and\n a dataframe mapping each index to an arbitrary vector, return a `n * k * m`\n array where the (`i`, `j`)'th element is `letter_to_vector_df.iloc[sequence[i][j]]`.\n\n The dataframe index and columns names are igno... |
Please provide a description of the function:def apply_hyperparameter_renames(cls, hyperparameters):
for (from_name, to_name) in cls.hyperparameter_renames.items():
if from_name in hyperparameters:
value = hyperparameters.pop(from_name)
if to_name:
... | [
"\n Handle hyperparameter renames.\n\n Parameters\n ----------\n hyperparameters : dict\n\n Returns\n -------\n dict : updated hyperparameters\n\n "
] |
Please provide a description of the function:def borrow_cached_network(klass, network_json, network_weights):
assert network_weights is not None
key = klass.keras_network_cache_key(network_json)
if key not in klass.KERAS_MODELS_CACHE:
# Cache miss.
import keras.m... | [
"\n Return a keras Model with the specified architecture and weights.\n As an optimization, when possible this will reuse architectures from a\n process-wide cache.\n\n The returned object is \"borrowed\" in the sense that its weights can\n change later after subsequent calls to t... |
Please provide a description of the function:def network(self, borrow=False):
if self._network is None and self.network_json is not None:
self.load_weights()
if borrow:
return self.borrow_cached_network(
self.network_json,
... | [
"\n Return the keras model associated with this predictor.\n\n Parameters\n ----------\n borrow : bool\n Whether to return a cached model if possible. See\n borrow_cached_network for details\n\n Returns\n -------\n keras.models.Model\n "
... |
Please provide a description of the function:def get_config(self):
self.update_network_description()
result = dict(self.__dict__)
result['_network'] = None
result['network_weights'] = None
result['network_weights_loader'] = None
result['prediction_cache'] = None
... | [
"\n serialize to a dict all attributes except model weights\n \n Returns\n -------\n dict\n "
] |
Please provide a description of the function:def from_config(cls, config, weights=None, weights_loader=None):
config = dict(config)
instance = cls(**config.pop('hyperparameters'))
instance.__dict__.update(config)
instance.network_weights = weights
instance.network_weight... | [
"\n deserialize from a dict returned by get_config().\n \n Parameters\n ----------\n config : dict\n weights : list of array, optional\n Network weights to restore\n weights_loader : callable, optional\n Function to call (no arguments) to load w... |
Please provide a description of the function:def load_weights(self):
if self.network_weights_loader:
self.network_weights = self.network_weights_loader()
self.network_weights_loader = None | [
"\n Load weights by evaluating self.network_weights_loader, if needed.\n\n After calling this, self.network_weights_loader will be None and\n self.network_weights will be the weights list, if available.\n "
] |
Please provide a description of the function:def peptides_to_network_input(self, peptides):
encoder = EncodableSequences.create(peptides)
if (self.hyperparameters['peptide_amino_acid_encoding'] == "embedding"):
encoded = encoder.variable_length_to_fixed_length_categorical(
... | [
"\n Encode peptides to the fixed-length encoding expected by the neural\n network (which depends on the architecture).\n \n Parameters\n ----------\n peptides : EncodableSequences or list of string\n\n Returns\n -------\n numpy.array\n "
] |
Please provide a description of the function:def fit(
self,
peptides,
affinities,
allele_encoding=None,
inequalities=None,
sample_weights=None,
shuffle_permutation=None,
verbose=1,
progress_preamble="",
... | [
"\n Fit the neural network.\n \n Parameters\n ----------\n peptides : EncodableSequences or list of string\n \n affinities : list of float\n nM affinities. Must be same length of as peptides.\n \n allele_encoding : AlleleEncoding, optional\n ... |
Please provide a description of the function:def predict(self, peptides, allele_encoding=None, batch_size=4096):
assert self.prediction_cache is not None
use_cache = (
allele_encoding is None and
isinstance(peptides, EncodableSequences))
if use_cache and peptides... | [
"\n Predict affinities.\n\n If peptides are specified as EncodableSequences, then the predictions\n will be cached for this predictor as long as the EncodableSequences object\n remains in memory. The cache is keyed in the object identity of the\n EncodableSequences, not the sequen... |
Please provide a description of the function:def make_network(
allele_encoding_dims,
kmer_size,
peptide_amino_acid_encoding,
embedding_input_dim,
embedding_output_dim,
allele_dense_layer_sizes,
peptide_dense_layer_sizes,
pep... | [
"\n Helper function to make a keras network for class1 affinity prediction.\n "
] |
Please provide a description of the function:def make_scores(
ic50_y,
ic50_y_pred,
sample_weight=None,
threshold_nm=500,
max_ic50=50000):
y_pred = from_ic50(ic50_y_pred, max_ic50)
try:
auc = sklearn.metrics.roc_auc_score(
ic50_y <= threshold_nm,
... | [
"\n Calculate AUC, F1, and Kendall Tau scores.\n\n Parameters\n -----------\n ic50_y : float list\n true IC50s (i.e. affinities)\n\n ic50_y_pred : float list\n predicted IC50s\n\n sample_weight : float list [optional]\n\n threshold_nm : float [optional]\n\n max_ic50 : float [op... |
Please provide a description of the function:def variable_length_to_fixed_length_categorical(
self, left_edge=4, right_edge=4, max_length=15):
cache_key = (
"fixed_length_categorical",
left_edge,
right_edge,
max_length)
if cache_key ... | [
"\n Encode variable-length sequences using a fixed-length encoding designed\n for preserving the anchor positions of class I peptides.\n \n The sequences must be of length at least left_edge + right_edge, and at\n most max_length.\n \n Parameters\n ----------\... |
Please provide a description of the function:def variable_length_to_fixed_length_vector_encoding(
self, vector_encoding_name, left_edge=4, right_edge=4, max_length=15):
cache_key = (
"fixed_length_vector_encoding",
vector_encoding_name,
left_edge,
... | [
"\n Encode variable-length sequences using a fixed-length encoding designed\n for preserving the anchor positions of class I peptides.\n\n The sequences must be of length at least left_edge + right_edge, and at\n most max_length.\n\n Parameters\n ----------\n vector_... |
Please provide a description of the function:def sequences_to_fixed_length_index_encoded_array(
klass, sequences, left_edge=4, right_edge=4, max_length=15):
# Result array is int32, filled with X (null amino acid) value.
result = numpy.full(
fill_value=amino_acid.AMINO_... | [
"\n Transform a sequence of strings, where each string is of length at least\n left_edge + right_edge and at most max_length into strings of length\n max_length using a scheme designed to preserve the anchor positions of\n class I peptides.\n\n The first left_edge characters in th... |
Please provide a description of the function:def robust_mean(log_values):
if log_values.shape[1] <= 3:
# Too few values to use robust mean.
return numpy.nanmean(log_values, axis=1)
without_nans = numpy.nan_to_num(log_values) # replace nan with 0
mask = (
(~numpy.isnan(log_value... | [
"\n Mean of values falling within the 25-75 percentiles.\n\n Parameters\n ----------\n log_values : 2-d numpy.array\n Center is computed along the second axis (i.e. per row).\n\n Returns\n -------\n center : numpy.array of length log_values.shape[1]\n\n "
] |
Please provide a description of the function:def neural_networks(self):
result = []
for models in self.allele_to_allele_specific_models.values():
result.extend(models)
result.extend(self.class1_pan_allele_models)
return result | [
"\n List of the neural networks in the ensemble.\n\n Returns\n -------\n list of `Class1NeuralNetwork`\n "
] |
Please provide a description of the function:def merge(cls, predictors):
assert len(predictors) > 0
if len(predictors) == 1:
return predictors[0]
allele_to_allele_specific_models = collections.defaultdict(list)
class1_pan_allele_models = []
allele_to_fixed_l... | [
"\n Merge the ensembles of two or more `Class1AffinityPredictor` instances.\n\n Note: the resulting merged predictor will NOT have calibrated percentile\n ranks. Call `calibrate_percentile_ranks` on it if these are needed.\n\n Parameters\n ----------\n predictors : sequence... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.