INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
.. todo:: store_param docstring
def store_param(self, value, param, clobber=False): """ .. todo:: store_param docstring """ # Imports from ..const import EnumAnharmRepoParam from ..error import RepoError as RErr # Must be a valid parameter name if not param in EnumAnharmRepoParam: ...
.. todo:: docstring for get_param
def get_param(self, param): """ .. todo:: docstring for get_param """ # Imports import os from ..const import EnumAnharmRepoParam from ..error import RepoError as RErr # Must be a valid parameter name if not param in EnumAnharmRepoParam: rais...
.. todo:: has_param docstring
def has_param(self, param): """ .. todo:: has_param docstring """ # Imports from ..error import RepoError # Try to get the param; pass along all errors, except 'data' error # from RepoError retval = True try: self.get_param(param) ex...
.. todo:: docstring for is_dirty
def is_dirty(self): """ .. todo:: docstring for is_dirty """ # Imports from ..error import RepoError as RErr # Get the return value from the dataset, complaining if repo not # bound. Using 'require_dataset' since any repo w/o a defined # 'dirty' value is just ...
.. todo:: docstring for get_xyz
def get_XYZ(self, mode, disp): """ .. todo:: docstring for get_xyz """ # Imports from ..xyz import OpanXYZ as XYZ from ..const import EnumAnharmRepoParam, EnumAnharmRepoData # Generate XYZ and return out_XYZ = XYZ(atom_syms=self.get_param(EnumAnharmRepoParam.ato...
.. todo:: set_clean docstring
def set_dirty(self, dirty): """ .. todo:: set_clean docstring """ # Complain if 'dirty' isn't boolean if not isinstance(dirty, bool): raise ValueError("'dirty' must be Boolean") ## end if # Try to retrieve the dataset; complain if repo not bound. try...
Stops the scheduler driver. If the 'failover' flag is set to False then it is expected that this framework will never reconnect to Mesos and all of its executors and tasks can be terminated. Otherwise, all executors and tasks will remain running (for some framework specific failover ti...
def stop(self, failover=False): """Stops the scheduler driver. If the 'failover' flag is set to False then it is expected that this framework will never reconnect to Mesos and all of its executors and tasks can be terminated. Otherwise, all executors and tasks will remain runni...
Requests resources from Mesos. (see mesos.proto for a description of Request and how, for example, to request resources from specific slaves.) Any resources available are offered to the framework via Scheduler.resourceOffers callback, asynchronously.
def request(self, requests): """Requests resources from Mesos. (see mesos.proto for a description of Request and how, for example, to request resources from specific slaves.) Any resources available are offered to the framework via Scheduler.resourceOffers callback, asynchronou...
Launches the given set of tasks. Any resources remaining (i.e., not used by the tasks or their executors) will be considered declined. The specified filters are applied on all unused resources (see mesos.proto for a description of Filters). Available resources are aggregated whe...
def launch(self, offer_id, tasks, filters=Filters()): """Launches the given set of tasks. Any resources remaining (i.e., not used by the tasks or their executors) will be considered declined. The specified filters are applied on all unused resources (see mesos.proto for a descri...
Kills the specified task. Note that attempting to kill a task is currently not reliable. If, for example, a scheduler fails over while it was attempting to kill a task it will need to retry in the future. Likewise, if unregistered / disconnected, the request will be dropped (the...
def kill(self, task_id): """Kills the specified task. Note that attempting to kill a task is currently not reliable. If, for example, a scheduler fails over while it was attempting to kill a task it will need to retry in the future. Likewise, if unregistered / disconnected, the ...
Allows the framework to query the status for non-terminal tasks. This causes the master to send back the latest task status for each task in 'statuses', if possible. Tasks that are no longer known will result in a TASK_LOST update. If statuses is empty, then the master will send the lat...
def reconcile(self, statuses): """Allows the framework to query the status for non-terminal tasks. This causes the master to send back the latest task status for each task in 'statuses', if possible. Tasks that are no longer known will result in a TASK_LOST update. If statuses is empty,...
Declines an offer in its entirety and applies the specified filters on the resources (see mesos.proto for a description of Filters). Note that this can be done at any time, it is not necessary to do this within the Scheduler::resourceOffers callback.
def decline(self, offer_id, filters=Filters()): """Declines an offer in its entirety and applies the specified filters on the resources (see mesos.proto for a description of Filters). Note that this can be done at any time, it is not necessary to do this within the Schedul...
Accepts the given offers and performs a sequence of operations on those accepted offers. See Offer.Operation in mesos.proto for the set of available operations. Available resources are aggregated when multiple offers are provided. Note that all offers must belong to the same slave. ...
def accept(self, offer_ids, operations, filters=Filters()): """Accepts the given offers and performs a sequence of operations on those accepted offers. See Offer.Operation in mesos.proto for the set of available operations. Available resources are aggregated when multiple offers are ...
Acknowledges the status update. This should only be called once the status update is processed durably by the scheduler. Not that explicit acknowledgements must be requested via the constructor argument, otherwise a call to this method will cause the driver to crash.
def acknowledge(self, status): """Acknowledges the status update. This should only be called once the status update is processed durably by the scheduler. Not that explicit acknowledgements must be requested via the constructor argument, otherwise a call to this method will cau...
Sends a message from the framework to one of its executors. These messages are best effort; do not expect a framework message to be retransmitted in any reliable fashion.
def message(self, executor_id, slave_id, message): """Sends a message from the framework to one of its executors. These messages are best effort; do not expect a framework message to be retransmitted in any reliable fashion. """ logging.info('Sends message `{}` to executor `{}` ...
Handles GtkBuilder signal connect events
def _connect_func(builder, obj, signal_name, handler_name, connect_object, flags, cls): '''Handles GtkBuilder signal connect events''' if connect_object is None: extra = () else: extra = (connect_object,) # The handler name refers to an attribute on the template insta...
Registers the template for the widget and hooks init_template
def _register_template(cls, template_bytes): '''Registers the template for the widget and hooks init_template''' # This implementation won't work if there are nested templates, but # we can't do that anyways due to PyGObject limitations so it's ok if not hasattr(cls, 'set_template'): raise Typ...
This would be better as an override for Gtk.Widget
def _init_template(self, cls, base_init_template): '''This would be better as an override for Gtk.Widget''' # TODO: could disallow using a metaclass.. but this is good enough # .. if you disagree, feel free to fix it and issue a PR :) if self.__class__ is not cls: raise TypeError("Inheritance f...
babel translation token extract function for haml files
def extract_haml(fileobj, keywords, comment_tags, options): """ babel translation token extract function for haml files """ import haml from mako import lexer, parsetree from mako.ext.babelplugin import extract_nodes encoding = options.get('input_encoding', options.get('encoding', None)) temp...
Return a list (of length patterns_per_label) of PatternGenerator instances. Should use pattern_type and pattern_parameters to create each pattern. properties is a dictionary, e.g. {'pattern_label': pattern_label}, which can be used to create PatternGenerators depending on the r...
def _create_patterns(self, properties=None): """ Return a list (of length patterns_per_label) of PatternGenerator instances. Should use pattern_type and pattern_parameters to create each pattern. properties is a dictionary, e.g. {'pattern_label': pattern_label}, which c...
Extends an ArgumentParser instance with the following commandline arguments: --bam --min-reads --min-mapping-quality --use-duplicate-reads --drop-secondary-alignments
def add_rna_args( parser, min_mapping_quality_default=MIN_READ_MAPPING_QUALITY): """ Extends an ArgumentParser instance with the following commandline arguments: --bam --min-reads --min-mapping-quality --use-duplicate-reads --drop-secondary-alignments ...
Parameters ---------- add_sequence_length_arg : bool If True then add the `--cdna-sequence-length` argument. This may be omitted if the cDNA sequence length is inferred from a protein length. **kwargs : dict Passed directly to argparse.ArgumentParser Creates argparse.ArgumentPa...
def make_variant_sequences_arg_parser(add_sequence_length_arg=False, **kwargs): """ Parameters ---------- add_sequence_length_arg : bool If True then add the `--cdna-sequence-length` argument. This may be omitted if the cDNA sequence length is inferred from a protein length. **kwarg...
A custom replacement for iter(), dispatching a few custom picklable iterators for known types.
def iter_(obj): """A custom replacement for iter(), dispatching a few custom picklable iterators for known types. """ if six.PY2: file_types = file, # noqa if six.PY3: file_types = io.IOBase, dict_items = {}.items().__class__ dict_values = {}.values().__class__ ...
Given a sequence of AlleleRead objects, which are expected to all have the same allele, return that allele.
def get_single_allele_from_reads(allele_reads): """ Given a sequence of AlleleRead objects, which are expected to all have the same allele, return that allele. """ allele_reads = list(allele_reads) if len(allele_reads) == 0: raise ValueError("Expected non-empty list of AlleleRead object...
Given a list of AlleleRead objects, extracts all unique (prefix, allele, suffix) sequences and associate each with a list of reads that contained that sequence.
def group_unique_sequences( allele_reads, max_prefix_size=None, max_suffix_size=None): """ Given a list of AlleleRead objects, extracts all unique (prefix, allele, suffix) sequences and associate each with a list of reads that contained that sequence. """ groups = default...
Given a list of AlleleRead objects, extracts all unique (prefix, allele, suffix) sequences and associate each with the number of reads that contain that sequence.
def count_unique_sequences( allele_reads, max_prefix_size=None, max_suffix_size=None): """ Given a list of AlleleRead objects, extracts all unique (prefix, allele, suffix) sequences and associate each with the number of reads that contain that sequence. """ groups = group...
Overload if special behaviour is required when a series ends.
def extract_specific_interval(self, interval_start, interval_end): """ Overload if special behaviour is required when a series ends. """ interval_start = int(interval_start) interval_end = int(interval_end) if interval_start >= interval_end: raise ValueError...
Perform a real Discrete Fourier Transform (DFT; implemented using a Fast Fourier Transform algorithm, FFT) of the current sample from the signal multiplied by the smoothing window. See numpy.rfft for information about the Fourier transform.
def _get_row_amplitudes(self): """ Perform a real Discrete Fourier Transform (DFT; implemented using a Fast Fourier Transform algorithm, FFT) of the current sample from the signal multiplied by the smoothing window. See numpy.rfft for information about the Fourier transform. ...
Return an iterator that yields every node which is a child of this one. This includes inline children, and control structure `else` clauses.
def iter_all_children(self): '''Return an iterator that yields every node which is a child of this one. This includes inline children, and control structure `else` clauses. ''' if self.inline_child: yield self.inline_child for x in self.children: ...
Transfer functions may need additional information before the supplied numpy array can be modified in place. For instance, transfer functions may have state which needs to be allocated in memory with a certain size. In other cases, the transfer function may need to know about the coordin...
def initialize(self, **kwargs): """ Transfer functions may need additional information before the supplied numpy array can be modified in place. For instance, transfer functions may have state which needs to be allocated in memory with a certain size. In other cases, the transfe...
Temporarily disable plasticity of internal state. This function should be implemented by all subclasses so that after a call, the output should always be the same for any given input pattern, and no call should have any effect that persists after restore_plasticity_state() is called. ...
def override_plasticity_state(self, new_plasticity_state): """ Temporarily disable plasticity of internal state. This function should be implemented by all subclasses so that after a call, the output should always be the same for any given input pattern, and no call should have ...
Setup integration Register plug-ins and integrate into the host Arguments: console (bool): DEPRECATED port (int, optional): DEPRECATED
def setup(console=False, port=None): """Setup integration Register plug-ins and integrate into the host Arguments: console (bool): DEPRECATED port (int, optional): DEPRECATED """ if self._has_been_setup: teardown() register_plugins() register_host() self._ha...
Register supported hosts
def register_host(): """Register supported hosts""" pyblish.api.register_host("hython") pyblish.api.register_host("hpython") pyblish.api.register_host("houdini")
Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... node.setSelected(on=False, clear_all_selected=True) >>> # Selection restored
def maintained_selection(): """Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... node.setSelected(on=False, clear_all_selected=True) >>> # Selection restored """ previous_selection = hou.selectedNodes() t...
Execute several statements in single DB transaction.
def execute_transaction(conn, statements: Iterable): """Execute several statements in single DB transaction.""" with conn: with conn.cursor() as cursor: for statement in statements: cursor.execute(statement) conn.commit()
Execute several statements each as a single DB transaction.
def execute_transactions(conn, statements: Iterable): """Execute several statements each as a single DB transaction.""" with conn.cursor() as cursor: for statement in statements: try: cursor.execute(statement) conn.commit() except psycopg2.Program...
Open a connection, commit a transaction, and close it.
def execute_closing_transaction(statements: Iterable): """Open a connection, commit a transaction, and close it.""" with closing(connect()) as conn: with conn.cursor() as cursor: for statement in statements: cursor.execute(statement)
Return a select statement's results as a namedtuple. Parameters ---------- conn : database connection query : select query string params : query parameters. name : server side cursor name. defaults to client side. itersize : number of records fetched by server.
def select(conn, query: str, params=None, name=None, itersize=5000): """Return a select statement's results as a namedtuple. Parameters ---------- conn : database connection query : select query string params : query parameters. name : server side cursor name. defaults to client side. i...
Return a select statement's results as dictionary. Parameters ---------- conn : database connection query : select query string params : query parameters. name : server side cursor name. defaults to client side. itersize : number of records fetched by server.
def select_dict(conn, query: str, params=None, name=None, itersize=5000): """Return a select statement's results as dictionary. Parameters ---------- conn : database connection query : select query string params : query parameters. name : server side cursor name. defaults to client side. ...
Run select query for each parameter set in single transaction.
def select_each(conn, query: str, parameter_groups, name=None): """Run select query for each parameter set in single transaction.""" with conn: with conn.cursor(name=name) as cursor: for parameters in parameter_groups: cursor.execute(query, parameters) yield ...
Lightweight query to retrieve column list of select query. Notes ----- Strongly urged to specify a cursor name for performance.
def query_columns(conn, query, name=None): """Lightweight query to retrieve column list of select query. Notes ----- Strongly urged to specify a cursor name for performance. """ with conn.cursor(name) as cursor: cursor.itersize = 1 cursor.execute(query) cursor.fetchmany...
Assuming that the transcript has a coding sequence, take a ReferenceSequenceKey (region of the transcript around the variant) and return a ReferenceCodingSequenceKey (or None).
def from_variant_and_transcript_and_sequence_key( cls, variant, transcript, sequence_key): """ Assuming that the transcript has a coding sequence, take a ReferenceSequenceKey (region of the transcript around the variant) and return a ReferenceCodingSequenceKey (or None). ...
Extracts the reference sequence around a variant locus on a particular transcript and determines the reading frame at the start of that sequence context. Parameters ---------- variant : varcode.Variant transcript : pyensembl.Transcript context_size : int ...
def from_variant_and_transcript( cls, variant, transcript, context_size): """ Extracts the reference sequence around a variant locus on a particular transcript and determines the reading frame at the start of that sequence context. ...
Parse the command line arguments :return:
def parse_arguments(): """ Parse the command line arguments :return: """ parser = argparse.ArgumentParser() parser.add_argument( "-c", dest="count", default=0, type=int, help="Number of pings to send" ) parser.add_argument( "-i", dest="interval", default=1, type=f...
Create new sketch Params: <int> width <str> path <int> flags <int> seed
def create(self, width=0, depth=0, path=None, flags=0, seed=0): """Create new sketch Params: <int> width <str> path <int> flags <int> seed """ return self.create_method(self, width, depth, path, flags, seed)
Add key-value Params: <str> key <int> key_length Return: <int> key_value
def get(self, key, key_length=0): """Add key-value Params: <str> key <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) return self.get_method(self, key, key_length)
Set value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value
def set(self, key, value, key_length=0): """Set value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) if self.k: self._...
Add value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value
def add(self, key, value, key_length=0): """Add value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) val = self.add_method(self, k...
Add value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value
def inc(self, key, key_length=0): """Add value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) val = self.add_method(self, key, key...
Clear sketch
def clear(self): """Clear sketch""" self.ranking = [] heapq.heapify(self.ranking) self.dq = deque(maxlen=self.k) self.num = 0 return self.clear_method(self)
Shrink sketch Params: <Sketch> src_sketch <int> width <str> path <int> flags
def shrink(self, src, width=0, path=None, flags=0): """Shrink sketch Params: <Sketch> src_sketch <int> width <str> path <int> flags """ self.shrink_method(self, src, width, path, flags)
Merge two sketches Params: <Sketch> sketch <lambda> | <function> lhs_filter <lambda> | <function> rhs_filter
def merge(self, rhs, lhs_filter=None, rhs_filter=None): """Merge two sketches Params: <Sketch> sketch <lambda> | <function> lhs_filter <lambda> | <function> rhs_filter """ if lhs_filter or rhs_filter: get_ = self.get___method se...
Dump all values Return: <generator> <int> val
def values(self): """Dump all values Return: <generator> <int> val """ table_id = 0 get = self.get___method for cell_id in range(self.width): val = get(self, table_id, cell_id) if val: yield val
Apply filter into all values Params <lambda> | <function> given_filter <bool> only_nonzero
def filter(self, given_filter, apply_zerovalue=False): """Apply filter into all values Params <lambda> | <function> given_filter <bool> only_nonzero """ get_ = self.get___method set_ = self.set___method max_value = self.max_value for table_...
Set values from dict Params: <dict <str> <int>> src_dict
def fromdict(self, src_dict, method='set'): """Set values from dict Params: <dict <str> <int>> src_dict """ if method == 'set': _method = self.set_method else: _method = self.add_method if hasattr(src_dict, 'iteritems'): for...
Create new sketch Params: <int> width <int> max_value <str> path <int> flags <int> seed
def create(self, width=0, max_value=0, path=None, flags=0, seed=0): """Create new sketch Params: <int> width <int> max_value <str> path <int> flags <int> seed """ return _madoka.Sketch_create(self, width, max_value, path, flags,...
Increment key-value Params: <str> key <int> key_length Return: <int> key_value
def inc(self, key, key_length=0): """Increment key-value Params: <str> key <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) return _madoka.Sketch_inc(self, key, key_length)
Shrink sketch Params: <Sketch> src_sketch <int> width <int> max_value <lambda> | <function> filter <str> path <int> flags
def shrink(self, src, width=0, max_value=0, filter_method=None, path=None, flags=0): """Shrink sketch Params: <Sketch> src_sketch <int> width <int> max_value <lambda> | <function> filter <str> path <int> flags ...
Try to convert content of README.md into rst format using pypandoc, write it into README and return it. If pypandoc cannot be imported write content of README.md unchanged into README and return it.
def create_readme_with_long_description(): '''Try to convert content of README.md into rst format using pypandoc, write it into README and return it. If pypandoc cannot be imported write content of README.md unchanged into README and return it. ''' this_dir = os.path.abspath(os.path.dirname(__f...
Install or update OpenSSL from source (statically linked, no shared libs). Args: version (str): Git tag or branch to install from. Default: 'master' ignore_test_fail: Continue with installation if `make test` fails. Default: False Example: > fab setup.openssl:...
def openssl(version='master', ignore_test_fail=False): ''' Install or update OpenSSL from source (statically linked, no shared libs). Args: version (str): Git tag or branch to install from. Default: 'master' ignore_test_fail: Continue with installation if `make test` fails. ...
Print download statistics for a package. \b Example: pypi stat requests
def stat(package, graph): """Print download statistics for a package. \b Example: pypi stat requests """ client = requests.Session() for name_or_url in package: package = get_package(name_or_url, client) if not package: secho(u'Invalid name or URL: "{name}"'...
Browse to a package's PyPI or project homepage.
def browse(package, homepage): """Browse to a package's PyPI or project homepage.""" p = Package(package) try: if homepage: secho(u'Opening homepage for "{0}"...'.format(package), bold=True) url = p.home_page else: secho(u'Opening PyPI page for "{0}"...'.f...
Search for a pypi package. \b Examples: \b pypi search requests pypi search 'requests oauth' pypi search requests -n 20 pypi search 'requests toolbelt' --web
def search(query, n_results, web): """Search for a pypi package. \b Examples: \b pypi search requests pypi search 'requests oauth' pypi search requests -n 20 pypi search 'requests toolbelt' --web """ if web: secho(u'Opening search page for "{0}"...'....
Get info about a package or packages.
def info(package, long_description, classifiers, license): """Get info about a package or packages. """ client = requests.Session() for name_or_url in package: package = get_package(name_or_url, client) if not package: secho(u'Invalid name or URL: "{name}"'.format(name=name_o...
Return a bar graph as a string, given a dictionary of data.
def bargraph(data, max_key_width=30): """Return a bar graph as a string, given a dictionary of data.""" lines = [] max_length = min(max(len(key) for key in data.keys()), max_key_width) max_val = max(data.values()) max_val_length = max( len(_style_value(val)) for val in data.values())...
Return a dictionary of version:download_count pairs.
def version_downloads(self): """Return a dictionary of version:download_count pairs.""" ret = OrderedDict() for release, info in self.release_info: download_count = sum(file_['downloads'] for file_ in info) ret[release] = download_count return ret
Version with the most downloads. :return: A tuple of the form (version, n_downloads)
def max_version(self): """Version with the most downloads. :return: A tuple of the form (version, n_downloads) """ data = self.version_downloads if not data: return None, 0 return max(data.items(), key=lambda item: item[1])
Version with the fewest downloads.
def min_version(self): """Version with the fewest downloads.""" data = self.version_downloads if not data: return (None, 0) return min(data.items(), key=lambda item: item[1])
dx4, dy4, dx2dy2, D = elasprep(dx,dy,Te,E=1E11,nu=0.25) Defines the variables that are required to create the 2D finite difference solution coefficient matrix
def elasprep(self): """ dx4, dy4, dx2dy2, D = elasprep(dx,dy,Te,E=1E11,nu=0.25) Defines the variables that are required to create the 2D finite difference solution coefficient matrix """ if self.Method != 'SAS_NG': self.dx4 = self.dx**4 self.dy4 = self.dy**4 self.dx2...
Selects the boundary conditions E-W is for inside each panel N-S is for the block diagonal matrix ("with fringes") Then calls the function to build the diagonal matrix The current method of coefficient matrix construction utilizes longer-range symmetry in the coefficient matrix to build it block-wi...
def BC_selector_and_coeff_matrix_creator(self): """ Selects the boundary conditions E-W is for inside each panel N-S is for the block diagonal matrix ("with fringes") Then calls the function to build the diagonal matrix The current method of coefficient matrix construction utilizes longer-range...
Utility function to help implement boundary conditions by specifying them for and applying them to the elastic thickness grid
def BC_Rigidity(self): """ Utility function to help implement boundary conditions by specifying them for and applying them to the elastic thickness grid """ ######################################### # FLEXURAL RIGIDITY BOUNDARY CONDITIONS # ######################################### # W...
Calculates the matrix of coefficients that is later used via sparse matrix solution techniques (scipy.sparse.linalg.spsolve) to compute the flexural response to the load. This step need only be performed once, and the coefficient matrix can very rapidly compute flexural solutions to any load. This makes...
def get_coeff_values(self): """ Calculates the matrix of coefficients that is later used via sparse matrix solution techniques (scipy.sparse.linalg.spsolve) to compute the flexural response to the load. This step need only be performed once, and the coefficient matrix can very rapidly compute flexur...
Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure (this code), grids are padded out to one maximum flexural wavelength, but in any case, the flexural wavelength is a good characteristic distance for any truncation limit
def calc_max_flexural_wavelength(self): """ Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure (this code), grids are padded out to one maximum flexural wavelength, but in any case, the flexural wavelength is a good characteristic...
w = fd_solve() Sparse flexural response calculation. Can be performed by direct factorization with UMFpack (defuault) or by an iterative minimum residual technique These are both the fastest of the standard Scipy builtin techniques in their respective classes Requires the coefficient matrix f...
def fd_solve(self): """ w = fd_solve() Sparse flexural response calculation. Can be performed by direct factorization with UMFpack (defuault) or by an iterative minimum residual technique These are both the fastest of the standard Scipy builtin techniques in their respective classes R...
Install the tools ripit and burnit in order to rip and burn audio cds. More info: http://forums.debian.net/viewtopic.php?f=16&t=36826
def ripping_of_cds(): '''Install the tools ripit and burnit in order to rip and burn audio cds. More info: http://forums.debian.net/viewtopic.php?f=16&t=36826 ''' # install and configure ripit install_package('ripit') install_file_legacy(path='~/.ripit/config', username=env.user) # install ...
Install and customize the tiling window manager i3.
def i3(): '''Install and customize the tiling window manager i3.''' install_package('i3') install_file_legacy(path='~/.i3/config', username=env.user, repos_dir='repos') # setup: hide the mouse if not in use # in ~/.i3/config: 'exec /home/<USERNAME>/repos/hhpc/hhpc -i 10 &' install_packages(['ma...
Set solarized colors in urxvt, tmux, and vim. More Infos: * Getting solarized colors right with urxvt, st, tmux and vim: https://bbs.archlinux.org/viewtopic.php?id=164108 * Creating ~/.Xresources: https://wiki.archlinux.org/index.php/Rxvt-unicode#Creating_.7E.2F.Xresources * Select a good...
def solarized(): '''Set solarized colors in urxvt, tmux, and vim. More Infos: * Getting solarized colors right with urxvt, st, tmux and vim: https://bbs.archlinux.org/viewtopic.php?id=164108 * Creating ~/.Xresources: https://wiki.archlinux.org/index.php/Rxvt-unicode#Creating_.7E.2F.Xresour...
Customize vim, install package manager pathogen and some vim-packages. pathogen will be installed as a git repo at ~/repos/vim-pathogen and activated in vim by a symbolic link at ~/.vim/autoload/pathogen.vim A ~/.vimrc will be installed which loads the package manager within of vim. The vim packages ...
def vim(): '''Customize vim, install package manager pathogen and some vim-packages. pathogen will be installed as a git repo at ~/repos/vim-pathogen and activated in vim by a symbolic link at ~/.vim/autoload/pathogen.vim A ~/.vimrc will be installed which loads the package manager within of vim. ...
Install or update the pyenv python environment. Checkout or update the pyenv repo at ~/.pyenv and enable the pyenv. Pyenv wird also als Github-Repo "installiert" unter ~/.pyenv More info: * https://github.com/yyuu/pyenv * https://github.com/yyuu/pyenv/wiki/Common-build-problems#requirements ...
def pyenv(): '''Install or update the pyenv python environment. Checkout or update the pyenv repo at ~/.pyenv and enable the pyenv. Pyenv wird also als Github-Repo "installiert" unter ~/.pyenv More info: * https://github.com/yyuu/pyenv * https://github.com/yyuu/pyenv/wiki/Common-build-proble...
Install a VirtualBox host system. More Infos: * overview: https://wiki.ubuntuusers.de/VirtualBox/ * installation: https://wiki.ubuntuusers.de/VirtualBox/Installation/
def virtualbox_host(): '''Install a VirtualBox host system. More Infos: * overview: https://wiki.ubuntuusers.de/VirtualBox/ * installation: https://wiki.ubuntuusers.de/VirtualBox/Installation/ ''' if query_yes_no(question='Uninstall virtualbox-dkms?', default='yes'): run('sudo apt...
Customize the server (user, authorized_keys, ...).
def server_customizations(): '''Customize the server (user, authorized_keys, ...).''' username = env.user env.user = 'root' # create user all_users = run('cut -d: -f1 /etc/passwd').split() if username not in all_users: host = env.host run(flo('adduser {username}')) #...
Install or update latest Pencil version 2, a GUI prototyping tool. Tip: For svg exports displayed proper in other programs (eg. inkscape, okular, reveal.js presentations) only use the 'Common Shapes' and 'Desktop - Sketchy GUI' elements. More info: github repo (forked version 2): https://githu...
def pencil2(): '''Install or update latest Pencil version 2, a GUI prototyping tool. Tip: For svg exports displayed proper in other programs (eg. inkscape, okular, reveal.js presentations) only use the 'Common Shapes' and 'Desktop - Sketchy GUI' elements. More info: github repo (forked ver...
Install or update latest Pencil version 3, a GUI prototyping tool. While it is the newer one and the GUI is more fancy, it is the "more beta" version of pencil. For exmaple, to display a svg export may fail from within a reveal.js presentation. More info: Homepage: http://pencil.evolus.vn/Nex...
def pencil3(): '''Install or update latest Pencil version 3, a GUI prototyping tool. While it is the newer one and the GUI is more fancy, it is the "more beta" version of pencil. For exmaple, to display a svg export may fail from within a reveal.js presentation. More info: Homepage: http:...
Install custom commands for user root at '/root/bin/'.
def server_prepare_root_bin_dir(): '''Install custom commands for user root at '/root/bin/'.''' commands = ['run_backup'] for command in commands: install_file_legacy(flo('/root/bin/{command}'), sudo=True) sudo(flo('chmod 755 /root/bin/{command}')) if command == 'run_backup': ...
Install and set up powerline-shell prompt. More infos: * https://github.com/banga/powerline-shell * https://github.com/ohnonot/powerline-shell * https://askubuntu.com/questions/283908/how-can-i-install-and-use-powerline-plugin
def powerline_shell(): '''Install and set up powerline-shell prompt. More infos: * https://github.com/banga/powerline-shell * https://github.com/ohnonot/powerline-shell * https://askubuntu.com/questions/283908/how-can-i-install-and-use-powerline-plugin ''' assert env.host == 'localhost',...
Install Telegram desktop client for linux (x64). More infos: https://telegram.org https://desktop.telegram.org/
def telegram(): '''Install Telegram desktop client for linux (x64). More infos: https://telegram.org https://desktop.telegram.org/ ''' if not exists('~/bin/Telegram', msg='Download and install Telegram:'): run('mkdir -p /tmp/telegram') run('cd /tmp/telegram && wget https:/...
The utililty requires boto3 clients to CloudFormation. Args: None Returns: Good or Bad; True or False
def _init_boto3_clients(self, profile, region): """ The utililty requires boto3 clients to CloudFormation. Args: None Returns: Good or Bad; True or False """ try: session = None if profile and region: sessi...
Determine the drift of the stack. Args: None Returns: Good or Bad; True or False
def determine_drift(self): """ Determine the drift of the stack. Args: None Returns: Good or Bad; True or False """ try: response = self._cloud_formation.detect_stack_drift(StackName=self._stack_name) drift_request_id = re...
Report the drift of the stack. Args: None Returns: Good or Bad; True or False Note: not yet implemented
def _print_drift_report(self): """ Report the drift of the stack. Args: None Returns: Good or Bad; True or False Note: not yet implemented """ try: response = self._cloud_formation.describe_stack_resources(StackName=self._sta...
Looks for settings under DJANGO_HISTORY_SETTINGS, supporting dot notation for nested lookups, eg. get_setting('EXCLUDE_CHANGES.fields')
def get_setting(name): """ Looks for settings under DJANGO_HISTORY_SETTINGS, supporting dot notation for nested lookups, eg. get_setting('EXCLUDE_CHANGES.fields') """ dh = getattr(settings, 'DJANGO_HISTORY_SETTINGS', {}) result = None for k in name.split('.'): if dh is None: cont...
Encrypt data
def CryptProtectData( data, description=None, optional_entropy=None, prompt_struct=None, flags=0, ): """ Encrypt data """ data_in = DATA_BLOB(data) entropy = DATA_BLOB(optional_entropy) if optional_entropy else None data_out = DATA_BLOB() res = _CryptProtectData( data_in, description, entropy, None, ...
Returns a tuple of (description, data) where description is the the description that was passed to the CryptProtectData call and data is the decrypted result.
def CryptUnprotectData( data, optional_entropy=None, prompt_struct=None, flags=0): """ Returns a tuple of (description, data) where description is the the description that was passed to the CryptProtectData call and data is the decrypted result. """ data_in = DATA_BLOB(data) entropy = DATA_BLOB(optional_entropy...
Use this method to set the data for this blob
def set_data(self, data): "Use this method to set the data for this blob" if data is None: self.data_size = 0 self.data = None return self.data_size = len(data) # create a string buffer so that null bytes aren't interpreted # as the end of the string self.data = ctypes.cast(ctypes.create_string_bu...
Get the data for this blob
def get_data(self): "Get the data for this blob" array = ctypes.POINTER(ctypes.c_char * len(self)) return ctypes.cast(self.data, array).contents.raw
Ask a question for input via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. The "answer" return value is a str.
def query_input(question, default=None, color=default_color): """Ask a question for input via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. The "answer" return value is a str. """ if de...
Create a repository for a new fabsetup-task addon. The repo will contain the fabsetup addon boilerplate. Running this task you have to enter: * your github user account (your pypi account should be the same or similar) * addon name * task name * headline, short description, and touched (and cr...
def new_addon(): '''Create a repository for a new fabsetup-task addon. The repo will contain the fabsetup addon boilerplate. Running this task you have to enter: * your github user account (your pypi account should be the same or similar) * addon name * task name * headline, short descript...
Prints metadata for given location. :param archive: CombineArchive instance :param location: :return:
def printMetaDataFor(archive, location): """ Prints metadata for given location. :param archive: CombineArchive instance :param location: :return: """ desc = archive.getMetadataForLocation(location) if desc.isEmpty(): print(" no metadata for '{0}'".format(location)) return ...
Prints content of combine archive :param fileName: path of archive :return: None
def printArchive(fileName): """ Prints content of combine archive :param fileName: path of archive :return: None """ archive = CombineArchive() if archive.initializeFromArchive(fileName) is None: print("Invalid Combine Archive") return None print('*'*80) print('Print ar...
Like cmd.exe's mklink except it will infer directory status of the target.
def mklink(): """ Like cmd.exe's mklink except it will infer directory status of the target. """ from optparse import OptionParser parser = OptionParser(usage="usage: %prog [options] link target") parser.add_option( '-d', '--directory', help="Target is a directory (only necessary if not present)", action="...
If creating a symlink from link to a target, determine if target is a directory (relative to dirname(link)).
def _is_target_a_directory(link, rel_target): """ If creating a symlink from link to a target, determine if target is a directory (relative to dirname(link)). """ target = os.path.join(os.path.dirname(link), rel_target) return os.path.isdir(target)