repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
dnephin/PyStaticConfiguration
staticconf/config.py
get_namespace
python
def get_namespace(name): if name not in configuration_namespaces: configuration_namespaces[name] = ConfigNamespace(name) return configuration_namespaces[name]
Return a :class:`ConfigNamespace` by name, creating the namespace if it does not exist.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L188-L194
null
""" Store configuration in :class:`ConfigNamespace` objects and provide tools for reloading, and displaying help messages. Configuration Reloading ----------------------- Configuration reloading is supported using a :class:`ConfigFacade`, which composes a :class:`ConfigurationWatcher` and a :class:`ReloadCallbackCha...
dnephin/PyStaticConfiguration
staticconf/config.py
reload
python
def reload(name=DEFAULT, all_names=False): for namespace in get_namespaces_from_names(name, all_names): for value_proxy in namespace.get_value_proxies(): value_proxy.reset()
Reload one or all :class:`ConfigNamespace`. Reload clears the cache of :mod:`staticconf.schema` and :mod:`staticconf.getters`, allowing them to pickup the latest values in the namespace. Defaults to reloading just the DEFAULT namespace. :param name: the name of the :class:`ConfigNamespace` to reload ...
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L197-L209
[ "def get_namespaces_from_names(name, all_names):\n \"\"\"Return a generator which yields namespace objects.\"\"\"\n names = configuration_namespaces.keys() if all_names else [name]\n for name in names:\n yield get_namespace(name)\n" ]
""" Store configuration in :class:`ConfigNamespace` objects and provide tools for reloading, and displaying help messages. Configuration Reloading ----------------------- Configuration reloading is supported using a :class:`ConfigFacade`, which composes a :class:`ConfigurationWatcher` and a :class:`ReloadCallbackCha...
dnephin/PyStaticConfiguration
staticconf/config.py
validate
python
def validate(name=DEFAULT, all_names=False): for namespace in get_namespaces_from_names(name, all_names): all(value_proxy.get_value() for value_proxy in namespace.get_value_proxies())
Validate all registered keys after loading configuration. Missing values or values which do not pass validation raise :class:`staticconf.errors.ConfigurationError`. By default only validates the `DEFAULT` namespace. :param name: the namespace to validate :type name: string :param all_names: i...
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L212-L225
[ "def get_namespaces_from_names(name, all_names):\n \"\"\"Return a generator which yields namespace objects.\"\"\"\n names = configuration_namespaces.keys() if all_names else [name]\n for name in names:\n yield get_namespace(name)\n" ]
""" Store configuration in :class:`ConfigNamespace` objects and provide tools for reloading, and displaying help messages. Configuration Reloading ----------------------- Configuration reloading is supported using a :class:`ConfigFacade`, which composes a :class:`ConfigurationWatcher` and a :class:`ReloadCallbackCha...
dnephin/PyStaticConfiguration
staticconf/config.py
has_duplicate_keys
python
def has_duplicate_keys(config_data, base_conf, raise_error): duplicate_keys = set(base_conf) & set(config_data) if not duplicate_keys: return msg = "Duplicate keys in config: %s" % duplicate_keys if raise_error: raise errors.ConfigurationError(msg) log.info(msg) return True
Compare two dictionaries for duplicate keys. if raise_error is True then raise on exception, otherwise log return True.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L276-L286
null
""" Store configuration in :class:`ConfigNamespace` objects and provide tools for reloading, and displaying help messages. Configuration Reloading ----------------------- Configuration reloading is supported using a :class:`ConfigFacade`, which composes a :class:`ConfigurationWatcher` and a :class:`ReloadCallbackCha...
dnephin/PyStaticConfiguration
staticconf/config.py
build_compare_func
python
def build_compare_func(err_logger=None): def compare_func(filename): try: return os.path.getmtime(filename) except OSError: if err_logger is not None: err_logger(filename) return -1 return compare_func
Returns a compare_func that can be passed to MTimeComparator. The returned compare_func first tries os.path.getmtime(filename), then calls err_logger(filename) if that fails. If err_logger is None, then it does nothing. err_logger is always called within the context of an OSError raised by os.path.getm...
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L436-L451
null
""" Store configuration in :class:`ConfigNamespace` objects and provide tools for reloading, and displaying help messages. Configuration Reloading ----------------------- Configuration reloading is supported using a :class:`ConfigFacade`, which composes a :class:`ConfigurationWatcher` and a :class:`ReloadCallbackCha...
dnephin/PyStaticConfiguration
staticconf/config.py
ConfigNamespace.get_config_dict
python
def get_config_dict(self): config_dict = {} for dotted_key, value in self.get_config_values().items(): subkeys = dotted_key.split('.') d = config_dict for key in subkeys: d = d.setdefault(key, value if key == subkeys[-1] else {}) return config_...
Reconstruct the nested structure of this object's configuration and return it as a dict.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L114-L124
[ "def get_config_values(self):\n \"\"\"Return all configuration stored in this object as a dict.\n \"\"\"\n return self.configuration_values\n" ]
class ConfigNamespace(object): """A container for related configuration values. Values are stored using flattened keys which map to values. Values are added to this container using :mod:`staticconf.loader`. When a :class:`ConfigNamespace` is created, it persists for the entire life of the process. ...
dnephin/PyStaticConfiguration
staticconf/config.py
ConfigHelp.view_help
python
def view_help(self): def format_desc(desc): return "%s (Type: %s, Default: %s)\n%s" % ( desc.name, desc.validator.__name__.replace('validate_', ''), desc.default, desc.help or '') def format_namespace(key, desc_...
Return a help message describing all the statically configured keys.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L238-L259
null
class ConfigHelp(object): """Register and display help messages about config keys.""" def __init__(self): self.descriptions = {} def add(self, name, validator, default, namespace, help): desc = KeyDescription(name, validator, default, help) self.descriptions.setdefault(namespace, [...
dnephin/PyStaticConfiguration
staticconf/config.py
ConfigurationWatcher.reload_if_changed
python
def reload_if_changed(self, force=False): if (force or self.should_check) and self.file_modified(): return self.reload()
If the file(s) being watched by this object have changed, their configuration will be loaded again using `config_loader`. Otherwise this is a noop. :param force: If True ignore the `min_interval` and proceed to file modified comparisons. To force a reload use :func:`rel...
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L369-L379
[ "def file_modified(self):\n self.last_check = time.time()\n return any(comp.has_changed() for comp in self.comparators)\n" ]
class ConfigurationWatcher(object): """Watches a file for modification and reloads the configuration when it's modified. Accepts a min_interval to throttle checks. The default :func:`reload()` operation is to reload all namespaces. To only reload a specific namespace use a :class:`ReloadCallbackChain`...
dnephin/PyStaticConfiguration
staticconf/config.py
ConfigFacade.load
python
def load( cls, filename, namespace, loader_func, min_interval=0, comparators=None, ): watcher = ConfigurationWatcher( build_loader_callable(loader_func, filename, namespace=namespace), filename, min_i...
Create a new :class:`ConfigurationWatcher` and load the initial configuration by calling `loader_func`. :param filename: a filename or list of filenames to monitor for changes :param namespace: the name of a namespace to use when loading configuration. All config data ...
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L585-L620
[ "def build_loader_callable(load_func, filename, namespace):\n def load_configuration():\n get_namespace(namespace).clear()\n return load_func(filename, namespace=namespace)\n return load_configuration\n", "def load_config(self):\n return self.config_loader()\n" ]
class ConfigFacade(object): """A facade around a :class:`ConfigurationWatcher` and a :class:`ReloadCallbackChain`. See :func:`ConfigFacade.load`. When a :class:`ConfigFacade` is loaded it will clear the namespace of all configuration and load the file into the namespace. If this is not the behaviou...
dnephin/PyStaticConfiguration
staticconf/validation.py
_validate_iterable
python
def _validate_iterable(iterable_type, value): if isinstance(value, six.string_types): msg = "Invalid iterable of type(%s): %s" raise ValidationError(msg % (type(value), value)) try: return iterable_type(value) except TypeError: raise ValidationError("Invalid iterable: %s" % ...
Convert the iterable to iterable_type, or raise a Configuration exception.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/validation.py#L90-L101
null
""" Validate a configuration value by converting it to a specific type. These functions are used by :mod:`staticconf.readers` and :mod:`staticconf.schema` to coerce config values to a type. """ import datetime import logging import re import time import six from staticconf.errors import ValidationError def validat...
dnephin/PyStaticConfiguration
staticconf/validation.py
build_list_type_validator
python
def build_list_type_validator(item_validator): def validate_list_of_type(value): return [item_validator(item) for item in validate_list(value)] return validate_list_of_type
Return a function which validates that the value is a list of items which are validated using item_validator.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/validation.py#L123-L129
null
""" Validate a configuration value by converting it to a specific type. These functions are used by :mod:`staticconf.readers` and :mod:`staticconf.schema` to coerce config values to a type. """ import datetime import logging import re import time import six from staticconf.errors import ValidationError def validat...
dnephin/PyStaticConfiguration
staticconf/validation.py
build_map_type_validator
python
def build_map_type_validator(item_validator): def validate_mapping(value): return dict(item_validator(item) for item in validate_list(value)) return validate_mapping
Return a function which validates that the value is a mapping of items. The function should return pairs of items that will be passed to the `dict` constructor.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/validation.py#L132-L139
null
""" Validate a configuration value by converting it to a specific type. These functions are used by :mod:`staticconf.readers` and :mod:`staticconf.schema` to coerce config values to a type. """ import datetime import logging import re import time import six from staticconf.errors import ValidationError def validat...
dnephin/PyStaticConfiguration
staticconf/getters.py
register_value_proxy
python
def register_value_proxy(namespace, value_proxy, help_text): namespace.register_proxy(value_proxy) config.config_help.add( value_proxy.config_key, value_proxy.validator, value_proxy.default, namespace.get_name(), help_text)
Register a value proxy with the namespace, and add the help_text.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/getters.py#L68-L73
[ "def add(self, name, validator, default, namespace, help):\n desc = KeyDescription(name, validator, default, help)\n self.descriptions.setdefault(namespace, []).append(desc)\n" ]
""" Functions used to retrieve proxies around values in a :class:`staticconf.config.ConfigNamespace`. All of the getter methods return a :class:`ValueProxy`. These proxies are wrappers around a configuration value. They don't access the configuration until some attribute of the object is accessed. .. warning:: T...
dnephin/PyStaticConfiguration
staticconf/getters.py
build_getter
python
def build_getter(validator, getter_namespace=None): def proxy_register(key_name, default=UndefToken, help=None, namespace=None): name = namespace or getter_namespace or config.DEFAULT namespace = config.get_namespace(name) return proxy_factory.build(validator, namespace, key_name, d...
Create a getter function for retrieving values from the config cache. Getters will default to the DEFAULT namespace.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/getters.py#L101-L110
null
""" Functions used to retrieve proxies around values in a :class:`staticconf.config.ConfigNamespace`. All of the getter methods return a :class:`ValueProxy`. These proxies are wrappers around a configuration value. They don't access the configuration until some attribute of the object is accessed. .. warning:: T...
dnephin/PyStaticConfiguration
staticconf/getters.py
ProxyFactory.build
python
def build(self, validator, namespace, config_key, default, help): proxy_attrs = validator, namespace, config_key, default proxy_key = repr(proxy_attrs) if proxy_key in self.proxies: return self.proxies[proxy_key] value_proxy = proxy.ValueProxy(*proxy_attrs) register_...
Build or retrieve a ValueProxy from the attributes. Proxies are keyed using a repr because default values can be mutable types.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/getters.py#L84-L95
[ "def register_value_proxy(namespace, value_proxy, help_text):\n \"\"\"Register a value proxy with the namespace, and add the help_text.\"\"\"\n namespace.register_proxy(value_proxy)\n config.config_help.add(\n value_proxy.config_key, value_proxy.validator, value_proxy.default,\n namespace.get...
class ProxyFactory(object): """Create ProxyValue objects so that there is never a duplicate proxy for any (namespace, validator, config_key, default) group. """ def __init__(self): self.proxies = {}
jlevy/strif
strif.py
new_timestamped_uid
python
def new_timestamped_uid(bits=32): return "%s-%s" % (re.sub('[^\w.]', '', datetime.now().isoformat()).replace(".", "Z-"), new_uid(bits))
A unique id that begins with an ISO timestamp followed by fractions of seconds and bits of randomness. The advantage of this is it sorts nicely by time, while still being unique. Example: 20150912T084555Z-378465-43vtwbx
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L76-L82
[ "def new_uid(bits=64):\n \"\"\"\n A random alphanumeric value with at least the specified bits of randomness. We use base 36,\n i.e. not case sensitive. Note this makes it suitable for filenames even on case-insensitive disks.\n \"\"\"\n return \"\".join(_RANDOM.sample(\"0123456789abcdefghijklmnopqrstuvwxyz\",...
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
abbreviate_str
python
def abbreviate_str(string, max_len=80, indicator="..."): if not string or not max_len or len(string) <= max_len: return string elif max_len <= len(indicator): return string[0:max_len] else: return string[0:max_len - len(indicator)] + indicator
Abbreviate a string, adding an indicator like an ellipsis if required.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L85-L94
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
abbreviate_list
python
def abbreviate_list(items, max_items=10, item_max_len=40, joiner=", ", indicator="..."): if not items: return items else: shortened = [abbreviate_str("%s" % item, max_len=item_max_len) for item in items[0:max_items]] if len(items) > max_items: shortened.append(indicator) return joiner.join(sho...
Abbreviate a list, truncating each element and adding an indicator at the end if the whole list was truncated. Set item_max_len to None or 0 not to truncate items.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L97-L108
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
expand_variables
python
def expand_variables(template_str, value_map, transformer=None): if template_str is None: return None else: if transformer is None: transformer = lambda v: v try: # Don't bother iterating items for Python 2+3 compatibility. transformed_value_map = {k: transformer(value_map[k]) for k in...
Expand a template string like "blah blah $FOO blah" using given value mapping.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L114-L128
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
shell_expand_to_popen
python
def shell_expand_to_popen(template, values): return [expand_variables(item, values) for item in shlex.split(template)]
Expand a template like "cp $SOURCE $TARGET/blah" into a list of popen arguments.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L139-L143
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
move_to_backup
python
def move_to_backup(path, backup_suffix=BACKUP_SUFFIX): if backup_suffix and os.path.exists(path): backup_path = path + backup_suffix # Some messy corner cases need to be handled for existing backups. # TODO: Note if this is a directory, and we do this twice at once, there is a potential race # that co...
Move the given file or directory to the same name, with a backup suffix. If backup_suffix not supplied, move it to the extension ".bak". NB: If backup_suffix is supplied and is None, don't do anything.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L149-L164
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
make_all_dirs
python
def make_all_dirs(path, mode=0o777): # Avoid races inherent to doing this in two steps (check then create). # Python 3 has exist_ok but the approach below works for Python 2+3. # https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python try: os.makedirs(path, mode=mode) except OSError as ...
Ensure local dir, with all its parent dirs, are created. Unlike os.makedirs(), will not fail if the path already exists.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L167-L182
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
make_parent_dirs
python
def make_parent_dirs(path, mode=0o777): parent = os.path.dirname(path) if parent: make_all_dirs(parent, mode) return path
Ensure parent directories of a file are created as needed.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L185-L192
[ "def make_all_dirs(path, mode=0o777):\n \"\"\"\n Ensure local dir, with all its parent dirs, are created.\n Unlike os.makedirs(), will not fail if the path already exists.\n \"\"\"\n # Avoid races inherent to doing this in two steps (check then create).\n # Python 3 has exist_ok but the approach below works f...
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
atomic_output_file
python
def atomic_output_file(dest_path, make_parents=False, backup_suffix=None, suffix=".partial.%s"): if dest_path == os.devnull: # Handle the (probably rare) case of writing to /dev/null. yield dest_path else: tmp_path = ("%s" + suffix) % (dest_path, new_uid()) if make_parents: make_parent_dirs(tm...
A context manager for convenience in writing a file or directory in an atomic way. Set up a temporary name, then rename it after the operation is done, optionally making a backup of the previous file or directory, if present.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L196-L221
[ "def new_uid(bits=64):\n \"\"\"\n A random alphanumeric value with at least the specified bits of randomness. We use base 36,\n i.e. not case sensitive. Note this makes it suitable for filenames even on case-insensitive disks.\n \"\"\"\n return \"\".join(_RANDOM.sample(\"0123456789abcdefghijklmnopqrstuvwxyz\",...
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
temp_output_file
python
def temp_output_file(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False): return _temp_output(False, prefix=prefix, suffix=suffix, dir=dir, make_parents=make_parents, always_clean=always_clean)
A context manager for convenience in creating a temporary file, which is deleted when exiting the context. Usage: with temp_output_file() as (fd, path): ...
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L224-L234
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
temp_output_dir
python
def temp_output_dir(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False): return _temp_output(True, prefix=prefix, suffix=suffix, dir=dir, make_parents=make_parents, always_clean=always_clean)
A context manager for convenience in creating a temporary directory, which is deleted when exiting the context. Usage: with temp_output_dir() as dirname: ...
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L237-L247
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
read_string_from_file
python
def read_string_from_file(path, encoding="utf8"): with codecs.open(path, "rb", encoding=encoding) as f: value = f.read() return value
Read entire contents of file into a string.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L278-L284
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
write_string_to_file
python
def write_string_to_file(path, string, make_parents=False, backup_suffix=BACKUP_SUFFIX, encoding="utf8"): with atomic_output_file(path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path: with codecs.open(tmp_path, "wb", encoding=encoding) as f: f.write(string)
Write entire file with given string contents, atomically. Keeps backup by default.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L287-L293
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
set_file_mtime
python
def set_file_mtime(path, mtime, atime=None): if not atime: atime = mtime f = open(path, 'a') try: os.utime(path, (atime, mtime)) finally: f.close()
Set access and modification times on a file.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L296-L304
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
copyfile_atomic
python
def copyfile_atomic(source_path, dest_path, make_parents=False, backup_suffix=None): with atomic_output_file(dest_path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path: shutil.copyfile(source_path, tmp_path) set_file_mtime(tmp_path, os.path.getmtime(source_path))
Copy file on local filesystem in an atomic way, so partial copies never exist. Preserves timestamps.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L307-L313
[ "def set_file_mtime(path, mtime, atime=None):\n \"\"\"Set access and modification times on a file.\"\"\"\n if not atime:\n atime = mtime\n f = open(path, 'a')\n try:\n os.utime(path, (atime, mtime))\n finally:\n f.close()\n" ]
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
copytree_atomic
python
def copytree_atomic(source_path, dest_path, make_parents=False, backup_suffix=None, symlinks=False): if os.path.isdir(source_path): with atomic_output_file(dest_path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path: shutil.copytree(source_path, tmp_path, symlinks=symlinks) else: co...
Copy a file or directory recursively, and atomically, reanaming file or top-level dir when done. Unlike shutil.copytree, this will not fail on a file.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L316-L325
[ "def copyfile_atomic(source_path, dest_path, make_parents=False, backup_suffix=None):\n \"\"\"\n Copy file on local filesystem in an atomic way, so partial copies never exist. Preserves timestamps.\n \"\"\"\n with atomic_output_file(dest_path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path:...
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
movefile
python
def movefile(source_path, dest_path, make_parents=False, backup_suffix=None): if make_parents: make_parent_dirs(dest_path) move_to_backup(dest_path, backup_suffix=backup_suffix) shutil.move(source_path, dest_path)
Move file. With a few extra options.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L328-L335
[ "def move_to_backup(path, backup_suffix=BACKUP_SUFFIX):\n \"\"\"\n Move the given file or directory to the same name, with a backup suffix.\n If backup_suffix not supplied, move it to the extension \".bak\".\n NB: If backup_suffix is supplied and is None, don't do anything.\n \"\"\"\n if backup_suffix and os....
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
rmtree_or_file
python
def rmtree_or_file(path, ignore_errors=False, onerror=None): # TODO: Could add an rsync-based delete, as in # https://github.com/vivlabs/instaclone/blob/master/instaclone/instaclone.py#L127-L143 if ignore_errors and not os.path.exists(path): return if os.path.isdir(path) and not os.path.islink(path): sh...
rmtree fails on files or symlinks. This removes the target, whatever it is.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L338-L349
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
chmod_native
python
def chmod_native(path, mode_expression, recursive=False): popenargs = ["chmod"] if recursive: popenargs.append("-R") popenargs.append(mode_expression) popenargs.append(path) subprocess.check_call(popenargs)
This is ugly and will only work on POSIX, but the built-in Python os.chmod support is very minimal, and neither supports fast recursive chmod nor "+X" type expressions, both of which are slow for large trees. So just shell out.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L352-L363
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
jlevy/strif
strif.py
file_sha1
python
def file_sha1(path): sha1 = hashlib.sha1() with open(path, "rb") as f: while True: block = f.read(2 ** 10) if not block: break sha1.update(block) return sha1.hexdigest()
Compute SHA1 hash of a file.
train
https://github.com/jlevy/strif/blob/5a066f7a075ca822da59d665cfe88f0afd39a793/strif.py#L366-L377
null
""" Strif is a tiny (<1000 loc) library of string- and file-related utilities for Python 2.7 and 3. More information: https://github.com/jlevy/strif """ from string import Template import re import os import errno import random import shutil import shlex import pipes import tempfile import hashlib import codecs from ...
edx/completion
completion/api/permissions.py
IsUserInUrl.has_permission
python
def has_permission(self, request, view): url_username = request.parser_context.get('kwargs', {}).get('username', '') if request.user.username.lower() != url_username.lower(): if request.user.is_staff: return False # staff gets 403 raise Http404() return T...
Returns true if the current request is by the user themselves. Note: a 404 is returned for non-staff instead of a 403. This is to prevent users from being able to detect the existence of accounts.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/api/permissions.py#L35-L47
null
class IsUserInUrl(BasePermission): """ Permission that checks to see if the request user matches the user in the URL. """
edx/completion
completion/fields.py
BigAutoField.db_type
python
def db_type(self, connection): conn_module = type(connection).__module__ if "mysql" in conn_module: return "bigint AUTO_INCREMENT" elif "postgres" in conn_module: return "bigserial" return super(BigAutoField, self).db_type(connection)
The type of the field to insert into the database.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/fields.py#L19-L28
null
class BigAutoField(models.AutoField): """ DO NOT USE - EXISTS FOR BACKWARDS COMPATIBILITY ONLY. AutoField that uses BigIntegers. This exists in Django as of version 1.10. """ def rel_db_type(self, connection): # pylint: disable=unused-argument """ The type to be used by rela...
edx/completion
completion/models.py
BlockCompletionManager.submit_completion
python
def submit_completion(self, user, course_key, block_key, completion): # Raise ValueError to match normal django semantics for wrong type of field. if not isinstance(course_key, CourseKey): raise ValueError( "course_key must be an instance of `opaque_keys.edx.keys.CourseKey`....
Update the completion value for the specified record. Parameters: * user (django.contrib.auth.models.User): The user for whom the completion is being submitted. * course_key (opaque_keys.edx.keys.CourseKey): The course in which the submitted block is found. ...
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/models.py#L46-L132
[ "def waffle():\n \"\"\"\n Returns the namespaced, cached, audited Waffle class for completion.\n \"\"\"\n return WaffleSwitchNamespace(name=WAFFLE_NAMESPACE, log_prefix='completion: ')\n" ]
class BlockCompletionManager(models.Manager): """ Custom manager for BlockCompletion model. Adds submit_completion and submit_batch_completion methods. """ @transaction.atomic() def submit_batch_completion(self, user, course_key, blocks): """ Performs a batch insertion of comp...
edx/completion
completion/models.py
BlockCompletionManager.submit_batch_completion
python
def submit_batch_completion(self, user, course_key, blocks): block_completions = {} for block, completion in blocks: (block_completion, is_new) = self.submit_completion(user, course_key, block, completion) block_completions[block_completion] = is_new return block_completi...
Performs a batch insertion of completion objects. Parameters: * user (django.contrib.auth.models.User): The user for whom the completions are being submitted. * course_key (opaque_keys.edx.keys.CourseKey): The course in which the submitted blocks are found. ...
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/models.py#L135-L169
[ "def submit_completion(self, user, course_key, block_key, completion):\n \"\"\"\n Update the completion value for the specified record.\n\n Parameters:\n * user (django.contrib.auth.models.User): The user for whom the\n completion is being submitted.\n * course_key (opaque_keys.edx.k...
class BlockCompletionManager(models.Manager): """ Custom manager for BlockCompletion model. Adds submit_completion and submit_batch_completion methods. """ def submit_completion(self, user, course_key, block_key, completion): """ Update the completion value for the specified record...
edx/completion
completion/models.py
BlockCompletion.full_block_key
python
def full_block_key(self): if self.block_key.run is None: # pylint: disable=unexpected-keyword-arg, no-value-for-parameter return self.block_key.replace(course_key=self.course_key) return self.block_key
Returns the "correct" usage key value with the run filled in.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/models.py#L202-L209
null
class BlockCompletion(TimeStampedModel, models.Model): """ Track completion of completable blocks. A completion is unique for each (user, course_key, block_key). The block_type field is included separately from the block_key to facilitate distinct aggregations of the completion of particular types...
edx/completion
completion/models.py
BlockCompletion.get_course_completions
python
def get_course_completions(cls, user, course_key): user_course_completions = cls.user_course_completion_queryset(user, course_key) return cls.completion_by_block_key(user_course_completions)
Returns a dictionary mapping BlockKeys to completion values for all BlockCompletion records for the given user and course_key. Return value: dict[BlockKey] = float
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/models.py#L212-L221
null
class BlockCompletion(TimeStampedModel, models.Model): """ Track completion of completable blocks. A completion is unique for each (user, course_key, block_key). The block_type field is included separately from the block_key to facilitate distinct aggregations of the completion of particular types...
edx/completion
completion/models.py
BlockCompletion.user_course_completion_queryset
python
def user_course_completion_queryset(cls, user, course_key): return cls.objects.filter(user=user, course_key=course_key)
Returns a Queryset of completions for a given user and course_key.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/models.py#L224-L228
null
class BlockCompletion(TimeStampedModel, models.Model): """ Track completion of completable blocks. A completion is unique for each (user, course_key, block_key). The block_type field is included separately from the block_key to facilitate distinct aggregations of the completion of particular types...
edx/completion
completion/handlers.py
scorable_block_completion
python
def scorable_block_completion(sender, **kwargs): # pylint: disable=unused-argument if not waffle.waffle().is_enabled(waffle.ENABLE_COMPLETION_TRACKING): return course_key = CourseKey.from_string(kwargs['course_id']) block_key = UsageKey.from_string(kwargs['usage_id']) block_cls = XBlock.load_cl...
When a problem is scored, submit a new BlockCompletion for that block.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/handlers.py#L15-L39
[ "def waffle():\n \"\"\"\n Returns the namespaced, cached, audited Waffle class for completion.\n \"\"\"\n return WaffleSwitchNamespace(name=WAFFLE_NAMESPACE, log_prefix='completion: ')\n" ]
""" Signal handlers to trigger completion updates. """ from __future__ import absolute_import, division, print_function, unicode_literals from django.contrib.auth.models import User from opaque_keys.edx.keys import CourseKey, UsageKey from xblock.completable import XBlockCompletionMode from xblock.core import XBlock ...
edx/completion
completion/api/v1/views.py
CompletionBatchView._validate_and_parse
python
def _validate_and_parse(self, batch_object): if not waffle.waffle().is_enabled(waffle.ENABLE_COMPLETION_TRACKING): raise ValidationError( _("BlockCompletion.objects.submit_batch_completion should not be called when the feature is disabled.") ) for key in self.REQ...
Performs validation on the batch object to make sure it is in the proper format. Parameters: * batch_object: The data provided to a POST. The expected format is the following: { "username": "username", "course_key": "course-key", "blocks":...
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/api/v1/views.py#L55-L107
null
class CompletionBatchView(APIView): """ Handles API requests to submit batch completions. """ authentication_classes = ( JwtAuthentication, OAuth2AuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser, ) permission_classes = (permissions.IsAuthenticated, IsStaffOrOwner,)...
edx/completion
completion/api/v1/views.py
CompletionBatchView._validate_and_parse_course_key
python
def _validate_and_parse_course_key(self, course_key): try: return CourseKey.from_string(course_key) except InvalidKeyError: raise ValidationError(_("Invalid course key: {}").format(course_key))
Returns a validated parsed CourseKey deserialized from the given course_key.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/api/v1/views.py#L109-L116
null
class CompletionBatchView(APIView): """ Handles API requests to submit batch completions. """ authentication_classes = ( JwtAuthentication, OAuth2AuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser, ) permission_classes = (permissions.IsAuthenticated, IsStaffOrOwner,)...
edx/completion
completion/api/v1/views.py
CompletionBatchView._validate_and_parse_block_key
python
def _validate_and_parse_block_key(self, block_key, course_key_obj): try: block_key_obj = UsageKey.from_string(block_key) except InvalidKeyError: raise ValidationError(_("Invalid block key: {}").format(block_key)) if block_key_obj.run is None: expected_matchin...
Returns a validated, parsed UsageKey deserialized from the given block_key.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/api/v1/views.py#L118-L137
null
class CompletionBatchView(APIView): """ Handles API requests to submit batch completions. """ authentication_classes = ( JwtAuthentication, OAuth2AuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser, ) permission_classes = (permissions.IsAuthenticated, IsStaffOrOwner,)...
edx/completion
completion/api/v1/views.py
CompletionBatchView.post
python
def post(self, request, *args, **kwargs): # pylint: disable=unused-argument batch_object = request.data or {} try: user, course_key, blocks = self._validate_and_parse(batch_object) BlockCompletion.objects.submit_batch_completion(user, course_key, blocks) except Validatio...
Inserts a batch of completions. REST Endpoint Format: { "username": "username", "course_key": "course-key", "blocks": { "block_key1": 0.0, "block_key2": 1.0, "block_key3": 1.0, } } **Returns** A Respon...
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/api/v1/views.py#L139-L187
null
class CompletionBatchView(APIView): """ Handles API requests to submit batch completions. """ authentication_classes = ( JwtAuthentication, OAuth2AuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser, ) permission_classes = (permissions.IsAuthenticated, IsStaffOrOwner,)...
edx/completion
completion/api/v1/views.py
SubsectionCompletionView.get
python
def get(self, request, username, course_key, subsection_id): def get_completion(course_completions, all_blocks, block_id): """ Recursively get the aggregate completion for a subsection, given the subsection block and a list of all blocks. Parameters: ...
Returns completion for a (user, subsection, course).
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/api/v1/views.py#L199-L252
[ "def get_completion(course_completions, all_blocks, block_id):\n \"\"\"\n Recursively get the aggregate completion for a subsection,\n given the subsection block and a list of all blocks.\n\n Parameters:\n course_completions: a dictionary of completion values by block IDs\n all_blocks: a d...
class SubsectionCompletionView(APIView): """ Handles API endpoints for the milestones experiments. TODO: EDUCATOR-2358 Remove this class after the milestones experiment is no longer running. """ authentication_classes = (JwtAuthentication, SessionAuthenticationAllowInactiveUser,) permission_...
edx/completion
completion/services.py
CompletionService.get_completions
python
def get_completions(self, candidates): queryset = BlockCompletion.user_course_completion_queryset(self._user, self._course_key).filter( block_key__in=candidates ) completions = BlockCompletion.completion_by_block_key(queryset) candidates_with_runs = [candidate.replace(course_...
Given an iterable collection of block_keys in the course, returns a mapping of the block_keys to the present completion values of their associated blocks. If a completion is not found for a given block in the current course, 0.0 is returned. The service does not attempt to verify that ...
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/services.py#L41-L70
null
class CompletionService(object): """ Service for handling completions for a user within a course. Exposes * self.completion_tracking_enabled() -> bool * self.get_completions(candidates) * self.vertical_is_complete(vertical_item) Constructor takes a user object and course_key as arguments....
edx/completion
completion/services.py
CompletionService.vertical_is_complete
python
def vertical_is_complete(self, item): if item.location.block_type != 'vertical': raise ValueError('The passed in xblock is not a vertical type!') if not self.completion_tracking_enabled(): return None # this is temporary local logic and will be removed when the whole co...
Calculates and returns whether a particular vertical is complete. The logic in this method is temporary, and will go away once the completion API is able to store a first-order notion of completeness for parent blocks (right now it just stores completion for leaves- problems, HTML, video...
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/services.py#L72-L94
[ "def completion_tracking_enabled(self):\n \"\"\"\n Exposes ENABLE_COMPLETION_TRACKING waffle switch to XModule runtime\n\n Return value:\n\n bool -> True if completion tracking is enabled.\n \"\"\"\n return waffle.waffle().is_enabled(waffle.ENABLE_COMPLETION_TRACKING)\n" ]
class CompletionService(object): """ Service for handling completions for a user within a course. Exposes * self.completion_tracking_enabled() -> bool * self.get_completions(candidates) * self.vertical_is_complete(vertical_item) Constructor takes a user object and course_key as arguments....
edx/completion
completion/services.py
CompletionService.can_mark_block_complete_on_view
python
def can_mark_block_complete_on_view(self, block): return ( XBlockCompletionMode.get_mode(block) == XBlockCompletionMode.COMPLETABLE and not getattr(block, 'has_custom_completion', False) and not getattr(block, 'has_score', False) )
Returns True if the xblock can be marked complete on view. This is true of any non-customized, non-scorable, completable block.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/services.py#L103-L112
null
class CompletionService(object): """ Service for handling completions for a user within a course. Exposes * self.completion_tracking_enabled() -> bool * self.get_completions(candidates) * self.vertical_is_complete(vertical_item) Constructor takes a user object and course_key as arguments....
edx/completion
completion/services.py
CompletionService.blocks_to_mark_complete_on_view
python
def blocks_to_mark_complete_on_view(self, blocks): blocks = {block for block in blocks if self.can_mark_block_complete_on_view(block)} completions = self.get_completions({block.location for block in blocks}) return {block for block in blocks if completions.get(block.location, 0) < 1.0}
Returns a set of blocks which should be marked complete on view and haven't been yet.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/services.py#L114-L120
[ "def get_completions(self, candidates):\n \"\"\"\n Given an iterable collection of block_keys in the course, returns a\n mapping of the block_keys to the present completion values of their\n associated blocks.\n\n If a completion is not found for a given block in the current course,\n 0.0 is retur...
class CompletionService(object): """ Service for handling completions for a user within a course. Exposes * self.completion_tracking_enabled() -> bool * self.get_completions(candidates) * self.vertical_is_complete(vertical_item) Constructor takes a user object and course_key as arguments....
edx/completion
completion/services.py
CompletionService.submit_group_completion
python
def submit_group_completion(self, block_key, completion, users=None, user_ids=None): if users is None: users = [] if user_ids is None: user_ids = [] more_users = User.objects.filter(id__in=user_ids) if len(more_users) < len(user_ids): found_ids = {u.id...
Submit a completion for a group of users. Arguments: block_key (opaque_key.edx.keys.UsageKey): The block to submit completions for. completion (float): A value in the range [0.0, 1.0] users ([django.contrib.auth.models.User]): An optional iterable of Users that completed th...
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/services.py#L122-L155
null
class CompletionService(object): """ Service for handling completions for a user within a course. Exposes * self.completion_tracking_enabled() -> bool * self.get_completions(candidates) * self.vertical_is_complete(vertical_item) Constructor takes a user object and course_key as arguments....
edx/completion
completion/services.py
CompletionService.submit_completion
python
def submit_completion(self, block_key, completion): return BlockCompletion.objects.submit_completion( user=self._user, course_key=self._course_key, block_key=block_key, completion=completion )
Submit a completion for the service user and course. Returns a (BlockCompletion, bool) where the boolean indicates whether the given BlockCompletion was newly created.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/services.py#L157-L169
null
class CompletionService(object): """ Service for handling completions for a user within a course. Exposes * self.completion_tracking_enabled() -> bool * self.get_completions(candidates) * self.vertical_is_complete(vertical_item) Constructor takes a user object and course_key as arguments....
edx/completion
completion/utilities.py
get_key_to_last_completed_course_block
python
def get_key_to_last_completed_course_block(user, course_key): last_completed_block = BlockCompletion.get_latest_block_completed(user, course_key) if last_completed_block is not None: return last_completed_block.block_key raise UnavailableCompletionData(course_key)
Returns the last block a "user" completed in a course (stated as "course_key"). raises UnavailableCompletionData when the user has not completed blocks in the course. raises UnavailableCompletionData when the visual progress waffle flag is disabled.
train
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/utilities.py#L13-L29
null
""" File is the public API for BlockCompletion. It is the interface that prevents external users from depending on the BlockCompletion model. Methods working with the BlockCompletion model should be included here. """ from __future__ import unicode_literals, absolute_import from .exceptions import UnavailableCompleti...
gitpython-developers/smmap
smmap/mman.py
WindowCursor._destroy
python
def _destroy(self): self.unuse_region() if self._rlist is not None: # Actual client count, which doesn't include the reference kept by the manager, nor ours # as we are about to be deleted try: if len(self._rlist) == 0: # Free all ...
Destruction code to decrement counters
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L55-L72
[ "def unuse_region(self):\n \"\"\"Unuse the current region. Does nothing if we have no current region\n\n **Note:** the cursor unuses the region automatically upon destruction. It is recommended\n to un-use the region once you are done reading from it in persistent cursors as it\n helps to free up resour...
class WindowCursor(object): """ Pointer into the mapped region of the memory manager, keeping the map alive until it is destroyed and no other client uses it. Cursors should not be created manually, but are instead returned by the SlidingWindowMapManager **Note:**: The current implementation is s...
gitpython-developers/smmap
smmap/mman.py
WindowCursor._copy_from
python
def _copy_from(self, rhs): self._manager = rhs._manager self._rlist = type(rhs._rlist)(rhs._rlist) self._region = rhs._region self._ofs = rhs._ofs self._size = rhs._size for region in self._rlist: region.increment_client_count() if self._region is no...
Copy all data from rhs into this instance, handles usage count
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L76-L88
null
class WindowCursor(object): """ Pointer into the mapped region of the memory manager, keeping the map alive until it is destroyed and no other client uses it. Cursors should not be created manually, but are instead returned by the SlidingWindowMapManager **Note:**: The current implementation is s...
gitpython-developers/smmap
smmap/mman.py
WindowCursor.use_region
python
def use_region(self, offset=0, size=0, flags=0): need_region = True man = self._manager fsize = self._rlist.file_size() size = min(size or fsize, man.window_size() or fsize) # clamp size to window size if self._region is not None: if self._region.includes_ofs(offse...
Assure we point to a window which allows access to the given offset into the file :param offset: absolute offset in bytes into the file :param size: amount of bytes to map. If 0, all available bytes will be mapped :param flags: additional flags to be given to os.open in case a file handle is in...
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L104-L142
null
class WindowCursor(object): """ Pointer into the mapped region of the memory manager, keeping the map alive until it is destroyed and no other client uses it. Cursors should not be created manually, but are instead returned by the SlidingWindowMapManager **Note:**: The current implementation is s...
gitpython-developers/smmap
smmap/mman.py
WindowCursor.buffer
python
def buffer(self): return buffer(self._region.buffer(), self._ofs, self._size)
Return a buffer object which allows access to our memory region from our offset to the window size. Please note that it might be smaller than you requested when calling use_region() **Note:** You can only obtain a buffer if this instance is_valid() ! **Note:** buffers should not be cached pass...
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L156-L164
[ "def buffer(obj, offset, size):\n # Actually, for gitpython this is fastest ... .\n return memoryview(obj)[offset:offset+size]\n" ]
class WindowCursor(object): """ Pointer into the mapped region of the memory manager, keeping the map alive until it is destroyed and no other client uses it. Cursors should not be created manually, but are instead returned by the SlidingWindowMapManager **Note:**: The current implementation is s...
gitpython-developers/smmap
smmap/mman.py
WindowCursor.includes_ofs
python
def includes_ofs(self, ofs): # unroll methods return (self._region._b + self._ofs) <= ofs < (self._region._b + self._ofs + self._size)
:return: True if the given absolute offset is contained in the cursors current region **Note:** cursor must be valid for this to work
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L201-L207
null
class WindowCursor(object): """ Pointer into the mapped region of the memory manager, keeping the map alive until it is destroyed and no other client uses it. Cursors should not be created manually, but are instead returned by the SlidingWindowMapManager **Note:**: The current implementation is s...
gitpython-developers/smmap
smmap/mman.py
WindowCursor.path
python
def path(self): if isinstance(self._rlist.path_or_fd(), int): raise ValueError("Path queried although mapping was applied to a file descriptor") # END handle type return self._rlist.path_or_fd()
:return: path of the underlying mapped file :raise ValueError: if attached path is not a path
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L217-L223
null
class WindowCursor(object): """ Pointer into the mapped region of the memory manager, keeping the map alive until it is destroyed and no other client uses it. Cursors should not be created manually, but are instead returned by the SlidingWindowMapManager **Note:**: The current implementation is s...
gitpython-developers/smmap
smmap/mman.py
WindowCursor.fd
python
def fd(self): if isinstance(self._rlist.path_or_fd(), string_types()): raise ValueError("File descriptor queried although mapping was generated from path") # END handle type return self._rlist.path_or_fd()
:return: file descriptor used to create the underlying mapping. **Note:** it is not required to be valid anymore :raise ValueError: if the mapping was not created by a file descriptor
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L225-L233
[ "def string_types():\n if sys.version_info[0] >= 3:\n return str\n else:\n return basestring\n" ]
class WindowCursor(object): """ Pointer into the mapped region of the memory manager, keeping the map alive until it is destroyed and no other client uses it. Cursors should not be created manually, but are instead returned by the SlidingWindowMapManager **Note:**: The current implementation is s...
gitpython-developers/smmap
smmap/mman.py
StaticWindowMapManager._collect_lru_region
python
def _collect_lru_region(self, size): num_found = 0 while (size == 0) or (self._memory_size + size > self._max_memory_size): lru_region = None lru_list = None for regions in self._fdict.values(): for region in regions: # check client...
Unmap the region which was least-recently used and has no client :param size: size of the region we want to map next (assuming its not already mapped partially or full if 0, we try to free any available region :return: Amount of freed regions .. Note:: We don't raise exc...
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L305-L344
null
class StaticWindowMapManager(object): """Provides a manager which will produce single size cursors that are allowed to always map the whole file. Clients must be written to specifically know that they are accessing their data through a StaticWindowMapManager, as they otherwise have to deal with their ...
gitpython-developers/smmap
smmap/mman.py
StaticWindowMapManager._obtain_region
python
def _obtain_region(self, a, offset, size, flags, is_recursive): if self._memory_size + size > self._max_memory_size: self._collect_lru_region(size) # END handle collection r = None if a: assert len(a) == 1 r = a[0] else: try: ...
Utilty to create a new region - for more information on the parameters, see MapCursor.use_region. :param a: A regions (a)rray :return: The newly created region
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L346-L382
null
class StaticWindowMapManager(object): """Provides a manager which will produce single size cursors that are allowed to always map the whole file. Clients must be written to specifically know that they are accessing their data through a StaticWindowMapManager, as they otherwise have to deal with their ...
gitpython-developers/smmap
smmap/mman.py
StaticWindowMapManager.make_cursor
python
def make_cursor(self, path_or_fd): regions = self._fdict.get(path_or_fd) if regions is None: regions = self.MapRegionListCls(path_or_fd) self._fdict[path_or_fd] = regions # END obtain region for path return self.WindowCursorCls(self, regions)
:return: a cursor pointing to the given path or file descriptor. It can be used to map new regions of the file into memory **Note:** if a file descriptor is given, it is assumed to be open and valid, but may be closed afterwards. To refer to the same file, you may reuse your existin...
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L387-L408
null
class StaticWindowMapManager(object): """Provides a manager which will produce single size cursors that are allowed to always map the whole file. Clients must be written to specifically know that they are accessing their data through a StaticWindowMapManager, as they otherwise have to deal with their ...
gitpython-developers/smmap
smmap/mman.py
StaticWindowMapManager.num_open_files
python
def num_open_files(self): return reduce(lambda x, y: x + y, (1 for rlist in self._fdict.values() if len(rlist) > 0), 0)
Amount of opened files in the system
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L419-L421
null
class StaticWindowMapManager(object): """Provides a manager which will produce single size cursors that are allowed to always map the whole file. Clients must be written to specifically know that they are accessing their data through a StaticWindowMapManager, as they otherwise have to deal with their ...
gitpython-developers/smmap
smmap/mman.py
StaticWindowMapManager.force_map_handle_removal_win
python
def force_map_handle_removal_win(self, base_path): if sys.platform != 'win32': return # END early bailout num_closed = 0 for path, rlist in self._fdict.items(): if path.startswith(base_path): for region in rlist: region.release...
ONLY AVAILABLE ON WINDOWS On windows removing files is not allowed if anybody still has it opened. If this process is ourselves, and if the whole process uses this memory manager (as far as the parent framework is concerned) we can enforce closing all memory maps whose path matches the g...
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L443-L468
null
class StaticWindowMapManager(object): """Provides a manager which will produce single size cursors that are allowed to always map the whole file. Clients must be written to specifically know that they are accessing their data through a StaticWindowMapManager, as they otherwise have to deal with their ...
gitpython-developers/smmap
smmap/util.py
align_to_mmap
python
def align_to_mmap(num, round_up): res = (num // ALLOCATIONGRANULARITY) * ALLOCATIONGRANULARITY if round_up and (res != num): res += ALLOCATIONGRANULARITY # END handle size return res
Align the given integer number to the closest page offset, which usually is 4096 bytes. :param round_up: if True, the next higher multiple of page size is used, otherwise the lower page_size will be used (i.e. if True, 1 becomes 4096, otherwise it becomes 0) :return: num rounded to closest page
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L32-L43
null
"""Module containing a memory memory manager which provides a sliding window on a number of memory mapped files""" import os import sys from mmap import mmap, ACCESS_READ from mmap import ALLOCATIONGRANULARITY __all__ = ["align_to_mmap", "is_64_bit", "buffer", "MapWindow", "MapRegion", "MapRegionList", "AL...
gitpython-developers/smmap
smmap/util.py
MapWindow.align
python
def align(self): nofs = align_to_mmap(self.ofs, 0) self.size += self.ofs - nofs # keep size constant self.ofs = nofs self.size = align_to_mmap(self.size, 1)
Assures the previous window area is contained in the new one
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L78-L83
[ "def align_to_mmap(num, round_up):\n \"\"\"\n Align the given integer number to the closest page offset, which usually is 4096 bytes.\n\n :param round_up: if True, the next higher multiple of page size is used, otherwise\n the lower page_size will be used (i.e. if True, 1 becomes 4096, otherwise it ...
class MapWindow(object): """Utility type which is used to snap windows towards each other, and to adjust their size""" __slots__ = ( 'ofs', # offset into the file in bytes 'size' # size of the window in bytes ) def __init__(self, offset, size): self.ofs = offs...
gitpython-developers/smmap
smmap/util.py
MapWindow.extend_left_to
python
def extend_left_to(self, window, max_size): rofs = self.ofs - window.ofs_end() nsize = rofs + self.size rofs -= nsize - min(nsize, max_size) self.ofs = self.ofs - rofs self.size += rofs
Adjust the offset to start where the given window on our left ends if possible, but don't make yourself larger than max_size. The resize will assure that the new window still contains the old window area
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L85-L93
null
class MapWindow(object): """Utility type which is used to snap windows towards each other, and to adjust their size""" __slots__ = ( 'ofs', # offset into the file in bytes 'size' # size of the window in bytes ) def __init__(self, offset, size): self.ofs = offs...
gitpython-developers/smmap
smmap/util.py
MapWindow.extend_right_to
python
def extend_right_to(self, window, max_size): self.size = min(self.size + (window.ofs - self.ofs_end()), max_size)
Adjust the size to make our window end where the right window begins, but don't get larger than max_size
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L95-L98
[ "def ofs_end(self):\n return self.ofs + self.size\n" ]
class MapWindow(object): """Utility type which is used to snap windows towards each other, and to adjust their size""" __slots__ = ( 'ofs', # offset into the file in bytes 'size' # size of the window in bytes ) def __init__(self, offset, size): self.ofs = offs...
gitpython-developers/smmap
smmap/util.py
MapRegion.includes_ofs
python
def includes_ofs(self, ofs): return self._b <= ofs < self._b + self._size
:return: True if the given offset can be read in our mapped region
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L181-L183
null
class MapRegion(object): """Defines a mapped region of memory, aligned to pagesizes **Note:** deallocates used region automatically on destruction""" __slots__ = [ '_b', # beginning of mapping '_mf', # mapped memory chunk (as returned by mmap) '_uc', # total amount of usages ...
gitpython-developers/smmap
smmap/util.py
MapRegion.increment_client_count
python
def increment_client_count(self, ofs = 1): self._uc += ofs assert self._uc > -1, "Increments must match decrements, usage counter negative: %i" % self._uc if self.client_count() == 0: self.release() return True else: return False
Adjust the usage count by the given positive or negative offset. If usage count equals 0, we will auto-release our resources :return: True if we released resources, False otherwise. In the latter case, we can still be used
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L189-L200
[ "def client_count(self):\n \"\"\":return: number of clients currently using this region\"\"\"\n return self._uc\n" ]
class MapRegion(object): """Defines a mapped region of memory, aligned to pagesizes **Note:** deallocates used region automatically on destruction""" __slots__ = [ '_b', # beginning of mapping '_mf', # mapped memory chunk (as returned by mmap) '_uc', # total amount of usages ...
gitpython-developers/smmap
smmap/util.py
MapRegionList.file_size
python
def file_size(self): if self._file_size is None: if isinstance(self._path_or_fd, string_types()): self._file_size = os.stat(self._path_or_fd).st_size else: self._file_size = os.fstat(self._path_or_fd).st_size # END handle path type # EN...
:return: size of file we manager
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L229-L238
[ "def string_types():\n if sys.version_info[0] >= 3:\n return str\n else:\n return basestring\n" ]
class MapRegionList(list): """List of MapRegion instances associating a path with a list of regions.""" __slots__ = ( '_path_or_fd', # path or file descriptor which is mapped by all our regions '_file_size' # total size of the file we map ) def __new__(cls, path): return su...
gitpython-developers/smmap
smmap/buf.py
SlidingWindowMapBuffer.begin_access
python
def begin_access(self, cursor=None, offset=0, size=sys.maxsize, flags=0): if cursor: self._c = cursor # END update our cursor # reuse existing cursors if possible if self._c is not None and self._c.is_associated(): res = self._c.use_region(offset, size, flags).is...
Call this before the first use of this instance. The method was already called by the constructor in case sufficient information was provided. For more information no the parameters, see the __init__ method :param path: if cursor is None the existing one will be used. :return: True if t...
train
https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/buf.py#L108-L134
null
class SlidingWindowMapBuffer(object): """A buffer like object which allows direct byte-wise object and slicing into memory of a mapped file. The mapping is controlled by the provided cursor. The buffer is relative, that is if you map an offset, index 0 will map to the first byte at the offset you used...
mozilla/django-tidings
tidings/models.py
multi_raw
python
def multi_raw(query, params, models, model_to_fields): cursor = connections[router.db_for_read(models[0])].cursor() cursor.execute(query, params) rows = cursor.fetchall() for row in rows: row_iter = iter(row) yield [model_class(**dict((a, next(row_iter)) for a...
Scoop multiple model instances out of the DB at once, given a query that returns all fields of each. Return an iterable of sequences of model instances parallel to the ``models`` sequence of classes. For example:: [(<User such-and-such>, <Watch such-and-such>), ...]
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/models.py#L16-L34
null
from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.contrib.contenttypes.fields import (GenericForeignKey, GenericRelation) from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Sit...
mozilla/django-tidings
tidings/models.py
Watch.unsubscribe_url
python
def unsubscribe_url(self): server_relative = ('%s?s=%s' % (reverse('tidings.unsubscribe', args=[self.pk]), self.secret)) return 'https://%s%s' % (Site.objects.get_current().domain, se...
Return the absolute URL to visit to delete me.
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/models.py#L83-L89
null
class Watch(ModelBase): """The registration of a user's interest in a certain event At minimum, specifies an event_type and thereby an :class:`~tidings.events.Event` subclass. May also specify a content type and/or object ID and, indirectly, any number of :class:`WatchFilters <WatchFilter>`. "...
mozilla/django-tidings
tidings/tasks.py
claim_watches
python
def claim_watches(user): Watch.objects.filter(email=user.email).update(email=None, user=user)
Attach any anonymous watches having a user's email to that user. Call this from your user registration process if you like.
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/tasks.py#L7-L13
null
from celery.task import task from tidings.models import Watch @task()
mozilla/django-tidings
tidings/utils.py
collate
python
def collate(*iterables, **kwargs): key = kwargs.pop('key', lambda a: a) reverse = kwargs.pop('reverse', False) min_or_max = max if reverse else min rows = [iter(iterable) for iterable in iterables if iterable] next_values = {} by_key = [] def gather_next_value(row, index): try: ...
Return an iterable ordered collation of the already-sorted items from each of ``iterables``, compared by kwarg ``key``. If ``reverse=True`` is passed, iterables must return their results in descending order rather than ascending.
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/utils.py#L13-L46
[ "def gather_next_value(row, index):\n try:\n next_value = next(row)\n except StopIteration:\n pass\n else:\n next_values[index] = next_value\n by_key.append((key(next_value), index))\n" ]
from zlib import crc32 from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.mail import EmailMessage from django.template import Context, loader from django.urls import reverse as django_reverse from django.utils.module_loading import import_string from .compat imp...
mozilla/django-tidings
tidings/utils.py
hash_to_unsigned
python
def hash_to_unsigned(data): if isinstance(data, string_types): # Return a CRC32 value identical across Python versions and platforms # by stripping the sign bit as on # http://docs.python.org/library/zlib.html. return crc32(data.encode('utf-8')) & 0xffffffff else: return ...
If ``data`` is a string or unicode string, return an unsigned 4-byte int hash of it. If ``data`` is already an int that fits those parameters, return it verbatim. If ``data`` is an int outside that range, behavior is undefined at the moment. We rely on the ``PositiveIntegerField`` on :class:`~tidin...
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/utils.py#L49-L76
null
from zlib import crc32 from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.mail import EmailMessage from django.template import Context, loader from django.urls import reverse as django_reverse from django.utils.module_loading import import_string from .compat imp...
mozilla/django-tidings
tidings/utils.py
emails_with_users_and_watches
python
def emails_with_users_and_watches( subject, template_path, vars, users_and_watches, from_email=settings.TIDINGS_FROM_ADDRESS, **extra_kwargs): template = loader.get_template(template_path) context = Context(vars) for u, w in users_and_watches: context['user'] = u # Arbitrary...
Return iterable of EmailMessages with user and watch values substituted. A convenience function for generating emails by repeatedly rendering a Django template with the given ``vars`` plus a ``user`` and ``watches`` key for each pair in ``users_and_watches`` :arg template_path: path to template file ...
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/utils.py#L79-L107
null
from zlib import crc32 from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.mail import EmailMessage from django.template import Context, loader from django.urls import reverse as django_reverse from django.utils.module_loading import import_string from .compat imp...
mozilla/django-tidings
tidings/utils.py
import_from_setting
python
def import_from_setting(setting_name, fallback): path = getattr(settings, setting_name, None) if path: try: return import_string(path) except ImportError: raise ImproperlyConfigured('%s: No such path.' % path) else: return fallback
Return the resolution of an import path stored in a Django setting. :arg setting_name: The name of the setting holding the import path :arg fallback: An alternate object to use if the setting is empty or doesn't exist Raise ImproperlyConfigured if a path is given that can't be resolved.
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/utils.py#L110-L127
null
from zlib import crc32 from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.mail import EmailMessage from django.template import Context, loader from django.urls import reverse as django_reverse from django.utils.module_loading import import_string from .compat imp...
mozilla/django-tidings
tidings/views.py
unsubscribe
python
def unsubscribe(request, watch_id): ext = getattr(settings, 'TIDINGS_TEMPLATE_EXTENSION', 'html') # Grab the watch and secret; complain if either is wrong: try: watch = Watch.objects.get(pk=watch_id) # 's' is for 'secret' but saves wrapping in mails secret = request.GET.get('s') ...
Unsubscribe from (i.e. delete) the watch of ID ``watch_id``. Expects an ``s`` querystring parameter matching the watch's secret. GET will result in a confirmation page (or a failure page if the secret is wrong). POST will actually delete the watch (again, if the secret is correct). Uses these tem...
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/views.py#L7-L44
null
from django.conf import settings from django.shortcuts import render from tidings.models import Watch
mozilla/django-tidings
tidings/events.py
_unique_by_email
python
def _unique_by_email(users_and_watches): def ensure_user_has_email(user, cluster_email): """Make sure the user in the user-watch pair has an email address. The caller guarantees us an email from either the user or the watch. If the passed-in user has no email, we return an EmailUser instead...
Given a sequence of (User/EmailUser, [Watch, ...]) pairs clustered by email address (which is never ''), yield from each cluster a single pair like this:: (User/EmailUser, [Watch, Watch, ...]). The User/Email is that of... (1) the first incoming pair where the User has an email and is not ...
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L24-L76
[ "def ensure_user_has_email(user, cluster_email):\n \"\"\"Make sure the user in the user-watch pair has an email address.\n\n The caller guarantees us an email from either the user or the watch. If\n the passed-in user has no email, we return an EmailUser instead having\n the email address from the watch...
from collections import Sequence from smtplib import SMTPException import random from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.core import mail from django.db.models import Q from celery.task import task from .co...
mozilla/django-tidings
tidings/events.py
Event.fire
python
def fire(self, exclude=None, delay=True): if delay: # Tasks don't receive the `self` arg implicitly. self._fire_task.apply_async( args=(self,), kwargs={'exclude': exclude}, serializer='pickle') else: self._fire_task(self...
Notify everyone watching the event. We are explicit about sending notifications; we don't just key off creation signals, because the receiver of a ``post_save`` signal has no idea what just changed, so it doesn't know which notifications to send. Also, we could easily send mail accident...
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L110-L136
null
class Event(object): """Abstract base class for events An :class:`Event` represents, simply, something that occurs. A :class:`~tidings.models.Watch` is a record of someone's interest in a certain type of :class:`Event`, distinguished by ``Event.event_type``. Fire an Event (``SomeEvent.fire()``) fr...
mozilla/django-tidings
tidings/events.py
Event._fire_task
python
def _fire_task(self, exclude=None): connection = mail.get_connection(fail_silently=True) # Warning: fail_silently swallows errors thrown by the generators, too. connection.open() for m in self._mails(self._users_watching(exclude=exclude)): connection.send_messages([m])
Build and send the emails as a celery task.
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L139-L145
null
class Event(object): """Abstract base class for events An :class:`Event` represents, simply, something that occurs. A :class:`~tidings.models.Watch` is a record of someone's interest in a certain type of :class:`Event`, distinguished by ``Event.event_type``. Fire an Event (``SomeEvent.fire()``) fr...
mozilla/django-tidings
tidings/events.py
Event._validate_filters
python
def _validate_filters(cls, filters): for k in iterkeys(filters): if k not in cls.filters: # Mirror "unexpected keyword argument" message: raise TypeError("%s got an unsupported filter type '%s'" % (cls.__name__, k))
Raise a TypeError if ``filters`` contains any keys inappropriate to this event class.
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L148-L155
null
class Event(object): """Abstract base class for events An :class:`Event` represents, simply, something that occurs. A :class:`~tidings.models.Watch` is a record of someone's interest in a certain type of :class:`Event`, distinguished by ``Event.event_type``. Fire an Event (``SomeEvent.fire()``) fr...
mozilla/django-tidings
tidings/events.py
Event._users_watching_by_filter
python
def _users_watching_by_filter(self, object_id=None, exclude=None, **filters): # I don't think we can use the ORM here, as there's no way to get a # second condition (name=whatever) into a left join. However, if we # were willing to have 2 subqueries run for ever...
Return an iterable of (``User``/:class:`~tidings.models.EmailUser`, [:class:`~tidings.models.Watch` objects]) tuples watching the event. Of multiple Users/EmailUsers having the same email address, only one is returned. Users are favored over EmailUsers so we are sure to be able to, for ...
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L157-L283
[ "def multi_raw(query, params, models, model_to_fields):\n \"\"\"Scoop multiple model instances out of the DB at once, given a query that\n returns all fields of each.\n\n Return an iterable of sequences of model instances parallel to the\n ``models`` sequence of classes. For example::\n\n [(<User...
class Event(object): """Abstract base class for events An :class:`Event` represents, simply, something that occurs. A :class:`~tidings.models.Watch` is a record of someone's interest in a certain type of :class:`Event`, distinguished by ``Event.event_type``. Fire an Event (``SomeEvent.fire()``) fr...
mozilla/django-tidings
tidings/events.py
Event._watches_belonging_to_user
python
def _watches_belonging_to_user(cls, user_or_email, object_id=None, **filters): # If we have trouble distinguishing subsets and such, we could store a # number_of_filters on the Watch. cls._validate_filters(filters) if isinstance(user_or_email, string_t...
Return a QuerySet of watches having the given user or email, having (only) the given filters, and having the event_type and content_type attrs of the class. Matched Watches may be either confirmed and unconfirmed. They may include duplicates if the get-then-create race condition in ...
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L286-L335
null
class Event(object): """Abstract base class for events An :class:`Event` represents, simply, something that occurs. A :class:`~tidings.models.Watch` is a record of someone's interest in a certain type of :class:`Event`, distinguished by ``Event.event_type``. Fire an Event (``SomeEvent.fire()``) fr...
mozilla/django-tidings
tidings/events.py
Event.is_notifying
python
def is_notifying(cls, user_or_email_, object_id=None, **filters): return cls._watches_belonging_to_user(user_or_email_, object_id=object_id, **filters).exists()
Return whether the user/email is watching this event (either active or inactive watches), conditional on meeting the criteria in ``filters``. Count only watches that match the given filters exactly--not ones which match merely a superset of them. This lets callers distinguish between ...
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L339-L361
[ "def _watches_belonging_to_user(cls, user_or_email, object_id=None,\n **filters):\n \"\"\"Return a QuerySet of watches having the given user or email, having\n (only) the given filters, and having the event_type and content_type\n attrs of the class.\n\n Matched Watches may...
class Event(object): """Abstract base class for events An :class:`Event` represents, simply, something that occurs. A :class:`~tidings.models.Watch` is a record of someone's interest in a certain type of :class:`Event`, distinguished by ``Event.event_type``. Fire an Event (``SomeEvent.fire()``) fr...
mozilla/django-tidings
tidings/events.py
Event.notify
python
def notify(cls, user_or_email_, object_id=None, **filters): # A test-for-existence-then-create race condition exists here, but it # doesn't matter: de-duplication on fire() and deletion of all matches # on stop_notifying() nullify its effects. try: # Pick 1 if >1 are returned...
Start notifying the given user or email address when this event occurs and meets the criteria given in ``filters``. Return the created (or the existing matching) Watch so you can call :meth:`~tidings.models.Watch.activate()` on it if you're so inclined. Implementations in subclasses ma...
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L364-L427
[ "def iteritems(d, **kw):\n return iter(d.items(**kw))\n", "def hash_to_unsigned(data):\n \"\"\"If ``data`` is a string or unicode string, return an unsigned 4-byte int\n hash of it. If ``data`` is already an int that fits those parameters,\n return it verbatim.\n\n If ``data`` is an int outside tha...
class Event(object): """Abstract base class for events An :class:`Event` represents, simply, something that occurs. A :class:`~tidings.models.Watch` is a record of someone's interest in a certain type of :class:`Event`, distinguished by ``Event.event_type``. Fire an Event (``SomeEvent.fire()``) fr...
mozilla/django-tidings
tidings/events.py
InstanceEvent.notify
python
def notify(cls, user_or_email, instance): return super(InstanceEvent, cls).notify(user_or_email, object_id=instance.pk)
Create, save, and return a watch which fires when something happens to ``instance``.
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L583-L587
null
class InstanceEvent(Event): """Abstract superclass for watching a specific instance of a Model. Subclasses must specify an ``event_type`` and should specify a ``content_type``. """ def __init__(self, instance, *args, **kwargs): """Initialize an InstanceEvent :arg instance: the inst...
mozilla/django-tidings
tidings/events.py
InstanceEvent.stop_notifying
python
def stop_notifying(cls, user_or_email, instance): super(InstanceEvent, cls).stop_notifying(user_or_email, object_id=instance.pk)
Delete the watch created by notify.
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L590-L593
null
class InstanceEvent(Event): """Abstract superclass for watching a specific instance of a Model. Subclasses must specify an ``event_type`` and should specify a ``content_type``. """ def __init__(self, instance, *args, **kwargs): """Initialize an InstanceEvent :arg instance: the inst...
mozilla/django-tidings
tidings/events.py
InstanceEvent.is_notifying
python
def is_notifying(cls, user_or_email, instance): return super(InstanceEvent, cls).is_notifying(user_or_email, object_id=instance.pk)
Check if the watch created by notify exists.
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L596-L599
null
class InstanceEvent(Event): """Abstract superclass for watching a specific instance of a Model. Subclasses must specify an ``event_type`` and should specify a ``content_type``. """ def __init__(self, instance, *args, **kwargs): """Initialize an InstanceEvent :arg instance: the inst...
mozilla/django-tidings
tidings/events.py
InstanceEvent._users_watching
python
def _users_watching(self, **kwargs): return self._users_watching_by_filter(object_id=self.instance.pk, **kwargs)
Return users watching this instance.
train
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L601-L604
null
class InstanceEvent(Event): """Abstract superclass for watching a specific instance of a Model. Subclasses must specify an ``event_type`` and should specify a ``content_type``. """ def __init__(self, instance, *args, **kwargs): """Initialize an InstanceEvent :arg instance: the inst...
deeplook/svglib
svglib/svglib.py
find_font
python
def find_font(font_name): if font_name in STANDARD_FONT_NAMES: return font_name, True elif font_name in _registered_fonts: return font_name, _registered_fonts[font_name] NOT_FOUND = (None, False) try: # Try first to register the font if it exists as ttf, # based on Repor...
Return the font and a Boolean indicating if the match is exact.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L79-L112
null
#!/usr/bin/env python # -*- coding: UTF-8 -*- """A library for reading and converting SVG. This is a converter from SVG to RLG (ReportLab Graphics) drawings. It converts mainly basic shapes, paths and simple text. The intended usage is either as module within other projects: from svglib.svglib import svg2rlg ...
deeplook/svglib
svglib/svglib.py
svg2rlg
python
def svg2rlg(path, **kwargs): "Convert an SVG file to an RLG Drawing object." # unzip .svgz file into .svg unzipped = False if isinstance(path, str) and os.path.splitext(path)[1].lower() == ".svgz": with gzip.open(path, 'rb') as f_in, open(path[:-1], 'wb') as f_out: shutil.copyfileob...
Convert an SVG file to an RLG Drawing object.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L1324-L1347
[ "def load_svg_file(path):\n parser = etree.XMLParser(remove_comments=True, recover=True)\n try:\n doc = etree.parse(path, parser=parser)\n svg_root = doc.getroot()\n except Exception as exc:\n logger.error(\"Failed to load input file! (%s)\" % exc)\n else:\n return svg_root\n...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """A library for reading and converting SVG. This is a converter from SVG to RLG (ReportLab Graphics) drawings. It converts mainly basic shapes, paths and simple text. The intended usage is either as module within other projects: from svglib.svglib import svg2rlg ...
deeplook/svglib
svglib/svglib.py
monkeypatch_reportlab
python
def monkeypatch_reportlab(): from reportlab.pdfgen.canvas import Canvas from reportlab.graphics import shapes original_renderPath = shapes._renderPath def patchedRenderPath(path, drawFuncs, **kwargs): # Patched method to transfer fillRule from Path to PDFPathObject # Get back from bound...
https://bitbucket.org/rptlab/reportlab/issues/95/ ReportLab always use 'Even-Odd' filling mode for paths, this patch forces RL to honor the path fill rule mode (possibly 'Non-Zero Winding') instead.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L1370-L1399
null
#!/usr/bin/env python # -*- coding: UTF-8 -*- """A library for reading and converting SVG. This is a converter from SVG to RLG (ReportLab Graphics) drawings. It converts mainly basic shapes, paths and simple text. The intended usage is either as module within other projects: from svglib.svglib import svg2rlg ...
deeplook/svglib
svglib/svglib.py
AttributeConverter.parseMultiAttributes
python
def parseMultiAttributes(self, line): attrs = line.split(';') attrs = [a.strip() for a in attrs] attrs = filter(lambda a:len(a)>0, attrs) new_attrs = {} for a in attrs: k, v = a.split(':') k, v = [s.strip() for s in (k, v)] new_attrs[k] = v ...
Try parsing compound attribute string. Return a dictionary with single attributes in 'line'.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L180-L196
null
class AttributeConverter(object): "An abstract class to locate and convert attributes in a DOM instance." def __init__(self): self.css_rules = None def findAttr(self, svgNode, name): """Search an attribute with some name in some node or above. First the node is searched, then its...
deeplook/svglib
svglib/svglib.py
AttributeConverter.findAttr
python
def findAttr(self, svgNode, name): # This needs also to lookup values like "url(#SomeName)"... if self.css_rules is not None and not svgNode.attrib.get('__rules_applied', False): if isinstance(svgNode, NodeTracker): svgNode.apply_rules(self.css_rules) else: ...
Search an attribute with some name in some node or above. First the node is searched, then its style attribute, then the search continues in the node's parent node. If no such attribute is found, '' is returned.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L198-L223
[ "def parseMultiAttributes(self, line):\n \"\"\"Try parsing compound attribute string.\n\n Return a dictionary with single attributes in 'line'.\n \"\"\"\n\n attrs = line.split(';')\n attrs = [a.strip() for a in attrs]\n attrs = filter(lambda a:len(a)>0, attrs)\n\n new_attrs = {}\n for a in a...
class AttributeConverter(object): "An abstract class to locate and convert attributes in a DOM instance." def __init__(self): self.css_rules = None def parseMultiAttributes(self, line): """Try parsing compound attribute string. Return a dictionary with single attributes in 'line'....