INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash ...
def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false ...
Ensure a Vault policy with the given name and rules is present. name The name of the policy rules Rules formatted as in-line HCL .. code-block:: yaml demo-policy: vault.policy_present: - name: foo/bar - rules: | path "secret/top-...
def policy_present(name, rules): ''' Ensure a Vault policy with the given name and rules is present. name The name of the policy rules Rules formatted as in-line HCL .. code-block:: yaml demo-policy: vault.policy_present: - name: foo/bar ...
Write the return data to a file on the minion.
def returner(ret): ''' Write the return data to a file on the minion. ''' opts = _get_options(ret) try: with salt.utils.files.flopen(opts['filename'], 'a') as logfile: salt.utils.json.dump(ret, logfile) logfile.write(str('\n')) # future lint: disable=blacklisted-func...
Write event data (return data and non-return data) to file on the master.
def event_return(events): ''' Write event data (return data and non-return data) to file on the master. ''' if not events: # events is an empty list. # Don't open the logfile in vain. return opts = _get_options({}) # Pass in empty ret, since this is a list of events try:...
Turn the layout data into usable vdevs spedcification We need to support 2 ways of passing the layout: .. code:: layout_new: - mirror: - disk0 - disk1 - mirror: - disk2 - disk3 .. code: layout_legacy: mirror-0: ...
def _layout_to_vdev(layout, device_dir=None): ''' Turn the layout data into usable vdevs spedcification We need to support 2 ways of passing the layout: .. code:: layout_new: - mirror: - disk0 - disk1 - mirror: - disk2 - disk3...
ensure storage pool is present on the system name : string name of storage pool properties : dict optional set of properties to set for the storage pool filesystem_properties : dict optional set of filesystem properties to set for the storage pool (creation only) layout: dict ...
def present(name, properties=None, filesystem_properties=None, layout=None, config=None): ''' ensure storage pool is present on the system name : string name of storage pool properties : dict optional set of properties to set for the storage pool filesystem_properties : dict ...
ensure storage pool is absent on the system name : string name of storage pool export : boolean export instread of destroy the zpool if present force : boolean force destroy or export
def absent(name, export=False, force=False): ''' ensure storage pool is absent on the system name : string name of storage pool export : boolean export instread of destroy the zpool if present force : boolean force destroy or export ''' ret = {'name': name, ...
Attempts to run systemctl --version. Returns None if unable to determine version.
def version(context=None): ''' Attempts to run systemctl --version. Returns None if unable to determine version. ''' contextkey = 'salt.utils.systemd.version' if isinstance(context, dict): # Can't put this if block on the same line as the above if block, # because it will break t...
Scopes were introduced in systemd 205, this function returns a boolean which is true when the minion is systemd-booted and running systemd>=205.
def has_scope(context=None): ''' Scopes were introduced in systemd 205, this function returns a boolean which is true when the minion is systemd-booted and running systemd>=205. ''' if not booted(context): return False _sd_version = version(context) if _sd_version is None: re...
Return a postgres connection.
def _get_conn(): ''' Return a postgres connection. ''' try: conn = psycopg2.connect( host=__opts__['master_job_cache.postgres.host'], user=__opts__['master_job_cache.postgres.user'], password=__opts__['master_job_cache.postgres.passwd'], ...
Format the job instance correctly
def _format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': salt.utils.json.loads(job.get('arg', '[]')), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-targe...
Generate an unique job id
def _gen_jid(cur): ''' Generate an unique job id ''' jid = salt.utils.jid.gen_jid(__opts__) sql = '''SELECT jid FROM jids WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() if not data: return jid return None
Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case
def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid). So do what you have to do to make sure that stays the case ''' conn = _get_conn() if conn is N...
Return data to a postgres server
def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_ty...
Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config.
def event_return(events): ''' Return event to a postgres server Require that configuration be enabled via 'event_return' option in master config. ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() for event in events: tag = event.get('tag', '') ...
Save the load to the specified jid id
def save_load(jid, clear_load, minions=None): ''' Save the load to the specified jid id ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO jids ''' \ '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, user...
Do proper formatting of the jid
def _escape_jid(jid): ''' Do proper formatting of the jid ''' jid = six.text_type(jid) jid = re.sub(r"'*", "", jid) return jid
Rebuild dict
def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] resu...
Return the load data that marks a specified jid
def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = ...
Return the information returned when the specified job id was executed
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT id, return FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,))...
Return a list of all job ids For master job cache this also formats the output and returns a string
def get_jids(): ''' Return a list of all job ids For master job cache this also formats the output and returns a string ''' conn = _get_conn() cur = conn.cursor() sql = '''SELECT ''' \ '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \ '''FROM jids''' i...
Query for all accounts which have 3 or more login failures. CLI Example: .. code-block:: bash salt <minion_id> shadow.login_failures ALL
def login_failures(user): ''' Query for all accounts which have 3 or more login failures. CLI Example: .. code-block:: bash salt <minion_id> shadow.login_failures ALL ''' cmd = 'lsuser -a unsuccessful_login_count {0}'.format(user) cmd += " | grep -E 'unsuccessful_login_count=([3...
Unlock user for locked account CLI Example: .. code-block:: bash salt <minion_id> shadow.unlock user
def unlock(user): ''' Unlock user for locked account CLI Example: .. code-block:: bash salt <minion_id> shadow.unlock user ''' cmd = 'chuser account_locked=false {0} | ' \ 'chsec -f /etc/security/lastlog -a "unsuccessful_login_count=0" -s {0}'.format(user) ret = __salt_...
Create an alert in OpsGenie. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: api_key It's the API Key you've copied while adding integration in OpsGenie. reason It will be used as alert's default message in OpsGenie. ...
def create_alert(name=None, api_key=None, reason=None, action_type="Create"): ''' Create an alert in OpsGenie. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: api_key It's the API Key you've copied while adding integration in...
Close an alert in OpsGenie. It's a wrapper function for create_alert. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: name It will be used as alert's alias. If you want to use the close functionality you must provide name...
def close_alert(name=None, api_key=None, reason="Conditions are met.", action_type="Close"): ''' Close an alert in OpsGenie. It's a wrapper function for create_alert. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: ...
Updates the probes dictionary with different levels of default values.
def _expand_probes(probes, defaults): ''' Updates the probes dictionary with different levels of default values. ''' expected_probes = {} for probe_name, probe_test in six.iteritems(probes): if probe_name not in expected_probes.keys(): expected_probes[probe_name] = {} ...
Compares configured probes on the device with the expected configuration and returns the differences.
def _compare_probes(configured_probes, expected_probes): ''' Compares configured probes on the device with the expected configuration and returns the differences. ''' new_probes = {} update_probes = {} remove_probes = {} # noth configured => configure with expected probes if not confi...
Will remove empty and useless values from the probes dictionary.
def _clean_probes(probes): ''' Will remove empty and useless values from the probes dictionary. ''' probes = _ordered_dict_to_dict(probes) # make sure we are working only with dict-type probes_copy = deepcopy(probes) for probe_name, probe_tests in six.iteritems(probes_copy): if not pr...
Ensure the networks device is configured as specified in the state SLS file. Probes not specified will be removed, while probes not confiured as expected will trigger config updates. :param probes: Defines the probes as expected to be configured on the device. In order to ease the configuration and av...
def managed(name, probes, defaults=None): ''' Ensure the networks device is configured as specified in the state SLS file. Probes not specified will be removed, while probes not confiured as expected will trigger config updates. :param probes: Defines the probes as expected to be configured on the ...
Send an email with the data
def returner(ret): ''' Send an email with the data ''' _options = _get_options(ret) from_addr = _options.get('from') to_addrs = _options.get('to').split(',') host = _options.get('host') port = _options.get('port') user = _options.get('username') passwd = _options.get('password')...
Return event data via SMTP
def event_return(events): ''' Return event data via SMTP ''' for event in events: ret = event.get('data', False) if ret: returner(ret)
Takes a tab list structure and renders it to a list for applying it to a file
def _render_tab(lst): ''' Takes a tab list structure and renders it to a list for applying it to a file ''' ret = [] for pre in lst['pre']: ret.append('{0}\n'.format(pre)) for cron in lst['crons']: ret.append('{0} {1} {2} {3}\n'.format(cron['path'], ...
Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron
def write_incron_file(user, path): ''' Writes the contents of a file to a user's incrontab CLI Example: .. code-block:: bash salt '*' incron.write_incron_file root /tmp/new_incron ''' return __salt__['cmd.retcode'](_get_incron_cmdstr(path), runas=user, python_shell=False) == 0
Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron
def write_incron_file_verbose(user, path): ''' Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron ''' return __salt__['cmd.run_all'](_get_incron_cmdstr(p...
Takes a list of lines to be committed to a user's incrontab and writes it
def _write_incron_lines(user, lines): ''' Takes a list of lines to be committed to a user's incrontab and writes it ''' if user == 'system': ret = {} ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines)) return ret else: path = salt.utils.files.mkst...
Writes a file to disk
def _write_file(folder, filename, data): ''' Writes a file to disk ''' path = os.path.join(folder, filename) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist'.format(filename, folder) log.error(msg) raise AttributeError(six.text_type(msg)) w...
Reads and returns the contents of a file
def _read_file(folder, filename): ''' Reads and returns the contents of a file ''' path = os.path.join(folder, filename) try: with salt.utils.files.fopen(path, 'rb') as contents: return salt.utils.data.decode(contents.readlines()) except (OSError, IOError): return ''
Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root
def raw_incron(user): ''' Return the contents of the user's incrontab CLI Example: .. code-block:: bash salt '*' incron.raw_incron root ''' if __grains__['os_family'] == 'Solaris': cmd = 'incrontab -l {0}'.format(user) else: cmd = 'incrontab -l -u {0}'.format(user)...
Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root
def list_tab(user): ''' Return the contents of the specified user's incrontab CLI Example: .. code-block:: bash salt '*' incron.list_tab root ''' if user == 'system': data = raw_system_incron() else: data = raw_incron(user) log.debug('incron user data %s', ...
Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"'
def set_job(user, path, mask, cmd): ''' Sets an incron job up for a specified user. CLI Example: .. code-block:: bash salt '*' incron.set_job root '/root' 'IN_MODIFY' 'echo "$$ $@ $# $% $&"' ''' # Scrub the types mask = six.text_type(mask).upper() # Check for valid mask types...
Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path
def rm_job(user, path, mask, cmd): ''' Remove a incron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' incron.rm_job root /path ...
IRC Bot for interacting with salt. nick Nickname of the connected Bot. host irc server (example - chat.freenode.net). port irc port. Default: 6667 password password for authenticating. If not provided, user will not authenticate on the irc server. channels ...
def start(nick, host, port=6667, username=None, password=None, channels=None, use_ssl=False, use_sasl=False, char='!', allow_hosts=False, allow_nicks=False, disable_query=True): ''' IRC Bot for interacting with salt. nick Nickname of the connected Bot. host irc server (exampl...
Checks to see if the specific apache mod is enabled. This will only be functional on operating systems that support `a2enmod -l` to list the enabled mods. CLI Example: .. code-block:: bash salt '*' apache.check_mod_enabled status
def check_mod_enabled(mod): ''' Checks to see if the specific apache mod is enabled. This will only be functional on operating systems that support `a2enmod -l` to list the enabled mods. CLI Example: .. code-block:: bash salt '*' apache.check_mod_enabled status ''' if mod.end...
Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id
def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profi...
Adds a grant to a key to specify who can access the key and under what conditions. CLI example:: salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]'
def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Adds a grant to a key to specify who can access the key and under what conditions. CLI examp...
Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key"
def create_key(policy=None, description=None, key_usage=None, region=None, key=None, keyid=None, profile=None): ''' Creates a master key. CLI example:: salt myminion boto_kms.create_key '{"Statement":...}' "My master key" ''' conn = _get_conn(region=region, key=key, keyid=ke...
Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext
def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Decrypt ciphertext. CLI example:: salt myminion boto_kms.decrypt encrypted_ciphertext ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile...
Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey'
def key_exists(key_id, region=None, key=None, keyid=None, profile=None): ''' Check for the existence of a key. CLI example:: salt myminion boto_kms.key_exists 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.de...
From an alias, get a key_id.
def _get_key_id(alias, region=None, key=None, keyid=None, profile=None): ''' From an alias, get a key_id. ''' key_metadata = describe_key( alias, region, key, keyid, profile )['key_metadata'] return key_metadata['KeyId']
Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey'
def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(...
Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}'
def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Encrypt plaintext into cipher text using specified key. CLI example:: salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' ...
Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias...
Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024
def generate_random(number_of_bytes=None, region=None, key=None, keyid=None, profile=None): ''' Generate a random string. CLI example:: salt myminion boto_kms.generate_random number_of_bytes=1024 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)...
Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy
def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profil...
Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey'
def get_key_rotation_status(key_id, region=None, key=None, keyid=None, profile=None): ''' Get status of whether or not key rotation is enabled for a key. CLI example:: salt myminion boto_kms.get_key_rotation_status 'alias/mykey' ''' conn = _get_conn(region=regio...
List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey'
def list_grants(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List grants for the specified key. CLI example:: salt myminion boto_kms.list_grants 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile...
List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey'
def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyi...
Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}'
def put_key_policy(key_id, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Attach a key policy to the specified key. CLI example:: salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}' ''' conn = _get_conn(region=regio...
Reencrypt encrypted data with a new master key. CLI example:: salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}'
def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Reencrypt encrypted data with a new master key. CLI example:: ...
Pretty print the stack trace and environment information for debugging those hard to reproduce user problems. :)
def _makepretty(printout, stack): ''' Pretty print the stack trace and environment information for debugging those hard to reproduce user problems. :) ''' printout.write('======== Salt Debug Stack Trace =========\n') traceback.print_stack(stack, file=printout) printout.write('==============...
Signal handler for SIGUSR1, only available on Unix-like systems
def _handle_sigusr1(sig, stack): ''' Signal handler for SIGUSR1, only available on Unix-like systems ''' # When running in the foreground, do the right thing # and spit out the debug info straight to the console if sys.stderr.isatty(): output = sys.stderr _makepretty(output, sta...
Signal handler for SIGUSR2, only available on Unix-like systems
def _handle_sigusr2(sig, stack): ''' Signal handler for SIGUSR2, only available on Unix-like systems ''' try: import yappi except ImportError: return if yappi.is_running(): yappi.stop() filename = 'callgrind.salt-{0}-{1}'.format(int(time.time()), os.getpid()) ...
Add signal handler for signal name if it exists on given platform
def enable_sig_handler(signal_name, handler): ''' Add signal handler for signal name if it exists on given platform ''' if hasattr(signal, signal_name): signal.signal(getattr(signal, signal_name), handler)
Get a name of a caller in the format module.class.method `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exceed stack height Source: https://gist.github.com/techto...
def caller_name(skip=2, include_lineno=False): ''' Get a name of a caller in the format module.class.method `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exce...
Ensure the NX-OS system image is running on the device. name Name of the salt state task system_image Name of the system image file on bootflash: kickstart_image Name of the kickstart image file on bootflash: This is not needed if the system_image is a combined system and ...
def image_running(name, system_image, kickstart_image=None, issu=True, **kwargs): ''' Ensure the NX-OS system image is running on the device. name Name of the salt state task system_image Name of the system image file on bootflash: kickstart_image Name of the kickstart ima...
Given the service instance si and tasks, it returns after all the tasks are complete
def WaitForTasks(tasks, si): """ Given the service instance si and tasks, it returns after all the tasks are complete """ pc = si.content.propertyCollector taskList = [str(task) for task in tasks] # Create filter objSpecs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task) ...
Calculates the checksum char used for the 16th char. Author: Vincenzo Palazzo
def checksum(value): """ Calculates the checksum char used for the 16th char. Author: Vincenzo Palazzo """ return chr(65 + sum(CHECKSUM_TABLE[index % 2][ALPHANUMERICS_DICT[char]] for index, char in enumerate(value)) % 26)
Returns random binary blob. Default blob size is 1 Mb.
def binary(self, length=(1 * 1024 * 1024)): """ Returns random binary blob. Default blob size is 1 Mb. """ blob = [self.generator.random.randrange(256) for _ in range(length)] return bytes(blob) if sys.version_info[0] >= 3 else bytearray(blob)
Calculates the md5 hash of a given string :example 'cfcd208495d565ef66e7dff9f98764da'
def md5(self, raw_output=False): """ Calculates the md5 hash of a given string :example 'cfcd208495d565ef66e7dff9f98764da' """ res = hashlib.md5(str(self.generator.random.random()).encode('utf-8')) if raw_output: return res.digest() return res.hexdiges...
Generates a random UUID4 string. :param cast_to: Specify what type the UUID should be cast to. Default is `str` :type cast_to: callable
def uuid4(self, cast_to=str): """ Generates a random UUID4 string. :param cast_to: Specify what type the UUID should be cast to. Default is `str` :type cast_to: callable """ # Based on http://stackoverflow.com/q/41186818 return cast_to(uuid.UUID(int=self.generator...
Generates a random password. @param length: Integer. Length of a password @param special_chars: Boolean. Whether to use special characters !@#$%^&*()_+ @param digits: Boolean. Whether to use digits @param upper_case: Boolean. Whether to use upper letters @param lower_case: Boolea...
def password( self, length=10, special_chars=True, digits=True, upper_case=True, lower_case=True): """ Generates a random password. @param length: Integer. Length of a password @param special_chars: Boolean. Whether ...
Calculates and returns a control digit for given list of characters basing on Identity Card Number standards.
def checksum_identity_card_number(characters): """ Calculates and returns a control digit for given list of characters basing on Identity Card Number standards. """ weights_for_check_digit = [7, 3, 1, 0, 7, 3, 1, 7, 3] check_digit = 0 for i in range(3): check_digit += weights_for_check_...
Returns 9 character Polish Identity Card Number, Polish: Numer Dowodu Osobistego. The card number consists of 3 letters followed by 6 digits (for example, ABA300000), of which the first digit (at position 3) is the check digit. https://en.wikipedia.org/wiki/Polish_identity_card
def identity_card_number(self): """ Returns 9 character Polish Identity Card Number, Polish: Numer Dowodu Osobistego. The card number consists of 3 letters followed by 6 digits (for example, ABA300000), of which the first digit (at position 3) is the check digit. https:...
A simple method that runs a Command.
def execute_from_command_line(argv=None): """A simple method that runs a Command.""" if sys.stdout.encoding is None: print('please set python env PYTHONIOENCODING=UTF-8, example: ' 'export PYTHONIOENCODING=UTF-8, when writing to stdout', file=sys.stderr) exit(1) ...
Given the command-line arguments, this creates a parser appropriate to that command, and runs it.
def execute(self): """ Given the command-line arguments, this creates a parser appropriate to that command, and runs it. """ # retrieve default language from system environment default_locale = os.environ.get('LANG', 'en_US').split('.')[0] if default_locale not i...
Calculate the check digit for ISBN-13. See https://en.wikipedia.org/wiki/International_Standard_Book_Number for calculation.
def _check_digit(self): """ Calculate the check digit for ISBN-13. See https://en.wikipedia.org/wiki/International_Standard_Book_Number for calculation. """ weights = (1 if x % 2 == 0 else 3 for x in range(12)) body = ''.join([self.ean, self.group, self.registrant, ...
Validates a french catch phrase. :param catch_phrase: The catch phrase to validate.
def _is_catch_phrase_valid(self, catch_phrase): """ Validates a french catch phrase. :param catch_phrase: The catch phrase to validate. """ for word in self.words_which_should_not_appear_twice: # Fastest way to check if a piece of word does not appear twice. ...
Generates a siret number (14 digits). It is in fact the result of the concatenation of a siren number (9 digits), a sequential number (4 digits) and a control number (1 digit) concatenation. If $max_sequential_digits is invalid, it is set to 2. :param max_sequential_digits The maximum nu...
def siret(self, max_sequential_digits=2): """ Generates a siret number (14 digits). It is in fact the result of the concatenation of a siren number (9 digits), a sequential number (4 digits) and a control number (1 digit) concatenation. If $max_sequential_digits is invalid, it is...
Remove accents from characters in the given string.
def remove_accents(value): """ Remove accents from characters in the given string. """ search = 'ΆΈΉΊΌΎΏάέήίόύώΪϊΐϋΰ' replace = 'ΑΕΗΙΟΥΩαεηιουωΙιιυυ' def replace_accented_character(match): matched = match.group(0) if matched in search: return replace[search.find(matc...
Converts (transliterates) greek letters to latin equivalents.
def latinize(value): """ Converts (transliterates) greek letters to latin equivalents. """ def replace_double_character(match): search = ('Θ Χ Ψ ' 'θ χ ψ ' 'ΟΥ ΑΥ ΕΥ ' 'Ου Αυ Ευ ' 'ου αυ ευ').split() replace = ('TH C...
Returns an Israeli identity number, known as Teudat Zehut ("tz"). https://en.wikipedia.org/wiki/Israeli_identity_card
def ssn(self): """ Returns an Israeli identity number, known as Teudat Zehut ("tz"). https://en.wikipedia.org/wiki/Israeli_identity_card """ newID = str(self.generator.random.randrange(111111, 99999999)) newID = newID.zfill(8) theSum = 0 indexRange = [0,...
:returns: An array of random words. for example: ['Lorem', 'ipsum', 'dolor'] Keyword arguments: :param nb: how many words to return :param ext_word_list: a list of words you would like to have instead of 'Lorem ipsum' :param unique: If True, the returned word list will conta...
def words(self, nb=3, ext_word_list=None, unique=False): """ :returns: An array of random words. for example: ['Lorem', 'ipsum', 'dolor'] Keyword arguments: :param nb: how many words to return :param ext_word_list: a list of words you would like to have instead of 'L...
Generate a random sentence :example 'Lorem ipsum dolor sit amet.' :param nb_words: around how many words the sentence should contain :param variable_nb_words: set to false if you want exactly ``nb`` words returned, otherwise the result may include a number of words of ``...
def sentence(self, nb_words=6, variable_nb_words=True, ext_word_list=None): """ Generate a random sentence :example 'Lorem ipsum dolor sit amet.' :param nb_words: around how many words the sentence should contain :param variable_nb_words: set to false if you want exactly ``nb`` ...
Generate an array of sentences :example ['Lorem ipsum dolor sit amet.', 'Consectetur adipisicing eli.'] Keyword arguments: :param nb: how many sentences to return :param ext_word_list: a list of words you would like to have instead of 'Lorem ipsum'. :rtype: list
def sentences(self, nb=3, ext_word_list=None): """ Generate an array of sentences :example ['Lorem ipsum dolor sit amet.', 'Consectetur adipisicing eli.'] Keyword arguments: :param nb: how many sentences to return :param ext_word_list: a list of words you would like to h...
:returns: A single paragraph. For example: 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.' Keyword arguments: :param nb_sentences: around how many sentences the paragraph should contain :param variable_nb_sentences: set to false ...
def paragraph( self, nb_sentences=3, variable_nb_sentences=True, ext_word_list=None): """ :returns: A single paragraph. For example: 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.' ...
Generate an array of paragraphs :example [paragraph1, paragraph2, paragraph3] :param nb: how many paragraphs to return :param ext_word_list: a list of words you would like to have instead of 'Lorem ipsum'. :rtype: list
def paragraphs(self, nb=3, ext_word_list=None): """ Generate an array of paragraphs :example [paragraph1, paragraph2, paragraph3] :param nb: how many paragraphs to return :param ext_word_list: a list of words you would like to have instead of 'Lorem ipsum'. :...
Generate a text string. Depending on the ``max_nb_chars, returns a string made of words, sentences, or paragraphs. :example 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.' Keyword arguments: :param max_nb_chars: Maximum number of cha...
def text(self, max_nb_chars=200, ext_word_list=None): """ Generate a text string. Depending on the ``max_nb_chars, returns a string made of words, sentences, or paragraphs. :example 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.' ...
:example 'Sashabury'
def city(self): """ :example 'Sashabury' """ pattern = self.random_element(self.city_formats) return self.generator.parse(pattern)
:example 'Crist Parks'
def street_name(self): """ :example 'Crist Parks' """ pattern = self.random_element(self.street_name_formats) return self.generator.parse(pattern)
:example '791 Crist Parks'
def street_address(self): """ :example '791 Crist Parks' """ pattern = self.random_element(self.street_address_formats) return self.generator.parse(pattern)
:example '791 Crist Parks, Sashabury, IL 86039-9874'
def address(self): """ :example '791 Crist Parks, Sashabury, IL 86039-9874' """ pattern = self.random_element(self.address_formats) return self.generator.parse(pattern)
Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace. Modified to optionally allow dots. Adapted from Django 1.9
def slugify(value, allow_dots=False, allow_unicode=False): """ Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace. Modified to optionally allow dots. Adapted from Django 1.9 """ if al...
:example '3番'
def ban(self): """ :example '3番' """ return "%d番" % self.generator.random.randint(1, 27)
:example '101-1212'
def postcode(self): """ :example '101-1212' """ return "%03d-%04d" % (self.generator.random.randint(0, 999), self.generator.random.randint(0, 9999))
Replaces all question mark ('?') occurrences with a random letter from postal_code_formats then passes result to numerify to insert numbers
def postcode(self): """ Replaces all question mark ('?') occurrences with a random letter from postal_code_formats then passes result to numerify to insert numbers """ temp = re.sub(r'\?', lambda x: self.postal_code_letter(), se...
Calculates and returns a control digit for given list of digits basing on REGON standard.
def regon_checksum(digits): """ Calculates and returns a control digit for given list of digits basing on REGON standard. """ weights_for_check_digit = [8, 9, 2, 3, 4, 5, 6, 7] check_digit = 0 for i in range(0, 8): check_digit += weights_for_check_digit[i] * digits[i] check_digit %...
Calculates and returns a control digit for given list of digits basing on local REGON standard.
def local_regon_checksum(digits): """ Calculates and returns a control digit for given list of digits basing on local REGON standard. """ weights_for_check_digit = [2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8] check_digit = 0 for i in range(0, 13): check_digit += weights_for_check_digit[i] * ...
Calculates and returns a control digit for given list of digits basing on NIP standard.
def company_vat_checksum(digits): """ Calculates and returns a control digit for given list of digits basing on NIP standard. """ weights_for_check_digit = [6, 5, 7, 2, 3, 4, 5, 6, 7] check_digit = 0 for i in range(0, 9): check_digit += weights_for_check_digit[i] * digits[i] check_...
Returns 9 character Polish National Business Registry Number, Polish: Rejestr Gospodarki Narodowej - REGON. https://pl.wikipedia.org/wiki/REGON
def regon(self): """ Returns 9 character Polish National Business Registry Number, Polish: Rejestr Gospodarki Narodowej - REGON. https://pl.wikipedia.org/wiki/REGON """ voivodeship_number = self.random_int(0, 49) * 2 + 1 regon_digits = [int(voivodeship_number / 1...
Returns 14 character Polish National Business Registry Number, local entity number. https://pl.wikipedia.org/wiki/REGON
def local_regon(self): """ Returns 14 character Polish National Business Registry Number, local entity number. https://pl.wikipedia.org/wiki/REGON """ regon_digits = [int(digit) for digit in list(self.regon())] for _ in range(4): regon_digits.append(...