_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q15200
find_release
train
def find_release(package, releases, dependencies=None): """Return the best release.""" dependencies = dependencies if dependencies is not None else {} for release in releases: url = release['url'] old_priority = dependencies.get(package, {}).get('priority', 0) for suffix, priority i...
python
{ "resource": "" }
q15201
_safe_path
train
def _safe_path(filepath, can_be_cwl=False): """Check if the path should be used in output.""" # Should not be in ignore paths. if filepath in {'.gitignore', '.gitattributes'}: return False # Ignore everything in .renku ... if filepath.startswith('.renku'): # ... unless it can be a C...
python
{ "resource": "" }
q15202
tabular
train
def tabular(client, datasets): """Format datasets with a tabular output.""" from renku.models._tabulate import tabulate click.echo( tabulate( datasets, headers=OrderedDict(( ('short_id', 'id'), ('name', None), ('created', None)...
python
{ "resource": "" }
q15203
jsonld
train
def jsonld(client, datasets): """Format datasets as JSON-LD.""" from renku.models._json import dumps from renku.models._jsonld import asjsonld data = [ asjsonld( dataset, basedir=os.path.relpath( '.', start=str(dataset.__reference__.parent) ) ...
python
{ "resource": "" }
q15204
_format_sha1
train
def _format_sha1(graph, node): """Return formatted text with the submodule information.""" try: submodules = node.submodules if submodules: submodule = ':'.join(submodules) return click.style(submodule, fg='green') + '@' + click.style( node.commit.hexsha[...
python
{ "resource": "" }
q15205
convert_arguments
train
def convert_arguments(value): """Convert arguments from various input formats.""" if isinstance(value, (list, tuple)): return [ CommandLineBinding(**item) if isinstance(item, dict) else item for item in value ] return shlex.split(value)
python
{ "resource": "" }
q15206
cli
train
def cli(ctx, path, renku_home, use_external_storage): """Check common Renku commands used in various situations.""" ctx.obj = LocalClient( path=path, renku_home=renku_home, use_external_storage=use_external_storage, )
python
{ "resource": "" }
q15207
update
train
def update(client, revision, no_output, siblings, paths): """Update existing files by rerunning their outdated workflow.""" graph = Graph(client) outputs = graph.build(revision=revision, can_be_cwl=no_output, paths=paths) outputs = {node for node in outputs if graph.need_update(node)} if not output...
python
{ "resource": "" }
q15208
config_path
train
def config_path(path=None, final=False): """Return config path.""" if final and path: return path if path is None: path = default_config_dir() try: os.makedirs(path) except OSError as e: # pragma: no cover if e.errno != errno.EEXIST: raise return os....
python
{ "resource": "" }
q15209
read_config
train
def read_config(path=None, final=False): """Read Renku configuration.""" try: with open(config_path(path, final=final), 'r') as configfile: return yaml.safe_load(configfile) or {} except FileNotFoundError: return {}
python
{ "resource": "" }
q15210
write_config
train
def write_config(config, path, final=False): """Write Renku configuration.""" with open(config_path(path, final=final), 'w+') as configfile: yaml.dump(config, configfile, default_flow_style=False)
python
{ "resource": "" }
q15211
with_config
train
def with_config(f): """Add config to function.""" # keep it. @click.pass_context def new_func(ctx, *args, **kwargs): # Invoked with custom config: if 'config' in kwargs: return ctx.invoke(f, *args, **kwargs) if ctx.obj is None: ctx.obj = {} conf...
python
{ "resource": "" }
q15212
create_project_config_path
train
def create_project_config_path( path, mode=0o777, parents=False, exist_ok=False ): """Create new project configuration folder.""" # FIXME check default directory mode project_path = Path(path).absolute().joinpath(RENKU_HOME) project_path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok) retur...
python
{ "resource": "" }
q15213
get_project_config_path
train
def get_project_config_path(path=None): """Return project configuration folder if exist.""" project_path = Path(path or '.').absolute().joinpath(RENKU_HOME) if project_path.exists() and project_path.is_dir(): return str(project_path)
python
{ "resource": "" }
q15214
find_project_config_path
train
def find_project_config_path(path=None): """Find project config path.""" path = Path(path) if path else Path.cwd() abspath = path.absolute() project_path = get_project_config_path(abspath) if project_path: return project_path for parent in abspath.parents: project_path = get_pr...
python
{ "resource": "" }
q15215
_nodes
train
def _nodes(output, parent=None): """Yield nodes from entities.""" # NOTE refactor so all outputs behave the same entity = getattr(output, 'entity', output) if isinstance(entity, Collection): for member in entity.members: if parent is not None: member = attr.evolve(me...
python
{ "resource": "" }
q15216
mapped
train
def mapped(cls, key='id', **kwargs): """Create list of instances from a mapping.""" kwargs.setdefault('metadata', {}) kwargs['metadata']['jsonldPredicate'] = {'mapSubject': key} kwargs.setdefault('default', attr.Factory(list)) def converter(value): """Convert mapping to a list of instances....
python
{ "resource": "" }
q15217
CWLClass.from_cwl
train
def from_cwl(cls, data, __reference__=None): """Return an instance from CWL data.""" class_name = data.get('class', None) cls = cls.registry.get(class_name, cls) if __reference__: with with_reference(__reference__): self = cls( **{k: v ...
python
{ "resource": "" }
q15218
template
train
def template(client, force): """Render templated configuration files.""" import pkg_resources # create the templated files for tpl_file in CI_TEMPLATES: tpl_path = client.path / tpl_file with pkg_resources.resource_stream(__name__, tpl_file) as tpl: content = tpl.read() ...
python
{ "resource": "" }
q15219
rerun
train
def rerun(client, run, job): """Re-run existing workflow or tool using CWL runner.""" from renku.models.provenance import ProcessRun activity = client.process_commmit() if not isinstance(activity, ProcessRun): click.secho('No tool was found.', fg='red', file=sys.stderr) return try:...
python
{ "resource": "" }
q15220
_format_default
train
def _format_default(client, value): """Format default values.""" if isinstance(value, File): return os.path.relpath( str((client.workflow_path / value.path).resolve()) ) return value
python
{ "resource": "" }
q15221
show_inputs
train
def show_inputs(client, workflow): """Show workflow inputs and exit.""" for input_ in workflow.inputs: click.echo( '{id}: {default}'.format( id=input_.id, default=_format_default(client, input_.default), ) ) sys.exit(0)
python
{ "resource": "" }
q15222
edit_inputs
train
def edit_inputs(client, workflow): """Edit workflow inputs.""" types = { 'int': int, 'string': str, 'File': lambda x: File(path=Path(x).resolve()), } for input_ in workflow.inputs: convert = types.get(input_.type, str) input_.default = convert( click.p...
python
{ "resource": "" }
q15223
rerun
train
def rerun(client, revision, roots, siblings, inputs, paths): """Recreate files generated by a sequence of ``run`` commands.""" graph = Graph(client) outputs = graph.build(paths=paths, revision=revision) # Check or extend siblings of outputs. outputs = siblings(graph, outputs) output_paths = {no...
python
{ "resource": "" }
q15224
datasets
train
def datasets(ctx, client): """Migrate dataset metadata.""" from renku.models._jsonld import asjsonld from renku.models.datasets import Dataset from renku.models.refs import LinkReference from ._checks.location_datasets import _dataset_metadata_pre_0_3_4 for old_path in _dataset_metadata_pre_0_...
python
{ "resource": "" }
q15225
detect_registry_url
train
def detect_registry_url(client, auto_login=True): """Return a URL of the Docker registry.""" repo = client.repo config = repo.config_reader() # Find registry URL in .git/config remote_url = None try: registry_url = config.get_value('renku', 'registry', None) except NoSectionError: ...
python
{ "resource": "" }
q15226
JSONEncoder.default
train
def default(self, obj): """Encode more types.""" if isinstance(obj, UUID): return obj.hex elif isinstance(obj, datetime.datetime): return obj.isoformat() return super().default(obj)
python
{ "resource": "" }
q15227
run
train
def run(client, outputs, no_output, success_codes, isolation, command_line): """Tracking work on a specific problem.""" working_dir = client.repo.working_dir mapped_std = _mapped_std_streams(client.candidate_paths) factory = CommandLineToolFactory( command_line=command_line, directory=os...
python
{ "resource": "" }
q15228
log
train
def log(client, revision, format, no_output, paths): """Show logs for a file.""" graph = Graph(client) if not paths: start, is_range, stop = revision.partition('..') if not is_range: stop = start elif not stop: stop = 'HEAD' commit = client.repo.rev_p...
python
{ "resource": "" }
q15229
status
train
def status(ctx, client, revision, no_output, path): """Show a status of the repository.""" graph = Graph(client) # TODO filter only paths = {graph.normalize_path(p) for p in path} status = graph.build_status(revision=revision, can_be_cwl=no_output) click.echo('On branch {0}'.format(client.repo.acti...
python
{ "resource": "" }
q15230
validate_name
train
def validate_name(ctx, param, value): """Validate a project name.""" if not value: value = os.path.basename(ctx.params['directory'].rstrip(os.path.sep)) return value
python
{ "resource": "" }
q15231
store_directory
train
def store_directory(ctx, param, value): """Store directory as a new Git home.""" Path(value).mkdir(parents=True, exist_ok=True) set_git_home(value) return value
python
{ "resource": "" }
q15232
init
train
def init(ctx, client, directory, name, force, use_external_storage): """Initialize a project.""" if not client.use_external_storage: use_external_storage = False ctx.obj = client = attr.evolve( client, path=directory, use_external_storage=use_external_storage, ) msg...
python
{ "resource": "" }
q15233
check_missing_files
train
def check_missing_files(client): """Find missing files listed in datasets.""" missing = defaultdict(list) for path, dataset in client.datasets.items(): for file in dataset.files: filepath = (path.parent / file) if not filepath.exists(): missing[str( ...
python
{ "resource": "" }
q15234
APIError.from_http_exception
train
def from_http_exception(cls, e): """Create ``APIError`` from ``requests.exception.HTTPError``.""" assert isinstance(e, requests.exceptions.HTTPError) response = e.response try: message = response.json()['message'] except (KeyError, ValueError): message = r...
python
{ "resource": "" }
q15235
UnexpectedStatusCode.return_or_raise
train
def return_or_raise(cls, response, expected_status_code): """Check for ``expected_status_code``.""" try: if response.status_code in expected_status_code: return response except TypeError: if response.status_code == expected_status_code: ret...
python
{ "resource": "" }
q15236
check_missing_references
train
def check_missing_references(client): """Find missing references.""" from renku.models.refs import LinkReference missing = [ ref for ref in LinkReference.iter_items(client) if not ref.reference.exists() ] if not missing: return True click.secho( WARNING + 'Ther...
python
{ "resource": "" }
q15237
get_git_home
train
def get_git_home(path='.'): """Get Git path from the current context.""" ctx = click.get_current_context(silent=True) if ctx and GIT_KEY in ctx.meta: return ctx.meta[GIT_KEY] from git import Repo return Repo(path, search_parent_directories=True).working_dir
python
{ "resource": "" }
q15238
get_git_isolation
train
def get_git_isolation(): """Get Git isolation from the current context.""" ctx = click.get_current_context(silent=True) if ctx and GIT_ISOLATION in ctx.meta: return ctx.meta[GIT_ISOLATION]
python
{ "resource": "" }
q15239
_safe_issue_checkout
train
def _safe_issue_checkout(repo, issue=None): """Safely checkout branch for the issue.""" branch_name = str(issue) if issue else 'master' if branch_name not in repo.heads: branch = repo.create_head(branch_name) else: branch = repo.heads[branch_name] branch.checkout()
python
{ "resource": "" }
q15240
attrib
train
def attrib(context=None, **kwargs): """Create a new attribute with context.""" kwargs.setdefault('metadata', {}) kwargs['metadata'][KEY] = context return attr.ib(**kwargs)
python
{ "resource": "" }
q15241
_container_attrib_builder
train
def _container_attrib_builder(name, container, mapper): """Builder for container attributes.""" context = {'@container': '@{0}'.format(name)} def _attrib(type, **kwargs): """Define a container attribute.""" kwargs.setdefault('metadata', {}) kwargs['metadata'][KEY_CLS] = type ...
python
{ "resource": "" }
q15242
asjsonld
train
def asjsonld( inst, recurse=True, filter=None, dict_factory=dict, retain_collection_types=False, export_context=True, basedir=None, ): """Dump a JSON-LD class to the JSON with generated ``@context`` field.""" jsonld_fields = inst.__class__._jsonld_fields attrs = tuple( fi...
python
{ "resource": "" }
q15243
JSONLDMixin.from_jsonld
train
def from_jsonld(cls, data, __reference__=None, __source__=None): """Instantiate a JSON-LD class from data.""" if isinstance(data, cls): return data if not isinstance(data, dict): raise ValueError(data) if '@type' in data: type_ = tuple(sorted(data['@...
python
{ "resource": "" }
q15244
JSONLDMixin.asjsonld
train
def asjsonld(self): """Create JSON-LD with the original source data.""" source = {} if self.__source__: source.update(self.__source__) source.update(asjsonld(self)) return source
python
{ "resource": "" }
q15245
JSONLDMixin.to_yaml
train
def to_yaml(self): """Store an instance to the referenced YAML file.""" import yaml with self.__reference__.open('w') as fp: yaml.dump(self.asjsonld(), fp, default_flow_style=False)
python
{ "resource": "" }
q15246
send_mail
train
def send_mail(subject, body_text, addr_from, recipient_list, fail_silently=False, auth_user=None, auth_password=None, attachments=None, body_html=None, html_message=None, connection=None, headers=None): """ Sends a multipart email containing text and html versions ...
python
{ "resource": "" }
q15247
topological
train
def topological(nodes): """Return nodes in a topological order.""" order, enter, state = deque(), set(nodes), {} def dfs(node): """Visit nodes in depth-first order.""" state[node] = GRAY for parent in nodes.get(node, ()): color = state.get(parent, None) if co...
python
{ "resource": "" }
q15248
check_dataset_metadata
train
def check_dataset_metadata(client): """Check location of dataset metadata.""" # Find pre 0.3.4 metadata files. old_metadata = list(_dataset_metadata_pre_0_3_4(client)) if not old_metadata: return True click.secho( WARNING + 'There are metadata files in the old location.' '\...
python
{ "resource": "" }
q15249
siblings
train
def siblings(client, revision, paths): """Show siblings for given paths.""" graph = Graph(client) nodes = graph.build(paths=paths, revision=revision) siblings_ = set(nodes) for node in nodes: siblings_ |= graph.siblings(node) paths = {node.path for node in siblings_} for path in pat...
python
{ "resource": "" }
q15250
inputs
train
def inputs(ctx, client, revision, paths): r"""Show inputs files in the repository. <PATHS> Files to show. If no files are given all input files are shown. """ from renku.models.provenance import ProcessRun graph = Graph(client) paths = set(paths) nodes = graph.build(revision=revision) ...
python
{ "resource": "" }
q15251
outputs
train
def outputs(ctx, client, revision, paths): r"""Show output files in the repository. <PATHS> Files to show. If no files are given all output files are shown. """ graph = Graph(client) filter = graph.build(paths=paths, revision=revision) output_paths = graph.output_paths click.echo('\n'.j...
python
{ "resource": "" }
q15252
_context_names
train
def _context_names(): """Return list of valid context names.""" import inspect from renku.models import provenance from renku.models._jsonld import JSONLDMixin for name in dir(provenance): cls = getattr(provenance, name) if inspect.isclass(cls) and issubclass(cls, JSONLDMixin): ...
python
{ "resource": "" }
q15253
print_context_names
train
def print_context_names(ctx, param, value): """Print all possible types.""" if not value or ctx.resilient_parsing: return click.echo('\n'.join(_context_names())) ctx.exit()
python
{ "resource": "" }
q15254
_context_json
train
def _context_json(name): """Return JSON-LD string for given context name.""" from renku.models import provenance cls = getattr(provenance, name) return { '@context': cls._jsonld_context, '@type': cls._jsonld_type, }
python
{ "resource": "" }
q15255
context
train
def context(names): """Show JSON-LD context for repository objects.""" import json contexts = [_context_json(name) for name in set(names)] if contexts: click.echo( json.dumps( contexts[0] if len(contexts) == 1 else contexts, indent=2, ) ...
python
{ "resource": "" }
q15256
workflow
train
def workflow(ctx, client): """List or manage workflows with subcommands.""" if ctx.invoked_subcommand is None: from renku.models.refs import LinkReference names = defaultdict(list) for ref in LinkReference.iter_items(client, common_path='workflows'): names[ref.reference.name...
python
{ "resource": "" }
q15257
validate_path
train
def validate_path(ctx, param, value): """Detect a workflow path if it is not passed.""" client = ctx.obj if value is None: from renku.models.provenance import ProcessRun activity = client.process_commit() if not isinstance(activity, ProcessRun): raise click.BadParameter...
python
{ "resource": "" }
q15258
create
train
def create(client, output_file, revision, paths): """Create a workflow description for a file.""" graph = Graph(client) outputs = graph.build(paths=paths, revision=revision) output_file.write( yaml.dump( ascwl( graph.ascwl(outputs=outputs), filter=lam...
python
{ "resource": "" }
q15259
endpoint
train
def endpoint(ctx, config, verbose): """Manage set of platform API endpoints.""" if ctx.invoked_subcommand is None: # TODO default_endpoint = config.get('core', {}).get('default') for endpoint, values in config.get('endpoints', {}).items(): # TODO is_default = default_endpoint == endp...
python
{ "resource": "" }
q15260
_wrap_path_or_stream
train
def _wrap_path_or_stream(method, mode): # noqa: D202 """Open path with context or close stream at the end.""" def decorator(path_or_stream): """Open the path if needed.""" if isinstance(path_or_stream, (str, Path)): return method(Path(path_or_stream).open(mode)) return meth...
python
{ "resource": "" }
q15261
doctor
train
def doctor(ctx, client): """Check your system and repository for potential problems.""" click.secho('\n'.join(textwrap.wrap(DOCTOR_INFO)) + '\n', bold=True) from . import _checks is_ok = True for attr in _checks.__all__: is_ok &= getattr(_checks, attr)(client) if is_ok: click....
python
{ "resource": "" }
q15262
DirectoryTree.from_list
train
def from_list(cls, values): """Construct a tree from a list with paths.""" self = cls() for value in values: self.add(value) return self
python
{ "resource": "" }
q15263
DirectoryTree.get
train
def get(self, value, default=None): """Return a subtree if exists.""" path = value if isinstance(value, Path) else Path(str(value)) subtree = self for part in path.parts: try: subtree = subtree[part] except KeyError: return default ...
python
{ "resource": "" }
q15264
DirectoryTree.add
train
def add(self, value): """Create a safe directory from a value.""" path = value if isinstance(value, Path) else Path(str(value)) if path and path != path.parent: destination = self for part in path.parts: destination = destination.setdefault(part, Directory...
python
{ "resource": "" }
q15265
default_endpoint_from_config
train
def default_endpoint_from_config(config, option=None): """Return a default endpoint.""" default_endpoint = config.get('core', {}).get('default') project_endpoint = config.get('project', {}).get('core', {}).get('default', default_end...
python
{ "resource": "" }
q15266
install_completion
train
def install_completion(ctx, attr, value): # pragma: no cover """Install completion for the current shell.""" import click_completion.core if not value or ctx.resilient_parsing: return value shell, path = click_completion.core.install() click.secho( '{0} completion installed in {1}...
python
{ "resource": "" }
q15267
default_endpoint
train
def default_endpoint(ctx, param, value): """Return default endpoint if specified.""" if ctx.resilient_parsing: return config = ctx.obj['config'] endpoint = default_endpoint_from_config(config, option=value) if endpoint is None: raise click.UsageError('No default endpoint found.') ...
python
{ "resource": "" }
q15268
validate_endpoint
train
def validate_endpoint(ctx, param, value): """Validate endpoint.""" try: config = ctx.obj['config'] except Exception: return endpoint = default_endpoint(ctx, param, value) if endpoint not in config.get('endpoints', {}): raise click.UsageError('Unknown endpoint: {0}'.format(e...
python
{ "resource": "" }
q15269
check_siblings
train
def check_siblings(graph, outputs): """Check that all outputs have their siblings listed.""" siblings = set() for node in outputs: siblings |= graph.siblings(node) siblings = {node.path for node in siblings} missing = siblings - {node.path for node in outputs} if missing: msg =...
python
{ "resource": "" }
q15270
with_siblings
train
def with_siblings(graph, outputs): """Include all missing siblings.""" siblings = set() for node in outputs: siblings |= graph.siblings(node) return siblings
python
{ "resource": "" }
q15271
echo_via_pager
train
def echo_via_pager(*args, **kwargs): """Display pager only if it does not fit in one terminal screen. NOTE: The feature is available only on ``less``-based pager. """ try: restore = 'LESS' not in os.environ os.environ.setdefault('LESS', '-iXFR') click.echo_via_pager(*args, **kwa...
python
{ "resource": "" }
q15272
OptionalGroup.parse_args
train
def parse_args(self, ctx, args): """Check if the first argument is an existing command.""" if args and args[0] in self.commands: args.insert(0, '') super(OptionalGroup, self).parse_args(ctx, args)
python
{ "resource": "" }
q15273
execute
train
def execute(client, output_file, output_paths=None): """Run the generated workflow using cwltool library.""" output_paths = output_paths or set() import cwltool.factory from cwltool import workflow from cwltool.context import LoadingContext, RuntimeContext from cwltool.utils import visit_class ...
python
{ "resource": "" }
q15274
pull
train
def pull(client, revision, auto_login): """Pull an existing image from the project registry.""" registry_url = detect_registry_url(client, auto_login=auto_login) repo = client.repo sha = repo.rev_parse(revision).hexsha short_sha = repo.git.rev_parse(sha, short=7) image = '{registry}:{short_sha...
python
{ "resource": "" }
q15275
tabular
train
def tabular(client, records): """Format dataset files with a tabular output. :param client: LocalClient instance. :param records: Filtered collection. """ from renku.models._tabulate import tabulate echo_via_pager( tabulate( records, headers=OrderedDict(( ...
python
{ "resource": "" }
q15276
jsonld
train
def jsonld(client, records): """Format dataset files as JSON-LD. :param client: LocalClient instance. :param records: Filtered collection. """ from renku.models._json import dumps from renku.models._jsonld import asjsonld data = [asjsonld(record) for record in records] echo_via_pager(d...
python
{ "resource": "" }
q15277
IssueFromTraceback.main
train
def main(self, *args, **kwargs): """Catch all exceptions.""" try: result = super().main(*args, **kwargs) return result except Exception: if HAS_SENTRY: self._handle_sentry() if not (sys.stdin.isatty() and sys.stdout.isatty()): ...
python
{ "resource": "" }
q15278
IssueFromTraceback._handle_sentry
train
def _handle_sentry(self): """Handle exceptions using Sentry.""" from sentry_sdk import capture_exception, configure_scope from sentry_sdk.utils import capture_internal_exceptions with configure_scope() as scope: with capture_internal_exceptions(): from git im...
python
{ "resource": "" }
q15279
IssueFromTraceback._handle_github
train
def _handle_github(self): """Handle exception and submit it as GitHub issue.""" value = click.prompt( _BUG + click.style( '1. Open an issue by typing "open";\n', fg='green', ) + click.style( '2. Print human-readable information by t...
python
{ "resource": "" }
q15280
IssueFromTraceback._format_issue_body
train
def _format_issue_body(self, limit=-5): """Return formatted body.""" from renku import __version__ re_paths = r'(' + r'|'.join([path or os.getcwd() for path in sys.path]) + r')' tb = re.sub(re_paths, '[...]', traceback.format_exc(limit=limit)) ...
python
{ "resource": "" }
q15281
IssueFromTraceback._format_issue_url
train
def _format_issue_url(self): """Format full issue URL.""" query = urlencode({ 'title': self._format_issue_title(), 'body': self._format_issue_body(), }) return self.REPO_URL + self.ISSUE_SUFFIX + '?' + query
python
{ "resource": "" }
q15282
IssueFromTraceback._process_open
train
def _process_open(self): """Open link in a browser.""" click.launch(self._format_issue_url()) if not click.confirm('Did it work?', default=True): click.echo() self._process_print() click.secho( '\nOpen the line manually and copy the text above\...
python
{ "resource": "" }
q15283
pass_local_client
train
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
{ "resource": "" }
q15284
_mapped_std_streams
train
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
{ "resource": "" }
q15285
_clean_streams
train
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
{ "resource": "" }
q15286
_expand_directories
train
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
{ "resource": "" }
q15287
dataset
train
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
{ "resource": "" }
q15288
create
train
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
{ "resource": "" }
q15289
add
train
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
{ "resource": "" }
q15290
ls_files
train
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
{ "resource": "" }
q15291
unlink
train
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
{ "resource": "" }
q15292
_include_exclude
train
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
{ "resource": "" }
q15293
_filter
train
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
{ "resource": "" }
q15294
_split_section_and_key
train
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
{ "resource": "" }
q15295
config
train
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
{ "resource": "" }
q15296
check_for_git_repo
train
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
{ "resource": "" }
q15297
env
train
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
{ "resource": "" }
q15298
_check_version
train
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
{ "resource": "" }
q15299
check_version
train
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
{ "resource": "" }