docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Removes flag with name for all appearances. A flag can be registered with its long name and an optional short name. This method removes both of them. This is different than __delattr__. Args: name: Either flag's long name or short name. Raises: UnrecognizedFlagError: When flag name is not...
def _RemoveAllFlagAppearances(self, name): flag_dict = self.FlagDict() if name not in flag_dict: raise exceptions.UnrecognizedFlagError(name) flag = flag_dict[name] names_to_remove = {name} names_to_remove.add(flag.name) if flag.short_name: names_to_remove.add(flag.short_name) ...
523,489
Changes the default value (and current value) of the named flag object. Call this method at the top level of a module to avoid overwriting the value passed at the command line. Args: name: A string, the name of the flag to modify. value: The new default value. Raises: UnrecognizedFl...
def SetDefault(self, name, value): fl = self.FlagDict() if name not in fl: self._SetUnknownFlag(name, value) return if self.IsParsed(): logging.warn( 'FLAGS.SetDefault called on flag "%s" after flag parsing. Call this ' 'method at the top level of a module to avoid...
523,490
Parses flags from argv; stores parsed flags into this FlagValues object. All unparsed arguments are returned. Args: argv: argument list. Can be of any type that may be converted to a list. known_only: parse and remove known flags, return rest untouched. Returns: The list of arguments...
def __call__(self, argv, known_only=False): if not argv: # Unfortunately, the old parser used to accept an empty argv, and some # users rely on that behaviour. Allow it as a special case for now. self.MarkAsParsed() self._AssertAllValidators() return [] # This pre parses the ...
523,491
Generates a help string for all known flags. Args: prefix: str, per-line output prefix. include_special_flags: bool, whether to include description of _SPECIAL_FLAGS, i.e. --flagfile and --undefok. Returns: str, formatted help message.
def GetHelp(self, prefix='', include_special_flags=True): # TODO(vrusinov): this function needs a test. helplist = [] flags_by_module = self.FlagsByModuleDict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_mo...
523,495
Generates a help string for the key flags of a given module. Args: module: A module object or a module name (a string). output_lines: A list of strings. The generated help message lines will be appended to this list. prefix: A string that is prepended to each generated help line.
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=''): key_flags = self._GetKeyFlagsForModule(module) if key_flags: self.__RenderModuleFlags(module, key_flags, output_lines, prefix)
523,498
Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module.
def ModuleHelp(self, module): helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist)
523,499
Returns filename from a flagfile_str of form -[-]flagfile=filename. The cases of --flagfile foo and -flagfile foo shouldn't be hitting this function, as they are dealt with in the level above this function. Args: flagfile_str: flagfile string. Returns: str filename from a flagfile_str...
def ExtractFilename(self, flagfile_str): if flagfile_str.startswith('--flagfile='): return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip()) elif flagfile_str.startswith('-flagfile='): return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip()) else: raise ...
523,502
Appends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from http://code.google.com/p/google-gflags Args: filename: string, name of the file.
def AppendFlagsIntoFile(self, filename): with open(filename, 'a') as out_file: out_file.write(self.FlagsIntoString())
523,506
Ensures that only one flag among flag_names is set. Args: flag_names: [str], a list of the flag names to be checked. required: Boolean, if set, exactly one of the flags must be set. Otherwise, it is also valid for none of the flags to be set. flag_values: An optional FlagValues instance to valida...
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=FLAGS): def validate_mutual_exclusion(flags_dict): flag_count = sum(1 for val in flags_dict.values() if val is not None) if flag_count == 1 or (not required and flag_count == 0): return True...
523,510
Declares that all flags key to a module are key to the current module. Args: module: A module object. flag_values: A FlagValues object. This should almost never need to be overridden. Raises: Error: When given an argument that is a module name (a string), instead of a module object.
def ADOPT_module_key_flags( # pylint: disable=g-bad-name module, flag_values=FLAGS): if not isinstance(module, types.ModuleType): raise Error('Expected a module object, not %r.' % (module,)) # TODO(vrusinov): _GetKeyFlagsForModule should be public. _internal_declare_key_flags( [f.name for f in f...
523,514
Registers a flag whose value is a comma-separated list of strings. The flag value is parsed with a CSV parser. Args: name: A string, the flag name. default: The default value of the flag. help: A help string. flag_values: FlagValues object with which the flag will be registered. **args: Dictio...
def DEFINE_list( # pylint: disable=g-bad-name,redefined-builtin name, default, help, flag_values=FLAGS, **args): parser = ListParser() serializer = CsvListSerializer(',') DEFINE(parser, name, default, help, flag_values, serializer, **args)
523,517
Defines an alias flag for an existing one. Args: name: A string, name of the alias flag. original_name: A string, name of the original flag. flag_values: FlagValues object with which the flag will be registered. module_name: A string, the name of the module that defines this flag. Raises: gfla...
def DEFINE_alias(name, original_name, flag_values=FLAGS, module_name=None): # pylint: disable=g-bad-name if original_name not in flag_values: raise UnrecognizedFlagError(original_name) flag = flag_values[original_name] class _Parser(ArgumentParser): def parse(self, argument): flag.parse(a...
523,522
Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item.
def parse(self, arguments): if not isinstance(arguments, list): # Default value may be a list of values. Most other arguments # will not be, so convert them into a single-item list to make # processing simpler below. arguments = [arguments] if self.present: # keep a backup r...
523,530
Initialize EnumParser. Args: enum_values: Array of values in the enum. case_sensitive: Whether or not the enum is to be case-sensitive.
def __init__(self, enum_values=None, case_sensitive=True): super(EnumParser, self).__init__() self.enum_values = enum_values self.case_sensitive = case_sensitive
523,536
Initializer. Args: comma_compat: bool - Whether to support comma as an additional separator. If false then only whitespace is supported. This is intended only for backwards compatibility with flags that used to be comma-separated.
def __init__(self, comma_compat=False): self._comma_compat = comma_compat name = 'whitespace or comma' if self._comma_compat else 'whitespace' BaseListParser.__init__(self, None, name)
523,541
Export this name as a token. This method exports the name into a byte string which can then be imported by using the `token` argument of the constructor. Args: composite (bool): whether or not use to a composite token -- :requires-ext:`rfc6680` Returns: ...
def export(self, composite=False): if composite: if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does " "not support RFC 6680 (the GSSAPI " "naming extensions...
523,860
Create a Mechanism from its SASL name Args: name (str): SASL name of the desired mechanism Returns: Mechanism: the desired mechanism Raises: GSSError :requires-ext:`rfc5801`
def from_sasl_name(cls, name=None): if rfc5801 is None: raise NotImplementedError("Your GSSAPI implementation does not " "have support for RFC 5801") if isinstance(name, six.text_type): name = name.encode(_utils._get_encoding()) ...
523,870
Get a generator of mechanisms supporting the specified attributes. See RFC 5587's :func:`indicate_mechs_by_attrs` for more information. Args: desired_attrs ([OID]): Desired attributes except_attrs ([OID]): Except attributes critical_attrs ([OID]): Critical attributes...
def from_attrs(cls, desired_attrs=None, except_attrs=None, critical_attrs=None): if isinstance(desired_attrs, roids.OID): desired_attrs = set([desired_attrs]) if isinstance(except_attrs, roids.OID): except_attrs = set([except_attrs]) if isinsta...
523,871
Import a GSSAPI extension module This method imports a GSSAPI extension module based on the name of the extension (not including the 'ext_' prefix). If the extension is not available, the method retuns None. Args: name (str): the name of the extension Returns: module: Either ...
def import_gssapi_extension(name): try: path = 'gssapi.raw.ext_{0}'.format(name) __import__(path) return sys.modules[path] except ImportError: return None
523,872
Creates a property based on an inquire result This method creates a property that calls the :python:`_inquire` method, and return the value of the requested information. Args: name (str): the name of the 'inquire' result information Returns: property: the created property
def inquire_property(name, doc=None): def inquire_property(self): if not self._started: msg = ("Cannot read {0} from a security context whose " "establishment has not yet been started.") raise AttributeError(msg) return getattr(self._inquire(**{name:...
523,874
Finds the bit error probability bounds according to Ziemer and Tranter page 656. parameters: ----------- j: number of parity bits used in single error correction block code SNRdB: Eb/N0 values in dB coded: Select single error correction code (True) or uncoded (False) M: modulation orde...
def block_single_error_Pb_bound(j,SNRdB,coded=True,M=2): Pb = np.zeros_like(SNRdB) Ps = np.zeros_like(SNRdB) SNR = 10.**(SNRdB/10.) n = 2**j-1 k = n-j for i,SNRn in enumerate(SNR): if coded: # compute Hamming code Ps if M == 2: Ps[i] = Q_fctn(np.sqrt...
524,249
Given a list of units, remove a specified number of each base unit. Arguments: units: an iterable of units to_remove: a mapping of base_unit => count, such as that returned from count_base_units Returns a 2-tuple of (factor, remaining_units).
def cancel_base_units(units, to_remove): # Copy the dict since we're about to mutate it to_remove = to_remove.copy() remaining_units = [] total_factor = Fraction(1) for unit in units: factor, base_unit = get_conversion_factor(unit) if not to_remove.get(base_unit, 0): ...
524,897
Merge donor and acceptor timestamps and particle arrays. Parameters: ts_d (array): donor timestamp array ts_par_d (array): donor particles array ts_a (array): acceptor timestamp array ts_par_a (array): acceptor particles array Returns: Arrays: timestamps, acceptor bool ...
def merge_da(ts_d, ts_par_d, ts_a, ts_par_a): ts = np.hstack([ts_d, ts_a]) ts_par = np.hstack([ts_par_d, ts_par_a]) a_ch = np.hstack([np.zeros(ts_d.shape[0], dtype=bool), np.ones(ts_a.shape[0], dtype=bool)]) index_sort = ts.argsort() return ts[index_sort], a_ch[index_sort]...
525,604
Print all the sub-groups in `group` and leaf-nodes children of `group`. Parameters: data_file (pytables HDF5 file object): the data file to print group (string): path name of the group to be printed. Default: '/', the root node.
def print_children(data_file, group='/'): base = data_file.get_node(group) print ('Groups in:\n %s\n' % base) for node in base._f_walk_groups(): if node is not base: print (' %s' % node) print ('\nLeaf-nodes in %s:' % group) for node in base._v_leaves.itervalues(): ...
525,624
Retrieve the function defined by the function_name. Arguments: fn_name: specification of the type module:function_name.
def get_function(fn_name): module_name, callable_name = fn_name.split(':') current = globals() if not callable_name: callable_name = module_name else: import importlib try: module = importlib.import_module(module_name) except ImportError: log....
526,132
Parse command line argument. See -h option. Arguments: argv: arguments on the command line must include caller file name.
def parse_command_line(argv): import textwrap example = textwrap.dedent().format(os.path.basename(argv[0])) formatter_class = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(description="Python mass editor", epilog=example, ...
526,133
Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module name where to find the function. - executable (str): executable file name to execute on input ...
def __init__(self, **kwds): self.code_objs = dict() self._codes = [] self._functions = [] self._executables = [] self.dry_run = None self.encoding = 'utf-8' self.newline = None if 'module' in kwds: self.import_module(kwds['module']) ...
526,138
Processes a file contents. First processes the contents line by line applying the registered expressions, then process the resulting contents using the registered functions. Arguments: original_lines (list of str): file content. file_name (str): name of the file.
def edit_content(self, original_lines, file_name): lines = [self.edit_line(line) for line in original_lines] for function in self._functions: try: lines = list(function(lines, file_name)) except UnicodeDecodeError as err: log.error('failed...
526,142
Edit file in place, returns a list of modifications (unified diff). Arguments: file_name (str, unicode): The name of the file.
def edit_file(self, file_name): with io.open(file_name, "r", encoding=self.encoding) as from_file: try: from_lines = from_file.readlines() except UnicodeDecodeError as err: log.error("encoding error (see --encoding): %s", err) rais...
526,143
Handle timeout gracefully. Args: delay (int): delay before raising the timeout (in seconds)
async def _perform_ping_timeout(self, delay: int): # pause for delay seconds await sleep(delay) # then continue error = TimeoutError( 'Ping timeout: no data received from server in {timeout} seconds.'.format( timeout=self.PING_TIMEOUT)) await...
527,381
Drives the build of the final image - get the list of steps and execute them. Args: client (docker.Client): docker client object that will build the image nobuild (bool): just create dockerfiles, don't actually build the image usecache (bool): use docker cache, or rebuild ev...
def build(self, client, nobuild=False, usecache=True, pull=False): if not nobuild: self.update_source_images(client, usecache=usecache, pull=pull) width = utils.get...
527,511
Drives an individual build step. Build steps are separated by build_directory. If a build has zero one or less build_directories, it will be built in a single step. Args: client (docker.Client): docker client object that will build the image pull (bool): whether to pull ...
def build(self, client, pull=False, usecache=True): print(colored(' Building step', 'blue'), colored(self.imagename, 'blue', attrs=['bold']), colored('defined in', 'blue'), colored(self.sourcefile, 'blue', attrs=['bold'])) if self.build_first and not ...
527,518
Topologically sort the docker commands by their requirements Note: Circular "requires" dependencies are assumed to have already been checked in get_external_base_image, they are not checked here Args: image (str): process this docker image's dependencies d...
def sort_dependencies(self, image, dependencies=None): if dependencies is None: dependencies = OrderedDict() # using this as an ordered set - not storing any values if image in dependencies: return requires = self.ymldefs[image].get('requires', []) fo...
527,545
Copies the file from source to target Args: startimage (str): name of the image to stage these files into newimage (str): name of the created image
def stage(self, startimage, newimage): client = utils.get_client() cprint(' Copying file from "%s:/%s" \n to "%s://%s/"' % (self.sourceimage, self.sourcepath, startimage, self.destpath), 'blue') # copy build artifacts from the container if...
527,556
Creates a highlight aggregator - this will pick one of the values to highlight. Args: name: The name of this aggregator. fn: Callable that takes (a, b) and returns True if b should be selected as the highlight, where as is the previous chosen highlight.
def __init__(self, name, fn, dataFormat = DataFormats.DEFAULT): Aggregator.__init__(self, name) self.fn = fn
527,663
Load and return formal context from CSV file. Args: filename: Path to the CSV file to load the context from. dialect: Syntax variant of the CSV file (``'excel'``, ``'excel-tab'``). encoding (str): Encoding of the file (``'utf-8'``, ``'latin1'``, ``'ascii'``, ...). Example: >>> ...
def load_csv(filename, dialect='excel', encoding='utf-8'): return Context.fromfile(filename, 'csv', encoding, dialect=dialect)
527,782
Adds a router to the list of routers Args: path (str or regex): The path on which the router binds router (growler.Router): The router which will respond to requests Raises: TypeError: If `strict_router_check` attribute is True and th...
def add_router(self, path, router): if self.strict_router_check and not isinstance(router, Router): raise TypeError("Expected object of type Router, found %r" % type(router)) log.info("{} Adding router {} on path {}", id(self), router, path) self.middleware.add(path=path, ...
527,859
Prints a unix-tree-like output of the structure of the web application to the file specified (stdout by default). Args: EOL (str): The character or string that ends the line. **kwargs: Arguments pass to the standard print function. This allows specifying the file...
def print_middleware_tree(self, *, EOL=os.linesep, **kwargs): # noqa pragma: no cover def mask_to_method_name(mask): if mask == HTTPMethod.ALL: return 'ALL' methods = set(HTTPMethod) - {HTTPMethod.ALL} names = (method.name for method in methods if m...
527,864
Constructor Args: path (str): Top level directory to search for template files - the path must exist and the path must be a directory. Raises: FileNotFoundError: If the provided path does not exists. NotADirectoryError: If the path is not a directory...
def __init__(self, path): self.path = Path(path).resolve() if not self.path.is_dir(): log.warning("path given to render engine is not a directory") raise NotADirectoryError("path '%s' is not a directory" % path)
527,875
Searches for a file matching the given template name. If found, this method returns the pathlib.Path object of the found template file. Args: template_name (str): Name of the template, with or without a file extension. Returns: pathlib.Path: Pat...
def find_template_filename(self, template_name): def next_file(): filename = self.path / template_name yield filename try: exts = self.default_file_extensions except AttributeError: return strfilename = str(fi...
527,877
Attempts simple body data validation by comparining incoming data to the content length header. If passes store the data into self._buffer. Parameters: data (bytes): Incoming client data to be added to the body Raises: HTTPErrorBadRequest: Raised if data is sent...
def validate_and_store_body_data(self, data): # add data to end of buffer self.body_buffer[-1:] = data # if len(self.body_buffer) > self.content_length: problem = "Content length exceeds expected value (%d > %d)" % ( len(self.body_buffer), self.cont...
527,884
(asyncio.Protocol member) Called upon when there is a new socket connection. This creates a new responder (as determined by the member 'responder_type') and stores in a list. Incoming data from this connection will always call on_data to the last element of this list. A...
def connection_made(self, transport): self.transport = transport self.responders = [self.make_responder(self)] try: good_func = callable(self.responders[0].on_data) except AttributeError: good_func = False if not good_func: err_str =...
527,892
(asyncio.Protocol member) Called upon when a socket closes. This class simply logs the disconnection Args: exc (Exception or None): Error if connection closed unexpectedly, None if closed cleanly.
def connection_lost(self, exc): if exc: log.error("{:d} connection_lost {}", id(self), exc) else: log.info("{:d} connection_lost", id(self))
527,893
(asyncio.Protocol member) Called upon when there is new data to be passed to the protocol. The data is forwarded to the top of the responder stack (via the on_data method). If an excpetion occurs while this is going on, the Exception is forwarded to the protocol's handle...
def data_received(self, data): try: self.responders[-1].on_data(data) except Exception as error: self.handle_error(error)
527,894
Construct Static method. Args: path (str or list): The directory path to search for files. If this is a list, the paths will be path-joined automatically.
def __init__(self, path): # if list, do a pathjoin if isinstance(path, list): path = os.path.join(*path) # store as pathlib.Path, to avoid unexpected relative # path redirection self.path = Path(path).resolve() # ensure that path exists if n...
527,895
Calculate an etag value Args: a_file (pathlib.Path): The filepath to the Returns: String of the etag value to be sent back in header
def calculate_etag(file_path): stat = file_path.stat() etag = "%x-%x" % (stat.st_mtime_ns, stat.st_size) return etag
527,897
Equivalent to the python dict update method. Update the dictionary with the key/value pairs from other, overwriting existing keys. Args: other (dict): The source of key value pairs to add to headers Keyword Args: All keyword arguments are stored in header direct...
def update(self, *args, **kwargs): for next_dict in chain(args, (kwargs, )): for k, v in next_dict.items(): self[k] = v
527,917
Add a header to the collection, including potential parameters. Args: key (str): The name of the header value (str): The value to store under that key params: Option parameters to be appended to the value, automatically formatting them in a standard way
def add_header(self, key, value, **params): key = self.escape(key) ci_key = key.casefold() def quoted_params(items): for p in items: param_name = self.escape(p[0]) param_val = self.de_quote(self.escape(p[1])) yield param_name...
527,918
Returns representation of headers as a valid HTTP header string. This is called by __str__. Args: use_bytes (bool): Returns a bytes object instead of a str.
def stringify(self, use_bytes=False): def _str_value(value): if isinstance(value, (list, tuple)): value = (self.EOL + '\t').join(map(_str_value, value)) elif callable(value): value = _str_value(value()) return value s = self.E...
527,919
Scan through attributes of object parameter looking for any which match a route signature. A router will be created and added to the object with parameter. Args: obj (object): The object (with attributes) from which to setup a router Returns: Router: The router created from...
def routerify(obj): router = Router() for info in get_routing_attributes(obj): router.add_route(*info) obj.__growler_router = router return router
527,933
Call the provided middleware upon requests matching the path. If path is not provided or None, all requests will match. Args: middleware (callable): Callable with the signature ``(res, req) -> None`` path (Optional[str or regex]): a specific path the ...
def use(self, middleware, path=None): self.log.info(" Using middleware {}", middleware) if path is None: path = MiddlewareChain.ROOT_PATTERN self.add(HTTPMethod.ALL, path, middleware) return self
527,937
Construct HTTP parser. Parameters: parent (growler.HTTPResponder): The 'parent' responder which will forward client data to the parser, and the parser will send parsed data back to this object.
def __init__(self, parent): self.parent = parent self._buffer = bytearray() self.encoding = 'utf-8' self.headers = dict() # create the parser generator 'object' self._http_parser = self._http_parser() self._http_parser.send(None)
527,943
Looks for a newline character in bytestring parameter 'data'. Currently only looks for strings '\r\n', '\n'. If '\n' is found at the first position of the string, this raises an exception. Parameters: data (bytes): The data to be searched Returns: None: ...
def determine_newline(data): line_end_pos = data.find(b'\n') if line_end_pos == -1: return None elif line_end_pos == 0: return b'\n' prev_char = data[line_end_pos - 1] return b'\r\n' if (prev_char is b'\r'[0]) else b'\n'
527,951
Construct ResponseTime middleware. Parameters: digits (int): precision log (Logger or None): Writes the time difference to the log units (str): Time units (default: milliseconds 'ms') header (str): Name of header to send response time as suffix (bool)...
def __init__(self, digits=3, log=None, units='ms', header="X-Response-Time", suffix=True, clobber_header=False): self.units = units self.header_name = header self.digits = digits ...
527,953
Add a function to the middleware chain. This function is returned when iterating over the chain with matching method and path. Args: method_mask (growler.http.HTTPMethod): A bitwise mask intended to match specific request methods. path (str or regex): An object w...
def add(self, method_mask, path, func): is_err = len(signature(func).parameters) == 3 is_subchain = isinstance(func, MiddlewareChain) tup = MiddlewareNode(func=func, mask=method_mask, path=path, is_er...
527,963
Returns whether the function is stored anywhere in the middleware chain. This runs recursively though any subchains. Args: func (callable): A function which may be present in the chain Returns: bool: True if func is a function contained anywhere in the chain.
def __contains__(self, func): return any((func is mw.func) or (mw.is_subchain and func in mw.func) for mw in self.mw_list)
527,964
Ensure that user is authenticated otherwise return ``401 Unauthorized``. If request fails to authenticate this authorization hook will also include list of ``WWW-Athenticate`` challenges. Args: req (falcon.Request): the request object. resp (falcon.Response): the response object. r...
def authentication_required(req, resp, resource, uri_kwargs): if 'user' not in req.context: args = ["Unauthorized", "This resource requires authentication"] # compat: falcon >= 1.0.0 requires the list of challenges if FALCON_VERSION >= (1, 0, 0): args.append(req.context.get...
528,571
Create fields dictionary to be used in resource class namespace. Pop all field objects from attributes dict (namespace) and store them under _field_storage_key atrribute. Also collect all fields from base classes in order that ensures fields can be overriden. Args: bases: a...
def _get_fields(mcs, bases, namespace): fields = [ (name, namespace.pop(name)) for name, attribute in list(namespace.items()) if isinstance(attribute, BaseField) ] for base in reversed(bases): if hasattr(base, mcs._fields_stor...
528,663
Get attribute of given object instance. Reason for existence of this method is the fact that 'attribute' can be also object's key from if is a dict or any other kind of mapping. Note: it will return None if attribute key does not exist Args: obj (object): internal object ...
def get_attribute(self, obj, attr): # '*' is a special wildcard character that means whole object # is passed if attr == '*': return obj # if this is any mapping then instead of attributes use keys if isinstance(obj, Mapping): return obj.get(attr...
528,668
Set value of attribute in given object instance. Reason for existence of this method is the fact that 'attribute' can be also a object's key if it is a dict or any other kind of mapping. Args: obj (object): object instance to modify attr (str): attribute (or key) to cha...
def set_attribute(self, obj, attr, value): # if this is any mutable mapping then instead of attributes use keys if isinstance(obj, MutableMapping): obj[attr] = value else: setattr(obj, attr, value)
528,669
Extend default meta dictionary value with pagination hints. Note: This method handler attaches values to ``meta`` dictionary without changing it's reference. This means that you should never replace ``meta`` dictionary with any other dict instance but simply modify ...
def add_pagination_meta(self, params, meta): meta['page_size'] = params['page_size'] meta['page'] = params['page'] meta['prev'] = "page={0}&page_size={1}".format( params['page'] - 1, params['page_size'] ) if meta['page'] > 0 else None meta['next'] = "page={...
528,701
Create params dictionary to be used in resource class namespace. Pop all parameter objects from attributes dict (namespace) and store them under _params_storage_key atrribute. Also collect all params from base classes in order that ensures params can be overriden. Args: ...
def _get_params(mcs, bases, namespace): params = [ (name, namespace.pop(name)) for name, attribute in list(namespace.items()) if isinstance(attribute, BaseParam) ] for base in reversed(bases): if hasattr(base, mcs._params_stor...
528,825
Require all defined parameters from request query string. Raises ``falcon.errors.HTTPMissingParam`` exception if any of required parameters is missing and ``falcon.errors.HTTPInvalidParam`` if any of parameters could not be understood (wrong format). Args: req (falcon.Reque...
def require_params(self, req): params = {} for name, param in self.params.items(): if name not in req.params and param.required: # we could simply raise with this single param or use get_param # with required=True parameter but for client convenience...
528,833
Require raw representation dictionary from falcon request object. This does not perform any field parsing or validation but only uses allowed content-encoding handler to decode content body. Note: Currently only JSON is allowed as content type. Args: req (falco...
def require_representation(self, req): try: type_, subtype, _ = parse_mime_type(req.content_type) content_type = '/'.join((type_, subtype)) except: raise falcon.HTTPUnsupportedMediaType( description="Invalid Content-Type header: {}".format( ...
528,835
Get user object for given identifier. Args: identified_with (object): authentication middleware used to identify the user. identifier: middleware specifix user identifier (string or tuple in case of all built in authentication middleware classes). ...
def get_user( self, identified_with, identifier, req, resp, resource, uri_kwargs ): stored_value = self.kv_store.get( self._get_storage_key(identified_with, identifier) ) if stored_value is not None: user = self.serialization.loads(stored_value.decode...
528,900
Register new key for given client identifier. This is only a helper method that allows to register new user objects for client identities (keys, tokens, addresses etc.). Args: identified_with (object): authentication middleware used to identify the user. ...
def register(self, identified_with, identifier, user): self.kv_store.set( self._get_storage_key(identified_with, identifier), self.serialization.dumps(user).encode(), )
528,901
Process resource after routing to it. This is basic falcon middleware handler. Args: req (falcon.Request): request object resp (falcon.Response): response object resource (object): resource object matched by falcon router uri_kwargs (dict): additional ke...
def process_resource(self, req, resp, resource, uri_kwargs=None): if 'user' in req.context: return identifier = self.identify(req, resp, resource, uri_kwargs) user = self.try_storage(identifier, req, resp, resource, uri_kwargs) if user is not None: req....
528,903
Try to find user in configured user storage object. Args: identifier: User identifier. Returns: user object.
def try_storage(self, identifier, req, resp, resource, uri_kwargs): if identifier is None: user = None # note: if user_storage is defined, always use it in order to # authenticate user. elif self.user_storage is not None: user = self.user_storage.g...
528,904
Get address from ``X-Forwarded-For`` header or use remote address. Remote address is used if the ``X-Forwarded-For`` header is not available. Note that this may not be safe to depend on both without proper authorization backend. Args: req (falcon.Request): falcon.Request ob...
def _get_client_address(self, req): try: forwarded_for = req.get_header('X-Forwarded-For', True) return forwarded_for.split(',')[0].strip() except (KeyError, HTTPMissingHeader): return ( req.env.get('REMOTE_ADDR') if self.remote_address_fallba...
528,910
Return validator function that ensures lower bound of a number. Result validation function will validate the internal value of resource instance field with the ``value >= min_value`` check Args: min_value: minimal value for new validator
def min_validator(min_value): def validator(value): if value < min_value: raise ValidationError("{} is not >= {}".format(value, min_value)) return validator
528,997
Return validator function that ensures upper bound of a number. Result validation function will validate the internal value of resource instance field with the ``value >= min_value`` check. Args: max_value: maximum value for new validator
def max_validator(max_value): def validator(value): if value > max_value: raise ValidationError("{} is not <= {}".format(value, max_value)) return validator
528,998
Return validator function that will check if ``value in choices``. Args: max_value (list, set, tuple): allowed choices for new validator
def choices_validator(choices): def validator(value): if value not in choices: # note: make it a list for consistent representation raise ValidationError( "{} is not in {}".format(value, list(choices)) ) return validator
528,999
Return validator function that will check if matches given expression. Args: match: if string then this will be converted to regular expression using ``re.compile``. Can be also any object that has ``match()`` method like already compiled regular regular expression or custom ...
def match_validator(expression): if isinstance(expression, str): compiled = re.compile(expression) elif hasattr(expression, 'match'): # check it early so we could say something is wrong early compiled = expression else: raise TypeError( 'Provided match is nor...
529,000
Generates a plane on the xz axis of a specific size and resolution. Normals and texture coordinates are also included. Args: size: (x, y) tuple resolution: (x, y) tuple Returns: A :py:class:`demosys.opengl.vao.VAO` instance
def plane_xz(size=(10, 10), resolution=(10, 10)) -> VAO: sx, sz = size rx, rz = resolution dx, dz = sx / rx, sz / rz # step ox, oz = -sx / 2, -sz / 2 # start offset def gen_pos(): for z in range(rz): for x in range(rx): yield ox + x * dx yi...
529,095
Generates random positions inside a confied box. Args: count (int): Number of points to generate Keyword Args: range_x (tuple): min-max range for x axis: Example (-10.0. 10.0) range_y (tuple): min-max range for y axis: Example (-10.0. 10.0) range_z (tuple): min-max range for z ...
def points_random_3d(count, range_x=(-10.0, 10.0), range_y=(-10.0, 10.0), range_z=(-10.0, 10.0), seed=None) -> VAO: random.seed(seed) def gen(): for _ in range(count): yield random.uniform(*range_x) yield random.uniform(*range_y) yield random.uniform(*range_z) ...
529,170
Set the current time jumping in the timeline. Args: value (float): The new time
def set_time(self, value: float): if value < 0: value = 0 self.controller.row = self.rps * value
529,205
Draw function called by the system every frame when the effect is active. This method raises ``NotImplementedError`` unless implemented. Args: time (float): The current time in seconds. frametime (float): The time the previous frame used to render in seconds. target ...
def draw(self, time: float, frametime: float, target: moderngl.Framebuffer): raise NotImplementedError("draw() is not implemented")
529,206
Get a program by its label Args: label (str): The label for the program Returns: py:class:`moderngl.Program` instance
def get_program(self, label: str) -> moderngl.Program: return self._project.get_program(label)
529,207
Get a texture by its label Args: label (str): The Label for the texture Returns: The py:class:`moderngl.Texture` instance
def get_texture(self, label: str) -> Union[moderngl.Texture, moderngl.TextureArray, moderngl.Texture3D, moderngl.TextureCube]: return self._project.get_texture(label)
529,208
Get an effect class by the class name Args: effect_name (str): Name of the effect class Keyword Args: package_name (str): The package the effect belongs to. This is optional and only needed when effect class names are not unique. Returns...
def get_effect_class(self, effect_name: str, package_name: str = None) -> Type['Effect']: return self._project.get_effect_class(effect_name, package_name=package_name)
529,209
Create a projection matrix with the following parameters. When ``aspect_ratio`` is not provided the configured aspect ratio for the window will be used. Args: fov (float): Field of view (float) near (float): Camera near value far (float): Camrea far value ...
def create_projection(self, fov: float = 75.0, near: float = 1.0, far: float = 100.0, aspect_ratio: float = None): return matrix44.create_perspective_projection_matrix( fov, aspect_ratio or self.window.aspect_ratio, near, far, dtype='f4', ...
529,210
Creates a transformation matrix woth rotations and translation. Args: rotation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3` translation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3` Returns: A 4x4 matrix as a :py:class:`numpy...
def create_transformation(self, rotation=None, translation=None): mat = None if rotation is not None: mat = Matrix44.from_eulers(Vector3(rotation)) if translation is not None: trans = matrix44.create_from_translation(Vector3(translation)) if mat is N...
529,211
Creates a normal matrix from modelview matrix Args: modelview: The modelview matrix Returns: A 3x3 Normal matrix as a :py:class:`numpy.array`
def create_normal_matrix(self, modelview): normal_m = Matrix33.from_matrix44(modelview) normal_m = normal_m.inverse normal_m = normal_m.transpose() return normal_m
529,212
Creates a 2D quad VAO using 2 triangles with normals and texture coordinates. Args: width (float): Width of the quad height (float): Height of the quad Keyword Args: xpos (float): Center position x ypos (float): Center position y Returns: A :py:class:`demosys.openg...
def quad_2d(width, height, xpos=0.0, ypos=0.0) -> VAO: pos = numpy.array([ xpos - width / 2.0, ypos + height / 2.0, 0.0, xpos - width / 2.0, ypos - height / 2.0, 0.0, xpos + width / 2.0, ypos - height / 2.0, 0.0, xpos - width / 2.0, ypos + height / 2.0, 0.0, xpos + width...
529,254
Set the current time. This can be used to jump in the timeline. Args: value (float): The new time
def set_time(self, value: float): if value < 0: value = 0 self.offset += self.get_time() - value
529,262
Draws a frame. Internally it calls the configured timeline's draw method. Args: current_time (float): The current time (preferrably always from the configured timer class) frame_time (float): The duration of the previous frame in seconds
def draw(self, current_time, frame_time): self.set_default_viewport() self.timeline.draw(current_time, frame_time, self.fbo)
529,295
Sets the clear values for the window buffer. Args: red (float): red compoent green (float): green compoent blue (float): blue compoent alpha (float): alpha compoent depth (float): depth value
def clear_values(self, red=0.0, green=0.0, blue=0.0, alpha=0.0, depth=1.0): self.clear_color = (red, green, blue, alpha) self.clear_depth = depth
529,297
Handles the standard keyboard events such as camera movements, taking a screenshot, closing the window etc. Can be overriden add new keyboard events. Ensure this method is also called if you want to keep the standard features. Arguments: key: The key that was pressed or rel...
def keyboard_event(self, key, action, modifier): # The well-known standard key for quick exit if key == self.keys.ESCAPE: self.close() return # Toggle pause time if key == self.keys.SPACE and action == self.keys.ACTION_PRESS: self.timer.toggl...
529,298
The standard mouse movement event method. Can be overriden to add new functionality. By default this feeds the system camera with new values. Args: x: The current mouse x position y: The current mouse y position dx: Delta x postion (x position difference from...
def cursor_event(self, x, y, dx, dy): self.sys_camera.rot_state(x, y)
529,299
Render the VAO. Args: program: The ``moderngl.Program`` Keyword Args: mode: Override the draw mode (``TRIANGLES`` etc) vertices (int): The number of vertices to transform first (int): The index of the first vertex to start with instances (int...
def render(self, program: moderngl.Program, mode=None, vertices=-1, first=0, instances=1): vao = self.instance(program) if mode is None: mode = self.mode vao.render(mode, vertices=vertices, first=first, instances=instances)
529,321
Transform vertices. Stores the output in a single buffer. Args: program: The ``moderngl.Program`` buffer: The ``moderngl.buffer`` to store the output Keyword Args: mode: Draw mode (for example ``moderngl.POINTS``) vertices (int): The number of vertices t...
def transform(self, program: moderngl.Program, buffer: moderngl.Buffer, mode=None, vertices=-1, first=0, instances=1): vao = self.instance(program) if mode is None: mode = self.mode vao.transform(buffer, mode=mode, vertices=vertices, first=first, instance...
529,323
Set the index buffer for this VAO Args: buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes`` Keyword Args: index_element_size (int): Byte size of each element. 1, 2 or 4
def index_buffer(self, buffer, index_element_size=4): if not type(buffer) in [moderngl.Buffer, numpy.ndarray, bytes]: raise VAOError("buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance") if isinstance(buffer, numpy.ndarray): buffer = self.ctx.bu...
529,325
Creates a cube VAO with normals and texture coordinates Args: width (float): Width of the cube height (float): Height of the cube depth (float): Depth of the cube Keyword Args: center: center of the cube as a 3-component tuple normals: (bool) Include normals uvs...
def cube(width, height, depth, center=(0.0, 0.0, 0.0), normals=True, uvs=True) -> VAO: width, height, depth = width / 2.0, height / 2.0, depth / 2.0 pos = numpy.array([ center[0] + width, center[1] - height, center[2] + depth, center[0] + width, center[1] + height, center[2] + depth, ...
529,328
Parse the effect package string. Can contain the package python path or path to effect class in an effect package. Examples:: # Path to effect pacakge examples.cubes # Path to effect class examples.cubes.Cubes Args: path: python path to effect package. May also in...
def parse_package_string(path): parts = path.split('.') # Is the last entry in the path capitalized? if parts[-1][0].isupper(): return ".".join(parts[:-1]), parts[-1] return path, ""
529,345
Get a package by python path. Can also contain path to an effect. Args: name (str): Path to effect package or effect Returns: The requested EffectPackage Raises: EffectError when no package is found
def get_package(self, name) -> 'EffectPackage': name, cls_name = parse_package_string(name) try: return self.package_map[name] except KeyError: raise EffectError("No package '{}' registered".format(name))
529,349
Find an effect class by class name or full python path to class Args: path (str): effect class name or full python path to effect class Returns: Effect class Raises: EffectError if no class is found
def find_effect_class(self, path) -> Type[Effect]: package_name, class_name = parse_package_string(path) if package_name: package = self.get_package(package_name) return package.find_effect_class(class_name, raise_for_error=True) for package in self.packages: ...
529,350
Create an effect instance adding it to the internal effects dictionary using the label as key. Args: label (str): The unique label for the effect instance name (str): Name or full python path to the effect class we want to instantiate args: Positional arguments to the e...
def create_effect(self, label: str, name: str, *args, **kwargs) -> Effect: effect_cls = effects.find_effect_class(name) effect = effect_cls(*args, **kwargs) effect._label = label if label in self._effects: raise ValueError("An effect with label '{}' already e...
529,379
Get an effect instance by label Args: label (str): The label for the effect instance Returns: Effect class instance
def get_effect(self, label: str) -> Effect: return self._get_resource(label, self._effects, "effect")
529,383
Get an effect class from the effect registry. Args: class_name (str): The exact class name of the effect Keyword Args: package_name (str): The python path to the effect package the effect name is located. This is optional and can be used t...
def get_effect_class(self, class_name, package_name=None) -> Type[Effect]: if package_name: return effects.find_effect_class("{}.{}".format(package_name, class_name)) return effects.find_effect_class(class_name)
529,384
Gets a scene by label Args: label (str): The label for the scene to fetch Returns: Scene instance
def get_scene(self, label: str) -> Scene: return self._get_resource(label, self._scenes, "scene")
529,385