INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create database relationships between the link node dataset and the channel input file. The link node dataset only stores references to the links and nodes--not the geometry. The link and node geometries are stored in the channel input file. The two files must be linked with database relationships to ...
def linkToChannelInputFile(self, session, channelInputFile, force=False): """ Create database relationships between the link node dataset and the channel input file. The link node dataset only stores references to the links and nodes--not the geometry. The link and node geometries are s...
Generate a KML visualization of the the link node dataset file. Link node dataset files are time stamped link node value datasets. This will yield a value for each stream node at each time step that output is written. The resulting KML visualization will be an animation. The stream nodes are r...
def getAsKmlAnimation(self, session, channelInputFile, path=None, documentName=None, styles={}): """ Generate a KML visualization of the the link node dataset file. Link node dataset files are time stamped link node value datasets. This will yield a value for each stream node at each ti...
Link Node Dataset File Read from File Method
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): """ Link Node Dataset File Read from File Method """ # Set file extension property self.fileExtension = extension # Dictionary of keywords/cards and parse...
Link Node Dataset File Write to File Method
def _write(self, session, openFile, replaceParamFile): """ Link Node Dataset File Write to File Method """ # Retrieve TimeStep objects timeSteps = self.timeSteps # Write Lines openFile.write('%s\n' % self.name) openFile.write('NUM_LINKS %s\n' % self.n...
Log into container.
def login(container): """Log into container.""" columns, lines = shutil.get_terminal_size() # Temporary try: subprocess.check_call([ "docker", "exec", "--env", f"COLUMNS={str(columns)},LINES={str(lines)}", # Temporary "--env", f"LINES={str(lines)}", # Temporary...
Adds/updates card for gssha project file
def _update_card(self, card_name, new_value, add_quotes=False): """ Adds/updates card for gssha project file """ self.project_manager.setCard(card_name, new_value, add_quotes)
Update GSSHA simulation start time
def _update_simulation_start(self, simulation_start): """ Update GSSHA simulation start time """ self.simulation_start = simulation_start if self.simulation_duration is not None and self.simulation_start is not None: self.simulation_end = self.simulation_start + self....
Update GSSHA cards for simulation start
def _update_simulation_start_cards(self): """ Update GSSHA cards for simulation start """ if self.simulation_start is not None: self._update_card("START_DATE", self.simulation_start.strftime("%Y %m %d")) self._update_card("START_TIME", self.simulation_start.strfti...
Update simulation end time from LSM
def _update_simulation_end_from_lsm(self): """ Update simulation end time from LSM """ te = self.l2g.xd.lsm.datetime[-1] simulation_end = te.replace(tzinfo=utc) \ .astimezone(tz=self.tz) \ .replace(tzinfo=None) if sel...
Adds a precip file to project with interpolation_type
def add_precip_file(self, precip_file_path, interpolation_type=None): """ Adds a precip file to project with interpolation_type """ # precip file read in self._update_card('PRECIP_FILE', precip_file_path, True) if interpolation_type is None: # check if precip...
Prepares Gage output for GSSHA simulation Parameters: lsm_precip_data_var(list or str): String of name for precipitation variable name or list of precip variable names. See: :func:`~gsshapy.grid.GRIDtoGSSHA.lsm_precip_to_gssha_precip_gage`. lsm_precip_type(str): Type of precipitation. ...
def prepare_gag_lsm(self, lsm_precip_data_var, lsm_precip_type, interpolation_type=None): """ Prepares Gage output for GSSHA simulation Parameters: lsm_precip_data_var(list or str): String of name for precipitation variable name or list of precip variable names. See: :func:`~gsshap...
Prepares RAPID streamflow for GSSHA simulation
def prepare_rapid_streamflow(self, path_to_rapid_qout, connection_list_file): """ Prepares RAPID streamflow for GSSHA simulation """ ihg_filename = '{0}.ihg'.format(self.project_manager.name) with tmp_chdir(self.project_manager.project_directory): # write out IHG file...
set the simulation_duration see: http://www.gsshawiki.com/Project_File:Required_Inputs
def set_simulation_duration(self, simulation_duration): """ set the simulation_duration see: http://www.gsshawiki.com/Project_File:Required_Inputs """ self.project_manager.setCard('TOT_TIME', str(simulation_duration.total_seconds()/60.0)) super(EventMode, self).set_simula...
Add a uniform precip event
def add_uniform_precip_event(self, intensity, duration): """ Add a uniform precip event """ self.project_manager.setCard('PRECIP_UNIF', '') self.project_manager.setCard('RAIN_INTENSITY', str(intensity)) self.project_manager.setCard('RAIN_DURATION', str(duration.total_seco...
Based on timezone and start date, the GMT card is updated
def _update_gmt(self): """ Based on timezone and start date, the GMT card is updated """ if self.simulation_start is not None: # NOTE: Because of daylight savings time, # offset result depends on time of the year offset_string = str(self.simulation_sta...
Prepares HMET data for GSSHA simulation from land surface model data. Parameters: lsm_data_var_map_array(str): Array with connections for LSM output and GSSHA input. See: :func:`~gsshapy.grid.GRIDtoGSSHA.` hmet_ascii_output_folder(Optional[str]): Path to diretory to output HMET ASCII fi...
def prepare_hmet_lsm(self, lsm_data_var_map_array, hmet_ascii_output_folder=None, netcdf_file_path=None): """ Prepares HMET data for GSSHA simulation from land surface model data. Parameters: lsm_data_var_map_array(str): Array with c...
Returns the terminal's width (number of character columns).
def terminal_width(): """Returns the terminal's width (number of character columns).""" try: if os.name == 'nt': _WindowsCSBI.initialize() return _WindowsCSBI.get_info(_WindowsCSBI.HANDLE_STDOUT)['terminal_width'] return struct.unpack('hhhh', fcntl.ioctl(0, termios.TIOCGW...
Returns the number of characters available if sample string were to be printed in the terminal. Positional arguments: sample_string -- gets the length of this string. Keyword arguments: max_terminal_width -- limit the overall width of everything to these many characters. Returns: Integer.
def get_remaining_width(sample_string, max_terminal_width=None): """Returns the number of characters available if sample string were to be printed in the terminal. Positional arguments: sample_string -- gets the length of this string. Keyword arguments: max_terminal_width -- limit the overall widt...
Defines structs and populates _WindowsCSBI.CSBI.
def _define_csbi(): """Defines structs and populates _WindowsCSBI.CSBI.""" if _WindowsCSBI.CSBI is not None: return class COORD(ctypes.Structure): """Windows COORD structure. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682119""" _fields_ = [('X'...
Initializes the WINDLL resource and populated the CSBI class variable.
def initialize(): """Initializes the WINDLL resource and populated the CSBI class variable.""" _WindowsCSBI._define_csbi() _WindowsCSBI.HANDLE_STDERR = _WindowsCSBI.HANDLE_STDERR or _WindowsCSBI.WINDLL.kernel32.GetStdHandle(-12) _WindowsCSBI.HANDLE_STDOUT = _WindowsCSBI.HANDLE_STDOUT or ...
Get information about this current console window (for Microsoft Windows only). Raises IOError if attempt to get information fails (if there is no console window). Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method. Positional arguments: ...
def get_info(handle): """Get information about this current console window (for Microsoft Windows only). Raises IOError if attempt to get information fails (if there is no console window). Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method. ...
Applying genotype calls to multi-way alignment incidence matrix :param alnfile: alignment incidence file (h5), :param gtypefile: genotype calls by GBRS (tsv), :param grpfile: gene ID to isoform ID mapping info (tsv) :return: genotyped version of alignment incidence file (h5)
def stencil(**kwargs): """ Applying genotype calls to multi-way alignment incidence matrix :param alnfile: alignment incidence file (h5), :param gtypefile: genotype calls by GBRS (tsv), :param grpfile: gene ID to isoform ID mapping info (tsv) :return: genotyped version of alignment incidence fi...
Quantify expected read counts :param alnfile: alignment incidence file (h5) :param grpfile: gene ID to isoform ID mapping info (tsv) :param lenfile: transcript lengths (tsv) :param multiread_model: emase model (default: 4) :param read_length: read length (default: 100) :param pseudocount: prior...
def quantify(**kwargs): """ Quantify expected read counts :param alnfile: alignment incidence file (h5) :param grpfile: gene ID to isoform ID mapping info (tsv) :param lenfile: transcript lengths (tsv) :param multiread_model: emase model (default: 4) :param read_length: read length (default...
Bulk ``register_item``. Args: items (iterable[Tree]): Sequence of nodes to be registered as children.
def register_items(self, items): """Bulk ``register_item``. Args: items (iterable[Tree]): Sequence of nodes to be registered as children. """ for item in items: item.set_parent(self) self.items.extend(items)
Get all the endpoints under this node in a tree like structure. Returns: (tuple): name (str): This node's name. endpoint (str): Endpoint name relative to root. children (list): ``child.endpoints for each child
def endpoints(self): """ Get all the endpoints under this node in a tree like structure. Returns: (tuple): name (str): This node's name. endpoint (str): Endpoint name relative to root. children (list): ``child.endpoints for each child ...
Get the absolute name of ``self``. Returns: str: the absolute name.
def absolute_name(self): """Get the absolute name of ``self``. Returns: str: the absolute name. """ if self.is_root() or self.parent.is_root(): return utils.slugify(self.name) return ':'.join([self.parent.absolute_name, utils.slugify(self.name)])
Get the absolute url of ``self``. Returns: str: the absolute url.
def absolute_url(self): """Get the absolute url of ``self``. Returns: str: the absolute url. """ if self.is_root(): return utils.concat_urls(self.url) return utils.concat_urls(self.parent.absolute_url, self.url)
assumes eastward motion
def split_tracks(lat,lon,*args): '''assumes eastward motion''' tracks = [] lt,ln = [lat[0]],[lon[0]] zz = [[z[0]] for z in args] for i in range(1,len(lon)): lt.append(lat[i]) for z,a in zip(zz,args): z.append(a[i]) d1 = abs(lon[...
Returns the fraction with additional whitespace.
def str_fraction(self): """Returns the fraction with additional whitespace.""" if self.undefined: return None denominator = locale.format('%d', self.denominator, grouping=True) numerator = self.str_numerator.rjust(len(denominator)) return '{0}/{1}'.format(numerator, d...
Returns the fraction with additional whitespace.
def str_fraction(self): """Returns the fraction with additional whitespace.""" if self._eta.undefined: return None # Determine denominator and its unit. unit_denominator, unit = self._unit_class(self.denominator).auto formatter = '%d' if unit_denominator == self.deno...
Returns the numerator with formatting.
def str_numerator(self): """Returns the numerator with formatting.""" if not self.undefined: return None unit_numerator, unit = self._unit_class(self.numerator).auto formatter = '%d' if unit_numerator == self.numerator else '%0.2f' numerator = locale.format(formatter,...
Returns a formatted ETA value for the progress bar.
def str_eta(self): """Returns a formatted ETA value for the progress bar.""" eta = eta_letters(self._eta.elapsed) if self.done else self._eta_string if not eta: return '' if eta.count(' ') > 1: eta = ' '.join(eta.split(' ')[:2]) # Only show up to two units (h and...
Returns the rate with formatting. If done, returns the overall rate instead.
def str_rate(self): """Returns the rate with formatting. If done, returns the overall rate instead.""" # Handle special cases. if not self._eta.started or self._eta.stalled or not self.rate: return '--.-KiB/s' unit_rate, unit = UnitByte(self._eta.rate_overall if self.done el...
Returns a formatted ETA value for the progress bar.
def str_eta(self): """Returns a formatted ETA value for the progress bar.""" if self.done: return eta_hms(self._eta.elapsed, always_show_hours=True, hours_leading_zero=True) if not self._eta_string: return '' return '{0} ETA'.format(self._eta_string)
Returns the numerator with formatting.
def str_numerator(self): """Returns the numerator with formatting.""" unit_numerator, unit = UnitByte(self.numerator).auto_no_thousands if unit_numerator >= 10: formatter = '%d' else: formatter = '%0.1f' return '{0} {1}'.format(locale.format(formatter, uni...
Returns the rate with formatting.
def str_rate(self): """Returns the rate with formatting.""" # Handle special cases. if not self._eta.started or self._eta.stalled or not self.rate: return '--- KiB/s' unit_rate, unit = UnitByte(self.rate).auto_no_thousands if unit_rate >= 10: formatter = ...
Initialize database with gsshapy tables
def init_db(sqlalchemy_url): """ Initialize database with gsshapy tables """ engine = create_engine(sqlalchemy_url) start = time.time() metadata.create_all(engine) return time.time() - start
Initialize SQLite in Memory Only Database Args: initTime(Optional[bool]): If True, it will print the amount of time to generate database. Returns: tuple: The tuple contains sqlalchemy_url(str), which is the path to use when creating a session as well as engine(str), which is the p...
def init_sqlite_memory(initTime=False): """ Initialize SQLite in Memory Only Database Args: initTime(Optional[bool]): If True, it will print the amount of time to generate database. Returns: tuple: The tuple contains sqlalchemy_url(str), which is the path to use when creat...
Initialize SQLite Database Args: path(str): Path to database (Ex. '/home/username/my_sqlite.db'). initTime(Optional[bool]): If True, it will print the amount of time to generate database. Example:: from gsshapy.lib.db_tools import init_sqlite_db, create_session ...
def init_sqlite_db(path, initTime=False): """ Initialize SQLite Database Args: path(str): Path to database (Ex. '/home/username/my_sqlite.db'). initTime(Optional[bool]): If True, it will print the amount of time to generate database. Example:: from gsshapy.lib.db_tools...
Initialize PostgreSQL Database .. note:: psycopg2 or similar driver required Args: username(str): Database username. host(str): Database host URL. database(str): Database name. port(Optional[int,str]): Database port. password(Optional[str]): Database password. ...
def init_postgresql_db(username, host, database, port='', password='', initTime=False): """ Initialize PostgreSQL Database .. note:: psycopg2 or similar driver required Args: username(str): Database username. host(str): Database host URL. database(str): Database name. ...
Initialize MySQL Database .. note:: mysql-python or similar driver required Args: username(str): Database username. host(str): Database host URL. database(str): Database name. port(Optional[int,str]): Database port. password(Optional[str]): Database password. ...
def init_mysql_db(username, host, database, port='', password='', initTime=False): """ Initialize MySQL Database .. note:: mysql-python or similar driver required Args: username(str): Database username. host(str): Database host URL. database(str): Database name. ...
Create session with database to work in
def get_sessionmaker(sqlalchemy_url, engine=None): """ Create session with database to work in """ if engine is None: engine = create_engine(sqlalchemy_url) return sessionmaker(bind=engine)
Load project manager and in memory sqlite db sessionmaker for GSSHA project
def get_project_session(project_name, project_directory, map_type=None): """ Load project manager and in memory sqlite db sessionmaker for GSSHA project """ sqlalchemy_url, sql_engine = init_sqlite_memory() gdb_sessionmaker = get_sessionmaker(sqlalchemy_url, sql_engine) project_manager = Project...
Load the settings from a named section. .. code-block:: python settings = plaster.get_settings(...) print(settings['foo']) :param config_uri: Anything that can be parsed by :func:`plaster.parse_uri`. :param section: The name of the section in the config file. If this is `...
def get_settings(config_uri, section=None, defaults=None): """ Load the settings from a named section. .. code-block:: python settings = plaster.get_settings(...) print(settings['foo']) :param config_uri: Anything that can be parsed by :func:`plaster.parse_uri`. :param se...
Find a :class:`plaster.ILoader` object capable of handling ``config_uri``. :param config_uri: Anything that can be parsed by :func:`plaster.parse_uri`. :param protocols: Zero or more :term:`loader protocol` identifiers that the loader must implement to match the desired ``config_uri``. :r...
def get_loader(config_uri, protocols=None): """ Find a :class:`plaster.ILoader` object capable of handling ``config_uri``. :param config_uri: Anything that can be parsed by :func:`plaster.parse_uri`. :param protocols: Zero or more :term:`loader protocol` identifiers that the loader mus...
Find all loaders that match the requested scheme and protocols. :param scheme: Any valid scheme. Examples would be something like ``ini`` or ``ini+pastedeploy``. :param protocols: Zero or more :term:`loader protocol` identifiers that the loader must implement. If ``None`` then only generic loa...
def find_loaders(scheme, protocols=None): """ Find all loaders that match the requested scheme and protocols. :param scheme: Any valid scheme. Examples would be something like ``ini`` or ``ini+pastedeploy``. :param protocols: Zero or more :term:`loader protocol` identifiers that the lo...
Overwriting :meth:`Actor.receive`, adds the checks and functionalities requiered by parallel methods. :param msg: The message is a dictionary using the constants defined in util.py (:mod:`pyactor.util`).
def receive(self, msg): ''' Overwriting :meth:`Actor.receive`, adds the checks and functionalities requiered by parallel methods. :param msg: The message is a dictionary using the constants defined in util.py (:mod:`pyactor.util`). ''' if msg[TYPE] == TELL an...
Combines multiple dicts in one. :param dicts: A sequence of dicts. :type dicts: dict :param copy: If True, it returns a deepcopy of input values. :type copy: bool, optional :param base: Base dict where combine multiple dicts in one. :type base: dict, optional :ret...
def combine_dicts(*dicts, copy=False, base=None): """ Combines multiple dicts in one. :param dicts: A sequence of dicts. :type dicts: dict :param copy: If True, it returns a deepcopy of input values. :type copy: bool, optional :param base: Base dict where combine m...
Merges and defines dictionaries with values identical to keys. :param kk: A sequence of keys and/or dictionaries. :type kk: object | dict, optional :param adict: A dictionary. :type adict: dict, optional :return: Merged dictionary. :rtype: dict Example:: ...
def kk_dict(*kk, **adict): """ Merges and defines dictionaries with values identical to keys. :param kk: A sequence of keys and/or dictionaries. :type kk: object | dict, optional :param adict: A dictionary. :type adict: dict, optional :return: Merged dictionary. ...
Returns the same arguments. :param inputs: Inputs values. :type inputs: T :param copy: If True, it returns a deepcopy of input values. :type copy: bool, optional :return: Same input values. :rtype: (T, ...), T Example:: >>> bypass('a', 'b', 'c') (...
def bypass(*inputs, copy=False): """ Returns the same arguments. :param inputs: Inputs values. :type inputs: T :param copy: If True, it returns a deepcopy of input values. :type copy: bool, optional :return: Same input values. :rtype: (T, ...), T Example::...
Returns a dict with new key values. :param key_map: A dictionary that maps the dict keys ({old key: new key} :type key_map: dict :param dicts: A sequence of dicts. :type dicts: dict :param copy: If True, it returns a deepcopy of input values. :type copy: bool, optional...
def map_dict(key_map, *dicts, copy=False, base=None): """ Returns a dict with new key values. :param key_map: A dictionary that maps the dict keys ({old key: new key} :type key_map: dict :param dicts: A sequence of dicts. :type dicts: dict :param copy: If True, it ...
Returns a new dict. :param key_map: A list that maps the dict keys ({old key: new key} :type key_map: list[str | dict | list] :param inputs: A sequence of data. :type inputs: iterable | dict | int | float | list | tuple :param copy: If True, it returns a deepcopy of input ...
def map_list(key_map, *inputs, copy=False, base=None): """ Returns a new dict. :param key_map: A list that maps the dict keys ({old key: new key} :type key_map: list[str | dict | list] :param inputs: A sequence of data. :type inputs: iterable | dict | int | float | list | tuple...
Selects the chosen dictionary keys from the given dictionary. :param keys: Keys to select. :type keys: list, tuple, set :param dictionary: A dictionary. :type dictionary: dict :param copy: If True the output contains deep-copies of the values. :type copy: bool :pa...
def selector(keys, dictionary, copy=False, output_type='dict', allow_miss=False): """ Selects the chosen dictionary keys from the given dictionary. :param keys: Keys to select. :type keys: list, tuple, set :param dictionary: A dictionary. :type dictionary: dict ...
Replicates `n` times the input value. :param n: Number of replications. :type n: int :param value: Value to be replicated. :type value: T :param copy: If True the list contains deep-copies of the value. :type copy: bool :return: A list with the value repli...
def replicate_value(value, n=2, copy=True): """ Replicates `n` times the input value. :param n: Number of replications. :type n: int :param value: Value to be replicated. :type value: T :param copy: If True the list contains deep-copies of the value. :type copy...
Return the parent function of a wrapped function (wrapped with :class:`functools.partial` and :class:`add_args`). :param func: Wrapped function. :type func: callable :param input_id: Index of the first input of the wrapped function. :type input_id: int :return: Parent ...
def parent_func(func, input_id=None): """ Return the parent function of a wrapped function (wrapped with :class:`functools.partial` and :class:`add_args`). :param func: Wrapped function. :type func: callable :param input_id: Index of the first input of the wrapped function. ...
Stacks the keys of nested-dictionaries into tuples and yields a list of k-v pairs. :param nested_dict: Nested dictionary. :type nested_dict: dict :param key: Initial keys. :type key: tuple, optional :param depth: Maximum keys depth. :type depth: int, optional ...
def stack_nested_keys(nested_dict, key=(), depth=-1): """ Stacks the keys of nested-dictionaries into tuples and yields a list of k-v pairs. :param nested_dict: Nested dictionary. :type nested_dict: dict :param key: Initial keys. :type key: tuple, optional :param depth...
Get/Initialize the value of nested-dictionaries. :param nested_dict: Nested dictionary. :type nested_dict: dict :param keys: Nested keys. :type keys: object :param default: Function used to initialize a new value. :type default: callable, optional :param init_nest...
def get_nested_dicts(nested_dict, *keys, default=None, init_nesting=dict): """ Get/Initialize the value of nested-dictionaries. :param nested_dict: Nested dictionary. :type nested_dict: dict :param keys: Nested keys. :type keys: object :param default: Function used...
Nested keys are inside of nested-dictionaries. :param nested_dict: Nested dictionary. :type nested_dict: dict :param keys: Nested keys. :type keys: object :return: True if nested keys are inside of nested-dictionaries, otherwise False. :rtype: bool
def are_in_nested_dicts(nested_dict, *keys): """ Nested keys are inside of nested-dictionaries. :param nested_dict: Nested dictionary. :type nested_dict: dict :param keys: Nested keys. :type keys: object :return: True if nested keys are inside of nested-dictionarie...
Merge nested-dictionaries. :param nested_dicts: Nested dictionaries. :type nested_dicts: dict :param depth: Maximum keys depth. :type depth: int, optional :param base: Base dict where combine multiple dicts in one. :type base: dict, optional :return: Combi...
def combine_nested_dicts(*nested_dicts, depth=-1, base=None): """ Merge nested-dictionaries. :param nested_dicts: Nested dictionaries. :type nested_dicts: dict :param depth: Maximum keys depth. :type depth: int, optional :param base: Base dict where combine multipl...
Decorator to add a function to a dispatcher. :param dsp: A dispatcher. :type dsp: schedula.Dispatcher :param inputs_kwargs: Do you want to include kwargs as inputs? :type inputs_kwargs: bool :param inputs_defaults: Do you want to set default values? :type inputs_...
def add_function(dsp, inputs_kwargs=False, inputs_defaults=False, **kw): """ Decorator to add a function to a dispatcher. :param dsp: A dispatcher. :type dsp: schedula.Dispatcher :param inputs_kwargs: Do you want to include kwargs as inputs? :type inputs_kwargs: bool ...
Constructs a Blueprint out of the current object. :param memo: A dictionary to cache Blueprints. :type memo: dict[T,schedula.utils.blue.Blueprint] :return: A Blueprint of the current object. :rtype: schedula.utils.blue.Blueprint
def blue(self, memo=None): """ Constructs a Blueprint out of the current object. :param memo: A dictionary to cache Blueprints. :type memo: dict[T,schedula.utils.blue.Blueprint] :return: A Blueprint of the current object. :rtype: schedula.utils.b...
Given a dictionary of data and this widget's name, returns the value of this widget. Returns None if it's not provided.
def value_from_datadict(self, data, files, name): """ Given a dictionary of data and this widget's name, returns the value of this widget. Returns None if it's not provided. """ value = super(FileSizeWidget, self).value_from_datadict(data, files, name) if value not in EMP...
represents physical limitation of the control
def control_force(self,c): '''represents physical limitation of the control''' # bring instance variables into local scope g = self.g s = self.s return g * (2/π) * arctan((s/g) * c)
control force plus the external forces (drag, etc)
def force(self,c): '''control force plus the external forces (drag, etc)''' # bring instance variables into local scope x = self.x v = self.v b = self.b k = self.k x0 = self.x0 F = self.control_force(c) return F - b*v - k...
of ascending node
def right_ascension(self): '''of ascending node''' nx,ny = self.node_line_vector n = self.node_line Ω = arccos(nx/n) if ny < 0: Ω = 2*π - Ω return Ω
P⃗,Q⃗,W⃗
def transform(self): '''P⃗,Q⃗,W⃗''' i = self.inclination Ω = self.longitude_of_ascending_node ω = self.argument_of_periapsis si = sin(i) ci = cos(i) sΩ = sin(Ω) cΩ = cos(Ω) sω = sin(ω) cω = cos(ω) Q = np.array([ [-sΩ*...
A "managed" SSH session. When the session is ready, we'll invoke the "ssh_cb" callback.
def connect_ssh_with_cb(ssh_cb, user, host, auth_cb, allow_new=True, verbosity=0): """A "managed" SSH session. When the session is ready, we'll invoke the "ssh_cb" callback. """ with connect_ssh(user, host, auth_cb, allow_new=True, verbosity=0) as ssh: ssh_cb(ssh)
A "managed" SFTP session. When the SSH session and an additional SFTP session are ready, invoke the sftp_cb callback.
def connect_sftp_with_cb(sftp_cb, *args, **kwargs): """A "managed" SFTP session. When the SSH session and an additional SFTP session are ready, invoke the sftp_cb callback. """ with _connect_sftp(*args, **kwargs) as (ssh, sftp): sftp_cb(ssh, sftp)
This is just a convenience function for key-based login.
def get_key_auth_cb(key_filepath): """This is just a convenience function for key-based login.""" def auth_cb(ssh): key = ssh_pki_import_privkey_file(key_filepath) ssh.userauth_publickey(key) return auth_cb
Returns a function that adds an edge to the `graph` checking only the out node. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :return: A function that adds an edge to the `graph`. :rtype: callable
def add_edge_fun(graph): """ Returns a function that adds an edge to the `graph` checking only the out node. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :return: A function that adds an edge to the `graph`. :rtype: callable """ # N...
Returns a function that removes an edge from the `graph`. ..note:: The out node is removed if this is isolate. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :return: A function that remove an edge from the `graph`. :rtype: callable
def remove_edge_fun(graph): """ Returns a function that removes an edge from the `graph`. ..note:: The out node is removed if this is isolate. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :return: A function that remove an edge from the `graph`...
Finds an unused node id in `graph`. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param initial_guess: Initial node id guess. :type initial_guess: str, optional :param _format: Format to generate the new node id if the given is already used...
def get_unused_node_id(graph, initial_guess='unknown', _format='{}<%d>'): """ Finds an unused node id in `graph`. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param initial_guess: Initial node id guess. :type initial_guess: str, optional :...
Adds function node edges. :param dsp: A dispatcher that identifies the model adopted. :type dsp: schedula.Dispatcher :param fun_id: Function node id. :type fun_id: str :param nodes_bunch: A container of nodes which will be iterated through once. :type nodes_bunch: iter...
def add_func_edges(dsp, fun_id, nodes_bunch, edge_weights=None, input=True, data_nodes=None): """ Adds function node edges. :param dsp: A dispatcher that identifies the model adopted. :type dsp: schedula.Dispatcher :param fun_id: Function node id. :type fun_i...
Adds edge to the dispatcher map. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param edges_weights: Edge weights. :type edges_weights: dict, optional :return: A function that adds an edge to the `graph`. :rtype: callable
def _add_edge_dmap_fun(graph, edges_weights=None): """ Adds edge to the dispatcher map. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param edges_weights: Edge weights. :type edges_weights: dict, optional :return: A function that ad...
Returns a dispatcher node that match the given node id. :param nodes: Dispatcher nodes. :type nodes: dict :param node_id: Node id. :type node_id: str :return: The dispatcher node and its id. :rtype: (str, dict)
def _get_node(nodes, node_id, fuzzy=True): """ Returns a dispatcher node that match the given node id. :param nodes: Dispatcher nodes. :type nodes: dict :param node_id: Node id. :type node_id: str :return: The dispatcher node and its id. :rtype: (str, dict) ...
Returns a sub node of a dispatcher. :param dsp: A dispatcher object or a sub dispatch function. :type dsp: schedula.Dispatcher | SubDispatch :param path: A sequence of node ids or a single node id. Each id identifies a sub-level node. :type path: tuple, str :param node_at...
def get_sub_node(dsp, path, node_attr='auto', solution=NONE, _level=0, _dsp_name=NONE): """ Returns a sub node of a dispatcher. :param dsp: A dispatcher object or a sub dispatch function. :type dsp: schedula.Dispatcher | SubDispatch :param path: A sequence of node...
Returns the full pipe of a dispatch run. :param sol: A Solution object. :type sol: schedula.utils.Solution :param base: Base node id. :type base: tuple[str] :return: Full pipe of a dispatch run. :rtype: DspPipe
def get_full_pipe(sol, base=()): """ Returns the full pipe of a dispatch run. :param sol: A Solution object. :type sol: schedula.utils.Solution :param base: Base node id. :type base: tuple[str] :return: Full pipe of a dispatch run. :rtype: DspPipe """ ...
Parse Storm Pipe CONNECT Chunk Method
def connectChunk(key, chunk): """ Parse Storm Pipe CONNECT Chunk Method """ schunk = chunk[0].strip().split() result = {'slinkNumber': schunk[1], 'upSjunc': schunk[2], 'downSjunc': schunk[3]} return result
Parse Super Junction (SJUNC) Chunk Method
def sjuncChunk(key, chunk): """ Parse Super Junction (SJUNC) Chunk Method """ schunk = chunk[0].strip().split() result = {'sjuncNumber': schunk[1], 'groundSurfaceElev': schunk[2], 'invertElev': schunk[3], 'manholeSA': schunk[4], 'inletCode': s...
Parse Super Link (SLINK) Chunk Method
def slinkChunk(key, lines): """ Parse Super Link (SLINK) Chunk Method """ KEYWORDS = ('SLINK', 'NODE', 'PIPE') result = {'slinkNumber':None, 'numPipes':None, 'nodes':[], 'pipes':[]} chunks = pt.chunk(KEYWORDS, lines) ...
Fetch database for items matching. Args: page (int): which page will be sliced slice size is ``self.per_page``. order_by (str): a field name to order query by. filters (dict): a ``filter name``: ``value`` dict. ...
def get_items(self, page=1, order_by=None, filters=None): """ Fetch database for items matching. Args: page (int): which page will be sliced slice size is ``self.per_page``. order_by (str): a field name to order query by. ...
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb http://matplotlib.org/examples/pylab_examples/multicolored_line.html Plot a colored line with coordinates x and y Optionally specify colors in the array z Optionally specify a colormap, a norm function and a lin...
def colorline(ax, x, y, z, **kwargs): """ http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb http://matplotlib.org/examples/pylab_examples/multicolored_line.html Plot a colored line with coordinates x and y Optionally specify colors in the array z Option...
Create list of line segments from x and y coordinates, in the correct format for LineCollection: an array of the form numlines x (points per line) x 2 (x and y) array
def make_segments(x, y): """ Create list of line segments from x and y coordinates, in the correct format for LineCollection: an array of the form numlines x (points per line) x 2 (x and y) array """ points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], point...
Generic File Read from File Method
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): """ Generic File Read from File Method """ # Persist name and extension of file self.name = name self.fileExtension = extension # Open file and pa...
r"""Return True if the set has no elements in common with other. Sets are disjoint iff their intersection is the empty set. >>> ms = Multiset('aab') >>> ms.isdisjoint('bc') False >>> ms.isdisjoint(Multiset('ccd')) True Args: other: The other set to ...
def isdisjoint(self, other): r"""Return True if the set has no elements in common with other. Sets are disjoint iff their intersection is the empty set. >>> ms = Multiset('aab') >>> ms.isdisjoint('bc') False >>> ms.isdisjoint(Multiset('ccd')) True Args:...
r"""Return a new multiset with all elements from the others removed. >>> ms = Multiset('aab') >>> sorted(ms.difference('bc')) ['a', 'a'] You can also use the ``-`` operator for the same effect. However, the operator version will only accept a set as other operator, not any iter...
def difference(self, *others): r"""Return a new multiset with all elements from the others removed. >>> ms = Multiset('aab') >>> sorted(ms.difference('bc')) ['a', 'a'] You can also use the ``-`` operator for the same effect. However, the operator version will only accep...
r"""Return a new multiset with all elements from the multiset and the others with maximal multiplicities. >>> ms = Multiset('aab') >>> sorted(ms.union('bc')) ['a', 'a', 'b', 'c'] You can also use the ``|`` operator for the same effect. However, the operator version will only ac...
def union(self, *others): r"""Return a new multiset with all elements from the multiset and the others with maximal multiplicities. >>> ms = Multiset('aab') >>> sorted(ms.union('bc')) ['a', 'a', 'b', 'c'] You can also use the ``|`` operator for the same effect. However, the ope...
r"""Return a new multiset with elements common to the multiset and all others. >>> ms = Multiset('aab') >>> sorted(ms.intersection('abc')) ['a', 'b'] You can also use the ``&`` operator for the same effect. However, the operator version will only accept a set as other operator,...
def intersection(self, *others): r"""Return a new multiset with elements common to the multiset and all others. >>> ms = Multiset('aab') >>> sorted(ms.intersection('abc')) ['a', 'b'] You can also use the ``&`` operator for the same effect. However, the operator version ...
r"""Return a new set with elements in either the set or other but not both. >>> ms = Multiset('aab') >>> sorted(ms.symmetric_difference('abc')) ['a', 'c'] You can also use the ``^`` operator for the same effect. However, the operator version will only accept a set as other oper...
def symmetric_difference(self, other): r"""Return a new set with elements in either the set or other but not both. >>> ms = Multiset('aab') >>> sorted(ms.symmetric_difference('abc')) ['a', 'c'] You can also use the ``^`` operator for the same effect. However, the operator versi...
Return a new set with each element's multiplicity multiplied with the given scalar factor. >>> ms = Multiset('aab') >>> sorted(ms.times(2)) ['a', 'a', 'a', 'a', 'b', 'b'] You can also use the ``*`` operator for the same effect: >>> sorted(ms * 3) ['a', 'a', 'a', 'a', '...
def times(self, factor): """Return a new set with each element's multiplicity multiplied with the given scalar factor. >>> ms = Multiset('aab') >>> sorted(ms.times(2)) ['a', 'a', 'a', 'a', 'b', 'b'] You can also use the ``*`` operator for the same effect: >>> sorted(ms...
r"""Like :meth:`dict.update` but add multiplicities instead of replacing them. >>> ms = Multiset('aab') >>> ms.update('abc') >>> sorted(ms) ['a', 'a', 'a', 'b', 'b', 'c'] Note that the operator ``+=`` is equivalent to :meth:`update`, except that the operator will only a...
def update(self, *others): r"""Like :meth:`dict.update` but add multiplicities instead of replacing them. >>> ms = Multiset('aab') >>> ms.update('abc') >>> sorted(ms) ['a', 'a', 'a', 'b', 'b', 'c'] Note that the operator ``+=`` is equivalent to :meth:`update`, except th...
r"""Update the multiset, adding elements from all others using the maximum multiplicity. >>> ms = Multiset('aab') >>> ms.union_update('bc') >>> sorted(ms) ['a', 'a', 'b', 'c'] You can also use the ``|=`` operator for the same effect. However, the operator version will o...
def union_update(self, *others): r"""Update the multiset, adding elements from all others using the maximum multiplicity. >>> ms = Multiset('aab') >>> ms.union_update('bc') >>> sorted(ms) ['a', 'a', 'b', 'c'] You can also use the ``|=`` operator for the same effect. How...
r"""Update the multiset, keeping only elements found in it and all others. >>> ms = Multiset('aab') >>> ms.intersection_update('bc') >>> sorted(ms) ['b'] You can also use the ``&=`` operator for the same effect. However, the operator version will only accept a set as ot...
def intersection_update(self, *others): r"""Update the multiset, keeping only elements found in it and all others. >>> ms = Multiset('aab') >>> ms.intersection_update('bc') >>> sorted(ms) ['b'] You can also use the ``&=`` operator for the same effect. However, the opera...
r"""Remove all elements contained the others from this multiset. >>> ms = Multiset('aab') >>> ms.difference_update('abc') >>> sorted(ms) ['a'] You can also use the ``-=`` operator for the same effect. However, the operator version will only accept a set as other operato...
def difference_update(self, *others): r"""Remove all elements contained the others from this multiset. >>> ms = Multiset('aab') >>> ms.difference_update('abc') >>> sorted(ms) ['a'] You can also use the ``-=`` operator for the same effect. However, the operator version ...
r"""Update the multiset to contain only elements in either this multiset or the other but not both. >>> ms = Multiset('aab') >>> ms.symmetric_difference_update('abc') >>> sorted(ms) ['a', 'c'] You can also use the ``^=`` operator for the same effect. However, the operator versi...
def symmetric_difference_update(self, other): r"""Update the multiset to contain only elements in either this multiset or the other but not both. >>> ms = Multiset('aab') >>> ms.symmetric_difference_update('abc') >>> sorted(ms) ['a', 'c'] You can also use the ``^=`` ope...
Update each this multiset by multiplying each element's multiplicity with the given scalar factor. >>> ms = Multiset('aab') >>> ms.times_update(2) >>> sorted(ms) ['a', 'a', 'a', 'a', 'b', 'b'] You can also use the ``*=`` operator for the same effect: >>> ms = Multiset(...
def times_update(self, factor): """Update each this multiset by multiplying each element's multiplicity with the given scalar factor. >>> ms = Multiset('aab') >>> ms.times_update(2) >>> sorted(ms) ['a', 'a', 'a', 'a', 'b', 'b'] You can also use the ``*=`` operator for t...
Adds an element to the multiset. >>> ms = Multiset() >>> ms.add('a') >>> sorted(ms) ['a'] An optional multiplicity can be specified to define how many of the element are added: >>> ms.add('b', 2) >>> sorted(ms) ['a', 'b', 'b'] This extends the ...
def add(self, element, multiplicity=1): """Adds an element to the multiset. >>> ms = Multiset() >>> ms.add('a') >>> sorted(ms) ['a'] An optional multiplicity can be specified to define how many of the element are added: >>> ms.add('b', 2) >>> sorted(ms)...
Removes an element from the multiset. If no multiplicity is specified, the element is completely removed from the multiset: >>> ms = Multiset('aabbbc') >>> ms.remove('a') 2 >>> sorted(ms) ['b', 'b', 'b', 'c'] If the multiplicity is given, it is subtracted from ...
def remove(self, element, multiplicity=None): """Removes an element from the multiset. If no multiplicity is specified, the element is completely removed from the multiset: >>> ms = Multiset('aabbbc') >>> ms.remove('a') 2 >>> sorted(ms) ['b', 'b', 'b', 'c'] ...
Removes the `element` from the multiset. If multiplicity is ``None``, all occurrences of the element are removed: >>> ms = Multiset('aab') >>> ms.discard('a') 2 >>> sorted(ms) ['b'] Otherwise, the multiplicity is subtracted from the one in the multiset and the ...
def discard(self, element, multiplicity=None): """Removes the `element` from the multiset. If multiplicity is ``None``, all occurrences of the element are removed: >>> ms = Multiset('aab') >>> ms.discard('a') 2 >>> sorted(ms) ['b'] Otherwise, the multip...
Clean-up the resources of all initialized executors. :param wait: If True then shutdown will not return until all running futures have finished executing and the resources used by the executors have been reclaimed. :type wait: bool :return: Shutdown pool executor. :rtyp...
def shutdown_executors(wait=True): """ Clean-up the resources of all initialized executors. :param wait: If True then shutdown will not return until all running futures have finished executing and the resources used by the executors have been reclaimed. :type wait: bool :re...