text
stringlengths
18
773k
def _is_builtin_module(module): """Is builtin or part of standard library """ if (not hasattr(module, '__file__')) or module.__name__ in sys.builtin_module_names: return True if module.__name__ in _stdlib._STD_LIB_MODULES: return True amp = os.path.abspath(module.__file__) if 's...
def _find_dependent_modules(self, module): """ Return the set of dependent modules for used modules, classes and routines. """ dms = set() for um in inspect.getmembers(module, inspect.ismodule): dms.add(um[1]) for uc in inspect.getmembers(module, insp...
def add_dependencies(self, module): """ Adds a module and its dependencies to the list of dependencies. Top-level entry point for adding a module and its dependecies. """ if module in self._processed_modules: return None if hasattr(module, "__name__"): ...
def _include_module(self, module, mn): """ See if a module should be included or excluded based upon included_packages and excluded_packages. As some packages have the following format: scipy.special.specfun scipy.linalg Where the top-level package name is just a prefi...
def _add_dependency(self, module, mn): """ Adds a module to the list of dependencies without handling the modules dependences. Modules in site-packages are excluded from being added into the toolkit. This mimics dill. """ _debug.debug("_add_dependency:module=%s",...
def freeze(self) -> dict: """ Returns a dictionary of all settings set for this object, including any values of its parents or hardcoded defaults. """ settings = {} for key, v in self._h.defaults.items(): settings[key] = self._unserialize(v.value, v.type) ...
def get(self, key: str, default=None, as_type: type = None, binary_file=False): """ Get a setting specified by key ``key``. Normally, settings are strings, but if you put non-strings into the settings object, you can request unserialization by specifying ``as_type``. If the key does not ...
def set(self, key: str, value: Any) -> None: """ Stores a setting to the database of its object. The write to the database is performed immediately and the cache in the cache backend is flushed. The cache within this object will be updated correctly. """ wc = se...
def delete(self, key: str) -> None: """ Deletes a setting from this object's storage. The write to the database is performed immediately and the cache in the cache backend is flushed. The cache within this object will be updated correctly. """ if key in self._wri...
def _get_vcap_services(vcap_services=None): """Retrieves the VCAP Services information from the `ConfigParams.VCAP_SERVICES` field in the config object. If `vcap_services` is not specified, it takes the information from VCAP_SERVICES environment variable. Args: vcap_services (str): Try to parse as ...
def _get_credentials(vcap_services, service_name=None): """Retrieves the credentials of the VCAP Service of the specified `service_name`. If `service_name` is not specified, it takes the information from STREAMING_ANALYTICS_SERVICE_NAME environment variable. Args: vcap_services (dict): A dict ...
def _get_rest_api_url_from_creds(session, credentials): """Retrieves the Streams REST API URL from the provided credentials. Args: session (:py:class:`requests.Session`): A Requests session object for making REST calls credentials (dict): A dict representation of the credentials. Returns: ...
def _get_iam_rest_api_url_from_creds(rest_client, credentials): """Retrieves the Streams REST API URL from the provided credentials using iam authentication. Args: rest_client (:py:class:`rest_primitives._IAMStreamsRestClient`): A client for making REST calls using IAM authentication credential...
def resource_url(self): """str: Root URL for IBM Streams REST API""" self._resource_url = self._resource_url or st.get_rest_api() return self._resource_url
def _get_element_by_id(self, resource_name, eclass, id): """Get a single element matching an id""" elements = self._get_elements(resource_name, eclass, id=id) if not elements: raise ValueError("No resource matching: {0}".format(id)) if len(elements) == 1: return e...
def get_domains(self): """Retrieves available domains. Returns: :py:obj:`list` of :py:class:`~.rest_primitives.Domain`: List of available domains """ # Domains are fixed and actually only one per REST api. if self._domains is None: self._domains = self._g...
def get_resources(self): """Retrieves a list of all known Streams high-level REST resources. Returns: :py:obj:`list` of :py:class:`~.rest_primitives.RestResource`: List of all Streams high-level REST resources. """ json_resources = self.rest_client.make_request(self.resource...
def of_definition(service_def): """Create a connection to a Streaming Analytics service. The single service is defined by `service_def` which can be one of * The `service credentials` copied from the `Service credentials` page of the service console (not the Streams console). Credentials ...
def resource_url(self): """str: Root URL for IBM Streams REST API""" if self._iam: self._resource_url = self._resource_url or _get_iam_rest_api_url_from_creds(self.rest_client, self.credentials) else: self._resource_url = self._resource_url or _get_rest_api_url_from_creds...
def is_authenticated(self, request, **kwargs): """ Verify 2-legged oauth request. Parameters accepted as values in the "Authorization" header, as a GET request parameter, or in a POST body. """ log.info("OAuth20Authentication") try: key = request.GET.g...
def check_scope(self, token, request): http_method = request.method if not hasattr(self, http_method): raise OAuthError("HTTP method is not recognized") required_scopes = getattr(self, http_method) # a None scope means always allowed if required_scopes is None: ...
def _is_args_eightbit(*args) -> bool: """ Check if input matches type: renderer.eightbit. """ if not args: return False elif args[0] is 0: return True elif isinstance(args[0], int): return True else: return False
def as_dict(self) -> Dict[str, str]: """ Export color register as dict. """ items: Dict[str, str] = {} for k, v in self.items(): if type(v) is str: items.update({k: v}) return items
def as_namedtuple(self): """ Export color register as namedtuple. """ d = self.as_dict() return namedtuple('ColorRegister', d.keys())(*d.values())
def _extract_attrs(x, n): """Extracts attributes for an image. n is the index where the attributes begin. Extracted elements are deleted from the element list x. Attrs are returned in pandoc format. """ try: return extract_attrs(x, n) except (ValueError, IndexError): if PAND...
def _process_figure(value, fmt): """Processes the figure. Returns a dict containing figure properties.""" # pylint: disable=global-statement global Nreferences # Global references counter global has_unnumbered_figures # Flags unnumbered figures were found global cursec ...
def process_figures(key, value, fmt, meta): # pylint: disable=unused-argument """Processes the figures.""" global has_unnumbered_figures # pylint: disable=global-statement # Process figures wrapped in Para elements if key == 'Para' and len(value) == 1 and \ value[0]['t'] == 'Image' and value[0]...
def main(): """Filters the document AST.""" # pylint: disable=global-statement global PANDOCVERSION global Image # Get the output format and document fmt = args.fmt doc = json.loads(STDIN.read()) # Initialize pandocxnos # pylint: disable=too-many-function-args PANDOCVERSION = ...
def i18n_javascript(self, request): """ Displays the i18n JavaScript that the Django admin requires. This takes into account the USE_I18N setting. If it's set to False, the generated JavaScript will be leaner and faster. """ if settings.USE_I18N: from django....
def file_links(items, opts=None): """ Turns a (optionally nested) list of FileNode objects into a list of strings, linking to the associated files. """ result = [] kwargs = get_kwargs_for_file_link(opts) for item in items: if isinstance(item, FileNode): result.append(get_file_link(item, **kwargs)) else: ...
def get_results(self, request): """ Temporarily decreases the `level` attribute of all search results in order to prevent indendation when displaying them. """ super(MediaTreeChangeList, self).get_results(request) try: reduce_levels = abs(int(get_request_attr(...
def forwards(self, orm): "Write your forwards methods here." for node in orm.FileNode.objects.all(): node.save()
def get_media_backend(fail_silently=True, handles_media_types=None, handles_file_extensions=None, supports_thumbnails=None): """ Returns the MediaBackend subclass that is configured for use with media_tree. """ backends = app_settings.MEDIA_TREE_MEDIA_BACKENDS if no...
def thumbnail_size(parser, token): """Returns a pre-configured thumbnail size, or assigns it to a context variable. Basic tag syntax:: {% thumbnail_size [size_name] [as var_name] %} The ``size`` parameter can be any of the size names configured using the setting ``MEDIA_TREE_THUMB...
def request(method, path, params=None, data=None, auto_retry=True): """ method - HTTP method. e.g. get, put, post, etc. path - Path to resource. e.g. /loss_sets/1234 params - Parameter to pass in the query string data - Dictionary of parameters to pass in the request body """ body = None ...
def file_length(file_obj): """ Returns the length in bytes of a given file object. Necessary because os.fstat only works on real files and not file-like objects. This works on more types of streams, primarily StringIO. """ file_obj.seek(0, 2) length = file_obj.tell() file_obj.seek(0) ...
def read_in_chunks(file_obj, chunk_size): """Generator to read a file piece by piece.""" offset = 0 while True: data = file_obj.read(chunk_size) if not data: break yield data, offset offset += len(data)
def parse_href(href): """Parses an Analyze Re href into collection name and ID""" url = urlparse(href) path = url.path.split('/') collection_name = path[1] id_ = path[2] return collection_name, id_
def vectorize(values): """ Takes a value or list of values and returns a single result, joined by "," if necessary. """ if isinstance(values, list): return ','.join(str(v) for v in values) return values
def vectorize_range(values): """ This function is for url encoding. Takes a value or a tuple or list of tuples and returns a single result, tuples are joined by "," if necessary, elements in tuple are joined by '_' """ if isinstance(values, tuple): return '_'.join(str(i) for i in values)...
def label_from_instance(self, obj): """ Creates labels which represent the tree level of each node when generating option labels. """ return u'%s %s %i' % (self.level_indicator * (getattr(obj, 'depth') - 1), smart_unicode(obj), obj.depth)
def upload_data(self, file_or_str, chunk_size=analyzere.upload_chunk_size, poll_interval=analyzere.upload_poll_interval, upload_callback=lambda x: None, commit_callback=lambda x: None): """ Accepts a file-like object or string and uploads it. F...
def delete_orphaned_files(modeladmin, request, queryset=None): """ Deletes orphaned files, i.e. media files existing in storage that are not in the database. """ execute = request.POST.get('execute') storage = get_media_storage() broken_node_links = [] orphaned_files_choices = [] ...
def rebuild_tree(modeladmin, request, queryset=None): """ Rebuilds whole tree in database using `parent` link. """ tree = FileNode.tree.rebuild() messages.success(request, message=_('The node tree was rebuilt.')) return HttpResponseRedirect('')
def clear_cache(modeladmin, request, queryset=None): """ Clears media cache files such as thumbnails. """ execute = request.POST.get('execute') files_in_storage = [] storage = get_media_storage() cache_files_choices = [] for storage_name in get_cache_files(): link = mar...
def south_field_triple(self): "Returns a suitable description of this field for South." from south.modelsinspector import introspector field_class = "django.db.models.fields.CharField" args, kwargs = introspector(self) return (field_class, args, kwargs)
def autodiscover_media_extensions(): """ Auto-discover INSTALLED_APPS media_extensions.py modules and fail silently when not present. This forces an import on them to register any media extension bits they may want. Rip of django.contrib.admin.autodiscover() """ import copy from django....
def multi_splitext(basename): """ Similar to os.path.slittext(), but with special handling for files with multiple extensions, such as "archive.tar.gz": Returns a list containg three elements, the first being the name without any extensions (taking into account hidden files/leading periods), the sec...
def join_formatted(text, new_text, glue_format_if_true = u'%s%s', glue_format_if_false = u'%s%s', condition=None, format = u'%s', escape=False): """ Joins two strings, optionally escaping the second, and using one of two string formats for glueing them together, depending on whether a condition is True ...
def widthratio(value, max_value, max_width): """ Does the same like Django's `widthratio` template tag (scales max_width to factor value/max_value) """ ratio = float(value) / float(max_value) return int(round(ratio * max_width))
def _initialize(self, path): """ Find metadata tree root, detect format version """ # Find the tree root root = os.path.abspath(path) try: while ".fmf" not in next(os.walk(root))[1]: if root == "/": raise utils.RootError( ...
def merge(self, parent=None): """ Merge parent data """ # Check parent, append source files if parent is None: parent = self.parent if parent is None: return self.sources = parent.sources + self.sources # Merge child data with parent data d...
def inherit(self): """ Apply inheritance """ # Preserve original data and merge parent # (original data needed for custom inheritance extensions) self.original_data = self.data self.merge() log.debug("Data for '{0}' inherited.".format(self)) log.data(pretty(self.d...
def update(self, data): """ Update metadata, handle virtual hierarchy """ # Nothing to do if no data if data is None: return for key, value in sorted(data.items()): # Handle child attributes if key.startswith('/'): name = key.lstrip('/'...
def get(self, name=None, default=None): """ Get attribute value or return default Whole data dictionary is returned when no attribute provided. Supports direct values retrieval from deep dictionaries as well. Dictionary path should be provided as list. The following two ...
def child(self, name, data, source=None): """ Create or update child with given data """ try: if isinstance(data, dict): self.children[name].update(data) else: self.children[name].grow(data) except KeyError: self.children[name] ...
def grow(self, path): """ Grow the metadata tree for the given directory path Note: For each path, grow() should be run only once. Growing the tree from the same path multiple times with attribute adding using the "+" sign leads to adding the value more than once! """ ...
def climb(self, whole=False): """ Climb through the tree (iterate leaf/all nodes) """ if whole or not self.children: yield self for name, child in self.children.items(): for node in child.climb(whole): yield node
def find(self, name): """ Find node with given name """ for node in self.climb(whole=True): if node.name == name: return node return None
def prune(self, whole=False, keys=[], names=[], filters=[]): """ Filter tree nodes based on given criteria """ for node in self.climb(whole): # Select only nodes with key content if not all([key in node.data for key in keys]): continue # Select nodes w...
def show(self, brief=False, formatting=None, values=[]): """ Show metadata """ # Show nothing if there's nothing if not self.data: return None # Custom formatting if formatting is not None: formatting = re.sub("\\\\n", "\n", formatting) name =...
def label_from_instance(self, obj): """ Creates labels which represent the tree level of each node when generating option labels. """ level = getattr(obj, obj._mptt_meta.level_attr) level_indicator = mark_safe(conditional_escape(self.level_indicator) * level) retu...
def save(self): """ Attempts to move the node using the selected target and position. If an invalid move is attempted, the related error message will be added to the form's non-field errors and the error will be re-raised. Callers should attempt to catch ``InvalidNode`` ...
def find(names, dirs, file_ext): """ Iterating a set of dirs under the static root, this method tries to find a file named like one of the names and file ext passed, and returns the storage path to the first file it encounters. Usage this method makes it possible to over...
def find(file_node, dirs=ICON_DIRS, default_name=None, file_ext='.png'): """ Iterating all icon dirs, try to find a file called like the node's extension / mime subtype / mime type (in that order). For instance, for an MP3 file ("audio/mpeg"), this would look for: "mp3.png" / "au...
def result_tree_flat(context, cl, request): """ Added 'filtered' param, so the template's js knows whether the results have been affected by a GET param or not. Only when the results are not filtered you can drag and sort the tree """ return { #'filtered': is_filtered_cl(cl, request), ...
def get_object(self, queryset=None): """ Returns the object the view is displaying. By default this requires `self.queryset` and a `pk` or `path` argument in the URLconf, but subclasses can override this to return any object. """ # Use a custom queryset if provided; this...
def get_detail_view(self, request, object, opts=None): """ Instantiates and returns the view class that will generate the actual context for this plugin. """ view = self.get_view(request, self.view_class, opts) view.object = object return view
def get_listing_view(self, request, queryset, opts=None): """ Instantiates and returns the view class that will generate the actual context for this plugin. ``queryset`` can be an actual QuerySet or any iterable. """ view = self.get_view(request, self.view_class, opts) ...
def get_view(self, request, view_class, opts=None): """ Instantiates and returns the view class that will generate the actual context for this plugin. """ kwargs = {} if opts: if not isinstance(opts, dict): opts = opts.__dict__ else: ...
def options_formatting(self): """ Formating options """ group = self.parser.add_argument_group("Format") group.add_argument( "--format", dest="formatting", default=None, help="Custom output format using the {} expansion") group.add_argument( "--value",...
def options_utils(self): """ Utilities """ group = self.parser.add_argument_group("Utils") group.add_argument( "--path", action="append", dest="paths", help="Path to the metadata tree (default: current directory)") group.add_argument( "--verbose", acti...
def command_ls(self): """ List names """ self.parser = argparse.ArgumentParser( description="List names of available objects") self.options_select() self.options_utils() self.options = self.parser.parse_args(self.arguments[2:]) self.show(brief=True)
def command_show(self): """ Show metadata """ self.parser = argparse.ArgumentParser( description="Show metadata of available objects") self.options_select() self.options_formatting() self.options_utils() self.options = self.parser.parse_args(self.arguments[2:]...
def command_init(self): """ Initialize tree """ self.parser = argparse.ArgumentParser( description="Initialize a new metadata tree") self.options_utils() self.options = self.parser.parse_args(self.arguments[2:]) # For each path create an .fmf directory and version fil...
def show(self, brief=False): """ Show metadata for each path given """ output = [] for path in self.options.paths or ["."]: if self.options.verbose: utils.info("Checking {0} for metadata.".format(path)) tree = fmf.Tree(path) for node in tree.pr...
def filter(filter, data, sensitive=True, regexp=False): """ Return true if provided filter matches given dictionary of values Filter supports disjunctive normal form with '|' used for OR, '&' for AND and '-' for negation. Individual values are prefixed with 'value:', leading/trailing white-space is...
def color(text, color=None, background=None, light=False, enabled="auto"): """ Return text in desired color if coloring enabled Available colors: black red green yellow blue magenta cyan white. Alternatively color can be prefixed with "light", e.g. lightgreen. """ colors = {"black": 30, "red": ...
def _create_logger(name='fmf', level=None): """ Create fmf logger """ # Create logger, handler and formatter logger = logging.getLogger(name) handler = logging.StreamHandler() handler.setFormatter(Logging.ColoredFormatter()) logger.addHandler(handler) # Save log l...
def filter(self, *args, **kwargs): """ Works just like the default Manager's :func:`filter` method, but you can pass an additional keyword argument named ``path`` specifying the full **path of the folder whose immediate child objects** you want to retrieve, e.g. ``"path/to/folder...
def exclude(self, *args, **kwargs): """ Works just like the default Manager's :func:`exclude` method, but you can pass an additional keyword argument named ``path`` specifying the full **path of the folder whose immediate child objects** you want to exclude, e.g. ``"path/to/folde...
def get(self, *args, **kwargs): """ Works just like the default Manager's :func:`get` method, but you can pass an additional keyword argument named ``path`` specifying the full path of the object you want to retrieve, e.g. ``"path/to/folder/readme.txt"``. """ if '...
def validate(self, value, model_instance): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ if not self.editable: # Skip validation for non-editable fields. return if self._choices and...
def get_qualified_file_url(self, field_name='file'): """Returns a fully qualified URL for the :attr:`file` field, including protocol, domain and port. In most cases, you can just use ``file.url`` instead, which (depending on your ``MEDIA_URL``) may or may not contain the domain. In some ...
def get_admin_url(self, query_params=None, use_path=False): """Returns the URL for viewing a FileNode in the admin.""" if not query_params: query_params = {} url = '' if self.is_top_node(): url = reverse('admin:media_tree_filenode_changelist'); elif use_...
def get_metadata_display(self, field_formats = {}, escape=True): """Returns object metadata that has been selected to be displayed to users, compiled as a string. """ def field_format(field): if field in field_formats: return field_formats[field] r...
def get_caption_formatted(self, field_formats = app_settings.MEDIA_TREE_METADATA_FORMATS, escape=True): """Returns object metadata that has been selected to be displayed to users, compiled as a string including default formatting, for example bold titles. You can use this method in temp...
def alt(self): """Returns object metadata suitable for use as the HTML ``alt`` attribute. You can use this method in templates:: <img src="{{ node.file.url }}" alt="{{ node.alt }}" /> """ if self.override_alt != '' and self.override_alt is not None: return self....
def save(self): """ Attempts to move the nodes using the selected target and position. If an invalid move is attempted, the related error message will be added to the form's non-field errors and the error will be re-raised. Callers should attempt to catch ``InvalidMove``...
def save(self): """ Deletes the selected files from storage """ storage = get_media_storage() for storage_name in self.cleaned_data['selected_files']: full_path = storage.path(storage_name) try: storage.delete(storage_name) ...
def get_merged_filenode_list(nodes, filter_media_types=None, exclude_media_types=None, filter=None, ordering=None, processors=None, max_depth=None, max_nodes=None): """ Almost the same as :func:`get_nested_filenode_list`, but returns a flat (one-dimensional) list. Using the same QuerySet as in the example f...
def get_file_link(node, use_metadata=False, include_size=False, include_extension=False, include_icon=False, href=None, extra_class='', extra=''): """ Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file. """ link_text = None if use_meta...
def delete_selected_tree(self, modeladmin, request, queryset): """ Deletes multiple instances and makes sure the MPTT fields get recalculated properly. (Because merely doing a bulk delete doesn't trigger the post_delete hooks.) """ # If the user has not yet confirmed the deletion...
def norm_name(build_module: str, target_name: str): """Return a normalized canonical target name for the `target_name` observed in build module `build_module`. A normalized canonical target name is of the form "<build module>:<name>", where <build module> is the relative normalized path from the pro...
def expand_target_selector(target_selector: str, conf: Config): """Return a normalized target name (where `**:*` is the normalized form of itself). Target specifier can be: - `**:*` - means to recursively build all targets under current working dir. - relative path from current working di...
def hashify_targets(targets: list, build_context) -> list: """Return sorted hashes of `targets`.""" return sorted(build_context.targets[target_name].hash(build_context) for target_name in listify(targets))
def hashify_files(files: list) -> dict: """Return mapping from file path to file hash.""" return {filepath.replace('\\', '/'): hash_tree(filepath) for filepath in listify(files)}
def process_prop(prop_type: PT, value, build_context): """Return a cachable representation of the prop `value` given its type.""" if prop_type in (PT.Target, PT.TargetList): return hashify_targets(value, build_context) elif prop_type in (PT.File, PT.FileList): return hashify_files(value) ...
def compute_json(self, build_context): """Compute and store a JSON serialization of this target for caching purposes. The serialization includes: - The build flavor - The builder name - Target tags - Hashes of target dependencies & buildenv - Processed...
def json(self, build_context) -> str: """Return JSON serialization of this target for caching purposes.""" if self._json is None: self.compute_json(build_context) return self._json