code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if operation_timeout is None:
operation_timeout = \
self.session.retry_timeout_config.operation_timeout
if operation_timeout > 0:
start_time = time.time()
while True:
try:
self.query_api_version()
except Err... | def wait_for_available(self, operation_timeout=None) | Wait for the Console (HMC) this client is connected to, to become
available. The Console is considered available if the
:meth:`~zhmcclient.Client.query_api_version` method succeeds.
If the Console does not become available within the operation timeout,
an :exc:`~zhmcclient.OperationTime... | 3.190202 | 2.662056 | 1.198398 |
full_properties = self.manager.session.get(self._uri)
self._properties = dict(full_properties)
self._properties_timestamp = int(time.time())
self._full_properties = True | def pull_full_properties(self) | Retrieve the full set of resource properties and cache them in this
object.
Authorization requirements:
* Object-access permission to this resource.
Raises:
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcclient.AuthError`
... | 5.344421 | 5.219699 | 1.023895 |
try:
return self._properties[name]
except KeyError:
if self._full_properties:
raise
self.pull_full_properties()
return self._properties[name] | def get_property(self, name) | Return the value of a resource property.
If the resource property is not cached in this object yet, the full set
of resource properties is retrieved and cached in this object, and the
resource property is again attempted to be returned.
Authorization requirements:
* Object-acc... | 3.779234 | 3.98422 | 0.948551 |
global USERID, PASSWORD # pylint: disable=global-statement
USERID = userid or USERID or \
six.input('Enter userid for HMC {}: '.format(zhmc))
PASSWORD = password or PASSWORD or \
getpass.getpass('Enter password for {}: '.format(USERID))
session = zhmcclient.Session(zhmc, USERID,... | def make_client(zhmc, userid=None, password=None) | Create a `Session` object for the specified HMC and log that on. Create a
`Client` object using that `Session` object, and return it.
If no userid and password are specified, and if no previous call to this
method was made, userid and password are interactively inquired.
Userid and password are saved i... | 2.859025 | 2.955585 | 0.96733 |
if text is None:
return 'None'
ret = _indent(text, amount=indent)
return ret.lstrip(' ') | def repr_text(text, indent) | Return a debug representation of a multi-line text (e.g. the result
of another repr...() function). | 6.870003 | 7.525999 | 0.912836 |
# pprint represents lists and tuples in one row if possible. We want one
# per row, so we iterate ourselves.
if _list is None:
return 'None'
if isinstance(_list, MutableSequence):
bm = '['
em = ']'
elif isinstance(_list, Iterable):
bm = '('
em = ')'
e... | def repr_list(_list, indent) | Return a debug representation of a list or tuple. | 5.350046 | 5.157012 | 1.037431 |
# pprint represents OrderedDict objects using the tuple init syntax,
# which is not very readable. Therefore, dictionaries are iterated over.
if _dict is None:
return 'None'
if not isinstance(_dict, Mapping):
raise TypeError("Object must be a mapping, but is a %s" %
... | def repr_dict(_dict, indent) | Return a debug representation of a dict or OrderedDict. | 3.764752 | 3.654255 | 1.030238 |
if timestamp is None:
return 'None'
dt = datetime_from_timestamp(timestamp)
ret = "%d (%s)" % (timestamp,
dt.strftime('%Y-%m-%d %H:%M:%S.%f %Z'))
return ret | def repr_timestamp(timestamp) | Return a debug representation of an HMC timestamp number. | 3.219038 | 2.95664 | 1.088749 |
# Note that in Python 2, "None < 0" is allowed and will return True,
# therefore we do an extra check for None.
if ts is None:
raise ValueError("HMC timestamp value must not be None.")
if ts < 0:
raise ValueError(
"Negative HMC timestamp value {} cannot be represented as... | def datetime_from_timestamp(ts) | Convert an :term:`HMC timestamp number <timestamp>` into a
:class:`~py:datetime.datetime` object.
The HMC timestamp number must be non-negative. This means the special
timestamp value -1 cannot be represented as datetime and will cause
``ValueError`` to be raised.
The date and time range supported... | 3.68514 | 3.397171 | 1.084767 |
if dt is None:
raise ValueError("datetime value must not be None.")
if dt.tzinfo is None:
# Apply default timezone to the timezone-naive input
dt = pytz.utc.localize(dt)
epoch_seconds = (dt - _EPOCH_DT).total_seconds()
ts = int(epoch_seconds * 1000)
return ts | def timestamp_from_datetime(dt) | Convert a :class:`~py:datetime.datetime` object into an
:term:`HMC timestamp number <timestamp>`.
The date and time range supported by this function has the following
bounds:
* The upper bounds is :attr:`py:datetime.datetime.max`, as follows:
* 9999-12-31 23:59:59 UTC, for 32-bit and 64-bit CPy... | 3.435698 | 4.701482 | 0.730769 |
if properties is None:
properties = {}
result = self.session.post(self._base_uri, body=properties)
# There should not be overlaps, but just in case there are, the
# returned props should overwrite the input props:
props = copy.deepcopy(properties)
pr... | def create(self, properties) | Create and configure a storage group.
The new storage group will be associated with the CPC identified by the
`cpc-uri` input property.
Authorization requirements:
* Object-access permission to the CPC that will be associated with
the new storage group.
* Task permis... | 4.85321 | 5.410991 | 0.896917 |
# We do here some lazy loading.
if not self._storage_volumes:
self._storage_volumes = StorageVolumeManager(self)
return self._storage_volumes | def storage_volumes(self) | :class:`~zhmcclient.StorageVolumeManager`: Access to the
:term:`storage volumes <storage volume>` in this storage group. | 6.126968 | 4.88896 | 1.253225 |
# We do here some lazy loading.
if not self._virtual_storage_resources:
self._virtual_storage_resources = \
VirtualStorageResourceManager(self)
return self._virtual_storage_resources | def virtual_storage_resources(self) | :class:`~zhmcclient.VirtualStorageResourceManager`: Access to the
:term:`virtual storage resources <Virtual Storage Resource>` in this
storage group. | 4.885727 | 3.938463 | 1.240516 |
# We do here some lazy loading.
if not self._cpc:
cpc_uri = self.get_property('cpc-uri')
cpc_mgr = self.manager.console.manager.client.cpcs
self._cpc = cpc_mgr.resource_object(cpc_uri)
return self._cpc | def cpc(self) | :class:`~zhmcclient.Cpc`: The :term:`CPC` to which this storage group
is associated.
The returned :class:`~zhmcclient.Cpc` has only a minimal set of
properties populated. | 5.515237 | 4.421077 | 1.247487 |
query_parms = []
if name is not None:
self.manager._append_query_parms(query_parms, 'name', name)
if status is not None:
self.manager._append_query_parms(query_parms, 'status', status)
query_parms_str = '&'.join(query_parms)
if query_parms_str:
... | def list_attached_partitions(self, name=None, status=None) | Return the partitions to which this storage group is currently
attached, optionally filtered by partition name and status.
Authorization requirements:
* Object-access permission to this storage group.
* Task permission to the "Configure Storage - System Programmer" task.
Param... | 2.874281 | 2.757231 | 1.042452 |
body = {
'adapter-port-uris': [p.uri for p in ports],
}
self.manager.session.post(
self.uri + '/operations/add-candidate-adapter-ports',
body=body) | def add_candidate_adapter_ports(self, ports) | Add a list of storage adapter ports to this storage group's candidate
adapter ports list.
This operation only applies to storage groups of type "fcp".
These adapter ports become candidates for use as backing adapters when
creating virtual storage resources when the storage group is att... | 4.541371 | 4.784651 | 0.949154 |
sg_cpc = self.cpc
adapter_mgr = sg_cpc.adapters
port_list = []
port_uris = self.get_property('candidate-adapter-port-uris')
if port_uris:
for port_uri in port_uris:
m = re.match(r'^(/api/adapters/[^/]*)/.*', port_uri)
adapter_... | def list_candidate_adapter_ports(self, full_properties=False) | Return the current candidate storage adapter port list of this storage
group.
The result reflects the actual list of ports used by the CPC, including
any changes that have been made during discovery. The source for this
information is the 'candidate-adapter-port-uris' property of the
... | 2.977488 | 2.697731 | 1.103701 |
result = self.session.post(self.cpc.uri + '/adapters', body=properties)
# There should not be overlaps, but just in case there are, the
# returned props should overwrite the input props:
props = copy.deepcopy(properties)
props.update(result)
name = props.get(self... | def create_hipersocket(self, properties) | Create and configure a HiperSockets Adapter in this CPC.
Authorization requirements:
* Object-access permission to the scoping CPC.
* Task permission to the "Create HiperSockets Adapter" task.
Parameters:
properties (dict): Initial property values.
Allowable pro... | 5.642114 | 4.841099 | 1.165461 |
# We do here some lazy loading.
if not self._ports:
family = self.get_property('adapter-family')
try:
port_type = self.port_type_by_family[family]
except KeyError:
port_type = None
self._ports = PortManager(self, po... | def ports(self) | :class:`~zhmcclient.PortManager`: Access to the :term:`Ports <Port>` of
this Adapter. | 4.896787 | 3.982337 | 1.229627 |
if self._port_uris_prop is None:
family = self.get_property('adapter-family')
try:
self._port_uris_prop = self.port_uris_prop_by_family[family]
except KeyError:
self._port_uris_prop = ''
return self._port_uris_prop | def port_uris_prop(self) | :term:`string`: Name of adapter property that specifies the adapter
port URIs, or the empty string ('') for adapters without ports.
For example, 'network-port-uris' for a network adapter. | 2.911953 | 2.580349 | 1.128511 |
if self._port_uri_segment is None:
family = self.get_property('adapter-family')
try:
self._port_uri_segment = self.port_uri_segment_by_family[
family]
except KeyError:
self._port_uri_segment = ''
return self... | def port_uri_segment(self) | :term:`string`: Adapter type specific URI segment for adapter port
URIs, or the empty string ('') for adapters without ports.
For example, 'network-ports' for a network adapter. | 3.329892 | 2.862792 | 1.163163 |
if self.get_property('adapter-family') != 'crypto':
return None
card_type = self.get_property('detected-card-type')
if card_type.startswith('crypto-express-'):
max_domains = self.manager.cpc.maximum_active_partitions
else:
raise ValueError("Un... | def maximum_crypto_domains(self) | Integer: The maximum number of crypto domains on this crypto adapter.
The following table shows the maximum number of crypto domains for
crypto adapters supported on IBM Z machine generations in DPM mode. The
corresponding LinuxONE machine generations are listed in the notes
below the t... | 6.797757 | 4.83476 | 1.406017 |
body = {'crypto-type': crypto_type}
if zeroize is not None:
body['zeroize'] = zeroize
self.manager.session.post(
self.uri + '/operations/change-crypto-type', body) | def change_crypto_type(self, crypto_type, zeroize=None) | Reconfigures a cryptographic adapter to a different crypto type.
This operation is only supported for cryptographic adapters.
The cryptographic adapter must be varied offline before its crypto
type can be reconfigured.
Authorization requirements:
* Object-access permission to ... | 3.5157 | 3.4146 | 1.029608 |
body = {'type': adapter_type}
self.manager.session.post(
self.uri + '/operations/change-adapter-type', body) | def change_adapter_type(self, adapter_type) | Reconfigures an adapter from one type to another, or to ungonfigured.
Currently, only storage adapters can be reconfigured, and their adapter
type is the supported storage protocol (FCP vs. FICON).
Storage adapter instances (i.e. :class:`~zhmcclient.Adapter` objects)
represent daughter ... | 6.273591 | 6.70444 | 0.935737 |
body = {}
result = self.manager.session.post(
self.uri + '/operations/stop',
body,
wait_for_completion=wait_for_completion,
operation_timeout=operation_timeout)
if wait_for_completion:
statuses = ["operating"]
if al... | def stop(self, wait_for_completion=True, operation_timeout=None,
status_timeout=None, allow_status_exceptions=False) | Stop this LPAR, using the HMC operation "Stop Logical
Partition". The stop operation stops the processors from
processing instructions.
This HMC operation has deferred status behavior: If the asynchronous
job on the HMC is complete, it takes a few seconds until the LPAR
status h... | 3.358942 | 3.218004 | 1.043797 |
if isinstance(exc, requests.exceptions.ConnectTimeout):
raise ConnectTimeout(_request_exc_message(exc), exc,
retry_timeout_config.connect_timeout,
retry_timeout_config.connect_retries)
elif isinstance(exc, requests.exceptions.ReadTimeout):
... | def _handle_request_exc(exc, retry_timeout_config) | Handle a :exc:`request.exceptions.RequestException` exception that was
raised. | 1.771455 | 1.773634 | 0.998771 |
if exc.args:
if isinstance(exc.args[0], Exception):
org_exc = exc.args[0]
if isinstance(org_exc, urllib3.exceptions.MaxRetryError):
reason_exc = org_exc.reason
message = str(reason_exc)
else:
message = str(org_exc.args[... | def _request_exc_message(exc) | Return a reasonable exception message from a
:exc:`request.exceptions.RequestException` exception.
The approach is to dig deep to the original reason, if the original
exception is present, skipping irrelevant exceptions such as
`urllib3.exceptions.MaxRetryError`, and eliminating useless object
repr... | 3.421068 | 3.276207 | 1.044216 |
if text is None:
text_repr = 'None'
elif len(text) > max_len:
text_repr = repr(text[0:max_len]) + '...'
else:
text_repr = repr(text)
return text_repr | def _text_repr(text, max_len=1000) | Return the input text as a Python string representation (i.e. using repr())
that is limited to a maximum length. | 1.978405 | 1.831084 | 1.080456 |
content_type = result.headers.get('content-type', None)
if content_type is None or content_type.startswith('application/json'):
# This function is only called when there is content expected.
# Therefore, a response without content will result in a ParseError.
try:
retur... | def _result_object(result) | Return the JSON payload in the HTTP response as a Python dict.
Parameters:
result (requests.Response): HTTP response object.
Raises:
zhmcclient.ParseError: Error parsing the returned JSON. | 3.367682 | 3.272503 | 1.029084 |
ret = RetryTimeoutConfig()
for attr in RetryTimeoutConfig._attrs:
value = getattr(self, attr)
if override_config and getattr(override_config, attr) is not None:
value = getattr(override_config, attr)
setattr(ret, attr, value)
return re... | def override_with(self, override_config) | Return a new configuration object that represents the configuration
from this configuration object acting as a default, and the specified
configuration object overriding that default.
Parameters:
override_config (:class:`~zhmcclient.RetryTimeoutConfig`):
The configuration... | 3.184766 | 2.785151 | 1.14348 |
if self._session_id is None:
return False
if verify:
try:
self.get('/api/console', logon_required=True)
except ServerAuthError:
return False
return True | def is_logon(self, verify=False) | Return a boolean indicating whether the session is currently logged on
to the HMC.
By default, this method checks whether there is a session-id set
and considers that sufficient for determining that the session is
logged on. The `verify` parameter can be used to verify the validity
... | 5.793538 | 5.919715 | 0.978685 |
if self._userid is None:
raise ClientAuthError("Userid is not provided.")
if self._password is None:
if self._get_password:
self._password = self._get_password(self._host, self._userid)
else:
raise ClientAuthError("Password is ... | def _do_logon(self) | Log on, unconditionally. This can be used to re-logon.
This requires credentials to be provided.
Raises:
:exc:`~zhmcclient.ClientAuthError`
:exc:`~zhmcclient.ServerAuthError`
:exc:`~zhmcclient.ConnectionError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcc... | 3.319466 | 3.161635 | 1.049921 |
retry = requests.packages.urllib3.Retry(
total=None,
connect=retry_timeout_config.connect_retries,
read=retry_timeout_config.read_retries,
method_whitelist=retry_timeout_config.method_whitelist,
redirect=retry_timeout_config.max_redirects)
... | def _new_session(retry_timeout_config) | Return a new `requests.Session` object. | 1.850678 | 1.745009 | 1.060555 |
session_uri = '/api/sessions/this-session'
self.delete(session_uri, logon_required=False)
self._session_id = None
self._session = None
self._headers.pop('X-API-Session', None) | def _do_logoff(self) | Log off, unconditionally.
Raises:
:exc:`~zhmcclient.ServerAuthError`
:exc:`~zhmcclient.ConnectionError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcclient.HTTPError` | 6.125429 | 7.525701 | 0.813935 |
if method == 'POST' and url.endswith('/api/sessions'):
# In Python 3 up to 3.5, json.loads() requires unicode strings.
if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \
isinstance(content, six.binary_type):
content = content.... | def _log_http_request(method, url, headers=None, content=None) | Log the HTTP request of an HMC REST API call, at the debug level.
Parameters:
method (:term:`string`): HTTP method name in upper case, e.g. 'GET'
url (:term:`string`): HTTP URL (base URL and operation URI)
headers (iterable): HTTP headers used for the request
content... | 4.04531 | 4.230929 | 0.956128 |
if method == 'POST' and url.endswith('/api/sessions'):
# In Python 3 up to 3.5, json.loads() requires unicode strings.
if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \
isinstance(content, six.binary_type):
content = content.... | def _log_http_response(method, url, status, headers=None, content=None) | Log the HTTP response of an HMC REST API call, at the debug level.
Parameters:
method (:term:`string`): HTTP method name in upper case, e.g. 'GET'
url (:term:`string`): HTTP URL (base URL and operation URI)
status (integer): HTTP status code
headers (iterable): HTTP ... | 3.571208 | 3.668683 | 0.973431 |
if logon_required:
self.logon()
url = self.base_url + uri
self._log_http_request('DELETE', url, headers=self.headers)
stats = self.time_stats_keeper.get_stats('delete ' + uri)
stats.begin()
req = self._session or requests
req_timeout = (self.r... | def delete(self, uri, logon_required=True) | Perform the HTTP DELETE method against the resource identified by a
URI.
A set of standard HTTP headers is automatically part of the request.
If the HMC session token is expired, this method re-logs on and retries
the operation.
Parameters:
uri (:term:`string`):
... | 3.001078 | 3.092723 | 0.970367 |
job_result_obj = self.session.get(self.uri)
job_status = job_result_obj['status']
if job_status == 'complete':
self.session.delete(self.uri)
op_status_code = job_result_obj['job-status-code']
if op_status_code in (200, 201):
op_result_... | def check_for_completion(self) | Check once for completion of the job and return completion status and
result if it has completed.
If the job completed in error, an :exc:`~zhmcclient.HTTPError`
exception is raised.
Returns:
: A tuple (status, result) with:
* status (:term:`string`): Completion st... | 2.256211 | 2.166304 | 1.041503 |
if operation_timeout is None:
operation_timeout = \
self.session.retry_timeout_config.operation_timeout
if operation_timeout > 0:
start_time = time.time()
while True:
job_status, op_result_obj = self.check_for_completion()
... | def wait_for_completion(self, operation_timeout=None) | Wait for completion of the job, then delete the job on the HMC and
return the result of the original asynchronous HMC operation, if it
completed successfully.
If the job completed in error, an :exc:`~zhmcclient.HTTPError`
exception is raised.
Parameters:
operation_ti... | 4.753313 | 2.946095 | 1.613428 |
request = current_request()
return request is not None and re.match(r'^django\.', request.__module__) | def supports(self, config, context) | Check whether this is a django request or not.
:param config: honeybadger configuration.
:param context: current honeybadger configuration.
:return: True if this is a django request, False else. | 15.380205 | 8.729347 | 1.761896 |
request = current_request()
payload = {
'url': request.build_absolute_uri(),
'component': request.resolver_match.app_name,
'action': request.resolver_match.func.__name__,
'params': {},
'session': {},
'cgi_data': dict(reque... | def generate_payload(self, config, context) | Generate payload by checking Django request object.
:param context: current context.
:param config: honeybadger configuration.
:return: a dict with the generated payload. | 3.369612 | 3.209895 | 1.049758 |
logger.debug('Called generic_div({}, {})'.format(a, b))
return a / b | def generic_div(a, b) | Simple function to divide two numbers | 4.529906 | 4.747963 | 0.954074 |
try:
from flask import request
except ImportError:
return False
else:
return bool(request) | def supports(self, config, context) | Check whether we are in a Flask request context.
:param config: honeybadger configuration.
:param context: current honeybadger configuration.
:return: True if this is a django request, False else. | 7.244771 | 4.302402 | 1.68389 |
from flask import current_app, session, request as _request
current_view = current_app.view_functions[_request.endpoint]
if hasattr(current_view, 'view_class'):
component = '.'.join((current_view.__module__, current_view.view_class.__name__))
else:
compo... | def generate_payload(self, config, context) | Generate payload by checking Flask request object.
:param context: current context.
:param config: honeybadger configuration.
:return: a dict with the generated payload. | 2.737763 | 2.596642 | 1.054347 |
from flask import request_tearing_down, got_request_exception
self.app = app
self.app.logger.info('Initializing Honeybadger')
self.report_exceptions = report_exceptions
self.reset_context_after_request = reset_context_after_request
self._initialize_honeybadger... | def init_app(self, app, report_exceptions=False, reset_context_after_request=False) | Initialize honeybadger and listen for errors.
:param Flask app: the Flask application object.
:param bool report_exceptions: whether to automatically report exceptions raised by Flask on requests
(i.e. by calling abort) or not.
:param bool reset_context_after_request: whether to reset ... | 3.506585 | 3.3636 | 1.04251 |
from flask import signals
if not signals.signals_available:
self.app.logger.warn('blinker needs to be installed in order to support %s'.format(description))
self.app.logger.info('Enabling {}'.format(description))
# Weak references won't work if handlers are methods ... | def _register_signal_handler(self, description, signal, handler) | Registers a handler for the given signal.
:param description: a short description of the signal to handle.
:param signal: the signal to handle.
:param handler: the function to use for handling the signal. | 7.95177 | 8.2471 | 0.96419 |
if config.get('DEBUG', False):
honeybadger.configure(environment='development')
honeybadger_config = {}
for key, value in iteritems(config):
if key.startswith(self.CONFIG_PREFIX):
honeybadger_config[key[len(self.CONFIG_PREFIX):].lower()] = value
... | def _initialize_honeybadger(self, config) | Initializes honeybadger using the given config object.
:param dict config: a dict or dict-like object that contains honeybadger configuration properties. | 2.860828 | 2.997114 | 0.954528 |
honeybadger.notify(exception)
if self.reset_context_after_request:
self._reset_context() | def _handle_exception(self, sender, exception=None) | Actual code handling the exception and sending it to honeybadger if it's enabled.
:param T sender: the object sending the exception event.
:param Exception exception: the exception to handle. | 8.536892 | 7.55982 | 1.129245 |
if plugin.name not in self._registered:
logger.info('Registering plugin %s' % plugin.name)
self._registered[plugin.name] = plugin
else:
logger.warn('Plugin %s already registered' % plugin.name) | def register(self, plugin) | Register the given plugin. Registration order is kept.
:param plugin: the plugin to register. | 2.228755 | 2.445664 | 0.911309 |
for name, plugin in iteritems(self._registered):
if plugin.supports(config, context):
logger.debug('Returning payload from plugin %s' % name)
return plugin.generate_payload(config, context)
logger.debug('No active plugin to generate payload')
... | def generate_payload(self, config=None, context=None) | Generate payload by iterating over registered plugins. Merges .
:param context: current context.
:param config: honeybadger configuration.
:return: a dict with the generated payload. | 4.298316 | 3.892788 | 1.104174 |
a = float(request.GET.get('a', '0'))
b = float(request.GET.get('b', '0'))
return JsonResponse({'result': a / b}) | def buggy_div(request) | A buggy endpoint to perform division between query parameters a and b. It will fail if b is equal to 0 or
either a or b are not float.
:param request: request object
:return: | 2.449738 | 2.603153 | 0.941066 |
from .._ascii import DAG
from .._echo import echo_via_pager
echo_via_pager(str(DAG(graph))) | def ascii(graph) | Format graph as an ASCII art. | 14.204096 | 11.882412 | 1.195388 |
import json
from pyld import jsonld
from renku.models._jsonld import asjsonld
output = getattr(jsonld, format)([
asjsonld(action) for action in graph.activities.values()
])
return json.dumps(output, indent=2) | def _jsonld(graph, format, *args, **kwargs) | Return formatted graph in JSON-LD ``format`` function. | 6.10049 | 5.907532 | 1.032663 |
import sys
from rdflib import ConjunctiveGraph
from rdflib.plugin import register, Parser
from rdflib.tools.rdf2dot import rdf2dot
register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')
g = ConjunctiveGraph().parse(
data=_jsonld(graph, 'expand'),
format='json... | def dot(graph, simple=True, debug=False, landscape=False) | Format graph as a dot file. | 2.326614 | 2.305333 | 1.009231 |
from itertools import chain
import re
path_re = re.compile(
r'file:///(?P<type>[a-zA-Z]+)/'
r'(?P<commit>\w+)'
r'(?P<path>.+)?'
)
inputs = g.query(
)
outputs = g.query(
)
activity_nodes = {}
artifact_nodes = {}
for source, ro... | def _rdf2dot_simple(g, stream) | Create a simple graph of processes and artifacts. | 2.368118 | 2.29395 | 1.032332 |
import cgi
import collections
import rdflib
from rdflib.tools.rdf2dot import LABEL_PROPERTIES, NODECOLOR
types = collections.defaultdict(set)
fields = collections.defaultdict(set)
nodes = {}
def node(x):
return nodes.setdefault(x, 'node{0}'.format(len(nodes)))
... | def _rdf2dot_reduced(g, stream) | A reduced dot graph.
Adapted from original source:
https://rdflib.readthedocs.io/en/stable/_modules/rdflib/tools/rdf2dot.html | 2.547671 | 2.521664 | 1.010313 |
from renku.models.provenance.activities import ProcessRun, WorkflowRun
for activity in graph.activities.values():
if not isinstance(activity, ProcessRun):
continue
elif isinstance(activity, WorkflowRun):
steps = activity.subprocesses.values()
else:
... | def makefile(graph) | Format graph as Makefile. | 4.934762 | 4.812548 | 1.025395 |
from rdflib import ConjunctiveGraph
from rdflib.plugin import register, Parser
register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')
click.echo(
ConjunctiveGraph().parse(
data=_jsonld(graph, 'expand'),
format='json-ld',
).serialize(format='nt'... | def nt(graph) | Format graph as n-tuples. | 3.755394 | 3.469204 | 1.082495 |
import pkg_resources
from git.index.fun import hook_path as get_hook_path
for hook in HOOKS:
hook_path = Path(get_hook_path(hook, client.repo.git_dir))
if hook_path.exists():
if not force:
click.echo(
'Hook already exists. Skipping {0}'.f... | def install(client, force) | Install Git hooks. | 2.924202 | 2.728989 | 1.071533 |
from git.index.fun import hook_path as get_hook_path
for hook in HOOKS:
hook_path = Path(get_hook_path(hook, client.repo.git_dir))
if hook_path.exists():
hook_path.unlink() | def uninstall(client) | Uninstall Git hooks. | 4.634419 | 3.777212 | 1.226942 |
if datetime_fmt and isinstance(cell, datetime):
return cell.strftime(datetime_fmt)
return cell | def format_cell(cell, datetime_fmt=None) | Format a cell. | 3.164407 | 3.055362 | 1.03569 |
if isinstance(headers, dict):
attrs = headers.keys()
# if mapping is not specified keep original
names = [
key if value is None else value for key, value in headers.items()
]
else:
attrs = names = headers
table = [(
format_cell(cell, datetime_... | def tabulate(collection, headers, datetime_fmt='%Y-%m-%d %H:%M:%S', **kwargs) | Pretty-print a collection. | 5.305233 | 5.329136 | 0.995514 |
output = {}
for k, v in value.items():
inst = DatasetFile.from_jsonld(v)
output[inst.path] = inst
return output | def _convert_dataset_files(value) | Convert dataset files. | 5.208471 | 5.202302 | 1.001186 |
from renku.api._git import _expand_directories
def fmt_path(path):
return str(Path(path).absolute().relative_to(client.path))
files = {
fmt_path(source): fmt_path(file_or_dir)
for file_or_dir in sources
for source in _expand_directories((file_or_dir, ))
}
... | def remove(ctx, client, sources) | Remove files and check repository for potential problems. | 4.460354 | 4.406829 | 1.012146 |
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 in SUFFIXES.items():
if url.endswith(suffix):
if old_priori... | def find_release(package, releases, dependencies=None) | Return the best release. | 2.939902 | 2.855024 | 1.029729 |
# 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 CWL.
if can_be_cwl and filepath.endswith('.cwl'):
return True
retu... | def _safe_path(filepath, can_be_cwl=False) | Check if the path should be used in output. | 5.717729 | 5.286663 | 1.081538 |
from renku.models._tabulate import tabulate
click.echo(
tabulate(
datasets,
headers=OrderedDict((
('short_id', 'id'),
('name', None),
('created', None),
('authors_csv', 'authors'),
)),
)
... | def tabular(client, datasets) | Format datasets with a tabular output. | 5.564604 | 5.570752 | 0.998896 |
from renku.models._json import dumps
from renku.models._jsonld import asjsonld
data = [
asjsonld(
dataset,
basedir=os.path.relpath(
'.', start=str(dataset.__reference__.parent)
)
) for dataset in datasets
]
click.echo(dumps(da... | def jsonld(client, datasets) | Format datasets as JSON-LD. | 5.814986 | 5.560704 | 1.045728 |
try:
submodules = node.submodules
if submodules:
submodule = ':'.join(submodules)
return click.style(submodule, fg='green') + '@' + click.style(
node.commit.hexsha[:8], fg='yellow'
)
except KeyError:
pass
return click.style(no... | def _format_sha1(graph, node) | Return formatted text with the submodule information. | 3.908655 | 3.281415 | 1.191149 |
if isinstance(value, (list, tuple)):
return [
CommandLineBinding(**item) if isinstance(item, dict) else item
for item in value
]
return shlex.split(value) | def convert_arguments(value) | Convert arguments from various input formats. | 4.543941 | 4.25471 | 1.067979 |
ctx.obj = LocalClient(
path=path,
renku_home=renku_home,
use_external_storage=use_external_storage,
) | def cli(ctx, path, renku_home, use_external_storage) | Check common Renku commands used in various situations. | 2.516641 | 2.299409 | 1.094473 |
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 outputs:
click.secho(
'All files were generated from the latest inputs.', fg='green'
)
sys.ex... | def update(client, revision, no_output, siblings, paths) | Update existing files by rerunning their outdated workflow. | 4.855447 | 4.744384 | 1.023409 |
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.path.join(path, 'config.yml') | def config_path(path=None, final=False) | Return config path. | 2.662292 | 2.440294 | 1.090972 |
try:
with open(config_path(path, final=final), 'r') as configfile:
return yaml.safe_load(configfile) or {}
except FileNotFoundError:
return {} | def read_config(path=None, final=False) | Read Renku configuration. | 3.134948 | 3.028176 | 1.035259 |
with open(config_path(path, final=final), 'w+') as configfile:
yaml.dump(config, configfile, default_flow_style=False) | def write_config(config, path, final=False) | Write Renku configuration. | 2.842604 | 2.896233 | 0.981483 |
if ctx.obj is None:
ctx.obj = {}
ctx.obj['config_path'] = value
ctx.obj['config'] = read_config(value)
return value | def config_load(ctx, param, value) | Print application config path. | 2.810399 | 2.525223 | 1.112931 |
# 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 = {}
config = ctx.obj['config']
project_enabled =... | def with_config(f) | Add config to function. | 2.971689 | 2.910008 | 1.021196 |
if not value or ctx.resilient_parsing:
return
click.echo(config_path(os.environ.get('RENKU_CONFIG')))
ctx.exit() | def print_app_config_path(ctx, param, value) | Print application config path. | 3.569684 | 3.354895 | 1.064023 |
# FIXME check default directory mode
project_path = Path(path).absolute().joinpath(RENKU_HOME)
project_path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
return str(project_path) | def create_project_config_path(
path, mode=0o777, parents=False, exist_ok=False
) | Create new project configuration folder. | 5.164571 | 5.209619 | 0.991353 |
project_path = Path(path or '.').absolute().joinpath(RENKU_HOME)
if project_path.exists() and project_path.is_dir():
return str(project_path) | def get_project_config_path(path=None) | Return project configuration folder if exist. | 4.266126 | 3.79357 | 1.124568 |
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_project_config_path(parent)
if project_path:
return pr... | def find_project_config_path(path=None) | Find project config path. | 2.135514 | 1.986024 | 1.075271 |
# 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(member, parent=parent)
yield from _nodes(member)
... | def _nodes(output, parent=None) | Yield nodes from entities. | 5.819522 | 4.789079 | 1.215165 |
kwargs.setdefault('metadata', {})
kwargs['metadata']['jsonldPredicate'] = {'mapSubject': key}
kwargs.setdefault('default', attr.Factory(list))
def converter(value):
if isinstance(value, dict):
result = []
for k, v in iteritems(value):
if not... | def mapped(cls, key='id', **kwargs) | Create list of instances from a mapping. | 3.827036 | 3.815246 | 1.00309 |
attrs = fields(inst.__class__)
rv = dict_factory()
def convert_value(v):
if isinstance(v, Path):
v = str(v)
return os.path.relpath(v, str(basedir)) if basedir else v
return v
for a in attrs:
if a.name.startswith('__'):
continue
... | def ascwl(
inst,
recurse=True,
filter=None,
dict_factory=dict,
retain_collection_types=False,
basedir=None,
) | Return the ``attrs`` attribute values of *inst* as a dict.
Support ``jsonldPredicate`` in a field metadata for generating
mappings from lists.
Adapted from ``attr._funcs``. | 2.253819 | 2.207687 | 1.020896 |
class_name = data.get('class', None)
cls = cls.registry.get(class_name, cls)
if __reference__:
with with_reference(__reference__):
self = cls(
**{k: v
for k, v in iteritems(data) if k != 'class'}
)
... | def from_cwl(cls, data, __reference__=None) | Return an instance from CWL data. | 2.747592 | 2.638035 | 1.04153 |
import yaml
with path.open(mode='r') as fp:
self = cls.from_cwl(yaml.safe_load(fp), __reference__=path)
return self | def from_yaml(cls, path) | Return an instance from a YAML file. | 6.924634 | 6.707411 | 1.032385 |
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()
if not force and tpl_path.exists():
click.confi... | def template(client, force) | Render templated configuration files. | 3.083673 | 3.038133 | 1.014989 |
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:
args = ['cwl-runner', activity.path]
if job:
job_file = ... | def rerun(client, run, job) | Re-run existing workflow or tool using CWL runner. | 3.961304 | 3.701006 | 1.070332 |
if isinstance(value, File):
return os.path.relpath(
str((client.workflow_path / value.path).resolve())
)
return value | def _format_default(client, value) | Format default values. | 6.071815 | 6.060686 | 1.001836 |
for input_ in workflow.inputs:
click.echo(
'{id}: {default}'.format(
id=input_.id,
default=_format_default(client, input_.default),
)
)
sys.exit(0) | def show_inputs(client, workflow) | Show workflow inputs and exit. | 3.845943 | 3.659793 | 1.050864 |
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.prompt(
'{0.id} ({0.type})'.format(input_),
... | def edit_inputs(client, workflow) | Edit workflow inputs. | 4.179832 | 4.002629 | 1.044271 |
graph = Graph(client)
outputs = graph.build(paths=paths, revision=revision)
# Check or extend siblings of outputs.
outputs = siblings(graph, outputs)
output_paths = {node.path for node in outputs}
# Normalize and check all starting paths.
roots = {graph.normalize_path(root) for root i... | def rerun(client, revision, roots, siblings, inputs, paths) | Recreate files generated by a sequence of ``run`` commands. | 6.034076 | 6.021332 | 1.002116 |
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_3_4(client):
with old_path.open('r') as fp:
... | def datasets(ctx, client) | Migrate dataset metadata. | 4.175218 | 3.997996 | 1.044328 |
click.secho('Use "renku storage pull" instead.', fg='red', err=True)
ctx.exit(2) | def path(ctx, paths) | DEPRECATED: use 'renku storage pull'. | 11.028033 | 4.04521 | 2.726196 |
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:
registry_url = None
remote_branch = repo.head.reference.tracking_branch()
i... | def detect_registry_url(client, auto_login=True) | Return a URL of the Docker registry. | 3.151392 | 3.147972 | 1.001086 |
if isinstance(obj, UUID):
return obj.hex
elif isinstance(obj, datetime.datetime):
return obj.isoformat()
return super().default(obj) | def default(self, obj) | Encode more types. | 2.77099 | 2.605579 | 1.063483 |
working_dir = client.repo.working_dir
mapped_std = _mapped_std_streams(client.candidate_paths)
factory = CommandLineToolFactory(
command_line=command_line,
directory=os.getcwd(),
working_dir=working_dir,
successCodes=success_codes,
**{
name: os.path.r... | def run(client, outputs, no_output, success_codes, isolation, command_line) | Tracking work on a specific problem. | 4.642105 | 4.558013 | 1.018449 |
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_parse(stop)
paths = (
str(client.path / item.a_path)
... | def log(client, revision, format, no_output, paths) | Show logs for a file. | 7.5281 | 7.769716 | 0.968903 |
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.active_branch))
if status['outdated']:
click.echo(
'Files generated fr... | def status(ctx, client, revision, no_output, path) | Show a status of the repository. | 3.272918 | 3.292335 | 0.994102 |
if not value:
value = os.path.basename(ctx.params['directory'].rstrip(os.path.sep))
return value | def validate_name(ctx, param, value) | Validate a project name. | 4.384735 | 3.534716 | 1.240477 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.