_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q264000 | get_author_and_version | validation | def get_author_and_version(package):
"""
Return package author and version as listed in `init.py`.
"""
init_py = open(os.path.join(package, '__init__.py')).read()
author = re.search("__author__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
version = re.search("__version__ = ['\"]([^'\"]+)['\"]", ini... | python | {
"resource": ""
} |
q264001 | api_subclass_factory | validation | def api_subclass_factory(name, docstring, remove_methods, base=SlackApi):
"""Create an API subclass with fewer methods than its base class.
Arguments:
name (:py:class:`str`): The name of the new class.
docstring (:py:class:`str`): The docstring for the new class.
remove_methods (:py:class:`di... | python | {
"resource": ""
} |
q264002 | SlackApi.execute_method | validation | async def execute_method(self, method, **params):
"""Execute a specified Slack Web API method.
Arguments:
method (:py:class:`str`): The name of the method.
**params (:py:class:`dict`): Any additional parameters
required.
Returns:
:py:class:`dict`: The ... | python | {
"resource": ""
} |
q264003 | SlackApi.method_exists | validation | def method_exists(cls, method):
"""Whether a given method exists in the known API.
Arguments:
method (:py:class:`str`): The name of the method.
Returns:
:py:class:`bool`: Whether the method is in the known API.
"""
methods = cls.API_METHODS
for key ... | python | {
"resource": ""
} |
q264004 | XPathSelectorHandler._add_parsley_ns | validation | def _add_parsley_ns(cls, namespace_dict):
"""
Extend XPath evaluation with Parsley extensions' namespace
"""
namespace_dict.update({
'parslepy' : cls.LOCAL_NAMESPACE,
'parsley' : cls.LOCAL_NAMESPACE,
})
return namespace_dict | python | {
"resource": ""
} |
q264005 | XPathSelectorHandler.extract | validation | def extract(self, document, selector, debug_offset=''):
"""
Try and convert matching Elements to unicode strings.
If this fails, the selector evaluation probably already
returned some string(s) of some sort, or boolean value,
or int/float, so return that instead.
"""
... | python | {
"resource": ""
} |
q264006 | SlackBot.join_rtm | validation | async def join_rtm(self, filters=None):
"""Join the real-time messaging service.
Arguments:
filters (:py:class:`dict`, optional): Dictionary mapping
message filters to the functions they should dispatch to.
Use a :py:class:`collections.OrderedDict` if precedence is
... | python | {
"resource": ""
} |
q264007 | SlackBot.handle_message | validation | async def handle_message(self, message, filters):
"""Handle an incoming message appropriately.
Arguments:
message (:py:class:`aiohttp.websocket.Message`): The incoming
message to handle.
filters (:py:class:`list`): The filters to apply to incoming
messages.
... | python | {
"resource": ""
} |
q264008 | SlackBot.message_is_to_me | validation | def message_is_to_me(self, data):
"""If you send a message directly to me"""
return (data.get('type') == 'message' and
data.get('text', '').startswith(self.address_as)) | python | {
"resource": ""
} |
q264009 | SlackBot.from_api_token | validation | async def from_api_token(cls, token=None, api_cls=SlackBotApi):
"""Create a new instance from the API token.
Arguments:
token (:py:class:`str`, optional): The bot's API token
(defaults to ``None``, which means looking in the
environment).
api_cls (:py:class:`... | python | {
"resource": ""
} |
q264010 | SlackBot._format_message | validation | def _format_message(self, channel, text):
"""Format an outgoing message for transmission.
Note:
Adds the message type (``'message'``) and incremental ID.
Arguments:
channel (:py:class:`str`): The channel to send to.
text (:py:class:`str`): The message text to send... | python | {
"resource": ""
} |
q264011 | SlackBot._get_socket_url | validation | async def _get_socket_url(self):
"""Get the WebSocket URL for the RTM session.
Warning:
The URL expires if the session is not joined within 30
seconds of the API call to the start endpoint.
Returns:
:py:class:`str`: The socket URL.
"""
data = awai... | python | {
"resource": ""
} |
q264012 | SlackBot._instruction_list | validation | def _instruction_list(self, filters):
"""Generates the instructions for a bot and its filters.
Note:
The guidance for each filter is generated by combining the
docstrings of the predicate filter and resulting dispatch
function with a single space between. The class's
... | python | {
"resource": ""
} |
q264013 | SlackBot._respond | validation | def _respond(self, channel, text):
"""Respond to a message on the current socket.
Args:
channel (:py:class:`str`): The channel to send to.
text (:py:class:`str`): The message text to send.
"""
result = self._format_message(channel, text)
if result is not Non... | python | {
"resource": ""
} |
q264014 | SlackBot._validate_first_message | validation | def _validate_first_message(cls, msg):
"""Check the first message matches the expected handshake.
Note:
The handshake is provided as :py:attr:`RTM_HANDSHAKE`.
Arguments:
msg (:py:class:`aiohttp.Message`): The message to validate.
Raises:
:py:class:`SlackA... | python | {
"resource": ""
} |
q264015 | get_app_locations | validation | def get_app_locations():
"""
Returns list of paths to tested apps
"""
return [os.path.dirname(os.path.normpath(import_module(app_name).__file__))
for app_name in PROJECT_APPS] | python | {
"resource": ""
} |
q264016 | get_tasks | validation | def get_tasks():
"""Get the imported task classes for each task that will be run"""
task_classes = []
for task_path in TASKS:
try:
module, classname = task_path.rsplit('.', 1)
except ValueError:
raise ImproperlyConfigured('%s isn\'t a task module' % task_path)
... | python | {
"resource": ""
} |
q264017 | get_task_options | validation | def get_task_options():
"""Get the options for each task that will be run"""
options = ()
task_classes = get_tasks()
for cls in task_classes:
options += cls.option_list
return options | python | {
"resource": ""
} |
q264018 | Database.to_cldf | validation | def to_cldf(self, dest, mdname='cldf-metadata.json'):
"""
Write the data from the db to a CLDF dataset according to the metadata in `self.dataset`.
:param dest:
:param mdname:
:return: path of the metadata file
"""
dest = Path(dest)
if not dest.exists():
... | python | {
"resource": ""
} |
q264019 | MessageHandler.description | validation | def description(self):
"""A user-friendly description of the handler.
Returns:
:py:class:`str`: The handler's description.
"""
if self._description is None:
text = '\n'.join(self.__doc__.splitlines()[1:]).strip()
lines = []
for line in map(... | python | {
"resource": ""
} |
q264020 | Parselet.from_jsonfile | validation | def from_jsonfile(cls, fp, selector_handler=None, strict=False, debug=False):
"""
Create a Parselet instance from a file containing
the Parsley script as a JSON object
>>> import parslepy
>>> with open('parselet.json') as fp:
... parslepy.Parselet.from_jsonfile(fp)
... | python | {
"resource": ""
} |
q264021 | Parselet.from_yamlfile | validation | def from_yamlfile(cls, fp, selector_handler=None, strict=False, debug=False):
"""
Create a Parselet instance from a file containing
the Parsley script as a YAML object
>>> import parslepy
>>> with open('parselet.yml') as fp:
... parslepy.Parselet.from_yamlfile(fp)
... | python | {
"resource": ""
} |
q264022 | Parselet._from_jsonlines | validation | def _from_jsonlines(cls, lines, selector_handler=None, strict=False, debug=False):
"""
Interpret input lines as a JSON Parsley script.
Python-style comment lines are skipped.
"""
return cls(json.loads(
"\n".join([l for l in lines if not cls.REGEX_COMMENT_LINE.mat... | python | {
"resource": ""
} |
q264023 | Parselet._compile | validation | def _compile(self, parselet_node, level=0):
"""
Build part of the abstract Parsley extraction tree
Arguments:
parselet_node (dict) -- part of the Parsley tree to compile
(can be the root dict/node)
level (int) -- current recursion depth (... | python | {
"resource": ""
} |
q264024 | Dataset.auto_constraints | validation | def auto_constraints(self, component=None):
"""
Use CLDF reference properties to implicitely create foreign key constraints.
:param component: A Table object or `None`.
"""
if not component:
for table in self.tables:
self.auto_constraints(table)
... | python | {
"resource": ""
} |
q264025 | Service.url_builder | validation | def url_builder(self, endpoint, *, root=None, params=None, url_params=None):
"""Create a URL for the specified endpoint.
Arguments:
endpoint (:py:class:`str`): The API endpoint to access.
root: (:py:class:`str`, optional): The root URL for the
service API.
para... | python | {
"resource": ""
} |
q264026 | raise_for_status | validation | def raise_for_status(response):
"""Raise an appropriate error for a given response.
Arguments:
response (:py:class:`aiohttp.ClientResponse`): The API response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate
error for the response's status.
"""
for er... | python | {
"resource": ""
} |
q264027 | truncate | validation | def truncate(text, max_len=350, end='...'):
"""Truncate the supplied text for display.
Arguments:
text (:py:class:`str`): The text to truncate.
max_len (:py:class:`int`, optional): The maximum length of the
text before truncation (defaults to 350 characters).
end (:py:class:`str`, opt... | python | {
"resource": ""
} |
q264028 | Sources.add | validation | def add(self, *entries):
"""
Add a source, either specified by glottolog reference id, or as bibtex record.
"""
for entry in entries:
if isinstance(entry, string_types):
self._add_entries(database.parse_string(entry, bib_format='bibtex'))
else:
... | python | {
"resource": ""
} |
q264029 | get_cache_key | validation | def get_cache_key(user_or_username, size, prefix):
"""
Returns a cache key consisten of a username and image size.
"""
if isinstance(user_or_username, get_user_model()):
user_or_username = user_or_username.username
return '%s_%s_%s' % (prefix, user_or_username, size) | python | {
"resource": ""
} |
q264030 | cache_result | validation | def cache_result(func):
"""
Decorator to cache the result of functions that take a ``user`` and a
``size`` value.
"""
def cache_set(key, value):
cache.set(key, value, AVATAR_CACHE_TIMEOUT)
return value
def cached_func(user, size):
prefix = func.__name__
cached_fu... | python | {
"resource": ""
} |
q264031 | invalidate_cache | validation | def invalidate_cache(user, size=None):
"""
Function to be called when saving or changing an user's avatars.
"""
sizes = set(AUTO_GENERATE_AVATAR_SIZES)
if size is not None:
sizes.add(size)
for prefix in cached_funcs:
for size in sizes:
cache.delete(get_cache_key(user,... | python | {
"resource": ""
} |
q264032 | get_field_for_proxy | validation | def get_field_for_proxy(pref_proxy):
"""Returns a field object instance for a given PrefProxy object.
:param PrefProxy pref_proxy:
:rtype: models.Field
"""
field = {
bool: models.BooleanField,
int: models.IntegerField,
float: models.FloatField,
datetime: models.Da... | python | {
"resource": ""
} |
q264033 | update_field_from_proxy | validation | def update_field_from_proxy(field_obj, pref_proxy):
"""Updates field object with data from a PrefProxy object.
:param models.Field field_obj:
:param PrefProxy pref_proxy:
"""
attr_names = ('verbose_name', 'help_text', 'default')
for attr_name in attr_names:
setattr(field_obj, attr_na... | python | {
"resource": ""
} |
q264034 | get_pref_model_class | validation | def get_pref_model_class(app, prefs, get_prefs_func):
"""Returns preferences model class dynamically crated for a given app or None on conflict."""
module = '%s.%s' % (app, PREFS_MODULE_NAME)
model_dict = {
'_prefs_app': app,
'_get_prefs': staticmethod(get_prefs_func),
... | python | {
"resource": ""
} |
q264035 | get_frame_locals | validation | def get_frame_locals(stepback=0):
"""Returns locals dictionary from a given frame.
:param int stepback:
:rtype: dict
"""
with Frame(stepback=stepback) as frame:
locals_dict = frame.f_locals
return locals_dict | python | {
"resource": ""
} |
q264036 | traverse_local_prefs | validation | def traverse_local_prefs(stepback=0):
"""Generator to walk through variables considered as preferences
in locals dict of a given frame.
:param int stepback:
:rtype: tuple
"""
locals_dict = get_frame_locals(stepback+1)
for k in locals_dict:
if not k.startswith('_') and k.upper() ==... | python | {
"resource": ""
} |
q264037 | print_file_info | validation | def print_file_info():
"""Prints file details in the current directory"""
tpl = TableLogger(columns='file,created,modified,size')
for f in os.listdir('.'):
size = os.stat(f).st_size
date_created = datetime.fromtimestamp(os.path.getctime(f))
date_modified = datetime.fromtimestamp(os.p... | python | {
"resource": ""
} |
q264038 | DispatchGroup._bind_args | validation | def _bind_args(sig, param_matchers, args, kwargs):
'''
Attempt to bind the args to the type signature. First try to just bind
to the signature, then ensure that all arguments match the parameter
types.
'''
#Bind to signature. May throw its own TypeError
bound = si... | python | {
"resource": ""
} |
q264039 | DispatchGroup._make_all_matchers | validation | def _make_all_matchers(cls, parameters):
'''
For every parameter, create a matcher if the parameter has an
annotation.
'''
for name, param in parameters:
annotation = param.annotation
if annotation is not Parameter.empty:
yield name, cls._m... | python | {
"resource": ""
} |
q264040 | DispatchGroup._make_wrapper | validation | def _make_wrapper(self, func):
'''
Makes a wrapper function that executes a dispatch call for func. The
wrapper has the dispatch and dispatch_first attributes, so that
additional overloads can be added to the group.
'''
#TODO: consider using a class to make attribute for... | python | {
"resource": ""
} |
q264041 | DispatchGroup.dispatch | validation | def dispatch(self, func):
'''
Adds the decorated function to this dispatch.
'''
self.callees.append(self._make_dispatch(func))
return self._make_wrapper(func) | python | {
"resource": ""
} |
q264042 | DispatchGroup.dispatch_first | validation | def dispatch_first(self, func):
'''
Adds the decorated function to this dispatch, at the FRONT of the order.
Useful for allowing third parties to add overloaded functionality
to be executed before default functionality.
'''
self.callees.appendleft(self._make_dispatch(func... | python | {
"resource": ""
} |
q264043 | DispatchGroup.execute | validation | def execute(self, args, kwargs):
'''
Dispatch a call. Call the first function whose type signature matches
the arguemts.
'''
return self.lookup_explicit(args, kwargs)(*args, **kwargs) | python | {
"resource": ""
} |
q264044 | convertShpToExtend | validation | def convertShpToExtend(pathToShp):
"""
reprojette en WGS84 et recupere l'extend
"""
driver = ogr.GetDriverByName('ESRI Shapefile')
dataset = driver.Open(pathToShp)
if dataset is not None:
# from Layer
layer = dataset.GetLayer()
spatialRef = layer.GetSpatialRef()
... | python | {
"resource": ""
} |
q264045 | convertGribToTiff | validation | def convertGribToTiff(listeFile,listParam,listLevel,liststep,grid,startDate,endDate,outFolder):
""" Convert GRIB to Tif"""
dicoValues={}
for l in listeFile:
grbs = pygrib.open(l)
grbs.seek(0)
index=1
for j in range(len(listLevel),0,-1):
for i in range(le... | python | {
"resource": ""
} |
q264046 | on_pref_update | validation | def on_pref_update(*args, **kwargs):
"""Triggered on dynamic preferences model save.
Issues DB save and reread.
"""
Preference.update_prefs(*args, **kwargs)
Preference.read_prefs(get_prefs()) | python | {
"resource": ""
} |
q264047 | bind_proxy | validation | def bind_proxy(values, category=None, field=None, verbose_name=None, help_text='', static=True, readonly=False):
"""Binds PrefProxy objects to module variables used by apps as preferences.
:param list|tuple values: Preference values.
:param str|unicode category: Category name the preference belongs to.
... | python | {
"resource": ""
} |
q264048 | register_admin_models | validation | def register_admin_models(admin_site):
"""Registers dynamically created preferences models for Admin interface.
:param admin.AdminSite admin_site: AdminSite object.
"""
global __MODELS_REGISTRY
prefs = get_prefs()
for app_label, prefs_items in prefs.items():
model_class = get_pref_m... | python | {
"resource": ""
} |
q264049 | autodiscover_siteprefs | validation | def autodiscover_siteprefs(admin_site=None):
"""Automatically discovers and registers all preferences available in all apps.
:param admin.AdminSite admin_site: Custom AdminSite object.
"""
if admin_site is None:
admin_site = admin.site
# Do not discover anything if called from manage.py (... | python | {
"resource": ""
} |
q264050 | unpatch_locals | validation | def unpatch_locals(depth=3):
"""Restores the original values of module variables
considered preferences if they are still PatchedLocal
and not PrefProxy.
"""
for name, locals_dict in traverse_local_prefs(depth):
if isinstance(locals_dict[name], PatchedLocal):
locals_dict[name] =... | python | {
"resource": ""
} |
q264051 | proxy_settings_module | validation | def proxy_settings_module(depth=3):
"""Replaces a settings module with a Module proxy to intercept
an access to settings.
:param int depth: Frame count to go backward.
"""
proxies = []
modules = sys.modules
module_name = get_frame_locals(depth)['__name__']
module_real = modules[modul... | python | {
"resource": ""
} |
q264052 | register_prefs | validation | def register_prefs(*args, **kwargs):
"""Registers preferences that should be handled by siteprefs.
Expects preferences as *args.
Use keyword arguments to batch apply params supported by
``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``.
Batch kwargs:
:param ... | python | {
"resource": ""
} |
q264053 | pref_group | validation | def pref_group(title, prefs, help_text='', static=True, readonly=False):
"""Marks preferences group.
:param str|unicode title: Group title
:param list|tuple prefs: Preferences to group.
:param str|unicode help_text: Field help text.
:param bool static: Leave this preference static (do not store ... | python | {
"resource": ""
} |
q264054 | pref | validation | def pref(preference, field=None, verbose_name=None, help_text='', static=True, readonly=False):
"""Marks a preference.
:param preference: Preference variable.
:param Field field: Django model field to represent this preference.
:param str|unicode verbose_name: Field verbose name.
:param str|unic... | python | {
"resource": ""
} |
q264055 | generate_versionwarning_data_json | validation | def generate_versionwarning_data_json(app, config=None, **kwargs):
"""
Generate the ``versionwarning-data.json`` file.
This file is included in the output and read by the AJAX request when
accessing to the documentation and used to compare the live versions with
the curent one.
Besides, this f... | python | {
"resource": ""
} |
q264056 | objective | validation | def objective(param_scales=(1, 1), xstar=None, seed=None):
"""Gives objective functions a number of dimensions and parameter range
Parameters
----------
param_scales : (int, int)
Scale (std. dev.) for choosing each parameter
xstar : array_like
Optimal parameters
"""
ndim = ... | python | {
"resource": ""
} |
q264057 | doublewell | validation | def doublewell(theta):
"""Pointwise minimum of two quadratic bowls"""
k0, k1, depth = 0.01, 100, 0.5
shallow = 0.5 * k0 * theta ** 2 + depth
deep = 0.5 * k1 * theta ** 2
obj = float(np.minimum(shallow, deep))
grad = np.where(deep < shallow, k1 * theta, k0 * theta)
return obj, grad | python | {
"resource": ""
} |
q264058 | rosenbrock | validation | def rosenbrock(theta):
"""Objective and gradient for the rosenbrock function"""
x, y = theta
obj = (1 - x)**2 + 100 * (y - x**2)**2
grad = np.zeros(2)
grad[0] = 2 * x - 400 * (x * y - x**3) - 2
grad[1] = 200 * (y - x**2)
return obj, grad | python | {
"resource": ""
} |
q264059 | beale | validation | def beale(theta):
"""Beale's function"""
x, y = theta
A = 1.5 - x + x * y
B = 2.25 - x + x * y**2
C = 2.625 - x + x * y**3
obj = A ** 2 + B ** 2 + C ** 2
grad = np.array([
2 * A * (y - 1) + 2 * B * (y ** 2 - 1) + 2 * C * (y ** 3 - 1),
2 * A * x + 4 * B * x * y + 6 * C * x * y... | python | {
"resource": ""
} |
q264060 | booth | validation | def booth(theta):
"""Booth's function"""
x, y = theta
A = x + 2 * y - 7
B = 2 * x + y - 5
obj = A**2 + B**2
grad = np.array([2 * A + 4 * B, 4 * A + 2 * B])
return obj, grad | python | {
"resource": ""
} |
q264061 | camel | validation | def camel(theta):
"""Three-hump camel function"""
x, y = theta
obj = 2 * x ** 2 - 1.05 * x ** 4 + x ** 6 / 6 + x * y + y ** 2
grad = np.array([
4 * x - 4.2 * x ** 3 + x ** 5 + y,
x + 2 * y
])
return obj, grad | python | {
"resource": ""
} |
q264062 | bohachevsky1 | validation | def bohachevsky1(theta):
"""One of the Bohachevsky functions"""
x, y = theta
obj = x ** 2 + 2 * y ** 2 - 0.3 * np.cos(3 * np.pi * x) - 0.4 * np.cos(4 * np.pi * y) + 0.7
grad = np.array([
2 * x + 0.3 * np.sin(3 * np.pi * x) * 3 * np.pi,
4 * y + 0.4 * np.sin(4 * np.pi * y) * 4 * np.pi,
... | python | {
"resource": ""
} |
q264063 | dixon_price | validation | def dixon_price(theta):
"""Dixon-Price function"""
x, y = theta
obj = (x - 1) ** 2 + 2 * (2 * y ** 2 - x) ** 2
grad = np.array([
2 * x - 2 - 4 * (2 * y ** 2 - x),
16 * (2 * y ** 2 - x) * y,
])
return obj, grad | python | {
"resource": ""
} |
q264064 | styblinski_tang | validation | def styblinski_tang(theta):
"""Styblinski-Tang function"""
x, y = theta
obj = 0.5 * (x ** 4 - 16 * x ** 2 + 5 * x + y ** 4 - 16 * y ** 2 + 5 * y)
grad = np.array([
2 * x ** 3 - 16 * x + 2.5,
2 * y ** 3 - 16 * y + 2.5,
])
return obj, grad | python | {
"resource": ""
} |
q264065 | S3Connection.get_all_buckets | validation | def get_all_buckets(self, *args, **kwargs):
"""Return a list of buckets in MimicDB.
:param boolean force: If true, API call is forced to S3
"""
if kwargs.pop('force', None):
buckets = super(S3Connection, self).get_all_buckets(*args, **kwargs)
for bucket in bucke... | python | {
"resource": ""
} |
q264066 | S3Connection.get_bucket | validation | def get_bucket(self, bucket_name, validate=True, headers=None, force=None):
"""Return a bucket from MimicDB if it exists. Return a
S3ResponseError if the bucket does not exist and validate is passed.
:param boolean force: If true, API call is forced to S3
"""
if force:
... | python | {
"resource": ""
} |
q264067 | S3Connection.create_bucket | validation | def create_bucket(self, *args, **kwargs):
"""Add the bucket to MimicDB after successful creation.
"""
bucket = super(S3Connection, self).create_bucket(*args, **kwargs)
if bucket:
mimicdb.backend.sadd(tpl.connection, bucket.name)
return bucket | python | {
"resource": ""
} |
q264068 | S3Connection.sync | validation | def sync(self, *buckets):
"""Sync either a list of buckets or the entire connection.
Force all API calls to S3 and populate the database with the current
state of S3.
:param \*string \*buckets: Buckets to sync
"""
if buckets:
for _bucket in buckets:
... | python | {
"resource": ""
} |
q264069 | Bucket.get_key | validation | def get_key(self, *args, **kwargs):
"""Return the key from MimicDB.
:param boolean force: If true, API call is forced to S3
"""
if kwargs.pop('force', None):
headers = kwargs.get('headers', {})
headers['force'] = True
kwargs['headers'] = headers
... | python | {
"resource": ""
} |
q264070 | Bucket._get_key_internal | validation | def _get_key_internal(self, *args, **kwargs):
"""Return None if key is not in the bucket set.
Pass 'force' in the headers to check S3 for the key, and after fetching
the key from S3, save the metadata and key to the bucket set.
"""
if args[1] is not None and 'force' in args[1]:
... | python | {
"resource": ""
} |
q264071 | Bucket.get_all_keys | validation | def get_all_keys(self, *args, **kwargs):
"""Return a list of keys from MimicDB.
:param boolean force: If true, API call is forced to S3
"""
if kwargs.pop('force', None):
headers = kwargs.get('headers', args[0] if len(args) else None) or dict()
headers['force'] = ... | python | {
"resource": ""
} |
q264072 | Bucket.delete_keys | validation | def delete_keys(self, *args, **kwargs):
"""Remove each key or key name in an iterable from the bucket set.
"""
ikeys = iter(kwargs.get('keys', args[0] if args else []))
while True:
try:
key = ikeys.next()
except StopIteration:
brea... | python | {
"resource": ""
} |
q264073 | Bucket._delete_key_internal | validation | def _delete_key_internal(self, *args, **kwargs):
"""Remove key name from bucket set.
"""
mimicdb.backend.srem(tpl.bucket % self.name, args[0])
mimicdb.backend.delete(tpl.key % (self.name, args[0]))
return super(Bucket, self)._delete_key_internal(*args, **kwargs) | python | {
"resource": ""
} |
q264074 | Bucket.list | validation | def list(self, *args, **kwargs):
"""Return an iterable of keys from MimicDB.
:param boolean force: If true, API call is forced to S3
"""
if kwargs.pop('force', None):
headers = kwargs.get('headers', args[4] if len(args) > 4 else None) or dict()
headers['force'] =... | python | {
"resource": ""
} |
q264075 | Bucket.sync | validation | def sync(self):
"""Sync a bucket.
Force all API calls to S3 and populate the database with the current state of S3.
"""
for key in mimicdb.backend.smembers(tpl.bucket % self.name):
mimicdb.backend.delete(tpl.key % (self.name, key))
mimicdb.backend.delete(tpl.bucket ... | python | {
"resource": ""
} |
q264076 | lbfgs | validation | def lbfgs(x, rho, f_df, maxiter=20):
"""
Minimize the proximal operator of a given objective using L-BFGS
Parameters
----------
f_df : function
Returns the objective and gradient of the function to minimize
maxiter : int
Maximum number of L-BFGS iterations
"""
def f_df... | python | {
"resource": ""
} |
q264077 | smooth | validation | def smooth(x, rho, penalty, axis=0, newshape=None):
"""
Applies a smoothing operator along one dimension
currently only accepts a matrix as input
Parameters
----------
penalty : float
axis : int, optional
Axis along which to apply the smoothing (Default: 0)
newshape : tuple, ... | python | {
"resource": ""
} |
q264078 | sdcone | validation | def sdcone(x, rho):
"""Projection onto the semidefinite cone"""
U, V = np.linalg.eigh(x)
return V.dot(np.diag(np.maximum(U, 0)).dot(V.T)) | python | {
"resource": ""
} |
q264079 | simplex | validation | def simplex(x, rho):
"""
Projection onto the probability simplex
http://arxiv.org/pdf/1309.1541v1.pdf
"""
# sort the elements in descending order
u = np.flipud(np.sort(x.ravel()))
lambdas = (1 - np.cumsum(u)) / (1. + np.arange(u.size))
ix = np.where(u + lambdas > 0)[0].max()
return... | python | {
"resource": ""
} |
q264080 | columns | validation | def columns(x, rho, proxop):
"""Applies a proximal operator to the columns of a matrix"""
xnext = np.zeros_like(x)
for ix in range(x.shape[1]):
xnext[:, ix] = proxop(x[:, ix], rho)
return xnext | python | {
"resource": ""
} |
q264081 | gradient_optimizer | validation | def gradient_optimizer(coro):
"""Turns a coroutine into a gradient based optimizer."""
class GradientOptimizer(Optimizer):
@wraps(coro)
def __init__(self, *args, **kwargs):
self.algorithm = coro(*args, **kwargs)
self.algorithm.send(None)
self.operators = []
... | python | {
"resource": ""
} |
q264082 | Optimizer.add | validation | def add(self, operator, *args):
"""Adds a proximal operator to the list of operators"""
if isinstance(operator, str):
op = getattr(proxops, operator)(*args)
elif isinstance(operator, proxops.ProximalOperatorBaseClass):
op = operator
else:
raise ValueE... | python | {
"resource": ""
} |
q264083 | Key._load_meta | validation | def _load_meta(self, size, md5):
"""Set key attributes to retrived metadata. Might be extended in the
future to support more attributes.
"""
if not hasattr(self, 'local_hashes'):
self.local_hashes = {}
self.size = int(size)
if (re.match('^[a-fA-F0-9]{32}$', ... | python | {
"resource": ""
} |
q264084 | Key._send_file_internal | validation | def _send_file_internal(self, *args, **kwargs):
"""Called internally for any type of upload. After upload finishes,
make sure the key is in the bucket set and save the metadata.
"""
super(Key, self)._send_file_internal(*args, **kwargs)
mimicdb.backend.sadd(tpl.bucket % self.buck... | python | {
"resource": ""
} |
q264085 | wrap | validation | def wrap(f_df, xref, size=1):
"""
Memoizes an objective + gradient function, and splits it into
two functions that return just the objective and gradient, respectively.
Parameters
----------
f_df : function
Must be unary (takes a single argument)
xref : list, dict, or array_like
... | python | {
"resource": ""
} |
q264086 | docstring | validation | def docstring(docstr):
"""
Decorates a function with the given docstring
Parameters
----------
docstr : string
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.__doc__ = docstr
return wrapper... | python | {
"resource": ""
} |
q264087 | check_grad | validation | def check_grad(f_df, xref, stepsize=1e-6, tol=1e-6, width=15, style='round', out=sys.stdout):
"""
Compares the numerical gradient to the analytic gradient
Parameters
----------
f_df : function
The analytic objective and gradient function to check
x0 : array_like
Parameter value... | python | {
"resource": ""
} |
q264088 | RegressionQualityValidator.evaluate | validation | def evaluate(self, repo, spec, args):
"""
Evaluate the files identified for checksum.
"""
status = []
# Do we have to any thing at all?
if len(spec['files']) == 0:
return status
with cd(repo.rootdir):
rules = None
... | python | {
"resource": ""
} |
q264089 | MetadataValidator.evaluate | validation | def evaluate(self, repo, spec, args):
"""
Check the integrity of the datapackage.json
"""
status = []
with cd(repo.rootdir):
files = spec.get('files', ['*'])
resource_files = repo.find_matching_files(files)
files = glob2.glob("**/*")
... | python | {
"resource": ""
} |
q264090 | TableRepresentation.read_file | validation | def read_file(self, filename):
"""
Guess the filetype and read the file into row sets
"""
#print("Reading file", filename)
try:
fh = open(filename, 'rb')
table_set = any_tableset(fh) # guess the type...
except:
#traceback.print_exc()
... | python | {
"resource": ""
} |
q264091 | TableRepresentation.get_schema | validation | def get_schema(self, filename):
"""
Guess schema using messytables
"""
table_set = self.read_file(filename)
# Have I been able to read the filename
if table_set is None:
return []
# Get the first table as rowset
row_set = table_... | python | {
"resource": ""
} |
q264092 | int2fin_reference | validation | def int2fin_reference(n):
"""Calculates a checksum for a Finnish national reference number"""
checksum = 10 - (sum([int(c) * i for c, i in zip(str(n)[::-1], it.cycle((7, 3, 1)))]) % 10)
if checksum == 10:
checksum = 0
return "%s%s" % (n, checksum) | python | {
"resource": ""
} |
q264093 | iso_reference_valid_char | validation | def iso_reference_valid_char(c, raise_error=True):
"""Helper to make sure the given character is valid for a reference number"""
if c in ISO_REFERENCE_VALID:
return True
if raise_error:
raise ValueError("'%s' is not in '%s'" % (c, ISO_REFERENCE_VALID))
return False | python | {
"resource": ""
} |
q264094 | iso_reference_str2int | validation | def iso_reference_str2int(n):
"""Creates the huge number from ISO alphanumeric ISO reference"""
n = n.upper()
numbers = []
for c in n:
iso_reference_valid_char(c)
if c in ISO_REFERENCE_VALID_NUMERIC:
numbers.append(c)
else:
numbers.append(str(iso_reference... | python | {
"resource": ""
} |
q264095 | iso_reference_isvalid | validation | def iso_reference_isvalid(ref):
"""Validates ISO reference number"""
ref = str(ref)
cs_source = ref[4:] + ref[:4]
return (iso_reference_str2int(cs_source) % 97) == 1 | python | {
"resource": ""
} |
q264096 | barcode | validation | def barcode(iban, reference, amount, due=None):
"""Calculates virtual barcode for IBAN account number and ISO reference
Arguments:
iban {string} -- IBAN formed account number
reference {string} -- ISO 11649 creditor reference
amount {decimal.Decimal} -- Amount in euros, 0.01 - 999999.99... | python | {
"resource": ""
} |
q264097 | add_file_normal | validation | def add_file_normal(f, targetdir, generator,script, source):
"""
Add a normal file including its source
"""
basename = os.path.basename(f)
if targetdir != ".":
relativepath = os.path.join(targetdir, basename)
else:
relativepath = basename
relpath = os.path.relpath(f, os.get... | python | {
"resource": ""
} |
q264098 | run_executable | validation | def run_executable(repo, args, includes):
"""
Run the executable and capture the input and output...
"""
# Get platform information
mgr = plugins_get_mgr()
repomgr = mgr.get(what='instrumentation', name='platform')
platform_metadata = repomgr.get_metadata()
print("Obtaining Commit Info... | python | {
"resource": ""
} |
q264099 | add | validation | def add(repo, args, targetdir,
execute=False, generator=False,
includes=[], script=False,
source=None):
"""
Add files to the repository by explicitly specifying them or by
specifying a pattern over files accessed during execution of an
executable.
Parameters
----------
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.