INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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 | 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. | 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 | 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. | 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. | 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] = {}
... |
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... |
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... |
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. | 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 | 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 | 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 | 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 | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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::
... |
Revoke a grant from a key. | def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None,
profile=None):
'''
Revoke a grant from a key.
CLI example::
salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j...
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... |
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 | 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. | 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. | 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. | 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. | 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. | 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 number of digits for the seq... | 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 ). | 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 ] | 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. | 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. ] | 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. | 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. | 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. | 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. | 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. | 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. | 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(... |
Returns 10 character tax identification number Polish: Numer identyfikacji podatkowej. | def company_vat(self):
"""
Returns 10 character tax identification number,
Polish: Numer identyfikacji podatkowej.
https://pl.wikipedia.org/wiki/NIP
"""
vat_digits = []
for _ in range(3):
vat_digits.append(self.random_digit_not_null())
for _... |
Returns the checksum of CPF digits. References to the algorithm: https:// pt. wikipedia. org/ wiki/ Cadastro_de_pessoas_f%C3%ADsicas#Algoritmo https:// metacpan. org/ source/ MAMAWE/ Algorithm - CheckDigits - v1. 3. 0/ lib/ Algorithm/ CheckDigits/ M11_004. pm | def checksum(digits):
"""
Returns the checksum of CPF digits.
References to the algorithm:
https://pt.wikipedia.org/wiki/Cadastro_de_pessoas_f%C3%ADsicas#Algoritmo
https://metacpan.org/source/MAMAWE/Algorithm-CheckDigits-v1.3.0/lib/Algorithm/CheckDigits/M11_004.pm
"""
s = 0
p = len(digit... |
Brazilian RG return plain numbers. Check: https:// www. ngmatematica. com/ 2014/ 02/ como - determinar - o - digito - verificador - do. html | def rg(self):
"""
Brazilian RG, return plain numbers.
Check: https://www.ngmatematica.com/2014/02/como-determinar-o-digito-verificador-do.html
"""
digits = self.generator.random.sample(range(0, 9), 8)
checksum = sum(i * digits[i - 2] for i in range(2, 10))
last_... |
Generate the information required to create an ISBN - 10 or ISBN - 13. | def _body(self):
""" Generate the information required to create an ISBN-10 or
ISBN-13.
"""
ean = self.random_element(RULES.keys())
reg_group = self.random_element(RULES[ean].keys())
# Given the chosen ean/group, decide how long the
# registrant/publication str... |
Separate the registration from the publication in a given string.: param reg_pub: A string of digits representing a registration and publication.: param rules: A list of RegistrantRules which designate where to separate the values in the string.: returns: A ( registrant publication ) tuple of strings. | def _registrant_publication(reg_pub, rules):
""" Separate the registration from the publication in a given
string.
:param reg_pub: A string of digits representing a registration
and publication.
:param rules: A list of RegistrantRules which designate where
to sepa... |
Ukrainian Реєстраційний номер облікової картки платника податків also known as Ідентифікаційний номер фізичної особи. | def ssn(self):
"""
Ukrainian "Реєстраційний номер облікової картки платника податків"
also known as "Ідентифікаційний номер фізичної особи".
"""
digits = []
# Number of days between 1899-12-31 and a birth date
for digit in str((self.generator.date_object() -
... |
: returns: A random state or territory abbreviation. | def state_abbr(self, include_territories=True):
"""
:returns: A random state or territory abbreviation.
:param include_territories: If True, territories will be included.
If False, only states will be returned.
"""
if include_territories:
self.random_elem... |
Generates a random string of upper and lowercase letters.: type min_chars: int: type max_chars: int: return: String. Random of random length between min and max characters. | def pystr(self, min_chars=None, max_chars=20):
"""
Generates a random string of upper and lowercase letters.
:type min_chars: int
:type max_chars: int
:return: String. Random of random length between min and max characters.
"""
if min_chars is None:
re... |
Returns a dictionary. | def pydict(self, nb_elements=10, variable_nb_elements=True, *value_types):
"""
Returns a dictionary.
:nb_elements: number of elements for dictionary
:variable_nb_elements: is use variable number of elements for dictionary
:value_types: type of dictionary values
"""
... |
See http:// web. archive. org/ web/ 20090930140939/ http:// www. govtalk. gov. uk/ gdsc/ html/ noframes/ PostCode - 2 - 1 - Release. htm | def postcode(self):
"""
See
http://web.archive.org/web/20090930140939/http://www.govtalk.gov.uk/gdsc/html/noframes/PostCode-2-1-Release.htm
"""
postcode = ''
pattern = self.random_element(self.postcode_formats)
for placeholder in pattern:
postcode += s... |
Generates Hungarian SSN equivalent ( személyazonosító szám or colloquially személyi szám ) | def ssn(self, dob=None, gender=None):
"""
Generates Hungarian SSN equivalent (személyazonosító szám or, colloquially, személyi szám)
:param dob: date of birth as a "YYMMDD" string - this determines the checksum regime and is also encoded
in the személyazonosító szám.
:type d... |
: example 4703 | def postcode_in_state(self, state_abbr=None):
"""
:example '4703'
"""
if state_abbr is None:
state_abbr = self.random_element(self.states_abbr)
if state_abbr in self.states_abbr:
postcode = "%d" % (self.generator.random.randint(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.