text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Modifier decorator to update a patch's settings. <END_TASK> <USER_TASK:> Description: def settings(**kwargs): """Modifier decorator to update a patch's settings. This only modifies the behaviour of the :func:`create_patches` function and the :func:`patches` decorator, given that their parameter ``use_decorators`` is set to ``True``. Parameters ---------- kwargs Settings to update. See :class:`Settings` for the list. Returns ------- object The decorated object. """
def decorator(wrapped): data = get_decorator_data(_get_base(wrapped), set_default=True) data.override.setdefault('settings', {}).update(kwargs) return wrapped return decorator
<SYSTEM_TASK:> Modifier decorator to force the inclusion or exclusion of an attribute. <END_TASK> <USER_TASK:> Description: def filter(value): """Modifier decorator to force the inclusion or exclusion of an attribute. This only modifies the behaviour of the :func:`create_patches` function and the :func:`patches` decorator, given that their parameter ``use_decorators`` is set to ``True``. Parameters ---------- value : bool ``True`` to force inclusion, ``False`` to force exclusion, and ``None`` to inherit from the behaviour defined by :func:`create_patches` or :func:`patches`. Returns ------- object The decorated object. """
def decorator(wrapped): data = get_decorator_data(_get_base(wrapped), set_default=True) data.filter = value return wrapped return decorator
<SYSTEM_TASK:> Create a patch for each member of a module or a class. <END_TASK> <USER_TASK:> Description: def create_patches(destination, root, settings=None, traverse_bases=True, filter=default_filter, recursive=True, use_decorators=True): """Create a patch for each member of a module or a class. Parameters ---------- destination : object Patch destination. root : object Root object, either a module or a class. settings : gorilla.Settings Settings. traverse_bases : bool If the object is a class, the base classes are also traversed. filter : function Attributes for which the function returns ``False`` are skipped. The function needs to define two parameters: ``name``, the attribute name, and ``obj``, the attribute value. If ``None``, no attribute is skipped. recursive : bool If ``True``, and a hit occurs due to an attribute at the destination already existing with the given name, and both the member and the target attributes are classes, then instead of creating a patch directly with the member attribute value as is, a patch for each of its own members is created with the target as new destination. use_decorators : bool ``True`` to take any modifier decorator into consideration to allow for more granular customizations. Returns ------- list of gorilla.Patch The patches. Note ---- A 'target' differs from a 'destination' in that a target represents an existing attribute at the destination about to be hit by a patch. See Also -------- :func:`patches`. """
if filter is None: filter = _true out = [] root_patch = Patch(destination, '', root, settings=settings) stack = collections.deque((root_patch,)) while stack: parent_patch = stack.popleft() members = _get_members(parent_patch.obj, traverse_bases=traverse_bases, filter=None, recursive=False) for name, value in members: patch = Patch(parent_patch.destination, name, value, settings=copy.deepcopy(parent_patch.settings)) if use_decorators: base = _get_base(value) decorator_data = get_decorator_data(base) filter_override = (None if decorator_data is None else decorator_data.filter) if ((filter_override is None and not filter(name, value)) or filter_override is False): continue if decorator_data is not None: patch._update(**decorator_data.override) elif not filter(name, value): continue if recursive and isinstance(value, _CLASS_TYPES): try: target = get_attribute(patch.destination, patch.name) except AttributeError: pass else: if isinstance(target, _CLASS_TYPES): patch.destination = target stack.append(patch) continue out.append(patch) return out
<SYSTEM_TASK:> Find all the patches created through decorators. <END_TASK> <USER_TASK:> Description: def find_patches(modules, recursive=True): """Find all the patches created through decorators. Parameters ---------- modules : list of module Modules and/or packages to search the patches in. recursive : bool ``True`` to search recursively in subpackages. Returns ------- list of gorilla.Patch Patches found. Raises ------ TypeError The input is not a valid package or module. See Also -------- :func:`patch`, :func:`patches`. """
out = [] modules = (module for package in modules for module in _module_iterator(package, recursive=recursive)) for module in modules: members = _get_members(module, filter=None) for _, value in members: base = _get_base(value) decorator_data = get_decorator_data(base) if decorator_data is None: continue out.extend(decorator_data.patches) return out
<SYSTEM_TASK:> Retrieve an attribute while bypassing the descriptor protocol. <END_TASK> <USER_TASK:> Description: def get_attribute(obj, name): """Retrieve an attribute while bypassing the descriptor protocol. As per the built-in |getattr()|_ function, if the input object is a class then its base classes might also be searched until the attribute is found. Parameters ---------- obj : object Object to search the attribute in. name : str Name of the attribute. Returns ------- object The attribute found. Raises ------ AttributeError The attribute couldn't be found. .. |getattr()| replace:: ``getattr()`` .. _getattr(): https://docs.python.org/library/functions.html#getattr """
objs = inspect.getmro(obj) if isinstance(obj, _CLASS_TYPES) else [obj] for obj_ in objs: try: return object.__getattribute__(obj_, name) except AttributeError: pass raise AttributeError("'%s' object has no attribute '%s'" % (type(obj), name))
<SYSTEM_TASK:> Retrieve any decorator data from an object. <END_TASK> <USER_TASK:> Description: def get_decorator_data(obj, set_default=False): """Retrieve any decorator data from an object. Parameters ---------- obj : object Object. set_default : bool If no data is found, a default one is set on the object and returned, otherwise ``None`` is returned. Returns ------- gorilla.DecoratorData The decorator data or ``None``. """
if isinstance(obj, _CLASS_TYPES): datas = getattr(obj, _DECORATOR_DATA, {}) data = datas.setdefault(obj, None) if data is None and set_default: data = DecoratorData() datas[obj] = data setattr(obj, _DECORATOR_DATA, datas) else: data = getattr(obj, _DECORATOR_DATA, None) if data is None and set_default: data = DecoratorData() setattr(obj, _DECORATOR_DATA, data) return data
<SYSTEM_TASK:> Retrieve the member attributes of a module or a class. <END_TASK> <USER_TASK:> Description: def _get_members(obj, traverse_bases=True, filter=default_filter, recursive=True): """Retrieve the member attributes of a module or a class. The descriptor protocol is bypassed."""
if filter is None: filter = _true out = [] stack = collections.deque((obj,)) while stack: obj = stack.popleft() if traverse_bases and isinstance(obj, _CLASS_TYPES): roots = [base for base in inspect.getmro(obj) if base not in (type, object)] else: roots = [obj] members = [] seen = set() for root in roots: for name, value in _iteritems(getattr(root, '__dict__', {})): if name not in seen and filter(name, value): members.append((name, value)) seen.add(name) members = sorted(members) for _, value in members: if recursive and isinstance(value, _CLASS_TYPES): stack.append(value) out.extend(members) return out
<SYSTEM_TASK:> Update some attributes. <END_TASK> <USER_TASK:> Description: def _update(self, **kwargs): """Update some attributes. If a 'settings' attribute is passed as a dict, then it updates the content of the settings, if any, instead of completely overwriting it. """
for key, value in _iteritems(kwargs): if key == 'settings': if isinstance(value, dict): if self.settings is None: self.settings = Settings(**value) else: self.settings._update(**value) else: self.settings = copy.deepcopy(value) else: setattr(self, key, value)
<SYSTEM_TASK:> List projects with searchstring. <END_TASK> <USER_TASK:> Description: def list_projects_search(self, searchstring): """List projects with searchstring."""
log.debug('List all projects with: %s' % searchstring) return self.collection('projects/search/%s.json' % quote_plus(searchstring))
<SYSTEM_TASK:> List passwords with searchstring. <END_TASK> <USER_TASK:> Description: def list_passwords_search(self, searchstring): """List passwords with searchstring."""
log.debug('List all passwords with: %s' % searchstring) return self.collection('passwords/search/%s.json' % quote_plus(searchstring))
<SYSTEM_TASK:> List my passwords with searchstring. <END_TASK> <USER_TASK:> Description: def list_mypasswords_search(self, searchstring): """List my passwords with searchstring."""
# http://teampasswordmanager.com/docs/api-my-passwords/#list_passwords log.debug('List MyPasswords with %s' % searchstring) return self.collection('my_passwords/search/%s.json' % quote_plus(searchstring))
<SYSTEM_TASK:> Check if Team Password Manager is up to date. <END_TASK> <USER_TASK:> Description: def up_to_date(self): """Check if Team Password Manager is up to date."""
VersionInfo = self.get_latest_version() CurrentVersion = VersionInfo.get('version') LatestVersion = VersionInfo.get('latest_version') if CurrentVersion == LatestVersion: log.info('TeamPasswordManager is up-to-date!') log.debug('Current Version: {} Latest Version: {}'.format(LatestVersion, LatestVersion)) return True else: log.warning('TeamPasswordManager is not up-to-date!') log.debug('Current Version: {} Latest Version: {}'.format(LatestVersion, LatestVersion)) return False
<SYSTEM_TASK:> Given a datetime ``t`` and a ``resolution``, flatten the precision beyond the given resolution. <END_TASK> <USER_TASK:> Description: def truncate_datetime(t, resolution): """ Given a datetime ``t`` and a ``resolution``, flatten the precision beyond the given resolution. ``resolution`` can be one of: year, month, day, hour, minute, second, microsecond Example:: >>> t = datetime.datetime(2000, 1, 2, 3, 4, 5, 6000) # Or, 2000-01-02 03:04:05.006000 >>> truncate_datetime(t, 'day') datetime.datetime(2000, 1, 2, 0, 0) >>> _.isoformat() '2000-01-02T00:00:00' >>> truncate_datetime(t, 'minute') datetime.datetime(2000, 1, 2, 3, 4) >>> _.isoformat() '2000-01-02T03:04:00' """
resolutions = ['year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond'] if resolution not in resolutions: raise KeyError("Resolution is not valid: {0}".format(resolution)) args = [] for r in resolutions: args += [getattr(t, r)] if r == resolution: break return datetime.datetime(*args)
<SYSTEM_TASK:> Return an aware datetime which is ``dt`` converted to ``timezone``. <END_TASK> <USER_TASK:> Description: def to_timezone(dt, timezone): """ Return an aware datetime which is ``dt`` converted to ``timezone``. If ``dt`` is naive, it is assumed to be UTC. For example, if ``dt`` is "06:00 UTC+0000" and ``timezone`` is "EDT-0400", then the result will be "02:00 EDT-0400". This method follows the guidelines in http://pytz.sourceforge.net/ """
if dt.tzinfo is None: dt = dt.replace(tzinfo=_UTC) return timezone.normalize(dt.astimezone(timezone))
<SYSTEM_TASK:> Return a naive datetime object for the given ``timezone``. A ``timezone`` <END_TASK> <USER_TASK:> Description: def now(timezone=None): """ Return a naive datetime object for the given ``timezone``. A ``timezone`` is any pytz- like or datetime.tzinfo-like timezone object. If no timezone is given, then UTC is assumed. This method is best used with pytz installed:: pip install pytz """
d = datetime.datetime.utcnow() if not timezone: return d return to_timezone(d, timezone).replace(tzinfo=None)
<SYSTEM_TASK:> Enumerate over SQLAlchemy query object ``q`` and yield individual results <END_TASK> <USER_TASK:> Description: def enumerate_query_by_limit(q, limit=1000): """ Enumerate over SQLAlchemy query object ``q`` and yield individual results fetched in batches of size ``limit`` using SQL LIMIT and OFFSET. """
for offset in count(0, limit): r = q.offset(offset).limit(limit).all() for row in r: yield row if len(r) < limit: break
<SYSTEM_TASK:> Validate a dictionary of data against the provided schema. <END_TASK> <USER_TASK:> Description: def validate_many(d, schema): """Validate a dictionary of data against the provided schema. Returns a list of values positioned in the same order as given in ``schema``, each value is validated with the corresponding validator. Raises formencode.Invalid if validation failed. Similar to get_many but using formencode validation. :param d: A dictionary of data to read values from. :param schema: A list of (key, validator) tuples. The key will be used to fetch a value from ``d`` and the validator will be applied to it. Example:: from formencode import validators email, password, password_confirm = validate_many(request.params, [ ('email', validators.Email(not_empty=True)), ('password', validators.String(min=4)), ('password_confirm', validators.String(min=4)), ]) """
return [validator.to_python(d.get(key), state=key) for key,validator in schema]
<SYSTEM_TASK:> Verify that each argument is hashable. <END_TASK> <USER_TASK:> Description: def assert_hashable(*args, **kw): """ Verify that each argument is hashable. Passes silently if successful. Raises descriptive TypeError otherwise. Example:: >>> assert_hashable(1, 'foo', bar='baz') >>> assert_hashable(1, [], baz='baz') Traceback (most recent call last): ... TypeError: Argument in position 1 is not hashable: [] >>> assert_hashable(1, 'foo', bar=[]) Traceback (most recent call last): ... TypeError: Keyword argument 'bar' is not hashable: [] """
try: for i, arg in enumerate(args): hash(arg) except TypeError: raise TypeError('Argument in position %d is not hashable: %r' % (i, arg)) try: for key, val in iterate_items(kw): hash(val) except TypeError: raise TypeError('Keyword argument %r is not hashable: %r' % (key, val))
<SYSTEM_TASK:> Memoize a function into an optionally-specificed cache container. <END_TASK> <USER_TASK:> Description: def memoized(fn=None, cache=None): """ Memoize a function into an optionally-specificed cache container. If the `cache` container is not specified, then the instance container is accessible from the wrapped function's `memoize_cache` property. Example:: >>> @memoized ... def foo(bar): ... print("Not cached.") >>> foo(1) Not cached. >>> foo(1) >>> foo(2) Not cached. Example with a specific cache container (in this case, the ``RecentlyUsedContainer``, which will only store the ``maxsize`` most recently accessed items):: >>> from unstdlib.standard.collections_ import RecentlyUsedContainer >>> lru_container = RecentlyUsedContainer(maxsize=2) >>> @memoized(cache=lru_container) ... def baz(x): ... print("Not cached.") >>> baz(1) Not cached. >>> baz(1) >>> baz(2) Not cached. >>> baz(3) Not cached. >>> baz(2) >>> baz(1) Not cached. >>> # Notice that the '2' key remains, but the '1' key was evicted from >>> # the cache. """
if fn: # This is a hack to support both @memoize and @memoize(...) return memoized(cache=cache)(fn) if cache is None: cache = {} def decorator(fn): wrapped = wraps(fn)(partial(_memoized_call, fn, cache)) wrapped.memoize_cache = cache return wrapped return decorator
<SYSTEM_TASK:> Memoize a class's method. <END_TASK> <USER_TASK:> Description: def memoized_method(method=None, cache_factory=None): """ Memoize a class's method. Arguments are similar to to `memoized`, except that the cache container is specified with `cache_factory`: a function called with no arguments to create the caching container for the instance. Note that, unlike `memoized`, the result cache will be stored on the instance, so cached results will be deallocated along with the instance. Example:: >>> class Person(object): ... def __init__(self, name): ... self._name = name ... @memoized_method ... def get_name(self): ... print("Calling get_name on %r" %(self._name, )) ... return self._name >>> shazow = Person("shazow") >>> shazow.get_name() Calling get_name on 'shazow' 'shazow' >>> shazow.get_name() 'shazow' >>> shazow._get_name_cache {((), ()): 'shazow'} Example with a specific cache container:: >>> from unstdlib.standard.collections_ import RecentlyUsedContainer >>> class Foo(object): ... @memoized_method(cache_factory=lambda: RecentlyUsedContainer(maxsize=2)) ... def add(self, a, b): ... print("Calling add with %r and %r" %(a, b)) ... return a + b >>> foo = Foo() >>> foo.add(1, 1) Calling add with 1 and 1 2 >>> foo.add(1, 1) 2 >>> foo.add(2, 2) Calling add with 2 and 2 4 >>> foo.add(3, 3) Calling add with 3 and 3 6 >>> foo.add(1, 1) Calling add with 1 and 1 2 """
if method is None: return lambda f: memoized_method(f, cache_factory=cache_factory) cache_factory = cache_factory or dict @wraps(method) def memoized_method_property(self): cache = cache_factory() cache_attr = "_%s_cache" %(method.__name__, ) setattr(self, cache_attr, cache) result = partial( _memoized_call, partial(method, self), cache ) result.memoize_cache = cache return result return memoized_property(memoized_method_property)
<SYSTEM_TASK:> Aggregate iterator values into buckets based on how frequently the <END_TASK> <USER_TASK:> Description: def groupby_count(i, key=None, force_keys=None): """ Aggregate iterator values into buckets based on how frequently the values appear. Example:: >>> list(groupby_count([1, 1, 1, 2, 3])) [(1, 3), (2, 1), (3, 1)] """
counter = defaultdict(lambda: 0) if not key: key = lambda o: o for k in i: counter[key(k)] += 1 if force_keys: for k in force_keys: counter[k] += 0 return counter.items()
<SYSTEM_TASK:> Return whether ``maybe_iter`` is an iterable, unless it's an instance of one <END_TASK> <USER_TASK:> Description: def is_iterable(maybe_iter, unless=(string_types, dict)): """ Return whether ``maybe_iter`` is an iterable, unless it's an instance of one of the base class, or tuple of base classes, given in ``unless``. Example:: >>> is_iterable('foo') False >>> is_iterable(['foo']) True >>> is_iterable(['foo'], unless=list) False >>> is_iterable(xrange(5)) True """
try: iter(maybe_iter) except TypeError: return False return not isinstance(maybe_iter, unless)
<SYSTEM_TASK:> Always return an iterable. <END_TASK> <USER_TASK:> Description: def iterate(maybe_iter, unless=(string_types, dict)): """ Always return an iterable. Returns ``maybe_iter`` if it is an iterable, otherwise it returns a single element iterable containing ``maybe_iter``. By default, strings and dicts are treated as non-iterable. This can be overridden by passing in a type or tuple of types for ``unless``. :param maybe_iter: A value to return as an iterable. :param unless: A type or tuple of types (same as ``isinstance``) to be treated as non-iterable. Example:: >>> iterate('foo') ['foo'] >>> iterate(['foo']) ['foo'] >>> iterate(['foo'], unless=list) [['foo']] >>> list(iterate(xrange(5))) [0, 1, 2, 3, 4] """
if is_iterable(maybe_iter, unless=unless): return maybe_iter return [maybe_iter]
<SYSTEM_TASK:> Iterate over an iterator ``i`` in ``size`` chunks, yield chunks. <END_TASK> <USER_TASK:> Description: def iterate_chunks(i, size=10): """ Iterate over an iterator ``i`` in ``size`` chunks, yield chunks. Similar to pagination. Example:: >>> list(iterate_chunks([1, 2, 3, 4], size=2)) [[1, 2], [3, 4]] """
accumulator = [] for n, i in enumerate(i): accumulator.append(i) if (n+1) % size == 0: yield accumulator accumulator = [] if accumulator: yield accumulator
<SYSTEM_TASK:> Similar to the ``issubclass`` builtin, but does not raise a ``TypeError`` <END_TASK> <USER_TASK:> Description: def is_subclass(o, bases): """ Similar to the ``issubclass`` builtin, but does not raise a ``TypeError`` if either ``o`` or ``bases`` is not an instance of ``type``. Example:: >>> is_subclass(IOError, Exception) True >>> is_subclass(Exception, None) False >>> is_subclass(None, Exception) False >>> is_subclass(IOError, (None, Exception)) True >>> is_subclass(Exception, (None, 42)) False """
try: return _issubclass(o, bases) except TypeError: pass if not isinstance(o, type): return False if not isinstance(bases, tuple): return False bases = tuple(b for b in bases if isinstance(b, type)) return _issubclass(o, bases)
<SYSTEM_TASK:> Returns a predictable number of elements out of ``d`` in a list for auto-expanding. <END_TASK> <USER_TASK:> Description: def get_many(d, required=[], optional=[], one_of=[]): """ Returns a predictable number of elements out of ``d`` in a list for auto-expanding. Keys in ``required`` will raise KeyError if not found in ``d``. Keys in ``optional`` will return None if not found in ``d``. Keys in ``one_of`` will raise KeyError if none exist, otherwise return the first in ``d``. Example:: uid, action, limit, offset = get_many(request.params, required=['uid', 'action'], optional=['limit', 'offset']) Note: This function has been added to the webhelpers package. """
d = d or {} r = [d[k] for k in required] r += [d.get(k)for k in optional] if one_of: for k in (k for k in one_of if k in d): return r + [d[k]] raise KeyError("Missing a one_of value.") return r
<SYSTEM_TASK:> Given an non-negative integer ``n``, convert it to a string composed of <END_TASK> <USER_TASK:> Description: def number_to_string(n, alphabet): """ Given an non-negative integer ``n``, convert it to a string composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> number_to_string(12345678, '01') '101111000110000101001110' >>> number_to_string(12345678, 'ab') 'babbbbaaabbaaaababaabbba' >>> number_to_string(12345678, string.ascii_letters + string.digits) 'ZXP0' >>> number_to_string(12345, ['zero ', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ']) 'one two three four five ' """
result = '' base = len(alphabet) current = int(n) if current < 0: raise ValueError("invalid n (must be non-negative): %s", n) while current: result = alphabet[current % base] + result current = current // base return result
<SYSTEM_TASK:> Given a string ``s``, convert it to an integer composed of the given <END_TASK> <USER_TASK:> Description: def string_to_number(s, alphabet): """ Given a string ``s``, convert it to an integer composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> string_to_number('101111000110000101001110', '01') 12345678 >>> string_to_number('babbbbaaabbaaaababaabbba', 'ab') 12345678 >>> string_to_number('ZXP0', string.ascii_letters + string.digits) 12345678 """
base = len(alphabet) inverse_alphabet = dict(zip(alphabet, xrange(0, base))) n = 0 exp = 0 for i in reversed(s): n += inverse_alphabet[i] * (base ** exp) exp += 1 return n
<SYSTEM_TASK:> Convert an integer to a corresponding string of bytes.. <END_TASK> <USER_TASK:> Description: def number_to_bytes(n, endian='big'): """ Convert an integer to a corresponding string of bytes.. :param n: Integer to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of number_to_string with a full base-256 ASCII alphabet. It is the reverse of ``bytes_to_number(b)``. Examples:: >>> r(number_to_bytes(42)) b'*' >>> r(number_to_bytes(255)) b'\\xff' >>> r(number_to_bytes(256)) b'\\x01\\x00' >>> r(number_to_bytes(256, endian='little')) b'\\x00\\x01' """
res = [] while n: n, ch = divmod(n, 256) if PY3: res.append(ch) else: res.append(chr(ch)) if endian == 'big': res.reverse() if PY3: return bytes(res) else: return ''.join(res)
<SYSTEM_TASK:> Return input converted into a float. If failed, then return ``default``. <END_TASK> <USER_TASK:> Description: def to_float(s, default=0.0, allow_nan=False): """ Return input converted into a float. If failed, then return ``default``. Note that, by default, ``allow_nan=False``, so ``to_float`` will not return ``nan``, ``inf``, or ``-inf``. Examples:: >>> to_float('1.5') 1.5 >>> to_float(1) 1.0 >>> to_float('') 0.0 >>> to_float('nan') 0.0 >>> to_float('inf') 0.0 >>> to_float('-inf', allow_nan=True) -inf >>> to_float(None) 0.0 >>> to_float(0, default='Empty') 0.0 >>> to_float(None, default='Empty') 'Empty' """
try: f = float(s) except (TypeError, ValueError): return default if not allow_nan: if f != f or f in _infs: return default return f
<SYSTEM_TASK:> Given a string or integer representing dollars, return an integer of <END_TASK> <USER_TASK:> Description: def dollars_to_cents(s, allow_negative=False): """ Given a string or integer representing dollars, return an integer of equivalent cents, in an input-resilient way. This works by stripping any non-numeric characters before attempting to cast the value. Examples:: >>> dollars_to_cents('$1') 100 >>> dollars_to_cents('1') 100 >>> dollars_to_cents(1) 100 >>> dollars_to_cents('1e2') 10000 >>> dollars_to_cents('-1$', allow_negative=True) -100 >>> dollars_to_cents('1 dollar') 100 """
# TODO: Implement cents_to_dollars if not s: return if isinstance(s, string_types): s = ''.join(RE_NUMBER.findall(s)) dollars = int(round(float(s) * 100)) if not allow_negative and dollars < 0: raise ValueError('Negative values not permitted.') return dollars
<SYSTEM_TASK:> Normalize `s` into ASCII and replace non-word characters with `delimiter`. <END_TASK> <USER_TASK:> Description: def slugify(s, delimiter='-'): """ Normalize `s` into ASCII and replace non-word characters with `delimiter`. """
s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii') return RE_SLUG.sub(delimiter, s).strip(delimiter).lower()
<SYSTEM_TASK:> Return a string that can be used as a parameter for cache-busting URLs <END_TASK> <USER_TASK:> Description: def get_cache_buster(src_path, method='importtime'): """ Return a string that can be used as a parameter for cache-busting URLs for this asset. :param src_path: Filesystem path to the file we're generating a cache-busting value for. :param method: Method for cache-busting. Supported values: importtime, mtime, md5 The default is 'importtime', because it requires the least processing. Note that the mtime and md5 cache busting methods' results are cached on the src_path. Example:: >>> SRC_PATH = os.path.join(os.path.dirname(__file__), 'html.py') >>> get_cache_buster(SRC_PATH) is _IMPORT_TIME True >>> get_cache_buster(SRC_PATH, method='mtime') == _cache_key_by_mtime(SRC_PATH) True >>> get_cache_buster(SRC_PATH, method='md5') == _cache_key_by_md5(SRC_PATH) True """
try: fn = _BUST_METHODS[method] except KeyError: raise KeyError('Unsupported busting method value: %s' % method) return fn(src_path)
<SYSTEM_TASK:> Yield compiled DOM attribute key-value strings. <END_TASK> <USER_TASK:> Description: def _generate_dom_attrs(attrs, allow_no_value=True): """ Yield compiled DOM attribute key-value strings. If the value is `True`, then it is treated as no-value. If `None`, then it is skipped. """
for attr in iterate_items(attrs): if isinstance(attr, basestring): attr = (attr, True) key, value = attr if value is None: continue if value is True and not allow_no_value: value = key # E.g. <option checked="true" /> if value is True: yield True # E.g. <option checked /> else: yield '%s="%s"' % (key, value.replace('"', '\\"'))
<SYSTEM_TASK:> Helper for programmatically building HTML tags. <END_TASK> <USER_TASK:> Description: def tag(tagname, content='', attrs=None): """ Helper for programmatically building HTML tags. Note that this barely does any escaping, and will happily spit out dangerous user input if used as such. :param tagname: Tag name of the DOM element we want to return. :param content: Optional content of the DOM element. If `None`, then the element is self-closed. By default, the content is an empty string. Supports iterables like generators. :param attrs: Optional dictionary-like collection of attributes for the DOM element. Example:: >>> tag('div', content='Hello, world.') u'<div>Hello, world.</div>' >>> tag('script', attrs={'src': '/static/js/core.js'}) u'<script src="/static/js/core.js"></script>' >>> tag('script', attrs=[('src', '/static/js/core.js'), ('type', 'text/javascript')]) u'<script src="/static/js/core.js" type="text/javascript"></script>' >>> tag('meta', content=None, attrs=dict(content='"quotedquotes"')) u'<meta content="\\\\"quotedquotes\\\\"" />' >>> tag('ul', (tag('li', str(i)) for i in xrange(3))) u'<ul><li>0</li><li>1</li><li>2</li></ul>' """
attrs_str = attrs and ' '.join(_generate_dom_attrs(attrs)) open_tag = tagname if attrs_str: open_tag += ' ' + attrs_str if content is None: return literal('<%s />' % open_tag) content = ''.join(iterate(content, unless=(basestring, literal))) return literal('<%s>%s</%s>' % (open_tag, content, tagname))
<SYSTEM_TASK:> Helper for programmatically building HTML JavaScript source include <END_TASK> <USER_TASK:> Description: def javascript_link(src_url, src_path=None, cache_bust=None, content='', extra_attrs=None): """ Helper for programmatically building HTML JavaScript source include links, with optional cache busting. :param src_url: Goes into the `src` attribute of the `<script src="...">` tag. :param src_path: Optional filesystem path to the source file, used when `cache_bust` is enabled. :param content: Optional content of the DOM element. If `None`, then the element is self-closed. :param cache_bust: Optional method to use for cache busting. Can be one of: importtime, md5, or mtime. If the value is md5 or mtime, then `src_path` must be supplied. Example:: >>> javascript_link('/static/js/core.js') u'<script src="/static/js/core.js" type="text/javascript"></script>' """
if cache_bust: append_suffix = get_cache_buster(src_path=src_path, method=cache_bust) delim = '&' if '?' in src_url else '?' src_url += delim + append_suffix attrs = { 'src': src_url, 'type': 'text/javascript', } if extra_attrs: attrs.update(extra_attrs) return tag('script', content=content, attrs=attrs)
<SYSTEM_TASK:> Create a zip file of the lambda script and its dependencies. <END_TASK> <USER_TASK:> Description: def package(self, ignore=None): """ Create a zip file of the lambda script and its dependencies. :param list ignore: a list of regular expression strings to match paths of files in the source of the lambda script against and ignore those files when creating the zip file. The paths to be matched are local to the source root. """
ignore = ignore or [] package = os.path.join(self._temp_workspace, 'lambda_package') # Copy site packages into package base LOG.info('Copying site packages') if hasattr(self, '_pkg_venv') and self._pkg_venv: lib_dir = 'lib/python*/site-packages' lib64_dir = 'lib64/python*/site-packages' if sys.platform == 'win32' or sys.platform == 'cygwin': lib_dir = 'lib\\site-packages' lib64_dir = 'lib64\\site-packages' # Look for the site packages lib_site_list = glob.glob(os.path.join( self._pkg_venv, lib_dir)) if lib_site_list: utils.copy_tree(lib_site_list[0], package) else: LOG.debug("no lib site packages found") lib64_site_list = glob.glob(os.path.join( self._pkg_venv, lib64_dir)) if lib64_site_list: lib64_site_packages = lib64_site_list[0] if not os.path.islink(lib64_site_packages): LOG.info('Copying lib64 site packages') utils.copy_tree(lib64_site_packages, package) lib64_site_packages = lib64_site_list[0] else: LOG.debug("no lib64 site packages found") # Append the temp workspace to the ignore list: ignore.append(r"^%s/.*" % re.escape(TEMP_WORKSPACE_NAME)) utils.copy_tree(self._path, package, ignore) # Add extra files for p in self._extra_files: LOG.info('Copying extra %s into package' % p) ignore.append(re.escape(p)) if os.path.isdir(p): utils.copy_tree(p, package, ignore=ignore, include_parent=True) else: shutil.copy(p, package) self._create_zip(package)
<SYSTEM_TASK:> Performs encoding of url parameters from dictionary to a string. It does <END_TASK> <USER_TASK:> Description: def encode_properties(parameters): """ Performs encoding of url parameters from dictionary to a string. It does not escape backslash because it is not needed. See: http://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-SetItemProperties """
result = [] for param in iter(sorted(parameters)): if isinstance(parameters[param], (list, tuple)): value = ','.join([escape_chars(x) for x in parameters[param]]) else: value = escape_chars(parameters[param]) result.append("%s=%s" % (param, value)) return '|'.join(result)
<SYSTEM_TASK:> Perform a GET request to url with optional authentication <END_TASK> <USER_TASK:> Description: def rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None): """ Perform a GET request to url with optional authentication """
res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify, cert=cert) return res.text, res.status_code
<SYSTEM_TASK:> Perform a DELETE request to url with optional authentication <END_TASK> <USER_TASK:> Description: def rest_del(self, url, params=None, auth=None, verify=True, cert=None): """ Perform a DELETE request to url with optional authentication """
res = requests.delete(url, params=params, auth=auth, verify=verify, cert=cert) return res.text, res.status_code
<SYSTEM_TASK:> Perform a chunked GET request to url with optional authentication <END_TASK> <USER_TASK:> Description: def rest_get_stream(self, url, auth=None, verify=True, cert=None): """ Perform a chunked GET request to url with optional authentication This is specifically to download files. """
res = requests.get(url, auth=auth, stream=True, verify=verify, cert=cert) return res.raw, res.status_code
<SYSTEM_TASK:> Uploads a given file-like object <END_TASK> <USER_TASK:> Description: def deploy(self, pathobj, fobj, md5=None, sha1=None, parameters=None): """ Uploads a given file-like object HTTP chunked encoding will be attempted """
if isinstance(fobj, urllib3.response.HTTPResponse): fobj = HTTPResponseWrapper(fobj) url = str(pathobj) if parameters: url += ";%s" % encode_matrix_parameters(parameters) headers = {} if md5: headers['X-Checksum-Md5'] = md5 if sha1: headers['X-Checksum-Sha1'] = sha1 text, code = self.rest_put_stream(url, fobj, headers=headers, auth=pathobj.auth, verify=pathobj.verify, cert=pathobj.cert) if code not in [200, 201]: raise RuntimeError("%s" % text)
<SYSTEM_TASK:> Move artifact from src to dst <END_TASK> <USER_TASK:> Description: def move(self, src, dst): """ Move artifact from src to dst """
url = '/'.join([src.drive, 'api/move', str(src.relative_to(src.drive)).rstrip('/')]) params = {'to': str(dst.relative_to(dst.drive)).rstrip('/')} text, code = self.rest_post(url, params=params, auth=src.auth, verify=src.verify, cert=src.cert) if code not in [200, 201]: raise RuntimeError("%s" % text)
<SYSTEM_TASK:> Perform the similarity join <END_TASK> <USER_TASK:> Description: def main(left_path, left_column, right_path, right_column, outfile, titles, join, minscore, count, warp): """Perform the similarity join"""
right_file = csv.reader(open(right_path, 'r')) if titles: right_header = next(right_file) index = NGram((tuple(r) for r in right_file), threshold=minscore, warp=warp, key=lambda x: lowstrip(x[right_column])) left_file = csv.reader(open(left_path, 'r')) out = csv.writer(open(outfile, 'w'), lineterminator='\n') if titles: left_header = next(left_file) out.writerow(left_header + ["Rank", "Similarity"] + right_header) for row in left_file: if not row: continue # skip blank lines row = tuple(row) results = index.search(lowstrip(row[left_column]), threshold=minscore) if results: if count > 0: results = results[:count] for rank, result in enumerate(results, 1): out.writerow(row + (rank, result[1]) + result[0]) elif join == "outer": out.writerow(row)
<SYSTEM_TASK:> Return a new NGram object with the same settings, and <END_TASK> <USER_TASK:> Description: def copy(self, items=None): """Return a new NGram object with the same settings, and referencing the same items. Copy is shallow in that each item is not recursively copied. Optionally specify alternate items to populate the copy. >>> from ngram import NGram >>> from copy import deepcopy >>> n = NGram(['eggs', 'spam']) >>> m = n.copy() >>> m.add('ham') >>> sorted(list(n)) ['eggs', 'spam'] >>> sorted(list(m)) ['eggs', 'ham', 'spam'] >>> p = n.copy(['foo', 'bar']) >>> sorted(list(p)) ['bar', 'foo'] """
return NGram(items if items is not None else self, self.threshold, self.warp, self._key, self.N, self._pad_len, self._pad_char)
<SYSTEM_TASK:> Retrieve the subset of items that share n-grams the query string. <END_TASK> <USER_TASK:> Description: def items_sharing_ngrams(self, query): """Retrieve the subset of items that share n-grams the query string. :param query: look up items that share N-grams with this string. :return: mapping from matched string to the number of shared N-grams. >>> from ngram import NGram >>> n = NGram(["ham","spam","eggs"]) >>> sorted(n.items_sharing_ngrams("mam").items()) [('ham', 2), ('spam', 2)] """
# From matched string to number of N-grams shared with query string shared = {} # Dictionary mapping n-gram to string to number of occurrences of that # ngram in the string that remain to be matched. remaining = {} for ngram in self.split(query): try: for match, count in self._grams[ngram].items(): remaining.setdefault(ngram, {}).setdefault(match, count) # match as many occurrences as exist in matched string if remaining[ngram][match] > 0: remaining[ngram][match] -= 1 shared.setdefault(match, 0) shared[match] += 1 except KeyError: pass return shared
<SYSTEM_TASK:> Search the index for items whose key exceeds the threshold <END_TASK> <USER_TASK:> Description: def searchitem(self, item, threshold=None): """Search the index for items whose key exceeds the threshold similarity to the key of the given item. :return: list of pairs of (item, similarity) by decreasing similarity. >>> from ngram import NGram >>> n = NGram([(0, "SPAM"), (1, "SPAN"), (2, "EG"), ... (3, "SPANN")], key=lambda x:x[1]) >>> sorted(n.searchitem((2, "SPA"), 0.35)) [((0, 'SPAM'), 0.375), ((1, 'SPAN'), 0.375)] """
return self.search(self.key(item), threshold)
<SYSTEM_TASK:> Search the index for items whose key exceeds threshold <END_TASK> <USER_TASK:> Description: def search(self, query, threshold=None): """Search the index for items whose key exceeds threshold similarity to the query string. :param query: returned items will have at least `threshold` \ similarity to the query string. :return: list of pairs of (item, similarity) by decreasing similarity. >>> from ngram import NGram >>> n = NGram([(0, "SPAM"), (1, "SPAN"), (2, "EG")], key=lambda x:x[1]) >>> sorted(n.search("SPA")) [((0, 'SPAM'), 0.375), ((1, 'SPAN'), 0.375)] >>> n.search("M") [((0, 'SPAM'), 0.125)] >>> n.search("EG") [((2, 'EG'), 1.0)] """
threshold = threshold if threshold is not None else self.threshold results = [] # Identify possible results for match, samegrams in self.items_sharing_ngrams(query).items(): allgrams = (len(self.pad(query)) + self.length[match] - (2 * self.N) - samegrams + 2) similarity = self.ngram_similarity(samegrams, allgrams, self.warp) if similarity >= threshold: results.append((match, similarity)) # Sort results by decreasing similarity results.sort(key=lambda x: x[1], reverse=True) return results
<SYSTEM_TASK:> Return most similar item to the provided one, or None if <END_TASK> <USER_TASK:> Description: def finditem(self, item, threshold=None): """Return most similar item to the provided one, or None if nothing exceeds the threshold. >>> from ngram import NGram >>> n = NGram([(0, "Spam"), (1, "Ham"), (2, "Eggsy"), (3, "Egggsy")], ... key=lambda x:x[1].lower()) >>> n.finditem((3, 'Hom')) (1, 'Ham') >>> n.finditem((4, "Oggsy")) (2, 'Eggsy') >>> n.finditem((4, "Oggsy"), 0.8) """
results = self.searchitem(item, threshold) if results: return results[0][0] else: return None
<SYSTEM_TASK:> Similarity for two sets of n-grams. <END_TASK> <USER_TASK:> Description: def ngram_similarity(samegrams, allgrams, warp=1.0): """Similarity for two sets of n-grams. :note: ``similarity = (a**e - d**e)/a**e`` where `a` is \ "all n-grams", `d` is "different n-grams" and `e` is the warp. :param samegrams: number of n-grams shared by the two strings. :param allgrams: total of the distinct n-grams across the two strings. :return: similarity in the range 0.0 to 1.0. >>> from ngram import NGram >>> NGram.ngram_similarity(5, 10) 0.5 >>> NGram.ngram_similarity(5, 10, warp=2) 0.75 >>> NGram.ngram_similarity(5, 10, warp=3) 0.875 >>> NGram.ngram_similarity(2, 4, warp=2) 0.75 >>> NGram.ngram_similarity(3, 4) 0.75 """
if abs(warp - 1.0) < 1e-9: similarity = float(samegrams) / allgrams else: diffgrams = float(allgrams - samegrams) similarity = ((allgrams ** warp - diffgrams ** warp) / (allgrams ** warp)) return similarity
<SYSTEM_TASK:> Compares two strings and returns their similarity. <END_TASK> <USER_TASK:> Description: def compare(s1, s2, **kwargs): """Compares two strings and returns their similarity. :param s1: first string :param s2: second string :param kwargs: additional keyword arguments passed to __init__. :return: similarity between 0.0 and 1.0. >>> from ngram import NGram >>> NGram.compare('spa', 'spam') 0.375 >>> NGram.compare('ham', 'bam') 0.25 >>> NGram.compare('spam', 'pam') #N=2 0.375 >>> NGram.compare('ham', 'ams', N=1) 0.5 """
if s1 is None or s2 is None: if s1 == s2: return 1.0 return 0.0 try: return NGram([s1], **kwargs).search(s2)[0][1] except IndexError: return 0.0
<SYSTEM_TASK:> Remove all elements from this set. <END_TASK> <USER_TASK:> Description: def clear(self): """Remove all elements from this set. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> sorted(list(n)) ['eggs', 'spam'] >>> n.clear() >>> list(n) [] """
super(NGram, self).clear() self._grams = {} self.length = {}
<SYSTEM_TASK:> Return the union of two or more sets as a new set. <END_TASK> <USER_TASK:> Description: def union(self, *others): """Return the union of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> sorted(list(a.union(b))) ['eggs', 'ham', 'spam'] """
return self.copy(super(NGram, self).union(*others))
<SYSTEM_TASK:> Return the difference of two or more sets as a new set. <END_TASK> <USER_TASK:> Description: def difference(self, *others): """Return the difference of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.difference(b)) ['eggs'] """
return self.copy(super(NGram, self).difference(*others))
<SYSTEM_TASK:> Return the intersection of two or more sets as a new set. <END_TASK> <USER_TASK:> Description: def intersection(self, *others): """Return the intersection of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.intersection(b)) ['spam'] """
return self.copy(super(NGram, self).intersection(*others))
<SYSTEM_TASK:> Update the set with the intersection of itself and other sets. <END_TASK> <USER_TASK:> Description: def intersection_update(self, *others): """Update the set with the intersection of itself and other sets. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> other = set(['spam', 'ham']) >>> n.intersection_update(other) >>> list(n) ['spam'] """
self.difference_update(super(NGram, self).difference(*others))
<SYSTEM_TASK:> Return the symmetric difference of two sets as a new set. <END_TASK> <USER_TASK:> Description: def symmetric_difference(self, other): """Return the symmetric difference of two sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> sorted(list(a.symmetric_difference(b))) ['eggs', 'ham'] """
return self.copy(super(NGram, self).symmetric_difference(other))
<SYSTEM_TASK:> Update the set with the symmetric difference of itself and `other`. <END_TASK> <USER_TASK:> Description: def symmetric_difference_update(self, other): """Update the set with the symmetric difference of itself and `other`. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> other = set(['spam', 'ham']) >>> n.symmetric_difference_update(other) >>> sorted(list(n)) ['eggs', 'ham'] """
intersection = super(NGram, self).intersection(other) self.update(other) # add items present in other self.difference_update(intersection)
<SYSTEM_TASK:> Subtract the arg from the value. <END_TASK> <USER_TASK:> Description: def sub(value, arg): """Subtract the arg from the value."""
try: nvalue, narg = handle_float_decimal_combinations( valid_numeric(value), valid_numeric(arg), '-') return nvalue - narg except (ValueError, TypeError): try: return value - arg except Exception: return ''
<SYSTEM_TASK:> Create the cli command line. <END_TASK> <USER_TASK:> Description: def cli(config, server, api_key, all, credentials, project): """Create the cli command line."""
# Check first for the pybossa.rc file to configure server and api-key home = expanduser("~") if os.path.isfile(os.path.join(home, '.pybossa.cfg')): config.parser.read(os.path.join(home, '.pybossa.cfg')) config.server = config.parser.get(credentials,'server') config.api_key = config.parser.get(credentials, 'apikey') try: config.all = config.parser.get(credentials, 'all') except ConfigParser.NoOptionError: config.all = None if server: config.server = server if api_key: config.api_key = api_key if all: config.all = all try: config.project = json.loads(project.read()) except JSONDecodeError as e: click.secho("Error: invalid JSON format in project.json:", fg='red') if e.msg == 'Expecting value': e.msg += " (if string enclose it with double quotes)" click.echo("%s\n%s: line %s column %s" % (e.doc, e.msg, e.lineno, e.colno)) raise click.Abort() try: project_schema = { "type": "object", "properties": { "name": {"type": "string"}, "short_name": {"type": "string"}, "description": {"type": "string"} } } jsonschema.validate(config.project, project_schema) except jsonschema.exceptions.ValidationError as e: click.secho("Error: invalid type in project.json", fg='red') click.secho("'%s': %s" % (e.path[0], e.message), fg='yellow') click.echo("'%s' must be a %s" % (e.path[0], e.validator_value)) raise click.Abort() config.pbclient = pbclient config.pbclient.set('endpoint', config.server) config.pbclient.set('api_key', config.api_key)
<SYSTEM_TASK:> Update a project in a loop. <END_TASK> <USER_TASK:> Description: def _update_project_watch(config, task_presenter, results, long_description, tutorial): # pragma: no cover """Update a project in a loop."""
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') path = os.getcwd() event_handler = PbsHandler(config, task_presenter, results, long_description, tutorial) observer = Observer() # We only want the current folder, not sub-folders observer.schedule(event_handler, path, recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
<SYSTEM_TASK:> Return project by short_name. <END_TASK> <USER_TASK:> Description: def find_project_by_short_name(short_name, pbclient, all=None): """Return project by short_name."""
try: response = pbclient.find_project(short_name=short_name, all=all) check_api_error(response) if (len(response) == 0): msg = '%s not found! You can use the all=1 argument to \ search in all the server.' error = 'Project Not Found' raise ProjectNotFound(msg, error) return response[0] except exceptions.ConnectionError: raise except ProjectNotFound: raise
<SYSTEM_TASK:> Check if returned API response contains an error. <END_TASK> <USER_TASK:> Description: def check_api_error(api_response): print(api_response) """Check if returned API response contains an error."""
if type(api_response) == dict and 'code' in api_response and api_response['code'] <> 200: print("Server response code: %s" % api_response['code']) print("Server response: %s" % api_response) raise exceptions.HTTPError('Unexpected response', response=api_response) if type(api_response) == dict and (api_response.get('status') == 'failed'): if 'ProgrammingError' in api_response.get('exception_cls'): raise DatabaseError(message='PyBossa database error.', error=api_response) if ('DBIntegrityError' in api_response.get('exception_cls') and 'project' in api_response.get('target')): msg = 'PyBossa project already exists.' raise ProjectAlreadyExists(message=msg, error=api_response) if 'project' in api_response.get('target'): raise ProjectNotFound(message='PyBossa Project not found', error=api_response) if 'task' in api_response.get('target'): raise TaskNotFound(message='PyBossa Task not found', error=api_response) else: print("Server response: %s" % api_response) raise exceptions.HTTPError('Unexpected response', response=api_response)
<SYSTEM_TASK:> Format the error for the given module. <END_TASK> <USER_TASK:> Description: def format_error(module, error): """Format the error for the given module."""
logging.error(module) # Beautify JSON error print error.message print json.dumps(error.error, sort_keys=True, indent=4, separators=(',', ': ')) exit(1)
<SYSTEM_TASK:> Create helping_material_info field. <END_TASK> <USER_TASK:> Description: def create_helping_material_info(helping): """Create helping_material_info field."""
helping_info = None file_path = None if helping.get('info'): helping_info = helping['info'] else: helping_info = helping if helping_info.get('file_path'): file_path = helping_info.get('file_path') del helping_info['file_path'] return helping_info, file_path
<SYSTEM_TASK:> Returns data belonging to an authorization code from redis or <END_TASK> <USER_TASK:> Description: def fetch_by_code(self, code): """ Returns data belonging to an authorization code from redis or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`. """
code_data = self.read(code) if code_data is None: raise AuthCodeNotFound return AuthorizationCode(**code_data)
<SYSTEM_TASK:> Stores the data belonging to an authorization code token in redis. <END_TASK> <USER_TASK:> Description: def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in redis. See :class:`oauth2.store.AuthCodeStore`. """
self.write(authorization_code.code, {"client_id": authorization_code.client_id, "code": authorization_code.code, "expires_at": authorization_code.expires_at, "redirect_uri": authorization_code.redirect_uri, "scopes": authorization_code.scopes, "data": authorization_code.data, "user_id": authorization_code.user_id})
<SYSTEM_TASK:> Create data needed by an access token. <END_TASK> <USER_TASK:> Description: def create_access_token_data(self, grant_type): """ Create data needed by an access token. :param grant_type: :type grant_type: str :return: A ``dict`` containing he ``access_token`` and the ``token_type``. If the value of ``TokenGenerator.expires_in`` is larger than 0, a ``refresh_token`` will be generated too. :rtype: dict """
result = {"access_token": self.generate(), "token_type": "Bearer"} if self.expires_in.get(grant_type, 0) > 0: result["refresh_token"] = self.generate() result["expires_in"] = self.expires_in[grant_type] return result
<SYSTEM_TASK:> Display token information or redirect to login prompt if none is <END_TASK> <USER_TASK:> Description: def _display_token(self): """ Display token information or redirect to login prompt if none is available. """
if self.token is None: return "301 Moved", "", {"Location": "/login"} return ("200 OK", self.TOKEN_TEMPLATE.format( access_token=self.token["access_token"]), {"Content-Type": "text/html"})
<SYSTEM_TASK:> Retrieve a client by its identifier. <END_TASK> <USER_TASK:> Description: def fetch_by_client_id(self, client_id): """ Retrieve a client by its identifier. :param client_id: Identifier of a client app. :return: An instance of :class:`oauth2.Client`. :raises: ClientNotFoundError """
if client_id not in self.clients: raise ClientNotFoundError return self.clients[client_id]
<SYSTEM_TASK:> Stores an access token and additional data in memory. <END_TASK> <USER_TASK:> Description: def save_token(self, access_token): """ Stores an access token and additional data in memory. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. """
self.access_tokens[access_token.token] = access_token unique_token_key = self._unique_token_key(access_token.client_id, access_token.grant_type, access_token.user_id) self.unique_token_identifier[unique_token_key] = access_token.token if access_token.refresh_token is not None: self.refresh_tokens[access_token.refresh_token] = access_token return True
<SYSTEM_TASK:> Find an access token by its refresh token. <END_TASK> <USER_TASK:> Description: def fetch_by_refresh_token(self, refresh_token): """ Find an access token by its refresh token. :param refresh_token: The refresh token that was assigned to an ``AccessToken``. :return: The :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` """
if refresh_token not in self.refresh_tokens: raise AccessTokenNotFound return self.refresh_tokens[refresh_token]
<SYSTEM_TASK:> Adds a Grant that the provider should support. <END_TASK> <USER_TASK:> Description: def add_grant(self, grant): """ Adds a Grant that the provider should support. :param grant: An instance of a class that extends :class:`oauth2.grant.GrantHandlerFactory` :type grant: oauth2.grant.GrantHandlerFactory """
if hasattr(grant, "expires_in"): self.token_generator.expires_in[grant.grant_type] = grant.expires_in if hasattr(grant, "refresh_expires_in"): self.token_generator.refresh_expires_in = grant.refresh_expires_in self.grant_types.append(grant)
<SYSTEM_TASK:> Checks which Grant supports the current request and dispatches to it. <END_TASK> <USER_TASK:> Description: def dispatch(self, request, environ): """ Checks which Grant supports the current request and dispatches to it. :param request: The incoming request. :type request: :class:`oauth2.web.Request` :param environ: Dict containing variables of the environment. :type environ: dict :return: An instance of ``oauth2.web.Response``. """
try: grant_type = self._determine_grant_type(request) response = self.response_class() grant_type.read_validate_params(request) return grant_type.process(request, response, environ) except OAuthInvalidNoRedirectError: response = self.response_class() response.add_header("Content-Type", "application/json") response.status_code = 400 response.body = json.dumps({ "error": "invalid_redirect_uri", "error_description": "Invalid redirect URI" }) return response except OAuthInvalidError as err: response = self.response_class() return grant_type.handle_error(error=err, response=response) except UnsupportedGrantError: response = self.response_class() response.add_header("Content-Type", "application/json") response.status_code = 400 response.body = json.dumps({ "error": "unsupported_response_type", "error_description": "Grant not supported" }) return response except: app_log.error("Uncaught Exception", exc_info=True) response = self.response_class() return grant_type.handle_error( error=OAuthInvalidError(error="server_error", explanation="Internal server error"), response=response)
<SYSTEM_TASK:> Enable the use of unique access tokens on all grant types that support <END_TASK> <USER_TASK:> Description: def enable_unique_tokens(self): """ Enable the use of unique access tokens on all grant types that support this option. """
for grant_type in self.grant_types: if hasattr(grant_type, "unique_token"): grant_type.unique_token = True
<SYSTEM_TASK:> Returns the value of the HTTP header identified by `name`. <END_TASK> <USER_TASK:> Description: def header(self, name, default=None): """ Returns the value of the HTTP header identified by `name`. """
wsgi_header = "HTTP_{0}".format(name.upper()) try: return self.env_raw[wsgi_header] except KeyError: return default
<SYSTEM_TASK:> Extracts the credentials of a client using HTTP Basic Auth. <END_TASK> <USER_TASK:> Description: def http_basic_auth(request): """ Extracts the credentials of a client using HTTP Basic Auth. Expects the ``client_id`` to be the username and the ``client_secret`` to be the password part of the Authorization header. :param request: The incoming request :type request: oauth2.web.Request :return: A tuple in the format of (<CLIENT ID>, <CLIENT SECRET>)` :rtype: tuple """
auth_header = request.header("authorization") if auth_header is None: raise OAuthInvalidError(error="invalid_request", explanation="Authorization header is missing") auth_parts = auth_header.strip().encode("latin1").split(None) if auth_parts[0].strip().lower() != b'basic': raise OAuthInvalidError( error="invalid_request", explanation="Provider supports basic authentication only") client_id, client_secret = b64decode(auth_parts[1]).split(b':', 1) return client_id.decode("latin1"), client_secret.decode("latin1")
<SYSTEM_TASK:> Authenticates a client by its identifier. <END_TASK> <USER_TASK:> Description: def by_identifier(self, request): """ Authenticates a client by its identifier. :param request: The incoming request :type request: oauth2.web.Request :return: The identified client :rtype: oauth2.datatype.Client :raises: :class OAuthInvalidNoRedirectError: """
client_id = request.get_param("client_id") if client_id is None: raise OAuthInvalidNoRedirectError(error="missing_client_id") try: client = self.client_store.fetch_by_client_id(client_id) except ClientNotFoundError: raise OAuthInvalidNoRedirectError(error="unknown_client") redirect_uri = request.get_param("redirect_uri") if redirect_uri is not None: try: client.redirect_uri = redirect_uri except RedirectUriUnknown: raise OAuthInvalidNoRedirectError( error="invalid_redirect_uri") return client
<SYSTEM_TASK:> Returns the time until the token expires. <END_TASK> <USER_TASK:> Description: def expires_in(self): """ Returns the time until the token expires. :return: The remaining time until expiration in seconds or 0 if the token has expired. """
time_left = self.expires_at - int(time.time()) if time_left > 0: return time_left return 0
<SYSTEM_TASK:> Executes a query and returns the identifier of the modified row. <END_TASK> <USER_TASK:> Description: def execute(self, query, *params): """ Executes a query and returns the identifier of the modified row. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: A `long` identifying the last altered row. """
cursor = self.connection.cursor() try: cursor.execute(query, params) self.connection.commit() return cursor.lastrowid finally: cursor.close()
<SYSTEM_TASK:> Returns the first result of the given query. <END_TASK> <USER_TASK:> Description: def fetchone(self, query, *args): """ Returns the first result of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: The retrieved row with each field being one element in a `tuple`. """
cursor = self.connection.cursor() try: cursor.execute(query, args) return cursor.fetchone() finally: cursor.close()
<SYSTEM_TASK:> Returns all results of the given query. <END_TASK> <USER_TASK:> Description: def fetchall(self, query, *args): """ Returns all results of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: A `list` of `tuple`s with each field being one element in the `tuple`. """
cursor = self.connection.cursor() try: cursor.execute(query, args) return cursor.fetchall() finally: cursor.close()
<SYSTEM_TASK:> Retrieve an access token issued to a client and user for a specific <END_TASK> <USER_TASK:> Description: def fetch_existing_token_of_user(self, client_id, grant_type, user_id): """ Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The identifier of the user the access token has been issued to. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` if not access token could be retrieved. """
token_data = self.fetchone(self.fetch_existing_token_of_user_query, client_id, grant_type, user_id) if token_data is None: raise AccessTokenNotFound scopes = self._fetch_scopes(access_token_id=token_data[0]) data = self._fetch_data(access_token_id=token_data[0]) return self._row_to_token(data=data, scopes=scopes, row=token_data)
<SYSTEM_TASK:> Retrieves an auth code by its code. <END_TASK> <USER_TASK:> Description: def fetch_by_code(self, code): """ Retrieves an auth code by its code. :param code: The code of an auth code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`oauth2.error.AuthCodeNotFound` if no auth code could be retrieved. """
auth_code_data = self.fetchone(self.fetch_code_query, code) if auth_code_data is None: raise AuthCodeNotFound data = dict() data_result = self.fetchall(self.fetch_data_query, auth_code_data[0]) if data_result is not None: for dataset in data_result: data[dataset[0]] = dataset[1] scopes = [] scope_result = self.fetchall(self.fetch_scopes_query, auth_code_data[0]) if scope_result is not None: for scope_set in scope_result: scopes.append(scope_set[0]) return AuthorizationCode(client_id=auth_code_data[1], code=auth_code_data[2], expires_at=auth_code_data[3], redirect_uri=auth_code_data[4], scopes=scopes, data=data, user_id=auth_code_data[5])
<SYSTEM_TASK:> Creates a new entry of an auth code in the database. <END_TASK> <USER_TASK:> Description: def save_code(self, authorization_code): """ Creates a new entry of an auth code in the database. :param authorization_code: An instance of :class:`oauth2.datatype.AuthorizationCode`. :return: `True` if everything went fine. """
auth_code_id = self.execute(self.create_auth_code_query, authorization_code.client_id, authorization_code.code, authorization_code.expires_at, authorization_code.redirect_uri, authorization_code.user_id) for key, value in list(authorization_code.data.items()): self.execute(self.create_data_query, key, value, auth_code_id) for scope in authorization_code.scopes: self.execute(self.create_scope_query, scope, auth_code_id) return True
<SYSTEM_TASK:> Retrieves a client by its identifier. <END_TASK> <USER_TASK:> Description: def fetch_by_client_id(self, client_id): """ Retrieves a client by its identifier. :param client_id: The identifier of a client. :return: An instance of :class:`oauth2.datatype.Client`. :raises: :class:`oauth2.error.ClientError` if no client could be retrieved. """
grants = None redirect_uris = None response_types = None client_data = self.fetchone(self.fetch_client_query, client_id) if client_data is None: raise ClientNotFoundError grant_data = self.fetchall(self.fetch_grants_query, client_data[0]) if grant_data: grants = [] for grant in grant_data: grants.append(grant[0]) redirect_uris_data = self.fetchall(self.fetch_redirect_uris_query, client_data[0]) if redirect_uris_data: redirect_uris = [] for redirect_uri in redirect_uris_data: redirect_uris.append(redirect_uri[0]) response_types_data = self.fetchall(self.fetch_response_types_query, client_data[0]) if response_types_data: response_types = [] for response_type in response_types_data: response_types.append(response_type[0]) return Client(identifier=client_data[1], secret=client_data[2], authorized_grants=grants, authorized_response_types=response_types, redirect_uris=redirect_uris)
<SYSTEM_TASK:> Returns data belonging to an authorization code from memcache or <END_TASK> <USER_TASK:> Description: def fetch_by_code(self, code): """ Returns data belonging to an authorization code from memcache or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`. """
code_data = self.mc.get(self._generate_cache_key(code)) if code_data is None: raise AuthCodeNotFound return AuthorizationCode(**code_data)
<SYSTEM_TASK:> Stores the data belonging to an authorization code token in memcache. <END_TASK> <USER_TASK:> Description: def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in memcache. See :class:`oauth2.store.AuthCodeStore`. """
key = self._generate_cache_key(authorization_code.code) self.mc.set(key, {"client_id": authorization_code.client_id, "code": authorization_code.code, "expires_at": authorization_code.expires_at, "redirect_uri": authorization_code.redirect_uri, "scopes": authorization_code.scopes, "data": authorization_code.data, "user_id": authorization_code.user_id})
<SYSTEM_TASK:> Stores the access token and additional data in memcache. <END_TASK> <USER_TASK:> Description: def save_token(self, access_token): """ Stores the access token and additional data in memcache. See :class:`oauth2.store.AccessTokenStore`. """
key = self._generate_cache_key(access_token.token) self.mc.set(key, access_token.__dict__) unique_token_key = self._unique_token_key(access_token.client_id, access_token.grant_type, access_token.user_id) self.mc.set(self._generate_cache_key(unique_token_key), access_token.__dict__) if access_token.refresh_token is not None: rft_key = self._generate_cache_key(access_token.refresh_token) self.mc.set(rft_key, access_token.__dict__)
<SYSTEM_TASK:> Creates a string out of a list of scopes. <END_TASK> <USER_TASK:> Description: def encode_scopes(scopes, use_quote=False): """ Creates a string out of a list of scopes. :param scopes: A list of scopes :param use_quote: Boolean flag indicating whether the string should be quoted :return: Scopes as a string """
scopes_as_string = Scope.separator.join(scopes) if use_quote: return quote(scopes_as_string) return scopes_as_string
<SYSTEM_TASK:> Formats an error as a response containing a JSON body. <END_TASK> <USER_TASK:> Description: def json_error_response(error, response, status_code=400): """ Formats an error as a response containing a JSON body. """
msg = {"error": error.error, "error_description": error.explanation} response.status_code = status_code response.add_header("Content-Type", "application/json") response.body = json.dumps(msg) return response
<SYSTEM_TASK:> Formats the response of a successful token request as JSON. <END_TASK> <USER_TASK:> Description: def json_success_response(data, response): """ Formats the response of a successful token request as JSON. Also adds default headers and status code. """
response.body = json.dumps(data) response.status_code = 200 response.add_header("Content-Type", "application/json") response.add_header("Cache-Control", "no-store") response.add_header("Pragma", "no-cache")
<SYSTEM_TASK:> Compares the scopes read from request with previously issued scopes. <END_TASK> <USER_TASK:> Description: def compare(self, previous_scopes): """ Compares the scopes read from request with previously issued scopes. :param previous_scopes: A list of scopes. :return: ``True`` """
for scope in self.scopes: if scope not in previous_scopes: raise OAuthInvalidError( error="invalid_scope", explanation="Invalid scope parameter in request") return True
<SYSTEM_TASK:> Parses scope value in given request. <END_TASK> <USER_TASK:> Description: def parse(self, request, source): """ Parses scope value in given request. Expects the value of the "scope" parameter in request to be a string where each requested scope is separated by a white space:: # One scope requested "profile_read" # Multiple scopes "profile_read profile_write" :param request: An instance of :class:`oauth2.web.Request`. :param source: Where to read the scope from. Pass "body" in case of a application/x-www-form-urlencoded body and "query" in case the scope is supplied as a query parameter in the URL of a request. """
if source == "body": req_scope = request.post_param("scope") elif source == "query": req_scope = request.get_param("scope") else: raise ValueError("Unknown scope source '" + source + "'") if req_scope is None: if self.default is not None: self.scopes = [self.default] self.send_back = True return elif len(self.available_scopes) != 0: raise OAuthInvalidError( error="invalid_scope", explanation="Missing scope parameter in request") else: return req_scopes = req_scope.split(self.separator) self.scopes = [scope for scope in req_scopes if scope in self.available_scopes] if len(self.scopes) == 0 and self.default is not None: self.scopes = [self.default] self.send_back = True
<SYSTEM_TASK:> Reads and validates data in an incoming request as required by <END_TASK> <USER_TASK:> Description: def read_validate_params(self, request): """ Reads and validates data in an incoming request as required by the Authorization Request of the Authorization Code Grant and the Implicit Grant. """
self.client = self.client_authenticator.by_identifier(request) response_type = request.get_param("response_type") if self.client.response_type_supported(response_type) is False: raise OAuthInvalidError(error="unauthorized_client") self.state = request.get_param("state") self.scope_handler.parse(request, "query") return True
<SYSTEM_TASK:> Controls all steps to authorize a request by a user. <END_TASK> <USER_TASK:> Description: def authorize(self, request, response, environ, scopes): """ Controls all steps to authorize a request by a user. :param request: The incoming :class:`oauth2.web.Request` :param response: The :class:`oauth2.web.Response` that will be returned eventually :param environ: The environment variables of this request :param scopes: The scopes requested by an application :return: A tuple containing (`dict`, user_id) or the response. """
if self.site_adapter.user_has_denied_access(request) is True: raise OAuthInvalidError(error="access_denied", explanation="Authorization denied by user") try: result = self.site_adapter.authenticate(request, environ, scopes, self.client) return self.sanitize_return_value(result) except UserNotAuthenticated: return self.site_adapter.render_auth_page(request, response, environ, scopes, self.client)
<SYSTEM_TASK:> Generates a new authorization token. <END_TASK> <USER_TASK:> Description: def process(self, request, response, environ): """ Generates a new authorization token. A form to authorize the access of the application can be displayed with the help of `oauth2.web.SiteAdapter`. """
data = self.authorize(request, response, environ, self.scope_handler.scopes) if isinstance(data, Response): return data code = self.token_generator.generate() expires = int(time.time()) + self.token_expiration auth_code = AuthorizationCode(client_id=self.client.identifier, code=code, expires_at=expires, redirect_uri=self.client.redirect_uri, scopes=self.scope_handler.scopes, data=data[0], user_id=data[1]) self.auth_code_store.save_code(auth_code) response.add_header("Location", self._generate_location(code)) response.body = "" response.status_code = 302 return response
<SYSTEM_TASK:> Redirects the client in case an error in the auth process occurred. <END_TASK> <USER_TASK:> Description: def handle_error(self, error, response): """ Redirects the client in case an error in the auth process occurred. """
query_params = {"error": error.error} query = urlencode(query_params) location = "%s?%s" % (self.client.redirect_uri, query) response.status_code = 302 response.body = "" response.add_header("Location", location) return response
<SYSTEM_TASK:> Generates a new access token and returns it. <END_TASK> <USER_TASK:> Description: def process(self, request, response, environ): """ Generates a new access token and returns it. Returns the access token and the type of the token as JSON. Calls `oauth2.store.AccessTokenStore` to persist the token. """
token_data = self.create_token( client_id=self.client.identifier, data=self.data, grant_type=AuthorizationCodeGrant.grant_type, scopes=self.scopes, user_id=self.user_id) self.auth_code_store.delete_code(self.code) if self.scopes: token_data["scope"] = encode_scopes(self.scopes) json_success_response(data=token_data, response=response) return response
<SYSTEM_TASK:> Takes the incoming request, asks the concrete SiteAdapter to validate <END_TASK> <USER_TASK:> Description: def process(self, request, response, environ): """ Takes the incoming request, asks the concrete SiteAdapter to validate it and issues a new access token that is returned to the client on successful validation. """
try: data = self.site_adapter.authenticate(request, environ, self.scope_handler.scopes, self.client) data = AuthorizeMixin.sanitize_return_value(data) except UserNotAuthenticated: raise OAuthInvalidError(error="invalid_client", explanation=self.OWNER_NOT_AUTHENTICATED) if isinstance(data, Response): return data token_data = self.create_token( client_id=self.client.identifier, data=data[0], grant_type=ResourceOwnerGrant.grant_type, scopes=self.scope_handler.scopes, user_id=data[1]) if self.scope_handler.send_back: token_data["scope"] = encode_scopes(self.scope_handler.scopes) json_success_response(data=token_data, response=response) return response