repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
SwissDataScienceCenter/renku-python | renku/cli/_client.py | pass_local_client | def pass_local_client(
method=None,
clean=None,
up_to_date=None,
commit=None,
ignore_std_streams=True,
lock=None,
):
"""Pass client from the current context to the decorated command."""
if method is None:
return functools.partial(
pass_local_client,
clean=... | python | def pass_local_client(
method=None,
clean=None,
up_to_date=None,
commit=None,
ignore_std_streams=True,
lock=None,
):
"""Pass client from the current context to the decorated command."""
if method is None:
return functools.partial(
pass_local_client,
clean=... | Pass client from the current context to the decorated command. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_client.py#L40-L83 |
SwissDataScienceCenter/renku-python | renku/api/_git.py | _mapped_std_streams | def _mapped_std_streams(lookup_paths, streams=('stdin', 'stdout', 'stderr')):
"""Get a mapping of standard streams to given paths."""
# FIXME add device number too
standard_inos = {}
for stream in streams:
try:
stream_stat = os.fstat(getattr(sys, stream).fileno())
key = s... | python | def _mapped_std_streams(lookup_paths, streams=('stdin', 'stdout', 'stderr')):
"""Get a mapping of standard streams to given paths."""
# FIXME add device number too
standard_inos = {}
for stream in streams:
try:
stream_stat = os.fstat(getattr(sys, stream).fileno())
key = s... | Get a mapping of standard streams to given paths. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/api/_git.py#L37-L61 |
SwissDataScienceCenter/renku-python | renku/api/_git.py | _clean_streams | def _clean_streams(repo, mapped_streams):
"""Clean mapped standard streams."""
for stream_name in ('stdout', 'stderr'):
stream = mapped_streams.get(stream_name)
if not stream:
continue
path = os.path.relpath(stream, start=repo.working_dir)
if (path, 0) not in repo.in... | python | def _clean_streams(repo, mapped_streams):
"""Clean mapped standard streams."""
for stream_name in ('stdout', 'stderr'):
stream = mapped_streams.get(stream_name)
if not stream:
continue
path = os.path.relpath(stream, start=repo.working_dir)
if (path, 0) not in repo.in... | Clean mapped standard streams. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/api/_git.py#L64-L77 |
SwissDataScienceCenter/renku-python | renku/api/_git.py | _expand_directories | def _expand_directories(paths):
"""Expand directory with all files it contains."""
for path in paths:
path_ = Path(path)
if path_.is_dir():
for expanded in path_.rglob('*'):
yield str(expanded)
else:
yield path | python | def _expand_directories(paths):
"""Expand directory with all files it contains."""
for path in paths:
path_ = Path(path)
if path_.is_dir():
for expanded in path_.rglob('*'):
yield str(expanded)
else:
yield path | Expand directory with all files it contains. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/api/_git.py#L80-L88 |
SwissDataScienceCenter/renku-python | renku/cli/dataset.py | dataset | def dataset(ctx, client, revision, datadir, format):
"""Handle datasets."""
ctx.meta['renku.datasets.datadir'] = datadir
if ctx.invoked_subcommand is not None:
return
if revision is None:
datasets = client.datasets.values()
else:
datasets = client.datasets_from_commit(clien... | python | def dataset(ctx, client, revision, datadir, format):
"""Handle datasets."""
ctx.meta['renku.datasets.datadir'] = datadir
if ctx.invoked_subcommand is not None:
return
if revision is None:
datasets = client.datasets.values()
else:
datasets = client.datasets_from_commit(clien... | Handle datasets. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L175-L187 |
SwissDataScienceCenter/renku-python | renku/cli/dataset.py | create | def create(client, name):
"""Create an empty dataset in the current repo."""
from renku.models.datasets import Author
with client.with_dataset(name=name) as dataset:
click.echo('Creating a dataset ... ', nl=False)
author = Author.from_git(client.repo)
if author not in dataset.author... | python | def create(client, name):
"""Create an empty dataset in the current repo."""
from renku.models.datasets import Author
with client.with_dataset(name=name) as dataset:
click.echo('Creating a dataset ... ', nl=False)
author = Author.from_git(client.repo)
if author not in dataset.author... | Create an empty dataset in the current repo. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L193-L203 |
SwissDataScienceCenter/renku-python | renku/cli/dataset.py | add | def add(client, name, urls, link, relative_to, target, force):
"""Add data to a dataset."""
try:
with client.with_dataset(name=name) as dataset:
target = target if target else None
with progressbar(urls, label='Adding data to dataset') as bar:
for url in bar:
... | python | def add(client, name, urls, link, relative_to, target, force):
"""Add data to a dataset."""
try:
with client.with_dataset(name=name) as dataset:
target = target if target else None
with progressbar(urls, label='Adding data to dataset') as bar:
for url in bar:
... | Add data to a dataset. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L222-L238 |
SwissDataScienceCenter/renku-python | renku/cli/dataset.py | ls_files | def ls_files(client, names, authors, include, exclude, format):
"""List files in dataset."""
records = _filter(
client, names=names, authors=authors, include=include, exclude=exclude
)
DATASET_FILES_FORMATS[format](client, records) | python | def ls_files(client, names, authors, include, exclude, format):
"""List files in dataset."""
records = _filter(
client, names=names, authors=authors, include=include, exclude=exclude
)
DATASET_FILES_FORMATS[format](client, records) | List files in dataset. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L269-L275 |
SwissDataScienceCenter/renku-python | renku/cli/dataset.py | unlink | def unlink(client, name, include, exclude, yes):
"""Remove matching files from a dataset."""
dataset = client.load_dataset(name=name)
records = _filter(
client, names=[dataset.name], include=include, exclude=exclude
)
if not yes and records:
prompt_text = (
'You are abou... | python | def unlink(client, name, include, exclude, yes):
"""Remove matching files from a dataset."""
dataset = client.load_dataset(name=name)
records = _filter(
client, names=[dataset.name], include=include, exclude=exclude
)
if not yes and records:
prompt_text = (
'You are abou... | Remove matching files from a dataset. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L296-L317 |
SwissDataScienceCenter/renku-python | renku/cli/dataset.py | remove | def remove(client, names):
"""Delete a dataset."""
from renku.models.refs import LinkReference
datasets = {name: client.dataset_path(name) for name in names}
if not datasets:
raise click.BadParameter(
'use dataset name or identifier', param_hint='names'
)
unknown = [
... | python | def remove(client, names):
"""Delete a dataset."""
from renku.models.refs import LinkReference
datasets = {name: client.dataset_path(name) for name in names}
if not datasets:
raise click.BadParameter(
'use dataset name or identifier', param_hint='names'
)
unknown = [
... | Delete a dataset. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L323-L362 |
SwissDataScienceCenter/renku-python | renku/cli/dataset.py | _include_exclude | def _include_exclude(file_path, include=None, exclude=None):
"""Check if file matches one of include filters and not in exclude filter.
:param file_path: Path to the file.
:param include: Tuple containing patterns to which include from result.
:param exclude: Tuple containing patterns to which exclude ... | python | def _include_exclude(file_path, include=None, exclude=None):
"""Check if file matches one of include filters and not in exclude filter.
:param file_path: Path to the file.
:param include: Tuple containing patterns to which include from result.
:param exclude: Tuple containing patterns to which exclude ... | Check if file matches one of include filters and not in exclude filter.
:param file_path: Path to the file.
:param include: Tuple containing patterns to which include from result.
:param exclude: Tuple containing patterns to which exclude from result. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L365-L383 |
SwissDataScienceCenter/renku-python | renku/cli/dataset.py | _filter | def _filter(client, names=None, authors=None, include=None, exclude=None):
"""Filter dataset files by specified filters.
:param names: Filter by specified dataset names.
:param authors: Filter by authors.
:param include: Include files matching file pattern.
:param exclude: Exclude files matching fi... | python | def _filter(client, names=None, authors=None, include=None, exclude=None):
"""Filter dataset files by specified filters.
:param names: Filter by specified dataset names.
:param authors: Filter by authors.
:param include: Include files matching file pattern.
:param exclude: Exclude files matching fi... | Filter dataset files by specified filters.
:param names: Filter by specified dataset names.
:param authors: Filter by authors.
:param include: Include files matching file pattern.
:param exclude: Exclude files matching file pattern. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L386-L418 |
SwissDataScienceCenter/renku-python | renku/cli/config.py | _split_section_and_key | def _split_section_and_key(key):
"""Return a tuple with config section and key."""
parts = key.split('.')
if len(parts) > 1:
return 'renku "{0}"'.format(parts[0]), '.'.join(parts[1:])
return 'renku', key | python | def _split_section_and_key(key):
"""Return a tuple with config section and key."""
parts = key.split('.')
if len(parts) > 1:
return 'renku "{0}"'.format(parts[0]), '.'.join(parts[1:])
return 'renku', key | Return a tuple with config section and key. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/config.py#L47-L52 |
SwissDataScienceCenter/renku-python | renku/cli/config.py | config | def config(client, key, value):
"""Get and set Renku repository and global options."""
if value is None:
cfg = client.repo.config_reader()
click.echo(cfg.get_value(*_split_section_and_key(key)))
else:
with client.repo.config_writer() as cfg:
section, config_key = _split_s... | python | def config(client, key, value):
"""Get and set Renku repository and global options."""
if value is None:
cfg = client.repo.config_reader()
click.echo(cfg.get_value(*_split_section_and_key(key)))
else:
with client.repo.config_writer() as cfg:
section, config_key = _split_s... | Get and set Renku repository and global options. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/config.py#L59-L68 |
SwissDataScienceCenter/renku-python | renku/api/datasets.py | check_for_git_repo | def check_for_git_repo(url):
"""Check if a url points to a git repository."""
u = parse.urlparse(url)
is_git = False
if os.path.splitext(u.path)[1] == '.git':
is_git = True
elif u.scheme in ('', 'file'):
from git import InvalidGitRepositoryError, Repo
try:
Repo(... | python | def check_for_git_repo(url):
"""Check if a url points to a git repository."""
u = parse.urlparse(url)
is_git = False
if os.path.splitext(u.path)[1] == '.git':
is_git = True
elif u.scheme in ('', 'file'):
from git import InvalidGitRepositoryError, Repo
try:
Repo(... | Check if a url points to a git repository. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/api/datasets.py#L443-L458 |
SwissDataScienceCenter/renku-python | renku/cli/env.py | env | def env(config, endpoint):
"""Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)"
"""
access_token = config['endpoints'][endpoint]['token']['access_token']
click.echo('export {0}={1}'.format('RENKU_ENDPOINT', endpoint))
click.echo(... | python | def env(config, endpoint):
"""Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)"
"""
access_token = config['endpoints'][endpoint]['token']['access_token']
click.echo('export {0}={1}'.format('RENKU_ENDPOINT', endpoint))
click.echo(... | Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)" | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/env.py#L29-L41 |
SwissDataScienceCenter/renku-python | renku/cli/_version.py | _check_version | def _check_version():
"""Check renku version."""
from ._config import APP_NAME
if VersionCache.load(APP_NAME).is_fresh:
return
from pkg_resources import parse_version
from renku.version import __version__
version = parse_version(__version__)
allow_prereleases = version.is_prerelea... | python | def _check_version():
"""Check renku version."""
from ._config import APP_NAME
if VersionCache.load(APP_NAME).is_fresh:
return
from pkg_resources import parse_version
from renku.version import __version__
version = parse_version(__version__)
allow_prereleases = version.is_prerelea... | Check renku version. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_version.py#L128-L157 |
SwissDataScienceCenter/renku-python | renku/cli/_version.py | check_version | def check_version(ctx, param, value):
"""Check for latest version of renku on PyPI."""
if ctx.resilient_parsing:
return
if not value and ctx.invoked_subcommand != 'run':
ctx.call_on_close(_check_version) | python | def check_version(ctx, param, value):
"""Check for latest version of renku on PyPI."""
if ctx.resilient_parsing:
return
if not value and ctx.invoked_subcommand != 'run':
ctx.call_on_close(_check_version) | Check for latest version of renku on PyPI. | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_version.py#L160-L166 |
sileht/cotyledon | cotyledon/oslo_config_glue.py | setup | def setup(service_manager, conf, reload_method="reload"):
"""Load services configuration from oslo config object.
It reads ServiceManager and Service configuration options from an
oslo_config.ConfigOpts() object. Also It registers a ServiceManager hook to
reload the configuration file on reload in the ... | python | def setup(service_manager, conf, reload_method="reload"):
"""Load services configuration from oslo config object.
It reads ServiceManager and Service configuration options from an
oslo_config.ConfigOpts() object. Also It registers a ServiceManager hook to
reload the configuration file on reload in the ... | Load services configuration from oslo config object.
It reads ServiceManager and Service configuration options from an
oslo_config.ConfigOpts() object. Also It registers a ServiceManager hook to
reload the configuration file on reload in the master process and in all
children. And then when each child ... | https://github.com/sileht/cotyledon/blob/319faa2673a986733d9a7622bee29e187f2e7391/cotyledon/oslo_config_glue.py#L68-L107 |
sileht/cotyledon | cotyledon/_service_manager.py | ServiceManager.register_hooks | def register_hooks(self, on_terminate=None, on_reload=None,
on_new_worker=None, on_dead_worker=None):
"""Register hook methods
This can be callable multiple times to add more hooks, hooks are
executed in added order. If a hook raised an exception, next hooks
will ... | python | def register_hooks(self, on_terminate=None, on_reload=None,
on_new_worker=None, on_dead_worker=None):
"""Register hook methods
This can be callable multiple times to add more hooks, hooks are
executed in added order. If a hook raised an exception, next hooks
will ... | Register hook methods
This can be callable multiple times to add more hooks, hooks are
executed in added order. If a hook raised an exception, next hooks
will be not executed.
:param on_terminate: method called on SIGTERM
:type on_terminate: callable()
:param on_reload:... | https://github.com/sileht/cotyledon/blob/319faa2673a986733d9a7622bee29e187f2e7391/cotyledon/_service_manager.py#L138-L172 |
sileht/cotyledon | cotyledon/_service_manager.py | ServiceManager.add | def add(self, service, workers=1, args=None, kwargs=None):
"""Add a new service to the ServiceManager
:param service: callable that return an instance of :py:class:`Service`
:type service: callable
:param workers: number of processes/workers for this service
:type workers: int
... | python | def add(self, service, workers=1, args=None, kwargs=None):
"""Add a new service to the ServiceManager
:param service: callable that return an instance of :py:class:`Service`
:type service: callable
:param workers: number of processes/workers for this service
:type workers: int
... | Add a new service to the ServiceManager
:param service: callable that return an instance of :py:class:`Service`
:type service: callable
:param workers: number of processes/workers for this service
:type workers: int
:param args: additional positional arguments for this service
... | https://github.com/sileht/cotyledon/blob/319faa2673a986733d9a7622bee29e187f2e7391/cotyledon/_service_manager.py#L177-L197 |
sileht/cotyledon | cotyledon/_service_manager.py | ServiceManager.reconfigure | def reconfigure(self, service_id, workers):
"""Reconfigure a service registered in ServiceManager
:param service_id: the service id
:type service_id: uuid.uuid4
:param workers: number of processes/workers for this service
:type workers: int
:raises: ValueError
""... | python | def reconfigure(self, service_id, workers):
"""Reconfigure a service registered in ServiceManager
:param service_id: the service id
:type service_id: uuid.uuid4
:param workers: number of processes/workers for this service
:type workers: int
:raises: ValueError
""... | Reconfigure a service registered in ServiceManager
:param service_id: the service id
:type service_id: uuid.uuid4
:param workers: number of processes/workers for this service
:type workers: int
:raises: ValueError | https://github.com/sileht/cotyledon/blob/319faa2673a986733d9a7622bee29e187f2e7391/cotyledon/_service_manager.py#L199-L216 |
sileht/cotyledon | cotyledon/_service_manager.py | ServiceManager.run | def run(self):
"""Start and supervise services workers
This method will start and supervise all children processes
until the master process asked to shutdown by a SIGTERM.
All spawned processes are part of the same unix process group.
"""
self._systemd_notify_once()
... | python | def run(self):
"""Start and supervise services workers
This method will start and supervise all children processes
until the master process asked to shutdown by a SIGTERM.
All spawned processes are part of the same unix process group.
"""
self._systemd_notify_once()
... | Start and supervise services workers
This method will start and supervise all children processes
until the master process asked to shutdown by a SIGTERM.
All spawned processes are part of the same unix process group. | https://github.com/sileht/cotyledon/blob/319faa2673a986733d9a7622bee29e187f2e7391/cotyledon/_service_manager.py#L218-L229 |
sileht/cotyledon | cotyledon/_service_manager.py | ServiceManager._reload | def _reload(self):
"""reload all children
posix only
"""
self._run_hooks('reload')
# Reset forktimes to respawn services quickly
self._forktimes = []
signal.signal(signal.SIGHUP, signal.SIG_IGN)
os.killpg(0, signal.SIGHUP)
signal.signal(signal.SI... | python | def _reload(self):
"""reload all children
posix only
"""
self._run_hooks('reload')
# Reset forktimes to respawn services quickly
self._forktimes = []
signal.signal(signal.SIGHUP, signal.SIG_IGN)
os.killpg(0, signal.SIGHUP)
signal.signal(signal.SI... | reload all children
posix only | https://github.com/sileht/cotyledon/blob/319faa2673a986733d9a7622bee29e187f2e7391/cotyledon/_service_manager.py#L262-L273 |
sileht/cotyledon | cotyledon/_service_manager.py | ServiceManager._get_last_worker_died | def _get_last_worker_died(self):
"""Return the last died worker information or None"""
for service_id in list(self._running_services.keys()):
# We copy the list to clean the orignal one
processes = list(self._running_services[service_id].items())
for process, worker_i... | python | def _get_last_worker_died(self):
"""Return the last died worker information or None"""
for service_id in list(self._running_services.keys()):
# We copy the list to clean the orignal one
processes = list(self._running_services[service_id].items())
for process, worker_i... | Return the last died worker information or None | https://github.com/sileht/cotyledon/blob/319faa2673a986733d9a7622bee29e187f2e7391/cotyledon/_service_manager.py#L333-L350 |
sileht/cotyledon | cotyledon/_service_manager.py | ServiceManager._systemd_notify_once | def _systemd_notify_once():
"""Send notification once to Systemd that service is ready.
Systemd sets NOTIFY_SOCKET environment variable with the name of the
socket listening for notifications from services.
This method removes the NOTIFY_SOCKET environment variable to ensure
not... | python | def _systemd_notify_once():
"""Send notification once to Systemd that service is ready.
Systemd sets NOTIFY_SOCKET environment variable with the name of the
socket listening for notifications from services.
This method removes the NOTIFY_SOCKET environment variable to ensure
not... | Send notification once to Systemd that service is ready.
Systemd sets NOTIFY_SOCKET environment variable with the name of the
socket listening for notifications from services.
This method removes the NOTIFY_SOCKET environment variable to ensure
notification is sent only once. | https://github.com/sileht/cotyledon/blob/319faa2673a986733d9a7622bee29e187f2e7391/cotyledon/_service_manager.py#L409-L430 |
mwshinn/paranoidscientist | paranoid/decorators.py | accepts | def accepts(*argtypes, **kwargtypes):
"""A function decorator to specify argument types of the function.
Types may be specified either in the order that they appear in the
function or via keyword arguments (just as if you were calling the
function).
Example usage:
| @accepts(Positive0)
... | python | def accepts(*argtypes, **kwargtypes):
"""A function decorator to specify argument types of the function.
Types may be specified either in the order that they appear in the
function or via keyword arguments (just as if you were calling the
function).
Example usage:
| @accepts(Positive0)
... | A function decorator to specify argument types of the function.
Types may be specified either in the order that they appear in the
function or via keyword arguments (just as if you were calling the
function).
Example usage:
| @accepts(Positive0)
| def square_root(x):
| ... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/decorators.py#L176-L217 |
mwshinn/paranoidscientist | paranoid/decorators.py | returns | def returns(returntype):
"""A function decorator to specify return type of the function.
Example usage:
| @accepts(Positive0)
| @returns(Positive0)
| def square_root(x):
| ...
"""
returntype = T.TypeFactory(returntype)
def _decorator(func):
# @returns decorator
... | python | def returns(returntype):
"""A function decorator to specify return type of the function.
Example usage:
| @accepts(Positive0)
| @returns(Positive0)
| def square_root(x):
| ...
"""
returntype = T.TypeFactory(returntype)
def _decorator(func):
# @returns decorator
... | A function decorator to specify return type of the function.
Example usage:
| @accepts(Positive0)
| @returns(Positive0)
| def square_root(x):
| ... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/decorators.py#L219-L236 |
mwshinn/paranoidscientist | paranoid/decorators.py | requires | def requires(condition):
"""A function decorator to specify entry conditions for the function.
Entry conditions should be a string, which will be evaluated as
Python code. Arguments of the function may be accessed by their
name.
The special syntax "-->" and "<-->" may be used to mean "if" and
... | python | def requires(condition):
"""A function decorator to specify entry conditions for the function.
Entry conditions should be a string, which will be evaluated as
Python code. Arguments of the function may be accessed by their
name.
The special syntax "-->" and "<-->" may be used to mean "if" and
... | A function decorator to specify entry conditions for the function.
Entry conditions should be a string, which will be evaluated as
Python code. Arguments of the function may be accessed by their
name.
The special syntax "-->" and "<-->" may be used to mean "if" and
"if and only if", respectively.... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/decorators.py#L239-L285 |
mwshinn/paranoidscientist | paranoid/decorators.py | ensures | def ensures(condition):
"""A function decorator to specify exit conditions for the function.
Exit conditions should be a string, which will be evaluated as
Python code. Arguments of the function may be accessed by their
name. The return value of the function may be accessed using the
special vari... | python | def ensures(condition):
"""A function decorator to specify exit conditions for the function.
Exit conditions should be a string, which will be evaluated as
Python code. Arguments of the function may be accessed by their
name. The return value of the function may be accessed using the
special vari... | A function decorator to specify exit conditions for the function.
Exit conditions should be a string, which will be evaluated as
Python code. Arguments of the function may be accessed by their
name. The return value of the function may be accessed using the
special variable name "return".
The sp... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/decorators.py#L288-L351 |
mwshinn/paranoidscientist | paranoid/decorators.py | paranoidclass | def paranoidclass(cls):
"""A class decorator to specify that class methods contain paranoid decorators.
Example usage:
| @paranoidclass
| class Point:
| def __init__(self, x, y):
| ...
| @returns(Number)
| def distance_from_zero():
| ...
... | python | def paranoidclass(cls):
"""A class decorator to specify that class methods contain paranoid decorators.
Example usage:
| @paranoidclass
| class Point:
| def __init__(self, x, y):
| ...
| @returns(Number)
| def distance_from_zero():
| ...
... | A class decorator to specify that class methods contain paranoid decorators.
Example usage:
| @paranoidclass
| class Point:
| def __init__(self, x, y):
| ...
| @returns(Number)
| def distance_from_zero():
| ... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/decorators.py#L354-L377 |
mwshinn/paranoidscientist | paranoid/decorators.py | paranoidconfig | def paranoidconfig(**kwargs):
"""A function decorator to set a local setting.
Settings may be set either globally (using
settings.Settings.set()) or locally using this decorator. The
setting name should be passed as a keyword argument, and the value
to assign the setting should be passed as the va... | python | def paranoidconfig(**kwargs):
"""A function decorator to set a local setting.
Settings may be set either globally (using
settings.Settings.set()) or locally using this decorator. The
setting name should be passed as a keyword argument, and the value
to assign the setting should be passed as the va... | A function decorator to set a local setting.
Settings may be set either globally (using
settings.Settings.set()) or locally using this decorator. The
setting name should be passed as a keyword argument, and the value
to assign the setting should be passed as the value. See
settings.Settings for t... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/decorators.py#L379-L399 |
mwshinn/paranoidscientist | paranoid/types/base.py | TypeFactory | def TypeFactory(v):
"""Ensure `v` is a valid Type.
This function is used to convert user-specified types into
internal types for the verification engine. It allows Type
subclasses, Type subclass instances, Python type, and user-defined
classes to be passed. Returns an instance of the type of `v`.... | python | def TypeFactory(v):
"""Ensure `v` is a valid Type.
This function is used to convert user-specified types into
internal types for the verification engine. It allows Type
subclasses, Type subclass instances, Python type, and user-defined
classes to be passed. Returns an instance of the type of `v`.... | Ensure `v` is a valid Type.
This function is used to convert user-specified types into
internal types for the verification engine. It allows Type
subclasses, Type subclass instances, Python type, and user-defined
classes to be passed. Returns an instance of the type of `v`.
Users should never ac... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/types/base.py#L12-L32 |
blockstack/blockstack-proofs-py | blockstack_proofs/proofs.py | profile_v3_to_proofs | def profile_v3_to_proofs(profile, fqdn, refresh=False, address = None):
"""
Convert profile format v3 to proofs
"""
proofs = []
try:
test = profile.items()
except:
return proofs
if 'account' in profile:
accounts = profile['account']
else:
return pro... | python | def profile_v3_to_proofs(profile, fqdn, refresh=False, address = None):
"""
Convert profile format v3 to proofs
"""
proofs = []
try:
test = profile.items()
except:
return proofs
if 'account' in profile:
accounts = profile['account']
else:
return pro... | Convert profile format v3 to proofs | https://github.com/blockstack/blockstack-proofs-py/blob/1aad1d5e14f7755fa334d4a4c6e1b7a6d2617922/blockstack_proofs/proofs.py#L207-L247 |
mwshinn/paranoidscientist | paranoid/utils.py | has_fun_prop | def has_fun_prop(f, k):
"""Test whether function `f` has property `k`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. If `f` is an unannotated function, this returns
False. If `f` has the property na... | python | def has_fun_prop(f, k):
"""Test whether function `f` has property `k`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. If `f` is an unannotated function, this returns
False. If `f` has the property na... | Test whether function `f` has property `k`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. If `f` is an unannotated function, this returns
False. If `f` has the property named `k`, it returns True.
O... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/utils.py#L12-L29 |
mwshinn/paranoidscientist | paranoid/utils.py | get_fun_prop | def get_fun_prop(f, k):
"""Get the value of property `k` from function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. If `f` does not have a property named `k`, this
throws an error. If `f` has ... | python | def get_fun_prop(f, k):
"""Get the value of property `k` from function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. If `f` does not have a property named `k`, this
throws an error. If `f` has ... | Get the value of property `k` from function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. If `f` does not have a property named `k`, this
throws an error. If `f` has the property named `k`, it retu... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/utils.py#L31-L44 |
mwshinn/paranoidscientist | paranoid/utils.py | set_fun_prop | def set_fun_prop(f, k, v):
"""Set the value of property `k` to be `v` in function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. This sets function `f`'s property named `k` to be
value `v`.
... | python | def set_fun_prop(f, k, v):
"""Set the value of property `k` to be `v` in function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. This sets function `f`'s property named `k` to be
value `v`.
... | Set the value of property `k` to be `v` in function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. This sets function `f`'s property named `k` to be
value `v`.
Users should never access this fun... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/utils.py#L46-L60 |
mwshinn/paranoidscientist | paranoid/utils.py | get_func_posargs_name | def get_func_posargs_name(f):
"""Returns the name of the function f's keyword argument parameter if it exists, otherwise None"""
sigparams = inspect.signature(f).parameters
for p in sigparams:
if sigparams[p].kind == inspect.Parameter.VAR_POSITIONAL:
return sigparams[p].name
return N... | python | def get_func_posargs_name(f):
"""Returns the name of the function f's keyword argument parameter if it exists, otherwise None"""
sigparams = inspect.signature(f).parameters
for p in sigparams:
if sigparams[p].kind == inspect.Parameter.VAR_POSITIONAL:
return sigparams[p].name
return N... | Returns the name of the function f's keyword argument parameter if it exists, otherwise None | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/utils.py#L62-L68 |
mwshinn/paranoidscientist | paranoid/utils.py | get_func_kwargs_name | def get_func_kwargs_name(f):
"""Returns the name of the function f's keyword argument parameter if it exists, otherwise None"""
sigparams = inspect.signature(f).parameters
for p in sigparams:
if sigparams[p].kind == inspect.Parameter.VAR_KEYWORD:
return sigparams[p].name
return None | python | def get_func_kwargs_name(f):
"""Returns the name of the function f's keyword argument parameter if it exists, otherwise None"""
sigparams = inspect.signature(f).parameters
for p in sigparams:
if sigparams[p].kind == inspect.Parameter.VAR_KEYWORD:
return sigparams[p].name
return None | Returns the name of the function f's keyword argument parameter if it exists, otherwise None | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/utils.py#L70-L76 |
mwshinn/paranoidscientist | paranoid/settings.py | Settings.set | def set(**kwargs):
"""Set configuration parameters.
Pass keyword arguments for the parameters you would like to
set.
This function is particularly useful to call at the head of
your script file to disable particular features. For example,
>>> from paranoid.settings ... | python | def set(**kwargs):
"""Set configuration parameters.
Pass keyword arguments for the parameters you would like to
set.
This function is particularly useful to call at the head of
your script file to disable particular features. For example,
>>> from paranoid.settings ... | Set configuration parameters.
Pass keyword arguments for the parameters you would like to
set.
This function is particularly useful to call at the head of
your script file to disable particular features. For example,
>>> from paranoid.settings import Settings
>>> Se... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/settings.py#L55-L70 |
mwshinn/paranoidscientist | paranoid/settings.py | Settings._set | def _set(name, value, function=None):
"""Internally set a config parameter.
If you call it with no function, it sets the global parameter.
If you call it with a function argument, it sets the value for
the specified function. Normally, this should only be called
with a function... | python | def _set(name, value, function=None):
"""Internally set a config parameter.
If you call it with no function, it sets the global parameter.
If you call it with a function argument, it sets the value for
the specified function. Normally, this should only be called
with a function... | Internally set a config parameter.
If you call it with no function, it sets the global parameter.
If you call it with a function argument, it sets the value for
the specified function. Normally, this should only be called
with a function argument for internal code.
This should... | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/settings.py#L71-L107 |
mwshinn/paranoidscientist | paranoid/settings.py | Settings.get | def get(name, function=None):
"""Get a setting.
`name` should be the name of the setting to look for. If the
optional argument `function` is passed, this will look for a
value local to the function before retrieving the global
value.
"""
if function is not None:... | python | def get(name, function=None):
"""Get a setting.
`name` should be the name of the setting to look for. If the
optional argument `function` is passed, this will look for a
value local to the function before retrieving the global
value.
"""
if function is not None:... | Get a setting.
`name` should be the name of the setting to look for. If the
optional argument `function` is passed, this will look for a
value local to the function before retrieving the global
value. | https://github.com/mwshinn/paranoidscientist/blob/a5e9198bc40b0a985174ad643cc5d6d0c46efdcd/paranoid/settings.py#L108-L120 |
GiulioRossetti/DEMON | demon/alg/Demon.py | timeit | def timeit(method):
"""
Decorator: Compute the execution time of a function
:param method: the function
:return: the method runtime
"""
def timed(*arguments, **kw):
ts = time.time()
result = method(*arguments, **kw)
te = time.time()
sys.stdout.write('Time: %r %... | python | def timeit(method):
"""
Decorator: Compute the execution time of a function
:param method: the function
:return: the method runtime
"""
def timed(*arguments, **kw):
ts = time.time()
result = method(*arguments, **kw)
te = time.time()
sys.stdout.write('Time: %r %... | Decorator: Compute the execution time of a function
:param method: the function
:return: the method runtime | https://github.com/GiulioRossetti/DEMON/blob/b075716b3903e388562b4ac0ae93c2f1f71c9af8/demon/alg/Demon.py#L13-L30 |
GiulioRossetti/DEMON | demon/alg/Demon.py | Demon.__read_graph | def __read_graph(self, network_filename):
"""
Read .ncol network file
:param network_filename: complete path for the .ncol file
:return: an undirected network
"""
self.g = nx.read_edgelist(network_filename, nodetype=int) | python | def __read_graph(self, network_filename):
"""
Read .ncol network file
:param network_filename: complete path for the .ncol file
:return: an undirected network
"""
self.g = nx.read_edgelist(network_filename, nodetype=int) | Read .ncol network file
:param network_filename: complete path for the .ncol file
:return: an undirected network | https://github.com/GiulioRossetti/DEMON/blob/b075716b3903e388562b4ac0ae93c2f1f71c9af8/demon/alg/Demon.py#L65-L72 |
GiulioRossetti/DEMON | demon/alg/Demon.py | Demon.execute | def execute(self):
"""
Execute Demon algorithm
"""
for n in self.g.nodes():
self.g.node[n]['communities'] = [n]
all_communities = {}
for ego in tqdm.tqdm(nx.nodes(self.g), ncols=35, bar_format='Exec: {l_bar}{bar}'):
ego_minus_ego = nx.ego_grap... | python | def execute(self):
"""
Execute Demon algorithm
"""
for n in self.g.nodes():
self.g.node[n]['communities'] = [n]
all_communities = {}
for ego in tqdm.tqdm(nx.nodes(self.g), ncols=35, bar_format='Exec: {l_bar}{bar}'):
ego_minus_ego = nx.ego_grap... | Execute Demon algorithm | https://github.com/GiulioRossetti/DEMON/blob/b075716b3903e388562b4ac0ae93c2f1f71c9af8/demon/alg/Demon.py#L75-L103 |
dw/alembic-autogenerate-enums | alembic_autogenerate_enums.py | get_defined_enums | def get_defined_enums(conn, schema):
"""
Return a dict mapping PostgreSQL enumeration types to the set of their
defined values.
:param conn:
SQLAlchemy connection instance.
:param str schema:
Schema name (e.g. "public").
:returns dict:
{
"my_enum": frozense... | python | def get_defined_enums(conn, schema):
"""
Return a dict mapping PostgreSQL enumeration types to the set of their
defined values.
:param conn:
SQLAlchemy connection instance.
:param str schema:
Schema name (e.g. "public").
:returns dict:
{
"my_enum": frozense... | Return a dict mapping PostgreSQL enumeration types to the set of their
defined values.
:param conn:
SQLAlchemy connection instance.
:param str schema:
Schema name (e.g. "public").
:returns dict:
{
"my_enum": frozenset(["a", "b", "c"]),
} | https://github.com/dw/alembic-autogenerate-enums/blob/80f2cbd2bbe4c4de8ceedac4929a42dcbc7e6380/alembic_autogenerate_enums.py#L15-L43 |
dw/alembic-autogenerate-enums | alembic_autogenerate_enums.py | get_declared_enums | def get_declared_enums(metadata, schema, default):
"""
Return a dict mapping SQLAlchemy enumeration types to the set of their
declared values.
:param metadata:
...
:param str schema:
Schema name (e.g. "public").
:returns dict:
{
"my_enum": frozenset(["a", "... | python | def get_declared_enums(metadata, schema, default):
"""
Return a dict mapping SQLAlchemy enumeration types to the set of their
declared values.
:param metadata:
...
:param str schema:
Schema name (e.g. "public").
:returns dict:
{
"my_enum": frozenset(["a", "... | Return a dict mapping SQLAlchemy enumeration types to the set of their
declared values.
:param metadata:
...
:param str schema:
Schema name (e.g. "public").
:returns dict:
{
"my_enum": frozenset(["a", "b", "c"]),
} | https://github.com/dw/alembic-autogenerate-enums/blob/80f2cbd2bbe4c4de8ceedac4929a42dcbc7e6380/alembic_autogenerate_enums.py#L46-L67 |
dw/alembic-autogenerate-enums | alembic_autogenerate_enums.py | compare_enums | def compare_enums(autogen_context, upgrade_ops, schema_names):
"""
Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG
schema for every definde Enum, then generate SyncEnumValuesOp migrations
for each defined enum that has grown new entries when compared to its
declared versio... | python | def compare_enums(autogen_context, upgrade_ops, schema_names):
"""
Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG
schema for every definde Enum, then generate SyncEnumValuesOp migrations
for each defined enum that has grown new entries when compared to its
declared versio... | Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG
schema for every definde Enum, then generate SyncEnumValuesOp migrations
for each defined enum that has grown new entries when compared to its
declared version.
Enums that don't exist in the database yet are ignored, since
S... | https://github.com/dw/alembic-autogenerate-enums/blob/80f2cbd2bbe4c4de8ceedac4929a42dcbc7e6380/alembic_autogenerate_enums.py#L130-L157 |
mikeboers/PyMemoize | memoize/core.py | Memoizer.get | def get(self, key, func=None, args=(), kwargs=None, **opts):
"""Manually retrieve a value from the cache, calculating as needed.
Params:
key -> string to store/retrieve value from.
func -> callable to generate value if it does not exist, or has
expired.
... | python | def get(self, key, func=None, args=(), kwargs=None, **opts):
"""Manually retrieve a value from the cache, calculating as needed.
Params:
key -> string to store/retrieve value from.
func -> callable to generate value if it does not exist, or has
expired.
... | Manually retrieve a value from the cache, calculating as needed.
Params:
key -> string to store/retrieve value from.
func -> callable to generate value if it does not exist, or has
expired.
args -> positional arguments to call the function with.
k... | https://github.com/mikeboers/PyMemoize/blob/b10f0d8937e519353a980b41c4a1243d7049133a/memoize/core.py#L71-L131 |
mikeboers/PyMemoize | memoize/core.py | Memoizer.delete | def delete(self, key, **opts):
"""Remove a key from the cache."""
key, store = self._expand_opts(key, opts)
try:
del store[key]
except KeyError:
pass | python | def delete(self, key, **opts):
"""Remove a key from the cache."""
key, store = self._expand_opts(key, opts)
try:
del store[key]
except KeyError:
pass | Remove a key from the cache. | https://github.com/mikeboers/PyMemoize/blob/b10f0d8937e519353a980b41c4a1243d7049133a/memoize/core.py#L133-L139 |
mikeboers/PyMemoize | memoize/core.py | Memoizer.expire_at | def expire_at(self, key, expiry, **opts):
"""Set the explicit unix expiry time of a key."""
key, store = self._expand_opts(key, opts)
data = store.get(key)
if data is not None:
data = list(data)
data[EXPIRY_INDEX] = expiry
store[key] = tuple(data)
... | python | def expire_at(self, key, expiry, **opts):
"""Set the explicit unix expiry time of a key."""
key, store = self._expand_opts(key, opts)
data = store.get(key)
if data is not None:
data = list(data)
data[EXPIRY_INDEX] = expiry
store[key] = tuple(data)
... | Set the explicit unix expiry time of a key. | https://github.com/mikeboers/PyMemoize/blob/b10f0d8937e519353a980b41c4a1243d7049133a/memoize/core.py#L141-L150 |
mikeboers/PyMemoize | memoize/core.py | Memoizer.expire | def expire(self, key, max_age, **opts):
"""Set the maximum age of a given key, in seconds."""
self.expire_at(key, time() + max_age, **opts) | python | def expire(self, key, max_age, **opts):
"""Set the maximum age of a given key, in seconds."""
self.expire_at(key, time() + max_age, **opts) | Set the maximum age of a given key, in seconds. | https://github.com/mikeboers/PyMemoize/blob/b10f0d8937e519353a980b41c4a1243d7049133a/memoize/core.py#L152-L154 |
mikeboers/PyMemoize | memoize/core.py | Memoizer.ttl | def ttl(self, key, **opts):
"""Get the time-to-live of a given key; None if not set."""
key, store = self._expand_opts(key, opts)
if hasattr(store, 'ttl'):
return store.ttl(key)
data = store.get(key)
if data is None:
return None
expiry = data[EXPIR... | python | def ttl(self, key, **opts):
"""Get the time-to-live of a given key; None if not set."""
key, store = self._expand_opts(key, opts)
if hasattr(store, 'ttl'):
return store.ttl(key)
data = store.get(key)
if data is None:
return None
expiry = data[EXPIR... | Get the time-to-live of a given key; None if not set. | https://github.com/mikeboers/PyMemoize/blob/b10f0d8937e519353a980b41c4a1243d7049133a/memoize/core.py#L156-L166 |
mikeboers/PyMemoize | memoize/core.py | Memoizer.exists | def exists(self, key, **opts):
"""Return if a key exists in the cache."""
key, store = self._expand_opts(key, opts)
data = store.get(key)
# Note that we do not actually delete the thing here as the max_age
# just for this call may have triggered a False.
if not data or se... | python | def exists(self, key, **opts):
"""Return if a key exists in the cache."""
key, store = self._expand_opts(key, opts)
data = store.get(key)
# Note that we do not actually delete the thing here as the max_age
# just for this call may have triggered a False.
if not data or se... | Return if a key exists in the cache. | https://github.com/mikeboers/PyMemoize/blob/b10f0d8937e519353a980b41c4a1243d7049133a/memoize/core.py#L173-L181 |
gitpython-developers/smmap | smmap/mman.py | WindowCursor._destroy | def _destroy(self):
"""Destruction code to decrement counters"""
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 l... | python | def _destroy(self):
"""Destruction code to decrement counters"""
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 l... | Destruction code to decrement counters | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L55-L72 |
gitpython-developers/smmap | smmap/mman.py | WindowCursor._copy_from | def _copy_from(self, rhs):
"""Copy all data from rhs into this instance, handles usage count"""
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._rlis... | python | def _copy_from(self, rhs):
"""Copy all data from rhs into this instance, handles usage count"""
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._rlis... | Copy all data from rhs into this instance, handles usage count | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L76-L88 |
gitpython-developers/smmap | smmap/mman.py | WindowCursor.use_region | def use_region(self, offset=0, size=0, flags=0):
"""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: additio... | python | def use_region(self, offset=0, size=0, flags=0):
"""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: additio... | 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... | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L104-L142 |
gitpython-developers/smmap | smmap/mman.py | WindowCursor.buffer | def buffer(self):
"""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:** buff... | python | def buffer(self):
"""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:** buff... | 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... | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L156-L164 |
gitpython-developers/smmap | smmap/mman.py | WindowCursor.includes_ofs | def includes_ofs(self, ofs):
""":return: True if the given absolute offset is contained in the cursors
current region
**Note:** cursor must be valid for this to work"""
# unroll methods
return (self._region._b + self._ofs) <= ofs < (self._region._b + self._ofs + self._size) | python | def includes_ofs(self, ofs):
""":return: True if the given absolute offset is contained in the cursors
current region
**Note:** cursor must be valid for this to work"""
# 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 | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L201-L207 |
gitpython-developers/smmap | smmap/mman.py | WindowCursor.path | def path(self):
""":return: path of the underlying mapped file
:raise ValueError: if attached path is not a path"""
if isinstance(self._rlist.path_or_fd(), int):
raise ValueError("Path queried although mapping was applied to a file descriptor")
# END handle type
retur... | python | def path(self):
""":return: path of the underlying mapped file
:raise ValueError: if attached path is not a path"""
if isinstance(self._rlist.path_or_fd(), int):
raise ValueError("Path queried although mapping was applied to a file descriptor")
# END handle type
retur... | :return: path of the underlying mapped file
:raise ValueError: if attached path is not a path | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L217-L223 |
gitpython-developers/smmap | smmap/mman.py | WindowCursor.fd | def fd(self):
""":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"""
if isinstance(self._rlist.path_or_fd(), string_types()):
raise ValueErr... | python | def fd(self):
""":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"""
if isinstance(self._rlist.path_or_fd(), string_types()):
raise ValueErr... | :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 | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L225-L233 |
gitpython-developers/smmap | smmap/mman.py | StaticWindowMapManager._collect_lru_region | def _collect_lru_region(self, size):
"""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
... | python | def _collect_lru_region(self, size):
"""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
... | 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... | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L305-L344 |
gitpython-developers/smmap | smmap/mman.py | StaticWindowMapManager._obtain_region | def _obtain_region(self, a, offset, size, flags, is_recursive):
"""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"""
if self._memory_size + size > self._max_memory_siz... | python | def _obtain_region(self, a, offset, size, flags, is_recursive):
"""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"""
if self._memory_size + size > self._max_memory_siz... | 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 | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L346-L382 |
gitpython-developers/smmap | smmap/mman.py | StaticWindowMapManager.make_cursor | def make_cursor(self, path_or_fd):
"""
: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 ref... | python | def make_cursor(self, path_or_fd):
"""
: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 ref... | :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... | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L387-L408 |
gitpython-developers/smmap | smmap/mman.py | StaticWindowMapManager.num_open_files | def num_open_files(self):
"""Amount of opened files in the system"""
return reduce(lambda x, y: x + y, (1 for rlist in self._fdict.values() if len(rlist) > 0), 0) | python | def num_open_files(self):
"""Amount of opened files in the system"""
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 | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L419-L421 |
gitpython-developers/smmap | smmap/mman.py | StaticWindowMapManager.force_map_handle_removal_win | def force_map_handle_removal_win(self, base_path):
"""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 en... | python | def force_map_handle_removal_win(self, base_path):
"""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 en... | 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... | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L443-L468 |
gitpython-developers/smmap | smmap/util.py | align_to_mmap | def align_to_mmap(num, round_up):
"""
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)
... | python | def align_to_mmap(num, round_up):
"""
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)
... | 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 | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L32-L43 |
gitpython-developers/smmap | smmap/util.py | MapWindow.align | def align(self):
"""Assures the previous window area is contained in the new one"""
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) | python | def align(self):
"""Assures the previous window area is contained in the new one"""
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 | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L78-L83 |
gitpython-developers/smmap | smmap/util.py | MapWindow.extend_left_to | def extend_left_to(self, window, max_size):
"""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"""
rofs = self.ofs - window.ofs_end()... | python | def extend_left_to(self, window, max_size):
"""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"""
rofs = self.ofs - window.ofs_end()... | 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 | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L85-L93 |
gitpython-developers/smmap | smmap/util.py | MapWindow.extend_right_to | def extend_right_to(self, window, max_size):
"""Adjust the size to make our window end where the right window begins, but don't
get larger than max_size"""
self.size = min(self.size + (window.ofs - self.ofs_end()), max_size) | python | def extend_right_to(self, window, max_size):
"""Adjust the size to make our window end where the right window begins, but don't
get larger than 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 | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L95-L98 |
gitpython-developers/smmap | smmap/util.py | MapRegion.includes_ofs | def includes_ofs(self, ofs):
""":return: True if the given offset can be read in our mapped region"""
return self._b <= ofs < self._b + self._size | python | def includes_ofs(self, ofs):
""":return: True if the given offset can be read in our mapped region"""
return self._b <= ofs < self._b + self._size | :return: True if the given offset can be read in our mapped region | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L181-L183 |
gitpython-developers/smmap | smmap/util.py | MapRegion.increment_client_count | def increment_client_count(self, ofs = 1):
"""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"""
self._uc += ofs
... | python | def increment_client_count(self, ofs = 1):
"""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"""
self._uc += ofs
... | 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 | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L189-L200 |
gitpython-developers/smmap | smmap/util.py | MapRegionList.file_size | def file_size(self):
""":return: size of file we manager"""
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
... | python | def file_size(self):
""":return: size of file we manager"""
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
... | :return: size of file we manager | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/util.py#L229-L238 |
gitpython-developers/smmap | smmap/buf.py | SlidingWindowMapBuffer.begin_access | def begin_access(self, cursor=None, offset=0, size=sys.maxsize, flags=0):
"""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
:pa... | python | def begin_access(self, cursor=None, offset=0, size=sys.maxsize, flags=0):
"""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
:pa... | 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... | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/buf.py#L108-L134 |
edx/pa11ycrawler | pa11ycrawler/html.py | make_parser | def make_parser():
"""
Returns an argparse instance for this script.
"""
parser = argparse.ArgumentParser(description="generate HTML from crawler JSON")
parser.add_argument(
"--data-dir", default="data",
help=u"Directory containing JSON data from crawler [%(default)s]"
)
pars... | python | def make_parser():
"""
Returns an argparse instance for this script.
"""
parser = argparse.ArgumentParser(description="generate HTML from crawler JSON")
parser.add_argument(
"--data-dir", default="data",
help=u"Directory containing JSON data from crawler [%(default)s]"
)
pars... | Returns an argparse instance for this script. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/html.py#L31-L44 |
edx/pa11ycrawler | pa11ycrawler/html.py | main | def main():
"""
Validates script arguments and calls the render_html() function with them.
"""
parser = make_parser()
args = parser.parse_args()
data_dir = Path(args.data_dir).expand()
if not data_dir.isdir(): # pylint: disable=no-value-for-parameter
msg = u"Data directory {dir} doe... | python | def main():
"""
Validates script arguments and calls the render_html() function with them.
"""
parser = make_parser()
args = parser.parse_args()
data_dir = Path(args.data_dir).expand()
if not data_dir.isdir(): # pylint: disable=no-value-for-parameter
msg = u"Data directory {dir} doe... | Validates script arguments and calls the render_html() function with them. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/html.py#L47-L65 |
edx/pa11ycrawler | pa11ycrawler/html.py | wcag_refs | def wcag_refs(code):
"""
Given a `code` from pa11y, return a list of the WCAG references.
These references are always of the form: one or more capital letters,
followed by one or more digits. One `code` may contain multiple
references, separated by commas.
"""
bits = code.split(".")
for ... | python | def wcag_refs(code):
"""
Given a `code` from pa11y, return a list of the WCAG references.
These references are always of the form: one or more capital letters,
followed by one or more digits. One `code` may contain multiple
references, separated by commas.
"""
bits = code.split(".")
for ... | Given a `code` from pa11y, return a list of the WCAG references.
These references are always of the form: one or more capital letters,
followed by one or more digits. One `code` may contain multiple
references, separated by commas. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/html.py#L68-L79 |
edx/pa11ycrawler | pa11ycrawler/html.py | render_template | def render_template(env, html_path, template_filename, context):
"""
Render a template file into the given output location.
"""
template = env.get_template(template_filename)
rendered_html = template.render(**context) # pylint: disable=no-member
html_path.write_text(rendered_html, encoding='utf... | python | def render_template(env, html_path, template_filename, context):
"""
Render a template file into the given output location.
"""
template = env.get_template(template_filename)
rendered_html = template.render(**context) # pylint: disable=no-member
html_path.write_text(rendered_html, encoding='utf... | Render a template file into the given output location. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/html.py#L82-L88 |
edx/pa11ycrawler | pa11ycrawler/html.py | render_html | def render_html(data_dir, output_dir):
"""
The main workhorse of this script. Finds all the JSON data files
from pa11ycrawler, and transforms them into HTML files via Jinja2 templating.
"""
env = Environment(loader=PackageLoader('pa11ycrawler', 'templates'))
env.globals["wcag_refs"] = wcag_refs
... | python | def render_html(data_dir, output_dir):
"""
The main workhorse of this script. Finds all the JSON data files
from pa11ycrawler, and transforms them into HTML files via Jinja2 templating.
"""
env = Environment(loader=PackageLoader('pa11ycrawler', 'templates'))
env.globals["wcag_refs"] = wcag_refs
... | The main workhorse of this script. Finds all the JSON data files
from pa11ycrawler, and transforms them into HTML files via Jinja2 templating. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/html.py#L91-L158 |
edx/pa11ycrawler | pa11ycrawler/pipelines/pa11y.py | ignore_rules_for_url | def ignore_rules_for_url(spider, url):
"""
Returns a list of ignore rules from the given spider,
that are relevant to the given URL.
"""
ignore_rules = getattr(spider, "pa11y_ignore_rules", {}) or {}
return itertools.chain.from_iterable(
rule_list
for url_glob, rule_list
... | python | def ignore_rules_for_url(spider, url):
"""
Returns a list of ignore rules from the given spider,
that are relevant to the given URL.
"""
ignore_rules = getattr(spider, "pa11y_ignore_rules", {}) or {}
return itertools.chain.from_iterable(
rule_list
for url_glob, rule_list
... | Returns a list of ignore rules from the given spider,
that are relevant to the given URL. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/pa11y.py#L21-L32 |
edx/pa11ycrawler | pa11ycrawler/pipelines/pa11y.py | ignore_rule_matches_result | def ignore_rule_matches_result(ignore_rule, pa11y_result):
"""
Returns a boolean result of whether the given ignore rule matches
the given pa11y result. The rule only matches the result if *all*
attributes of the rule match.
"""
return all(
fnmatch.fnmatch(pa11y_result.get(attr), ignore_... | python | def ignore_rule_matches_result(ignore_rule, pa11y_result):
"""
Returns a boolean result of whether the given ignore rule matches
the given pa11y result. The rule only matches the result if *all*
attributes of the rule match.
"""
return all(
fnmatch.fnmatch(pa11y_result.get(attr), ignore_... | Returns a boolean result of whether the given ignore rule matches
the given pa11y result. The rule only matches the result if *all*
attributes of the rule match. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/pa11y.py#L35-L44 |
edx/pa11ycrawler | pa11ycrawler/pipelines/pa11y.py | load_pa11y_results | def load_pa11y_results(stdout, spider, url):
"""
Load output from pa11y, filtering out the ignored messages.
The `stdout` parameter is a bytestring, not a unicode string.
"""
if not stdout:
return []
results = json.loads(stdout.decode('utf8'))
ignore_rules = ignore_rules_for_url(sp... | python | def load_pa11y_results(stdout, spider, url):
"""
Load output from pa11y, filtering out the ignored messages.
The `stdout` parameter is a bytestring, not a unicode string.
"""
if not stdout:
return []
results = json.loads(stdout.decode('utf8'))
ignore_rules = ignore_rules_for_url(sp... | Load output from pa11y, filtering out the ignored messages.
The `stdout` parameter is a bytestring, not a unicode string. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/pa11y.py#L47-L63 |
edx/pa11ycrawler | pa11ycrawler/pipelines/pa11y.py | write_pa11y_config | def write_pa11y_config(item):
"""
The only way that pa11y will see the same page that scrapy sees
is to make sure that pa11y requests the page with the same headers.
However, the only way to configure request headers with pa11y is to
write them into a config file.
This function will create a co... | python | def write_pa11y_config(item):
"""
The only way that pa11y will see the same page that scrapy sees
is to make sure that pa11y requests the page with the same headers.
However, the only way to configure request headers with pa11y is to
write them into a config file.
This function will create a co... | The only way that pa11y will see the same page that scrapy sees
is to make sure that pa11y requests the page with the same headers.
However, the only way to configure request headers with pa11y is to
write them into a config file.
This function will create a config file, write the config into it,
a... | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/pa11y.py#L66-L89 |
edx/pa11ycrawler | pa11ycrawler/pipelines/pa11y.py | check_title_match | def check_title_match(expected_title, pa11y_results, logger):
"""
Check if Scrapy reports any issue with the HTML <title> element.
If so, compare that <title> element to the title that we got in the
A11yItem. If they don't match, something is screwy, and pa11y isn't
parsing the page that we expect.
... | python | def check_title_match(expected_title, pa11y_results, logger):
"""
Check if Scrapy reports any issue with the HTML <title> element.
If so, compare that <title> element to the title that we got in the
A11yItem. If they don't match, something is screwy, and pa11y isn't
parsing the page that we expect.
... | Check if Scrapy reports any issue with the HTML <title> element.
If so, compare that <title> element to the title that we got in the
A11yItem. If they don't match, something is screwy, and pa11y isn't
parsing the page that we expect. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/pa11y.py#L92-L125 |
edx/pa11ycrawler | pa11ycrawler/pipelines/pa11y.py | track_pa11y_stats | def track_pa11y_stats(pa11y_results, spider):
"""
Keep track of the number of pa11y errors, warnings, and notices that
we've seen so far, using the Scrapy stats collector:
http://doc.scrapy.org/en/1.1/topics/stats.html
"""
num_err, num_warn, num_notice = pa11y_counts(pa11y_results)
stats = s... | python | def track_pa11y_stats(pa11y_results, spider):
"""
Keep track of the number of pa11y errors, warnings, and notices that
we've seen so far, using the Scrapy stats collector:
http://doc.scrapy.org/en/1.1/topics/stats.html
"""
num_err, num_warn, num_notice = pa11y_counts(pa11y_results)
stats = s... | Keep track of the number of pa11y errors, warnings, and notices that
we've seen so far, using the Scrapy stats collector:
http://doc.scrapy.org/en/1.1/topics/stats.html | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/pa11y.py#L128-L138 |
edx/pa11ycrawler | pa11ycrawler/pipelines/pa11y.py | write_pa11y_results | def write_pa11y_results(item, pa11y_results, data_dir):
"""
Write the output from pa11y into a data file.
"""
data = dict(item)
data['pa11y'] = pa11y_results
# it would be nice to use the URL as the filename,
# but that gets complicated (long URLs, special characters, etc)
# so we'll ma... | python | def write_pa11y_results(item, pa11y_results, data_dir):
"""
Write the output from pa11y into a data file.
"""
data = dict(item)
data['pa11y'] = pa11y_results
# it would be nice to use the URL as the filename,
# but that gets complicated (long URLs, special characters, etc)
# so we'll ma... | Write the output from pa11y into a data file. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/pa11y.py#L141-L161 |
edx/pa11ycrawler | pa11ycrawler/pipelines/pa11y.py | Pa11yPipeline.process_item | def process_item(self, item, spider):
"""
Use the Pa11y command line tool to get an a11y report.
"""
config_file = write_pa11y_config(item)
args = [
self.pa11y_path,
item["url"],
'--config={file}'.format(file=config_file.name),
]
... | python | def process_item(self, item, spider):
"""
Use the Pa11y command line tool to get an a11y report.
"""
config_file = write_pa11y_config(item)
args = [
self.pa11y_path,
item["url"],
'--config={file}'.format(file=config_file.name),
]
... | Use the Pa11y command line tool to get an a11y report. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/pa11y.py#L202-L255 |
jessemiller/HamlPy | hamlpy/hamlpy_watcher.py | watched_extension | def watched_extension(extension):
"""Return True if the given extension is one of the watched extensions"""
for ext in hamlpy.VALID_EXTENSIONS:
if extension.endswith('.' + ext):
return True
return False | python | def watched_extension(extension):
"""Return True if the given extension is one of the watched extensions"""
for ext in hamlpy.VALID_EXTENSIONS:
if extension.endswith('.' + ext):
return True
return False | Return True if the given extension is one of the watched extensions | https://github.com/jessemiller/HamlPy/blob/acb79e14381ce46e6d1cb64e7cb154751ae02dfe/hamlpy/hamlpy_watcher.py#L52-L57 |
jessemiller/HamlPy | hamlpy/hamlpy_watcher.py | watch_folder | def watch_folder():
"""Main entry point. Expects one or two arguments (the watch folder + optional destination folder)."""
argv = sys.argv[1:] if len(sys.argv) > 1 else []
args = arg_parser.parse_args(sys.argv[1:])
compiler_args = {}
input_folder = os.path.realpath(args.input_dir)
if not ar... | python | def watch_folder():
"""Main entry point. Expects one or two arguments (the watch folder + optional destination folder)."""
argv = sys.argv[1:] if len(sys.argv) > 1 else []
args = arg_parser.parse_args(sys.argv[1:])
compiler_args = {}
input_folder = os.path.realpath(args.input_dir)
if not ar... | Main entry point. Expects one or two arguments (the watch folder + optional destination folder). | https://github.com/jessemiller/HamlPy/blob/acb79e14381ce46e6d1cb64e7cb154751ae02dfe/hamlpy/hamlpy_watcher.py#L59-L108 |
jessemiller/HamlPy | hamlpy/hamlpy_watcher.py | _watch_folder | def _watch_folder(folder, destination, compiler_args):
"""Compares "modified" timestamps against the "compiled" dict, calls compiler
if necessary."""
for dirpath, dirnames, filenames in os.walk(folder):
for filename in filenames:
# Ignore filenames starting with ".#" for Emacs compatibil... | python | def _watch_folder(folder, destination, compiler_args):
"""Compares "modified" timestamps against the "compiled" dict, calls compiler
if necessary."""
for dirpath, dirnames, filenames in os.walk(folder):
for filename in filenames:
# Ignore filenames starting with ".#" for Emacs compatibil... | Compares "modified" timestamps against the "compiled" dict, calls compiler
if necessary. | https://github.com/jessemiller/HamlPy/blob/acb79e14381ce46e6d1cb64e7cb154751ae02dfe/hamlpy/hamlpy_watcher.py#L110-L131 |
jessemiller/HamlPy | hamlpy/hamlpy_watcher.py | compile_file | def compile_file(fullpath, outfile_name, compiler_args):
"""Calls HamlPy compiler."""
if Options.VERBOSE:
print '%s %s -> %s' % (strftime("%H:%M:%S"), fullpath, outfile_name)
try:
if Options.DEBUG:
print "Compiling %s -> %s" % (fullpath, outfile_name)
haml_lines = codecs.... | python | def compile_file(fullpath, outfile_name, compiler_args):
"""Calls HamlPy compiler."""
if Options.VERBOSE:
print '%s %s -> %s' % (strftime("%H:%M:%S"), fullpath, outfile_name)
try:
if Options.DEBUG:
print "Compiling %s -> %s" % (fullpath, outfile_name)
haml_lines = codecs.... | Calls HamlPy compiler. | https://github.com/jessemiller/HamlPy/blob/acb79e14381ce46e6d1cb64e7cb154751ae02dfe/hamlpy/hamlpy_watcher.py#L136-L150 |
edx/pa11ycrawler | pa11ycrawler/pipelines/__init__.py | DuplicatesPipeline.is_sequence_start_page | def is_sequence_start_page(self, url):
"""
Does this URL represent the first page in a section sequence? E.g.
/courses/{coursename}/courseware/{block_id}/{section_id}/1
This will return the same page as the pattern
/courses/{coursename}/courseware/{block_id}/{section_id}.
... | python | def is_sequence_start_page(self, url):
"""
Does this URL represent the first page in a section sequence? E.g.
/courses/{coursename}/courseware/{block_id}/{section_id}/1
This will return the same page as the pattern
/courses/{coursename}/courseware/{block_id}/{section_id}.
... | Does this URL represent the first page in a section sequence? E.g.
/courses/{coursename}/courseware/{block_id}/{section_id}/1
This will return the same page as the pattern
/courses/{coursename}/courseware/{block_id}/{section_id}. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/__init__.py#L27-L39 |
edx/pa11ycrawler | pa11ycrawler/pipelines/__init__.py | DuplicatesPipeline.process_item | def process_item(self, item, spider): # pylint: disable=unused-argument
"""
Stops processing item if we've already seen this URL before.
"""
url = self.clean_url(item["url"])
if self.is_sequence_start_page(url):
url = url.parent
if url in self.urls_seen:
... | python | def process_item(self, item, spider): # pylint: disable=unused-argument
"""
Stops processing item if we've already seen this URL before.
"""
url = self.clean_url(item["url"])
if self.is_sequence_start_page(url):
url = url.parent
if url in self.urls_seen:
... | Stops processing item if we've already seen this URL before. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/__init__.py#L41-L54 |
edx/pa11ycrawler | pa11ycrawler/pipelines/__init__.py | DropDRFPipeline.process_item | def process_item(self, item, spider): # pylint: disable=unused-argument
"Check for DRF urls."
url = URLObject(item["url"])
if url.path.startswith("/api/"):
raise DropItem(u"Dropping DRF url {url}".format(url=url))
else:
return item | python | def process_item(self, item, spider): # pylint: disable=unused-argument
"Check for DRF urls."
url = URLObject(item["url"])
if url.path.startswith("/api/"):
raise DropItem(u"Dropping DRF url {url}".format(url=url))
else:
return item | Check for DRF urls. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/__init__.py#L62-L68 |
edx/pa11ycrawler | pa11ycrawler/util.py | pa11y_counts | def pa11y_counts(results):
"""
Given a list of pa11y results, return three integers:
number of errors, number of warnings, and number of notices.
"""
num_error = 0
num_warning = 0
num_notice = 0
for result in results:
if result['type'] == 'error':
num_error += 1
... | python | def pa11y_counts(results):
"""
Given a list of pa11y results, return three integers:
number of errors, number of warnings, and number of notices.
"""
num_error = 0
num_warning = 0
num_notice = 0
for result in results:
if result['type'] == 'error':
num_error += 1
... | Given a list of pa11y results, return three integers:
number of errors, number of warnings, and number of notices. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/util.py#L16-L31 |
edx/pa11ycrawler | pa11ycrawler/spiders/edx.py | get_csrf_token | def get_csrf_token(response):
"""
Extract the CSRF token out of the "Set-Cookie" header of a response.
"""
cookie_headers = [
h.decode('ascii') for h in response.headers.getlist("Set-Cookie")
]
if not cookie_headers:
return None
csrf_headers = [
h for h in cookie_head... | python | def get_csrf_token(response):
"""
Extract the CSRF token out of the "Set-Cookie" header of a response.
"""
cookie_headers = [
h.decode('ascii') for h in response.headers.getlist("Set-Cookie")
]
if not cookie_headers:
return None
csrf_headers = [
h for h in cookie_head... | Extract the CSRF token out of the "Set-Cookie" header of a response. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L31-L46 |
edx/pa11ycrawler | pa11ycrawler/spiders/edx.py | load_pa11y_ignore_rules | def load_pa11y_ignore_rules(file=None, url=None): # pylint: disable=redefined-builtin
"""
Load the pa11y ignore rules from the given file or URL.
"""
if not file and not url:
return None
if file:
file = Path(file)
if not file.isfile():
msg = (
u"... | python | def load_pa11y_ignore_rules(file=None, url=None): # pylint: disable=redefined-builtin
"""
Load the pa11y ignore rules from the given file or URL.
"""
if not file and not url:
return None
if file:
file = Path(file)
if not file.isfile():
msg = (
u"... | Load the pa11y ignore rules from the given file or URL. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L49-L74 |
edx/pa11ycrawler | pa11ycrawler/spiders/edx.py | EdxSpider.handle_error | def handle_error(self, failure):
"""
Provides basic error information for bad requests.
If the error was an HttpError or DNSLookupError, it
prints more specific information.
"""
self.logger.error(repr(failure))
if failure.check(HttpError):
response = ... | python | def handle_error(self, failure):
"""
Provides basic error information for bad requests.
If the error was an HttpError or DNSLookupError, it
prints more specific information.
"""
self.logger.error(repr(failure))
if failure.check(HttpError):
response = ... | Provides basic error information for bad requests.
If the error was an HttpError or DNSLookupError, it
prints more specific information. | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L146-L166 |
edx/pa11ycrawler | pa11ycrawler/spiders/edx.py | EdxSpider.start_requests | def start_requests(self):
"""
Gets the spider started.
If both `self.login_email` and `self.login_password` are set,
this method generates a request to login with those credentials.
Otherwise, this method generates a request to go to the "auto auth"
page and get credentia... | python | def start_requests(self):
"""
Gets the spider started.
If both `self.login_email` and `self.login_password` are set,
this method generates a request to login with those credentials.
Otherwise, this method generates a request to go to the "auto auth"
page and get credentia... | Gets the spider started.
If both `self.login_email` and `self.login_password` are set,
this method generates a request to login with those credentials.
Otherwise, this method generates a request to go to the "auto auth"
page and get credentials from there. Either way, this method
... | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L168-L228 |
edx/pa11ycrawler | pa11ycrawler/spiders/edx.py | EdxSpider.after_initial_csrf | def after_initial_csrf(self, response):
"""
This method is called *only* if the crawler is started with an
email and password combination.
In order to log in, we need a CSRF token from a GET request. This
method takes the result of a GET request, extracts the CSRF token,
... | python | def after_initial_csrf(self, response):
"""
This method is called *only* if the crawler is started with an
email and password combination.
In order to log in, we need a CSRF token from a GET request. This
method takes the result of a GET request, extracts the CSRF token,
... | This method is called *only* if the crawler is started with an
email and password combination.
In order to log in, we need a CSRF token from a GET request. This
method takes the result of a GET request, extracts the CSRF token,
and uses it to make a login request. The response to this lo... | https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L230-L258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.