text
stringlengths
81
112k
Cleanup a remotely merged branch. def merged(): # type: () -> None """ Cleanup a remotely merged branch. """ develop = conf.get('git.devel_branch', 'develop') master = conf.get('git.master_branch', 'master') branch = git.current_branch(refresh=True) common.assert_branch_type('hotfix') # P...
Run the shell command Returns: ShellCommand: return this ShellCommand instance for chaining def run(self): """ Run the shell command Returns: ShellCommand: return this ShellCommand instance for chaining """ if not self.block: self.ou...
Send text to stdin. Can only be used on non blocking commands Args: value (str): the text to write on stdin Raises: TypeError: If command is blocking Returns: ShellCommand: return this ShellCommand instance for chaining def send(self, value): """ ...
Append lines from stdout to self.output. Returns: list: The lines added since last call def poll_output(self): """ Append lines from stdout to self.output. Returns: list: The lines added since last call """ if self.block: return self...
Append lines from stderr to self.errors. Returns: list: The lines added since last call def poll_error(self): """ Append lines from stderr to self.errors. Returns: list: The lines added since last call """ if self.block: return self....
Kill the current non blocking command Raises: TypeError: If command is blocking def kill(self): """ Kill the current non blocking command Raises: TypeError: If command is blocking """ if self.block: raise TypeError(NON_BLOCKING_ERROR...
Block until a pattern have been found in stdout and stderr Args: pattern(:class:`~re.Pattern`): The pattern to search timeout(int): Maximum number of second to wait. If None, wait infinitely Raises: TimeoutError: When timeout is reach def wait_for(self, pattern, t...
Check if the command is currently running Returns: bool: True if running, else False def is_running(self): """ Check if the command is currently running Returns: bool: True if running, else False """ if self.block: return False ...
Block and print the output of the command Raises: TypeError: If command is blocking def print_live_output(self): ''' Block and print the output of the command Raises: TypeError: If command is blocking ''' if self.block: raise TypeErr...
Create an instance of :class:`~ShellCommand` and run it Args: command (str): :class:`~ShellCommand` block (bool): See :class:`~ShellCommand` cwd (str): Override the runner cwd. Useb by the :class:`~ShellCommand` instance def run(self, command, block=True, cwd=None, stdin=su...
Bivariate, Correlated Errors and intrinsic Scatter (BCES) translated from the FORTRAN code by Christina Bird and Matthew Bershady (Akritas & Bershady, 1996) Linear regression in the presence of heteroscedastic errors on both variables and intrinsic scatter Parameters ---------- x1 ...
Used mainly to measure scatter for the BCES best-fit def scatter(slope, zero, x1, x2, x1err=[], x2err=[]): """ Used mainly to measure scatter for the BCES best-fit """ n = len(x1) x2pred = zero + slope * x1 s = sum((x2 - x2pred) ** 2) / (n - 1) if len(x2err) == n: s_obs = sum((x2er...
Python wrapper for the linear regression MCMC of Kelly (2007). Requires pidly (http://astronomy.sussex.ac.uk/~anthonys/pidly/) and an IDL license. Parameters ---------- x1 : array of floats Independent variable, or observable x2 : array of floats ...
Use emcee to find the best-fit linear relation or power law accounting for measurement uncertainties and intrinsic scatter Parameters ---------- x1 : array of floats Independent variable, or observable x2 : array of floats Dependent variable ...
Maximum Likelihood Estimation of best-fit parameters Parameters ---------- x1, x2 : float arrays the independent and dependent variables. x1err, x2err : float arrays (optional) measurement uncertainties on independent and dependent variables....
Take linear measurements and uncertainties and transform to log values. def to_log(x1, x2, x1err, x2err): """ Take linear measurements and uncertainties and transform to log values. """ logx1 = numpy.log10(numpy.array(x1)) logx2 = numpy.log10(numpy.array(x2)) x1err = numpy.log10(numpy.array(x1...
Put quotes around all paths and join them with space in-between. def wrap_paths(paths): # type: (list[str]) -> str """ Put quotes around all paths and join them with space in-between. """ if isinstance(paths, string_types): raise ValueError( "paths cannot be a string. " "Use...
Walk recursively starting at *path* excluding files matching *exclude* Args: path (str): A starting path. This has to be an existing directory. include (list[str]): A white list of glob patterns. If given, only files that match those globs will be yielded (filter...
Test whether the given *path* matches any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of glob string patterns to test against. If *path* matches any of those patters, it will return True. Returns: ...
Test whether the given *path* contains any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of glob string patterns to test against. If *path* matches any of those patters, it will return True. Returns: ...
--pretend aware file writing. You can always write files manually but you should always handle the --pretend case. Args: path (str): content (str): mode (str): def write_file(path, content, mode='w'): # type: (Text, Union[Text,bytes], Text) -> None """ --pretend aware file...
Run pep8 and pylint on all project files. You can configure the linting paths using the lint.paths config variable. This should be a list of paths that will be linted. If a path to a directory is given, all files in that directory and it's subdirectories will be used. The pep8 and pylint config pa...
Runs a command using the subprocess module :param command: List containing the command and all args :param timeout_sec (float) seconds to wait before killing the command. :param output (bool) True collects output, False ignores output :return: Dict containing the command output and return code ...
Gets the ip addresses from ifconfig :return: (dict) of devices and aliases with the IPv4 address def get_ip_addresses(): """Gets the ip addresses from ifconfig :return: (dict) of devices and aliases with the IPv4 address """ log = logging.getLogger(mod_logger + '.get_ip_addresses') command =...
Returns the Mac Address given a device index :param device_index: (int) Device index :return: (str) Mac address or None def get_mac_address(device_index=0): """Returns the Mac Address given a device index :param device_index: (int) Device index :return: (str) Mac address or None """ log =...
Emulates bash chmod command This method sets the file permissions to the specified mode. :param path: (str) Full path to the file or directory :param mode: (str) Mode to be set (e.g. 0755) :param recursive: (bool) Set True to make a recursive call :return: int exit code of the chmod command :r...
Emulates 'mkdir -p' in bash :param path: (str) Path to create :return: None :raises CommandError def mkdir_p(path): """Emulates 'mkdir -p' in bash :param path: (str) Path to create :return: None :raises CommandError """ log = logging.getLogger(mod_logger + '.mkdir_p') if not i...
Emulates 'source' command in bash :param script: (str) Full path to the script to source :return: Updated environment :raises CommandError def source(script): """Emulates 'source' command in bash :param script: (str) Full path to the script to source :return: Updated environment :raises C...
Run a yum update on this system This public method runs the yum -y update command to update packages from yum. If downloadonly is set to true, the yum updates will be downloaded to the specified dest_dir. :param dest_dir: (str) Full path to the download directory :param downloadonly: Boolean :...
Installs (or downloads) a list of packages from yum This public method installs a list of packages from yum or downloads the packages to the specified destination directory using the yum-downloadonly yum plugin. :param downloadonly: Boolean, set to only download the package and not install it ...
This method installs all RPM files in a specific dir :param install_dir: (str) Full path to the directory :return int exit code form the rpm command :raises CommandError def rpm_install(install_dir): """This method installs all RPM files in a specific dir :param install_dir: (str) Full path to th...
Python impl of the bash sed command This method emulates the functionality of a bash sed command. :param file_path: (str) Full path to the file to be edited :param pattern: (str) Search pattern to replace as a regex :param replace_str: (str) String to replace the pattern :param g: (int) Whether to...
Creates a zip file of a directory tree This method creates a zip archive using the directory tree dir_path and adds to zip_file output. :param dir_path: (str) Full path to directory to be zipped :param zip_file: (str) Full path to the output zip file :return: None :raises CommandError def zip...
This method return the IP address :param interface: (int) Interface number (e.g. 0 for eth0) :return: (str) IP address or None def get_ip(interface=0): """This method return the IP address :param interface: (int) Interface number (e.g. 0 for eth0) :return: (str) IP address or None """ log...
Updates the /etc/hosts file for the specified ip This method updates the /etc/hosts file for the specified IP address with the specified entry. :param ip: (str) IP address to be added or updated :param entry: (str) Hosts file entry to be added :return: None :raises CommandError def update_hos...
Sets this hosts hostname This method updates /etc/sysconfig/network and calls the hostname command to set a hostname on a Linux system. :param new_hostname: (str) New hostname :param pretty_hostname: (str) new pretty hostname, set to the same as new_hostname if not provided :return (int) e...
Sets the NTP server on Linux :param server: (str) NTP server IP or hostname :return: None :raises CommandError def set_ntp_server(server): """Sets the NTP server on Linux :param server: (str) NTP server IP or hostname :return: None :raises CommandError """ log = logging.getLogger(...
Copies an existing ifcfg network script to another :param source_interface: String (e.g. 1) :param dest_interface: String (e.g. 0:0) :return: None :raises TypeError, OSError def copy_ifcfg_file(source_interface, dest_interface): """Copies an existing ifcfg network script to another :param sou...
Removes the ifcfg file at the specified device index and restarts the network service :param device_index: (int) Device Index :return: None :raises CommandError def remove_ifcfg_file(device_index='0'): """Removes the ifcfg file at the specified device index and restarts the network service ...
Adds a NAT rule to iptables :param port: String or int port number :param source_interface: String (e.g. 1) :param dest_interface: String (e.g. 0:0) :return: None :raises: TypeError, OSError def add_nat_rule(port, source_interface, dest_interface): """Adds a NAT rule to iptables :param po...
Restarts the network service on linux :return: None :raises CommandError def service_network_restart(): """Restarts the network service on linux :return: None :raises CommandError """ log = logging.getLogger(mod_logger + '.service_network_restart') command = ['service', 'network', 'rest...
Saves iptables rules to the provided rules file :return: None :raises OSError def save_iptables(rules_file='/etc/sysconfig/iptables'): """Saves iptables rules to the provided rules file :return: None :raises OSError """ log = logging.getLogger(mod_logger + '.save_iptables') # Run ipt...
Retrieves the value of an environment variable of a remote host over SSH :param host: (str) host to query :param environment_variable: (str) variable to query :return: (str) value of the environment variable :raises: TypeError, CommandError def get_remote_host_environment_variable(host, environmen...
Sets an environment variable on the remote host in the specified environment file :param host: (str) host to set environment variable on :param variable_name: (str) name of the variable :param variable_value: (str) value of the variable :param env_file: (str) full path to the environment file to se...
Retrieves the value of an environment variable of a remote host over SSH :param host: (str) host to query :param command: (str) command :param timeout_sec (float) seconds to wait before killing the command. :return: (str) command output :raises: TypeError, CommandError def run_remote_command(h...
Queries a remote host over SSH to check for existence of a marker file :param host: (str) host to query :param file_path: (str) path to the marker file :return: (bool) True if the marker file exists :raises: TypeError, CommandError def check_remote_host_marker_file(host, file_path): """Queries...
Restores and saves firewall rules from the firewall_rules file :param firewall_rules: (str) Full path to the firewall rules file :return: None :raises OSError def restore_iptables(firewall_rules): """Restores and saves firewall rules from the firewall_rules file :param firewall_rules: (str) Full ...
Removes Default Gateway configuration from /etc/sysconfig/network and restarts networking :return: None :raises: OSError def remove_default_gateway(): """Removes Default Gateway configuration from /etc/sysconfig/network and restarts networking :return: None :raises: OSError ""...
Determines whether this system uses systemd :return: (bool) True if this distro has systemd def is_systemd(): """Determines whether this system uses systemd :return: (bool) True if this distro has systemd """ os_family = platform.system() if os_family != 'Linux': raise OSError('This m...
Use to run Linux sysv or systemd service commands :param service_name (str) name of the service to start :param service_action (str) action to perform on the service :param systemd (bool) True if the command should use systemd :param output (bool) True to print output :return: None :raises: OSE...
Reboots the system after a specified wait time. Must be run as root :param wait_time_sec: (int) number of sec to wait before performing the reboot :return: None :raises: SystemRebootError, SystemRebootTimeoutError def system_reboot(wait_time_sec=20): """Reboots the system after a specified wait time....
Sample usage for this python module This main method simply illustrates sample usage for this python module. :return: None def main(): """Sample usage for this python module This main method simply illustrates sample usage for this python module. :return: None """ mkdir_p('/tmp/...
Logs consistent event for easy parsing/analysis. :param name: Name of the event. Will be logged as EVENT_XXX with XXX in capitals. :param request: Django REST framework Request (optional) :param data: Even data (optional) :param ip: Even IP (optional) def log_event(name: str, request: Request=None, dat...
AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELF...
AES decrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES decrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELF...
AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#bytes) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWE...
AES decrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES decrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELF...
Adds padding to get the correct block sizes for AES encryption @s: #str being AES encrypted or decrypted @block_size: the AES block size @padding: character to pad with -> padded #str .. from vital.security import aes_pad aes_pad("swing") # ...
Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix, so this is helpful against timing attacks. .. from vital.security import lscmp lscmp("ringo", "starr") # -> False lscmp("ringo", "ringo") ...
Encodes or decodes a signed cookie. @data: cookie data @key_salt: HMAC key signing salt @secret: HMAC signing secret key @digestmod: hashing algorithm to sign with, recommended >=sha256 -> HMAC signed or unsigned cookie data .. from vital.security import coo...
Converts integers to a sequence of strings, and reverse. This is not intended to obfuscate numbers in any kind of cryptographically secure way, in fact it's the opposite. It's for predictable, reversable, obfuscation. It can also be used to transform a random bit integer to a string of t...
.. log2(keyspace^x_chars) = bits log(keyspace^x_chars) = log(2) * bits exp(log(keyspace^x_chars)) = exp(log(2) * bits) x_chars = log(exp(log(2) * bits)) / log(keyspace) .. -> (#int) number of characters in @bits of entropy given the @keyspace def chars_in(bits, keyspace)...
|log2(keyspace^length) = bits| -> (#float) number of bits of entropy in @length of characters for a given a @keyspace def bits_in(length, keyspace): """ |log2(keyspace^length) = bits| -> (#float) number of bits of entropy in @length of characters for a given a @keyspace ...
Yields a cryptographically secure random key of desired @bits of entropy within @keyspace using :class:random.SystemRandom @bits: (#int) minimum bits of entropy @keyspace: (#str) or iterable allowed output chars .. from vital.security import iter_rand for char ...
Returns a cryptographically secure random key of desired @bits of entropy within @keyspace using :class:random.SystemRandom @bits: (#int) minimum bits of entropy @keyspace: (#str) or iterable allowed output chars @rng: the random number generator to use. Defaults to :class:r...
Returns a cryptographically secure random string of desired @size (in character length) within @keyspace using :class:random.SystemRandom @size: (#int) number of random characters to generate @keyspace: (#str) or iterable allowed output chars @rng: the random number generator to use. De...
load requirements from a pip requirements file def parse_requirements(filename): """ load requirements from a pip requirements file """ lineiter = (line.strip() for line in open(filename)) return (line for line in lineiter if line and not line.startswith("#"))
round floating point x to n significant figures def round_sig(x, n, scien_notation = False): if x < 0: x = x * -1 symbol = '-' else: symbol = '' '''round floating point x to n significant figures''' if type(n) is not types.IntType: raise TypeError, "n must be a...
Find ex rounded to n sig-figs and make the floating point x match the number of decimals. If [paren], the string is returned as quantity(error) format def round_sig_error(x, ex, n, paren=False): '''Find ex rounded to n sig-figs and make the floating point x match the number of decimals. If [paren], t...
Format a table such that the errors have n significant figures. [cols] and [errors] should be a list of 1D arrays that correspond to data and errors in columns. [n] is the number of significant figures to keep in the errors. [labels] is an optional column of strings that will be in the first column. ...
Find min(ex1,ex2) rounded to n sig-figs and make the floating point x and max(ex,ex2) match the number of decimals. def round_sig_error2(x, ex1, ex2, n): '''Find min(ex1,ex2) rounded to n sig-figs and make the floating point x and max(ex,ex2) match the number of decimals.''' minerr = min(ex1,ex2) m...
data = { "table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist, "columns_name" : [first_column_name,second_column_name,...,last_column_name], "rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...] } def send_to_azure_multi_threads(i...
data = { "table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist, "columns_name" : [first_column_name,second_column_name,...,last_column_name], "rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...] } def send_to_azure(instance, data,...
Adds the items to the invoice Format of 'items': [ InvoiceItem( name="VIP Ticket", quantity= 2, unit_price= "3500", total_price= "7000", description= "VIP Tickets for the Party" } ,... ] def create(self...
Returns the status of the invoice STATUSES: pending, completed, cancelled def confirm(self, token=None): """Returns the status of the invoice STATUSES: pending, completed, cancelled """ _token = token if token else self._response.get("token") return self._process('chec...
Appends the data to the 'taxes' key in the request object 'taxes' should be in format: [("tax_name", "tax_amount")] For example: [("Other TAX", 700), ("VAT", 5000)] def add_taxes(self, taxes): """Appends the data to the 'taxes' key in the request object 'taxes' should be in fo...
Updates the list of items in the current transaction def add_item(self, item): """Updates the list of items in the current transaction""" _idx = len(self.items) self.items.update({"item_" + str(_idx + 1): item})
Formats the data in the current transaction for processing def _prepare_data(self): """Formats the data in the current transaction for processing""" total_amount = self.total_amount or self.calculate_total_amt() self._data = { "invoice": { "items": self.__encode_item...
Returns the total amount/cost of items in the current invoice def calculate_total_amt(self, items={}): """Returns the total amount/cost of items in the current invoice""" _items = items.items() or self.items.items() return sum(float(x[1].total_price) for x in _items)
Encodes the InvoiceItems into a JSON serializable format items = [('item_1',InvoiceItem(name='VIP Ticket', quantity=2, unit_price='3500', total_price='7000', description='VIP Tickets for party')),...] def __encode_items(self, items): """Encodes...
Sample usage for this python module This main method simply illustrates sample usage for this python module. :return: None def main(): """Sample usage for this python module This main method simply illustrates sample usage for this python module. :return: None """ log = logging....
Sets self.deployment_home This method finds and sets deployment home, primarily based on the DEPLOYMENT_HOME environment variable. If not set, this method will attempt to determine deployment home. :return: None def set_deployment_home(self): """Sets self.deployment_home ...
Reads the deployment properties file This method reads the deployment properties file into the "properties" dictionary object. :return: None :raises: DeploymentError def read_deployment_properties(self): """Reads the deployment properties file This method reads the de...
Gets the name of a specific property This public method is passed a regular expression and returns the matching property name. If either the property is not found or if the passed string matches more than one property, this function will return None. :param regex: Regular expre...
Returns a list of property names matching the provided regular expression :param regex: Regular expression to search on :return: (list) of property names matching the regex def get_matching_property_names(self, regex): """Returns a list of property names matching the provided r...
Returns the value associated to the passed property This public method is passed a specific property as a string and returns the value of that property. If the property is not found, None will be returned. :param property_name (str) The name of the property :return: (str) value...
Set the cons3rt_role_name member for this system :return: None :raises: DeploymentError def set_cons3rt_role_name(self): """Set the cons3rt_role_name member for this system :return: None :raises: DeploymentError """ log = logging.getLogger(self.cls_logger + '.s...
Determines the CONS3RT_ROLE_NAME for this Linux system, and Set the cons3rt_role_name member for this system This method determines the CONS3RT_ROLE_NAME for this system in the deployment by first checking for the environment variable, if not set, determining the value from the ...
Returns the ASSET_DIR environment variable This method gets the ASSET_DIR environment variable for the current asset install. It returns either the string value if set or None if it is not set. :return: None def set_asset_dir(self): """Returns the ASSET_DIR environment variabl...
Populates the list of scenario role names in this deployment and populates the scenario_master with the master role Gets a list of deployment properties containing "isMaster" because there is exactly one per scenario host, containing the role name :return: def set_scenario_role_names(...
Populates a list of network info for each scenario host from deployment properties :return: None def set_scenario_network_info(self): """Populates a list of network info for each scenario host from deployment properties :return: None """ log = logging.getLogger...
Sets the deployment name from deployment properties :return: None def set_deployment_name(self): """Sets the deployment name from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_deployment_name') self.deployment_name = self.get_v...
Sets the deployment ID from deployment properties :return: None def set_deployment_id(self): """Sets the deployment ID from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_deployment_id') deployment_id_val = self.get_value('cons3...
Sets the deployment run name from deployment properties :return: None def set_deployment_run_name(self): """Sets the deployment run name from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_deployment_run_name') self.deployment_r...
Sets the deployment run ID from deployment properties :return: None def set_deployment_run_id(self): """Sets the deployment run ID from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_deployment_run_id') deployment_run_id_val = s...
Sets the virtualization realm type from deployment properties :return: None def set_virtualization_realm_type(self): """Sets the virtualization realm type from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_virtualization_realm_type') ...
Updated the hosts file depending on the OS :param ip: (str) IP address to update :param entry: (str) entry to associate to the IP address :return: None def update_hosts_file(self, ip, entry): """Updated the hosts file depending on the OS :param ip: (str) IP address to update ...
Adds hosts file entries for each system in the scenario for the specified network_name provided :param network_name: (str) Name of the network to add to the hosts file :param domain_name: (str) Domain name to include in the hosts file entries if provided :return: None def set_scenario_...
Adds an entry to the hosts file for a scenario host given the role name and network name :param role_name: (str) role name of the host to add :param network_name: (str) Name of the network to add to the hosts file :param fqdn: (str) Fully qualified domain name to use in the hosts file e...
Given a network name, returns the IP address :param network_name: (str) Name of the network to search for :return: (str) IP address on the specified network or None def get_ip_on_network(self, network_name): """Given a network name, returns the IP address :param network_name: (str) Na...