text
stringlengths
18
773k
def do_alarm_history(mc, args): '''Alarm state transition history.''' fields = {} fields['alarm_id'] = args.id if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: alarm = mc.alarms.history(**fields) except (osc_exc.ClientExc...
def do_alarm_history_list(mc, args): '''List alarms state history.''' fields = {} if args.dimensions: fields['dimensions'] = utils.format_parameters(args.dimensions) if args.starttime: _translate_starttime(args) fields['start_time'] = args.starttime if args.endtime: f...
def do_notification_type_list(mc, args): '''List notification types supported by monasca.''' try: notification_types = mc.notificationtypes.list() except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: if ar...
def requires_auth(f): """A decorator for flask api methods that validates auth0 tokens, hence ensuring that the user is authenticated. Code coped from: https://github.com/auth0/auth0-python/tree/master/examples/flask-api """ @wraps(f) def requires_auth_decorator(*args, **kwargs): try: ...
def add_auth(f): """A decorator that adds the authentication header to requests arguments""" def add_auth_decorator(*args, **kwargs): token = get_user_token() if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['Authorization'] = "Bearer %s" % token ...
def load_auth_token(token, load=True): """Validate an auth0 token. Returns the token's payload, or an exception of the type:""" assert get_config().jwt_secret, "No JWT secret configured for pymacaron" assert get_config().jwt_issuer, "No JWT issuer configured for pymacaron" assert get_config().jwt_a...
def authenticate_http_request(token=None): """Validate auth0 tokens passed in the request's header, hence ensuring that the user is authenticated. Code copied from: https://github.com/auth0/auth0-python/tree/master/examples/flask-api Return a PntCommonException if failed to validate authentication. ...
def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None): """Generate a new JWT token for this user_id. Default expiration date is 1 year from creation time""" assert user_id, "No user_id passed to generate_token()" assert isinstance(data, dict), "generate_token(data=) should be a dic...
def get_user_token(): """Return the authenticated user's auth token""" if not hasattr(stack.top, 'current_user'): return '' current_user = stack.top.current_user return current_user.get('token', '')
def get_token_issuer(): """Return the issuer in which this user's token was created""" try: current_user = stack.top.current_user return current_user.get('iss', get_config().jwt_issuer) except Exception: pass return get_config().jwt_issuer
def _search(self, limit, format): ''' Returns a list of result objects, with the url for the next page MsCognitive search url. ''' limit = min(limit, self.MAX_SEARCH_PER_QUERY) payload = { 'q' : self.query, 'count' : limit, #currently 50 is max per search. ...
def create(self, **kwargs): """Create a notification.""" body = self.client.create(url=self.base_url, json=kwargs) return body
def get(self, **kwargs): """Get the details for a specific notification.""" # NOTE(trebskit) should actually be find_one, but # monasca does not support expected response format url = '%s/%s' % (self.base_url, kwargs['notification_id']) resp = self.client.list(path=url) ...
def delete(self, **kwargs): """Delete a notification.""" url = self.base_url + '/%s' % kwargs['notification_id'] resp = self.client.delete(url=url) return resp
def create(self, **kwargs): """Create an alarm definition.""" resp = self.client.create(url=self.base_url, json=kwargs) return resp
def update(self, **kwargs): """Update a specific alarm definition.""" url_str = self.base_url + '/%s' % kwargs['alarm_id'] del kwargs['alarm_id'] resp = self.client.create(url=url_str, method='PUT', json=kwargs) ...
def compute_y(self, coefficients, num_x): """ Return calculated y-values for the domain of x-values in [1, num_x]. """ y_vals = [] for x in range(1, num_x + 1): y = sum([c * x ** i for i, c in enumerate(coefficients[::-1])]) y_vals.append(y) return y_vals
def compute_err(self, solution_y, coefficients): """ Return an error value by finding the absolute difference for each element in a list of solution-generated y-values versus expected values. Compounds error by 50% for each negative coefficient in the solution. solution_y: lis...
def eval_fitness(self, chromosome): """ Evaluate the polynomial equation using coefficients represented by a solution/chromosome, returning its error as the solution's fitness. return: fitness value """ coefficients = self.translator.translate_chromosome(chromosome) ...
def read_config(ip, mac): """Read the current configuration of a myStrom device.""" click.echo("Read configuration from %s" % ip) request = requests.get( 'http://{}/{}/{}/'.format(ip, URI, mac), timeout=TIMEOUT) print(request.json())
def write_config(ip, mac, single, double, long, touch): """Write the current configuration of a myStrom button.""" click.echo("Write configuration to device %s" % ip) data = { 'single': single, 'double': double, 'long': long, 'touch': touch, } request = requests.post(...
def write_ha_config(ip, mac, hass, port, id): """Write the configuration for Home Assistant to a myStrom button.""" click.echo("Write configuration for Home Assistant to device %s..." % ip) action = "get://{1}:{2}/api/mystrom?{0}={3}" data = { 'single': action.format('single', hass, port, id), ...
def reset_config(ip, mac): """Reset the current configuration of a myStrom WiFi Button.""" click.echo("Reset configuration of button %s..." % ip) data = { 'single': "", 'double': "", 'long': "", 'touch': "", } request = requests.post( 'http://{}/{}/{}/'.format...
def color(ip, mac, hue, saturation, value): """Switch the bulb on with the given color.""" bulb = MyStromBulb(ip, mac) bulb.set_color_hsv(hue, saturation, value)
def is_ec2_instance(): """Try fetching instance metadata at 'curl http://169.254.169.254/latest/meta-data/' to see if host is on an ec2 instance""" # Note: this code assumes that docker containers running on ec2 instances # inherit instances metadata, which they do as of 2016-08-25 global IS_EC2_I...
def to_epoch(t): """Take a datetime, either as a string or a datetime.datetime object, and return the corresponding epoch""" if isinstance(t, str): if '+' not in t: t = t + '+00:00' t = parser.parse(t) elif t.tzinfo is None or t.tzinfo.utcoffset(t) is None: t = t.repl...
def get_container_version(): """Return the version of the docker container running the present server, or '' if not in a container""" root_dir = os.path.dirname(os.path.realpath(sys.argv[0])) version_file = os.path.join(root_dir, 'VERSION') if os.path.exists(version_file): with open(version_...
def get_app_name(): """Return a generic name for this app, usefull when reporting to monitoring/logging frameworks""" conf = get_config() if is_ec2_instance(): return conf.app_name_live if hasattr(conf, 'app_name_live') else 'PYMACARON_LIVE' else: return conf.app_name_dev if hasattr(conf...
def run_all(plot=True, seed=None): """ Run all examples. """ if seed is not None: import random random.seed(seed) print("Running biggest_multiple.py") biggest_multiple.run(plot=plot) print("Running polynomials.py") polynomials.run(plot=plot) print("Running travelling_sales...
def create_random(cls, length, **kwargs): """ Return a new instance of this gene class with random DNA, with characters chosen from ``GENETIC_MATERIAL_OPTIONS``. length: the number of characters in the randomized DNA **kwargs: forwarded to the ``cls`` constructor ...
def mutate(self, p_mutate): """ Simulate mutation against a probability. p_mutate: probability for mutation to occur """ new_dna = [] for bit in self.dna: if random.random() < p_mutate: new_bit = bit while new_bit ==...
def copy(self): """ Return a new instance of this gene with the same DNA. """ return type(self)(self.dna, suppressed=self.suppressed, name=self.name)
def _check_dna(self, dna): """ Check that a DNA string only contains characters in ``GENETIC_MATERIAL_OPTIONS``. """ valid_chars = set(self.GENETIC_MATERIAL_OPTIONS) assert all(char in valid_chars for char in dna)
def mutate(self, p_mutate): """ Check each element for mutation, swapping "0" for "1" and vice-versa. """ new_dna = [] for bit in self.dna: if random.random() < p_mutate: bit = '1' if bit == '0' else '0' new_dna.ap...
def deep_merge(base, extra): """ Deeply merge two dictionaries, overriding existing keys in the base. :param base: The base dictionary which will be merged into. :param extra: The dictionary to merge into the base. Keys from this dictionary will take precedence. """ if extra is None: ...
def make_client(api_version, session=None, endpoint=None, service_type='monitoring'): """Returns an monitoring API client.""" client_cls = utils.get_client_class('monitoring', api_version, VERSION_MAP) c = client_cls( session=session, service_type=service_type, endpo...
def create_command_class(name, func_module): """Dynamically creates subclass of MigratingCommand. Method takes name of the function, module it is part of and builds the subclass of :py:class:`MigratingCommand`. Having a subclass of :py:class:`cliff.command.Command` is mandatory for the osc-lib inte...
def _session(kwargs): """Returns or reuses session. Method takes care of providing instance of session object for the client. :param kwargs: all params (without api_version) client was initialized with :type kwargs: dict :returns: session object :rtype keystoneauth1.session.Session "...
def load(cls, path): """ Loads an instance of the class from a file. Parameters ---------- path : str Path to an HDF5 file. Examples -------- This is an abstract data type, but let us say that ``Foo`` inherits from ``Saveable``. To co...
def register(cls, name): """Decorator to register a class.""" def register_decorator(reg_cls): def name_func(self): return name reg_cls.name = property(name_func) assert issubclass(reg_cls, cls), \ "Must be subclass matching your NamedR...
def construct(cls, name, *args, **kwargs): """ Constructs an instance of an object given its name. """ return cls.REGISTRY[name](*args, **kwargs)
def config(): """ Loads and returns a ConfigParser from ``~/.deepdish.conf``. """ conf = ConfigParser() # Set up defaults conf.add_section('io') conf.set('io', 'compression', 'zlib') conf.read(os.path.expanduser('~/.deepdish.conf')) return conf
def resize_by_factor(im, factor): """ Resizes the image according to a factor. The image is pre-filtered with a Gaussian and then resampled with bilinear interpolation. This function uses scikit-image and essentially combines its `pyramid_reduce` with `pyramid_expand` into one function. Return...
def asgray(im): """ Takes an image and returns its grayscale version by averaging the color channels. if an alpha channel is present, it will simply be ignored. If a grayscale image is given, the original image is returned. Parameters ---------- image : ndarray, ndim 2 or 3 RGB or ...
def crop(im, size): """ Crops an image in the center. Parameters ---------- size : tuple, (height, width) Finally size after cropping. """ diff = [im.shape[index] - size[index] for index in (0, 1)] im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 + size[1]] re...
def crop_or_pad(im, size, value=0): """ Crops an image in the center. Parameters ---------- size : tuple, (height, width) Finally size after cropping. """ diff = [im.shape[index] - size[index] for index in (0, 1)] im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 +...
def load(path, dtype=np.float64): """ Loads an image from file. Parameters ---------- path : str Path to image file. dtype : np.dtype Defaults to ``np.float64``, which means the image will be returned as a float with values between 0 and 1. If ``np.uint8`` is specified, ...
def load_raw(path): """ Load image using PIL/Pillow without any processing. This is particularly useful for palette images, which will be loaded using their palette index values as opposed to `load` which will convert them to RGB. Parameters ---------- path : str Path to image file....
def save(path, im): """ Saves an image to file. If the image is type float, it will assume to have values in [0, 1]. Parameters ---------- path : str Path to which the image will be saved. im : ndarray (image) Image. """ from PIL import Image if im.dtype == np.u...
def integrate(ii, r0, c0, r1, c1): """ Use an integral image to integrate over a given window. Parameters ---------- ii : ndarray Integral image. r0, c0 : int Top-left corner of block to be summed. r1, c1 : int Bottom-right corner of block to be summed. Returns ...
def offset(img, offset, fill_value=0): """ Moves the contents of image without changing the image size. The missing values are given a specified fill value. Parameters ---------- img : array Image. offset : (vertical_offset, horizontal_offset) Tuple of length 2, specifying t...
def bounding_box(alpha, threshold=0.1): """ Returns a bounding box of the support. Parameters ---------- alpha : ndarray, ndim=2 Any one-channel image where the background has zero or low intensity. threshold : float The threshold that divides background from foreground. Re...
def bounding_box_as_binary_map(alpha, threshold=0.1): """ Similar to `bounding_box`, except returns the bounding box as a binary map the same size as the input. Same parameters as `bounding_box`. Returns ------- binary_map : ndarray, ndim=2, dtype=np.bool_ Binary map with True if o...
def extract_patches(images, patch_shape, samples_per_image=40, seed=0, cycle=True): """ Takes a set of images and yields randomly chosen patches of specified size. Parameters ---------- images : iterable The images have to be iterable, and each element must be a Numpy ar...
def bytesize(arr): """ Returns the memory byte size of a Numpy array as an integer. """ byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize return byte_size
def apply_once(func, arr, axes, keepdims=True): """ Similar to `numpy.apply_over_axes`, except this performs the operation over a flattened version of all the axes, meaning that the function will only be called once. This only makes a difference for non-linear functions. Parameters ---------- ...
def tupled_argmax(a): """ Argmax that returns an index tuple. Note that `numpy.argmax` will return a scalar index as if you had flattened the array. Parameters ---------- a : array_like Input array. Returns ------- index : tuple Tuple of index, even if `a` is one-di...
def timed(name=None, file=sys.stdout, callback=None, wall_clock=True): """ Context manager to make it easy to time the execution of a piece of code. This timer will never run your code several times and is meant more for simple in-production timing, instead of benchmarking. Reports the wall-clock ti...
def pad(data, padwidth, value=0.0): """ Pad an array with a specific value. Parameters ---------- data : ndarray Numpy array of any dimension and type. padwidth : int or tuple If int, it will pad using this amount at the beginning and end of all dimensions. If it is a tu...
def pad_to_size(data, shape, value=0.0): """ This is similar to `pad`, except you specify the final shape of the array. Parameters ---------- data : ndarray Numpy array of any dimension and type. shape : tuple Final shape of padded array. Should be tuple of length ``data.ndim``....
def pad_repeat_border(data, padwidth): """ Similar to `pad`, except the border value from ``data`` is used to pad. Parameters ---------- data : ndarray Numpy array of any dimension and type. padwidth : int or tuple If int, it will pad using this amount at the beginning and end o...
def pad_repeat_border_corner(data, shape): """ Similar to `pad_repeat_border`, except the padding is always done on the upper end of each axis and the target size is specified. Parameters ---------- data : ndarray Numpy array of any dimension and type. shape : tuple Final sh...
def _dict_native_ok(d): """ This checks if a dictionary can be saved natively as HDF5 groups. If it can't, it will be pickled. """ if len(d) >= 256: return False # All keys must be strings for k in d: if not isinstance(k, six.string_types): return False ret...
def _load_nonlink_level(handler, level, pathtable, pathname): """ Loads level and builds appropriate type, without handling softlinks """ if isinstance(level, tables.Group): if _sns and (level._v_title.startswith('SimpleNamespace:') or DEEPDISH_IO_ROOT_IS_SNS in level._v_att...
def _load_level(handler, level, pathtable): """ Loads level and builds appropriate type, handling softlinks if necessary """ if isinstance(level, tables.link.SoftLink): # this is a link, so see if target is already loaded, return it pathname = level.target node = level() else...
def save(path, data, compression='default'): """ Save any Python structure to an HDF5 file. It is particularly suited for Numpy arrays. This function works similar to ``numpy.save``, except if you save a Python object at the top level, you do not need to issue ``data.flat[0]`` to retrieve it from in...
def load(path, group=None, sel=None, unpack=False): """ Loads an HDF5 saved with `save`. This function requires the `PyTables <http://www.pytables.org/>`_ module to be installed. Parameters ---------- path : string Filename from which to load the data. group : string or list ...
def sorted_maybe_numeric(x): """ Sorts x with numeric semantics if all keys are nonnegative integers. Otherwise uses standard string sorting. """ all_numeric = all(map(str.isdigit, x)) if all_numeric: return sorted(x, key=int) else: return sorted(x)
def abbreviate(s, maxlength=25): """Color-aware abbreviator""" assert maxlength >= 4 skip = False abbrv = None i = 0 for j, c in enumerate(s): if c == '\033': skip = True elif skip: if c == 'm': skip = False else: i += 1...
def extend_settings(self, data_id, files, secrets): """Extend the settings the manager will serialize. :param data_id: The :class:`~resolwe.flow.models.Data` object id being prepared for. :param files: The settings dictionary to be serialized. Keys are filenames, values ...
def get_tools_paths(self): """Get tools' paths.""" if settings.DEBUG or is_testing(): return list(get_apps_tools().values()) else: tools_root = settings.FLOW_TOOLS_ROOT subdirs = next(os.walk(tools_root))[1] return [os.path.join(tools_root, sdir)...
def resolve_data_path(self, data=None, filename=None): """Resolve data path for use with the executor. :param data: Data object instance :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given data file in programs executed usin...
def resolve_upload_path(self, filename=None): """Resolve upload path for use with the executor. :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given uploaded file in programs executed using this executor """ ...
def wrap(access_pyxb, read_only=False): """Work with the AccessPolicy in a SystemMetadata PyXB object. Args: access_pyxb : AccessPolicy PyXB object The AccessPolicy to modify. read_only: bool Do not update the wrapped AccessPolicy. When only a single AccessPolicy operation is ...
def wrap_sysmeta_pyxb(sysmeta_pyxb, read_only=False): """Work with the AccessPolicy in a SystemMetadata PyXB object. Args: sysmeta_pyxb : SystemMetadata PyXB object SystemMetadata containing the AccessPolicy to modify. read_only: bool Do not update the wrapped AccessPolicy. Wh...
def get_highest_perm_str(self, subj_str): """ Args: subj_str : str Subject for which to retrieve the highest permission. Return: The highest permission for subject or None if subject does not have any permissions. """ pres_perm_set = self._present_perm_set_for_subj(self...
def get_effective_perm_list(self, subj_str): """ Args: subj_str : str Subject for which to retrieve the effective permissions. Returns: list of str: List of permissions up to and including the highest permission for subject, ordered lower to higher, or empty list if subject do...
def get_subjects_with_equal_or_higher_perm(self, perm_str): """ Args: perm_str : str Permission, ``read``, ``write`` or ``changePermission``. Returns: set of str : Subj that have perm equal or higher than ``perm_str``. Since the lowest permission a subject can have is ``read`...
def dump(self): """Dump the current state to debug level log.""" logging.debug('AccessPolicy:') map( logging.debug, [ ' {}'.format(s) for s in pprint.pformat(self.get_normalized_perm_list()).splitlines() ], )
def subj_has_perm(self, subj_str, perm_str): """Returns: bool: ``True`` if ``subj_str`` has perm equal to or higher than ``perm_str``. """ self._assert_valid_permission(perm_str) return perm_str in self.get_effective_perm_list(subj_str)
def add_authenticated_read(self): """Add ``read`` perm for all authenticated subj. Public ``read`` is removed if present. """ self.remove_perm(d1_common.const.SUBJECT_PUBLIC, 'read') self.add_perm(d1_common.const.SUBJECT_AUTHENTICATED, 'read')
def add_verified_read(self): """Add ``read`` perm for all verified subj. Public ``read`` is removed if present. """ self.remove_perm(d1_common.const.SUBJECT_PUBLIC, 'read') self.add_perm(d1_common.const.SUBJECT_VERIFIED, 'read')
def add_perm(self, subj_str, perm_str): """Add a permission for a subject. Args: subj_str : str Subject for which to add permission(s) perm_str : str Permission to add. Implicitly adds all lower permissions. E.g., ``write`` will also add ``read``...
def remove_perm(self, subj_str, perm_str): """Remove permission from a subject. Args: subj_str : str Subject for which to remove permission(s) perm_str : str Permission to remove. Implicitly removes all higher permissions. E.g., ``write`` will al...
def remove_subj(self, subj_str): """Remove all permissions for subject. Args: subj_str : str Subject for which to remove all permissions. Since subjects can only be present in the AccessPolicy when they have one or more permissions, this removes the subject...
def _perm_dict_from_pyxb(self, access_pyxb): """Return dict representation of AccessPolicy PyXB obj.""" subj_dict = self._subj_dict_from_pyxb(access_pyxb) return self._perm_dict_from_subj_dict(subj_dict)
def _perm_dict_from_subj_dict(self, subj_dict): """Return dict where keys and values of ``subj_dict`` have been flipped around.""" perm_dict = {} for subj_str, perm_set in list(subj_dict.items()): for perm_str in perm_set: perm_dict.setdefault(perm_str, set())...
def _pyxb_from_perm_dict(self, perm_dict): """Return an AccessPolicy PyXB representation of ``perm_dict`` - If ``norm_perm_list`` is empty, None is returned. The schema does not allow AccessPolicy to be empty, but in SystemMetadata, it can be left out altogether. So returning None inste...
def _pyxb_from_norm_perm_list(self, norm_perm_list): """Return an AccessPolicy PyXB representation of ``norm_perm_list``""" # Using accessPolicy() instead of AccessPolicy() and accessRule() instead of # AccessRule() gives PyXB the type information required for using this as a # root elem...
def _subj_dict_from_pyxb(self, access_pyxb): """Return a dict representation of ``access_pyxb``, which is an AccessPolicy PyXB object. This also remove any duplicate subjects and permissions in the PyXB object. """ subj_dict = {} for allow_pyxb in access_pyxb.allow: ...
def _highest_perm_dict_from_perm_dict(self, perm_dict): """Return a perm_dict where only the highest permission for each subject is included.""" highest_perm_dict = copy.copy(perm_dict) for ordered_str in reversed(ORDERED_PERM_LIST): for lower_perm in self._lower_perm_list(or...
def _norm_perm_list_from_perm_dict(self, perm_dict): """Return a minimal, ordered, hashable list of subjects and permissions.""" high_perm_dict = self._highest_perm_dict_from_perm_dict(perm_dict) return [ [k, list(sorted(high_perm_dict[k]))] for k in ORDERED_PERM_LIST ...
def _effective_perm_list_from_iter(self, perm_iter): """Return list of effective permissions for for highest permission in ``perm_iter``, ordered lower to higher, or None if ``perm_iter`` is empty.""" highest_perm_str = self._highest_perm_from_iter(perm_iter) return ( self._e...
def _present_perm_set_for_subj(self, perm_dict, subj_str): """Return a set containing only the permissions that are present in the ``perm_dict`` for ``subj_str``""" return {p for p, s in list(perm_dict.items()) if subj_str in s}
def _highest_perm_from_iter(self, perm_iter): """Return the highest perm present in ``perm_iter`` or None if ``perm_iter`` is empty.""" perm_set = set(perm_iter) for perm_str in reversed(ORDERED_PERM_LIST): if perm_str in perm_set: return perm_str
def _ordered_idx_from_perm(self, perm_str): """Return the ordered index of ``perm_str`` or None if ``perm_str`` is not a valid permission.""" for i, ordered_str in enumerate(ORDERED_PERM_LIST): if perm_str == ordered_str: return i
def _assert_valid_permission(self, perm_str): """Raise D1 exception if ``perm_str`` is not a valid permission.""" if perm_str not in ORDERED_PERM_LIST: raise d1_common.types.exceptions.InvalidRequest( 0, 'Permission must be one of {}. perm_str="{}"'.format( ...
def handle_unexpected_exception(max_traceback_levels=100): """Suppress stack traces for common errors and provide hints for how to resolve them.""" exc_type, exc_msgs = sys.exc_info()[:2] if exc_type.__name__ == "SSLError": d1_cli.impl.util.print_error( """HTTPS / TLS / SSL / X.509v3...
def create_sciobj(request, sysmeta_pyxb): """Create object file and database entries for a new native locally stored (non- proxied) science object. This method takes a request object and is only called from the views that handle: - MNStorage.create() - MNStorage.update() Various sanity ch...
def _save_sciobj_bytes_from_request(request, pid): """Django stores small uploads in memory and streams large uploads directly to disk. Uploads stored in memory are represented by UploadedFile and on disk, TemporaryUploadedFile. To store an UploadedFile on disk, it's iterated and saved in chunks. To st...