text
stringlengths
18
773k
def create(self, validated_data): """Create ``Relation`` object and add partitions of ``Entities``.""" # `partitions` field is renamed to `relationpartition_set` based on source of nested serializer partitions = validated_data.pop('relationpartition_set') with transaction.atomic(): ...
def update(self, instance, validated_data): """Update ``Relation``.""" # `partitions` field is renamed to `relationpartition_set` based on source of nested serializer partitions = validated_data.pop('relationpartition_set', None) with transaction.atomic(): instance = super()...
def output(file_like_object, path, verbose=False): """Display or save file like object.""" if not path: for line in file_like_object: if verbose: print_info(line.rstrip()) else: print(line.rstrip()) else: try: object_file = ...
def _print_level(level, msg): """Print the information in Unicode safe manner.""" for l in str(msg.rstrip()).split("\n"): print("{0:<9s}{1}".format(level, str(l)))
def get_process_definition_start(fname, slug): """Find the first line of process definition. The first line of process definition is the line with a slug. :param str fname: Path to filename with processes :param string slug: process slug :return: line where the process definiton starts :rtype:...
def get_processes(process_dir, base_source_uri): """Find processes in path. :param str process_dir: Path to the directory where to search for processes :param str base_source_uri: Base URL of the source code repository with process definitions :return: Dictionary of processes where keys are URLs pointi...
def setup(app): """Register directives. When sphinx loads the extension (= imports the extension module) it also executes the setup() function. Setup is the way extension informs Sphinx about everything that the extension enables: which config_values are introduced, which custom nodes/directives/ro...
def make_field(self, field_name, field_body): """Fill content into nodes. :param string field_name: Field name of the field :param field_name: Field body if the field :type field_name: str or instance of docutils.nodes :return: field instance filled with given name and body ...
def make_properties_list(self, field): """Fill the ``field`` into a properties list and return it. :param dict field: the content of the property list to make :return: field_list instance filled with given field :rtype: nodes.field_list """ properties_list = nodes.field...
def make_process_header(self, slug, typ, version, source_uri, description, inputs): """Generate a process definition header. :param str slug: process' slug :param str typ: process' type :param str version: process' version :param str source_uri: url to the process definition ...
def make_process_node(self, process): """Fill the content of process definiton node. :param dict process: process data as given from yaml.load function :return: process node """ name = process['name'] slug = process['slug'] typ = process['type'] version ...
def run(self): """Create a list of process definitions.""" config = self.state.document.settings.env.config # Get all processes: processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url) process_nodes = [] for process in sorted(proces...
def run(self): """Create a category tree.""" config = self.state.document.settings.env.config # Group processes by category processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url) processes.sort(key=itemgetter('category')) categorize...
def run(self): """Create a type list.""" config = self.state.document.settings.env.config # Group processes by category processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url) processes.sort(key=itemgetter('type')) processes_by_types...
async def get(self, file_stream, pid, vendor_specific=None): """MNRead.get() Retrieve the SciObj bytes and write them to a file or other stream. Args: file_stream: Open file-like object Stream to which the SciObj bytes will be written. pid: str ...
async def synchronize(self, pid, vendor_specific=None): """Send an object synchronization request to the CN.""" return await self._request_pyxb( "post", ["synchronize", pid], {}, mmp_dict={"pid": pid}, vendor_specific=vendor_specific, )
def _datetime_to_iso8601(self, query_dict): """Encode any datetime query parameters to ISO8601.""" return { k: v if not isinstance(v, datetime.datetime) else v.isoformat() for k, v in list(query_dict.items()) }
def to_representation(self, value): """Project outgoing native value.""" value = apply_subfield_projection(self, value, deep=True) return super().to_representation(value)
def synchronizeResponse(self, pid, vendorSpecific=None): """CNRead.synchronize(session, pid) → boolean POST /synchronize. Args: pid: vendorSpecific: """ mmp_dict = {'pid': pid} return self.POST(['synchronize'], fields=mmp_dict, headers=vendorSpecific)
def synchronize(self, pid, vendorSpecific=None): """See Also: synchronizeResponse() Args: pid: vendorSpecific: Returns: """ response = self.synchronizeResponse(pid, vendorSpecific) return self._read_boolean_response(response)
def handle(self, *args, **options): """Command handle.""" verbosity = int(options['verbosity']) if self.has_filter(options): self.filter_indices(options, verbosity) else: # Process all indices. index_builder.build()
def validate_bagit_file(bagit_path): """Check if a BagIt file is valid. Raises: ServiceFailure If the BagIt zip archive file fails any of the following checks: - Is a valid zip file. - The tag and manifest files are correctly formatted. - Contains all th...
def create_bagit_stream(dir_name, payload_info_list): """Create a stream containing a BagIt zip archive. Args: dir_name : str The name of the root directory in the zip file, under which all the files are placed (avoids "zip bombs"). payload_info_list: list L...
def _add_path(dir_name, payload_info_list): """Add a key with the path to each payload_info_dict.""" for payload_info_dict in payload_info_list: file_name = payload_info_dict['filename'] or payload_info_dict['pid'] payload_info_dict['path'] = d1_common.utils.filesystem.gen_safe_path( ...
def _add_payload_files(zip_file, payload_info_list): """Add the payload files to the zip.""" payload_byte_count = 0 payload_file_count = 0 for payload_info_dict in payload_info_list: zip_file.write_iter(payload_info_dict['path'], payload_info_dict['iter']) payload_byte_count += payload_i...
def _add_tag_files( zip_file, dir_name, payload_info_list, payload_byte_count, payload_file_count ): """Generate the tag files and add them to the zip.""" tag_info_list = [] _add_tag_file(zip_file, dir_name, tag_info_list, _gen_bagit_text_file_tup()) _add_tag_file( zip_file, dir_name...
def _add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list): """Generate the manifest files and add them to the zip.""" for checksum_algorithm in _get_checksum_algorithm_set(payload_info_list): _add_tag_file( zip_file, dir_name, tag_info_list, ...
def _add_tag_manifest_file(zip_file, dir_name, tag_info_list): """Generate the tag manifest file and add it to the zip.""" _add_tag_file( zip_file, dir_name, tag_info_list, _gen_tag_manifest_file_tup(tag_info_list) )
def _add_tag_file(zip_file, dir_name, tag_info_list, tag_tup): """Add a tag file to zip_file and record info for the tag manifest file.""" tag_name, tag_str = tag_tup tag_path = d1_common.utils.filesystem.gen_safe_path(dir_name, tag_name) tag_iter = _create_and_add_tag_iter(zip_file, tag_path, tag_str) ...
def handle(self, *args, **options): """Command handle.""" verbosity = int(options['verbosity']) skip_mapping = options['skip_mapping'] if self.has_filter(options): self.filter_indices(options, verbosity, skip_mapping=skip_mapping) else: # Process all indi...
def pyxb_to_dict(node_list_pyxb): """ Returns: dict : Representation of ``node_list_pyxb``, keyed on the Node identifier (``urn:node:*``). Example:: { u'urn:node:ARCTIC': { 'base_url': u'https://arcticdata.io/metacat/d1/mn', 'description': u'The US National Science Foundati...
def filter_queryset(self, request, queryset, view): """Filter permissions queryset.""" user = request.user app_label = queryset.model._meta.app_label # pylint: disable=protected-access model_name = queryset.model._meta.model_name # pylint: disable=protected-access kwargs = {}...
def has_object_permission(self, request, view, obj): """Check object permissions.""" # admins can do anything if request.user.is_superuser: return True # `share` permission is required for editing permissions if 'permissions' in view.action: self.perms_ma...
def get_active_subject_set(self, request): """Get a set containing all subjects for which the current connection has been successfully authenticated.""" # Handle complete certificate in vendor specific extension. if django.conf.settings.DEBUG_GMN: if 'HTTP_VENDOR_INCLUDE_CERT...
def log_setup(debug_bool): """Set up logging. We output only to stdout. Instead of also writing to a log file, redirect stdout to a log file when the script is executed from cron. """ level = logging.DEBUG if debug_bool else logging.INFO logging.config.dictConfig( { "vers...
def connect(self, dsn): """Connect to DB. dbname: the database name user: user name used to authenticate password: password used to authenticate host: database host address (defaults to UNIX socket if not provided) port: connection port number (defaults to 5432 if not provided) ...
def get_query_param(self, key, default=None): """Get query parameter uniformly for GET and POST requests.""" value = self.request.query_params.get(key, None) if value is None: value = self.request.data.get(key, None) if value is None: value = default retur...
def get_query_params(self): """Get combined query parameters (GET and POST).""" params = self.request.query_params.copy() params.update(self.request.data) return params
def order_search(self, search): """Order given search by the ordering parameter given in request. :param search: ElasticSearch query object """ ordering = self.get_query_param('ordering', self.ordering) if not ordering: return search sort_fields = [] ...
def filter_search(self, search): """Filter given search by the filter parameter given in request. :param search: ElasticSearch query object """ builder = QueryBuilder( self.filtering_fields, self.filtering_map, self ) search, unmatche...
def filter_permissions(self, search): """Filter given query based on permissions of the user in the request. :param search: ElasticSearch query object """ user = self.request.user if user.is_superuser: return search if user.is_anonymous: user = g...
def paginate_response(self, queryset, serializers_kwargs={}): """Optionally return paginated response. If pagination parameters are provided in the request, then paginated response is returned, otherwise response is not paginated. """ page = self.paginate_queryset(queryset) ...
def search(self): """Handle the search request.""" search = self.document_class().search() # pylint: disable=not-callable search = self.custom_filter(search) search = self.filter_search(search) search = self.order_search(search) search = self.filter_permissions(search)...
def list_with_post(self, request): """Endpoint handler.""" if self.is_search_request(): search = self.search() page = self.paginate_queryset(search) if page is None: items = search else: items = page try: ...
def getattr(self, path, fh): """Called by FUSE when the attributes for a file or directory are required. Returns a dictionary with keys identical to the stat C structure of stat(2). st_atime, st_mtime and st_ctime should be floats. On OSX, st_nlink should count all files inside the dire...
def readdir(self, path, fh): """Called by FUSE when a directory is opened. Returns a list of file and directory names for the directory. """ log.debug('readdir(): {}'.format(path)) try: dir = self._directory_cache[path] except KeyError: dir = sel...
def open(self, path, flags): """Called by FUSE when a file is opened. Determines if the provided path and open flags are valid. """ log.debug('open(): {}'.format(path)) # ONEDrive is currently read only. Anything but read access is denied. if (flags & self._READ_ONLY_AC...
def get_inline_expression(self, text): """Extract an inline expression from the given text.""" text = text.strip() if not text.startswith(self.inline_tags[0]) or not text.endswith(self.inline_tags[1]): return return text[2:-2]
def _filter_queryset(self, queryset): """Filter queryset by entity, label and position. Due to a bug in django-filter these filters have to be applied manually: https://github.com/carltongibson/django-filter/issues/883 """ entities = self.request.query_params.getlist('en...
def update(self, request, *args, **kwargs): """Update the ``Relation`` object. Reject the update if user doesn't have ``EDIT`` permission on the collection referenced in the ``Relation``. """ instance = self.get_object() if (not request.user.has_perm('edit_collection', i...
def _process_permission(perm): """Rebuild indexes affected by the given permission.""" # XXX: Optimize: rebuild only permissions, not whole document codename = perm.permission.codename if not codename.startswith('view') and not codename.startswith('owner'): return index_builder.build(perm.c...
def parse_response(response, encoding='utf-8'): """Parse a multipart Requests.Response into a tuple of BodyPart objects. Args: response: Requests.Response encoding: The parser will assume that any text in the HTML body is encoded with this encoding when decoding it for use in the `...
def parse_str(mmp_bytes, content_type, encoding='utf-8'): """Parse multipart document bytes into a tuple of BodyPart objects. Args: mmp_bytes: bytes Multipart document. content_type : str Must be on the form, ``multipart/form-data; boundary=<BOUNDARY>``, where ``<BOUNDARY>`...
def normalize(body_part_tup,): """Normalize a tuple of BodyPart objects to a string. Normalization is done by sorting the body_parts by the Content- Disposition headers, which is typically on the form, ``form-data; name="name_of_part``. """ return '\n\n'.join( [ '{}\n\n{}'.form...
def is_multipart(header_dict): """ Args: header_dict : CaseInsensitiveDict Returns: bool: ``True`` if ``header_dict`` has a Content-Type key (case insensitive) with value that begins with 'multipart'. """ return ( {k.lower(): v for k, v in header_dict.items()} .get('content-ty...
def _split_path_by_reserved_name(self, path): """Return: object_tree_path, resolver, controlled_path.""" for i, e in enumerate(path): if e in self._resolvers or e == self._get_readme_filename(): return path[:i], path[i], path[i + 1 :] raise d1_onedrive.impl.onedrive_e...
def _generate_readme_text(self, object_tree_path): """Generate a human readable description of the folder in text format.""" wdef_folder = self._object_tree.get_source_tree_folder(object_tree_path) res = StringIO() if len(object_tree_path): folder_name = object_tree_path[-1]...
def _serialize_data(self, data): """Return serialized data or list of ids, depending on `hydrate_data` query param.""" if self.request and self.request.query_params.get('hydrate_data', False): serializer = DataSerializer(data, many=True, read_only=True) serializer.bind('data', se...
def _filter_queryset(self, perms, queryset): """Filter object objects by permissions of user in request.""" user = self.request.user if self.request else AnonymousUser() return get_objects_for_user(user, perms, queryset)
def get_data(self, collection): """Return serialized list of data objects on collection that user has `view` permission on.""" data = self._filter_queryset('view_data', collection.data.all()) return self._serialize_data(data)
def get_fields(self): """Dynamically adapt fields based on the current request.""" fields = super(CollectionSerializer, self).get_fields() if self.request.method == "GET": fields['data'] = serializers.SerializerMethodField() else: fields['data'] = serializers.Pri...
def load_engines(manager, class_name, base_module, engines, class_key='ENGINE', engine_type='engine'): """Load engines.""" loaded_engines = {} for module_name_or_dict in engines: if not isinstance(module_name_or_dict, dict): module_name_or_dict = { class_key: module_name...
def is_sysmeta_pyxb(sysmeta_pyxb): """Args: sysmeta_pyxb: Object that may or may not be a SystemMetadata PyXB object. Returns: bool: - ``True`` if ``sysmeta_pyxb`` is a SystemMetadata PyXB object. - ``False`` if ``sysmeta_pyxb`` is not a PyXB object or is a PyXB object of a type...
def normalize_in_place(sysmeta_pyxb, reset_timestamps=False): """Normalize SystemMetadata PyXB object in-place. Args: sysmeta_pyxb: SystemMetadata PyXB object to normalize. reset_timestamps: bool ``True``: Timestamps in the SystemMetadata are set to a standard value so that ...
def are_equivalent_pyxb(a_pyxb, b_pyxb, ignore_timestamps=False): """Determine if SystemMetadata PyXB objects are semantically equivalent. Normalize then compare SystemMetadata PyXB objects for equivalency. Args: a_pyxb, b_pyxb : SystemMetadata PyXB objects to compare reset_timestamps: bool ...
def are_equivalent_xml(a_xml, b_xml, ignore_timestamps=False): """Determine if two SystemMetadata XML docs are semantically equivalent. Normalize then compare SystemMetadata XML docs for equivalency. Args: a_xml, b_xml: bytes UTF-8 encoded SystemMetadata XML docs to compare ignore_tim...
def clear_elements(sysmeta_pyxb, clear_replica=True, clear_serial_version=True): """{clear_replica} causes any replica information to be removed from the object. {clear_replica} ignores any differences in replica information, as this information is often different between MN and CN. """ if clear_r...
def update_elements(dst_pyxb, src_pyxb, el_list): """Copy elements specified in ``el_list`` from ``src_pyxb`` to ``dst_pyxb`` Only elements that are children of root are supported. See SYSMETA_ROOT_CHILD_LIST. If an element in ``el_list`` does not exist in ``src_pyxb``, it is removed from ``dst_py...
def get_full_perm(perm, obj): """Join action with the content type of ``obj``. Permission is returned in the format of ``<action>_<object_type>``. """ ctype = ContentType.objects.get_for_model(obj) # Camel case class names are converted into a space-separated # content types, so spaces have to ...
def copy_permissions(src_obj, dest_obj): """Copy permissions form ``src_obj`` to ``dest_obj``.""" def _process_permission(codename, user_or_group, dest_obj, relabel): """Process single permission.""" if relabel: codename = change_perm_ctype(codename, dest_obj) if codename...
def fetch_user(query): """Get user by ``pk`` or ``username``. Raise error if it doesn't exist.""" user_filter = {'pk': query} if query.isdigit() else {'username': query} user_model = get_user_model() try: return user_model.objects.get(**user_filter) except user_model.DoesNotExist: r...
def fetch_group(query): """Get group by ``pk`` or ``name``. Raise error if it doesn't exist.""" group_filter = {'pk': query} if query.isdigit() else {'name': query} try: return Group.objects.get(**group_filter) except Group.DoesNotExist: raise exceptions.ParseError("Unknown group: {}".f...
def check_owner_permission(payload, allow_user_owner): """Raise ``PermissionDenied``if ``owner`` found in ``data``.""" for entity_type in ['users', 'groups']: for perm_type in ['add', 'remove']: for perms in payload.get(entity_type, {}).get(perm_type, {}).values(): if 'owner'...
def check_public_permissions(payload): """Raise ``PermissionDenied`` if public permissions are too open.""" allowed_public_permissions = ['view', 'add', 'download'] for perm_type in ['add', 'remove']: for perm in payload.get('public', {}).get(perm_type, []): if perm not in allowed_public...
def check_user_permissions(payload, user_pk): """Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``.""" for perm_type in ['add', 'remove']: user_pks = payload.get('users', {}).get(perm_type, {}).keys() if user_pk in user_pks: raise exceptions.PermissionDenied("You cannot ...
def remove_permission(payload, permission): """Remove all occurrences of ``permission`` from ``payload``.""" payload = copy.deepcopy(payload) for entity_type in ['users', 'groups']: for perm_type in ['add', 'remove']: for perms in payload.get(entity_type, {}).get(perm_type, {}).values()...
def update_permission(obj, data): """Update object permissions.""" full_permissions = get_all_perms(obj) def apply_perm(perm_func, perms, entity): """Apply permissions using given ``perm_func``. ``perm_func`` is intended to be ``assign_perms`` or ``remove_perms`` shortcut function ...
def assign_contributor_permissions(obj, contributor=None): """Assign all permissions to object's contributor.""" for permission in get_all_perms(obj): assign_perm(permission, contributor if contributor else obj.contributor, obj)
async def start(self): """Start process execution.""" # Workaround for pylint issue #1469 # (https://github.com/PyCQA/pylint/issues/1469). self.proc = await subprocess.create_subprocess_exec( # pylint: disable=no-member *shlex.split(self.command), stdin=subproces...
async def run_script(self, script): """Execute the script and save results.""" script = os.linesep.join(['set -x', 'set +B', script, 'exit']) + os.linesep self.proc.stdin.write(script.encode('utf-8')) await self.proc.stdin.drain() self.proc.stdin.close()
async def terminate(self): """Terminate a running script.""" self.proc.terminate() await asyncio.wait_for(self.proc.wait(), self.kill_delay) if self.proc.returncode is None: self.proc.kill() await self.proc.wait() await super().terminate()
async def _make_connection(self): """Construct a connection to Redis.""" return await aioredis.create_redis( 'redis://{}:{}'.format( self._redis_params.get('host', 'localhost'), self._redis_params.get('port', 6379) ), db=int(self._redis...
async def _call_redis(self, meth, *args, **kwargs): """Perform a Redis call and handle connection dropping.""" while True: try: if not self._redis: self._redis = await self._make_connection() return await meth(self._redis, *args, **kwargs) ...
async def clear_queue(self): """Reset the executor queue channel to an empty state.""" conn = await self._make_connection() try: script = """ local keys = redis.call('KEYS', ARGV[1]) redis.call('DEL', unpack(keys)) """ await con...
def terminate(self): """Stop the standalone manager.""" logger.info(__( "Terminating Resolwe listener on channel '{}'.", state.MANAGER_EXECUTOR_CHANNELS.queue )) self._should_stop = True
def _queue_response_channel(self, obj): """Generate the feedback channel name from the object's id. :param obj: The Channels message object. """ return '{}.{}'.format(state.MANAGER_EXECUTOR_CHANNELS.queue_response, obj[ExecutorProtocol.DATA_ID])
async def _send_reply(self, obj, reply): """Send a reply with added standard fields back to executor. :param obj: The original Channels message object to which we're replying. :param reply: The message contents dictionary. The data id is added automatically (``reply`` is...
def hydrate_spawned_files(self, exported_files_mapper, filename, data_id): """Pop the given file's map from the exported files mapping. :param exported_files_mapper: The dict of file mappings this process produced. :param filename: The filename to format and remove from the ...
def handle_update(self, obj, internal_call=False): """Handle an incoming ``Data`` object update request. :param obj: The Channels message object. Command object format: .. code-block:: none { 'command': 'update', 'data_id': [id of th...
def handle_finish(self, obj): """Handle an incoming ``Data`` finished processing request. :param obj: The Channels message object. Command object format: .. code-block:: none { 'command': 'finish', 'data_id': [id of the :class:`~reso...
def handle_abort(self, obj): """Handle an incoming ``Data`` abort processing request. .. IMPORTANT:: This only makes manager's state consistent and doesn't affect Data object in any way. Any changes to the Data must be applied over ``handle_update`` method. ...
def handle_log(self, obj): """Handle an incoming log processing request. :param obj: The Channels message object. Command object format: .. code-block:: none { 'command': 'log', 'message': [log message] } """ ...
async def push_stats(self): """Push current stats to Redis.""" snapshot = self._make_stats() try: serialized = json.dumps(snapshot) await self._call_redis(aioredis.Redis.set, state.MANAGER_LISTENER_STATS, serialized) await self._call_redis(aioredis.Redis.expir...
def check_critical_load(self): """Check for critical load and log an error if necessary.""" if self.load_avg.intervals['1m'].value > 1: if self.last_load_level == 1 and time.time() - self.last_load_log < 30: return self.last_load_log = time.time() self...
async def run(self): """Run the main listener run loop. Doesn't return until :meth:`terminate` is called. """ logger.info(__( "Starting Resolwe listener on channel '{}'.", state.MANAGER_EXECUTOR_CHANNELS.queue )) while not self._should_stop: ...
def dokanMain(self, dokanOptions, dokanOperations): """Issue callback to start dokan drive. :param DokanOptions: drive options :type DokanOptions: DOKAN_OPTIONS :param DokanOperations: pointers implemented file system calls :type DokanOperations: DokanOperations :return:...
def createFile( self, fileName, desiredAccess, shareMode, creationDisposition, flagsAndAttributes, dokanFileInfo, ): """Creates a file. :param fileName: name of file to create :type fileName: ctypes.c_wchar_p :param desiredAcce...
def readFile( self, fileName, buffer, numberOfBytesToRead, numberOfBytesRead, offset, dokanFileInfo, ): """Read a file. :param fileName: name of file to read :type fileName: ctypes.c_wchar_p :param buffer: buffer for content re...
def writeFile( self, fileName, buffer, numberOfBytesToWrite, numberOfBytesWritten, offset, dokanFileInfo, ): """Read a file. :param fileName: name of file to write :type fileName: ctypes.c_wchar_p :param buffer: buffer to write...
def findFilesWithPattern( self, fileName, searchPattern, fillFindData, dokanFileInfo ): """Find files in a certain path that match the search pattern. :param fileName: path to search :type fileName: ctypes.c_wchar_p :param searchPattern: pattern to search for :type s...