INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Format a dict to a list of tuples: param d: the dictionary: param as_list: return a list of lists rather than a list of tuples: return: formatted dictionary list
def dict_as_tuple_list(d, as_list=False): """ Format a dict to a list of tuples :param d: the dictionary :param as_list: return a list of lists rather than a list of tuples :return: formatted dictionary list """ dd = list() for k, v in d.items(): dd.append([k, v] if as_list else ...
Search tuple array by index and value: param t: tuple array: param i: index of the value in each tuple: param v: value: return: the first tuple in the array with the specific index/ value
def tuple_search(t, i, v): """ Search tuple array by index and value :param t: tuple array :param i: index of the value in each tuple :param v: value :return: the first tuple in the array with the specific index / value """ for e in t: if e[i] == v: return e retur...
Looks for base91 telemetry found in comment field Returns [ remaining_text telemetry ]
def parse_comment_telemetry(text): """ Looks for base91 telemetry found in comment field Returns [remaining_text, telemetry] """ parsed = {} match = re.findall(r"^(.*?)\|([!-{]{4,14})\|(.*)$", text) if match and len(match[0][1]) % 2 == 0: text, telemetry, post = match[0] tex...
Parses an APRS packet and returns a dict with decoded data
def parse(packet): """ Parses an APRS packet and returns a dict with decoded data - All attributes are in metric units """ if not isinstance(packet, string_type_parse): raise TypeError("Expected packet to be str/unicode/bytes, got %s", type(packet)) if len(packet) == 0: raise ...
Takes a base91 char string and returns decimal
def to_decimal(text): """ Takes a base91 char string and returns decimal """ if not isinstance(text, string_type): raise TypeError("expected str or unicode, %s given" % type(text)) if findall(r"[\x00-\x20\x7c-\xff]", text): raise ValueError("invalid character in sequence") tex...
Takes a decimal and returns base91 char string. With optional parameter for fix with output
def from_decimal(number, width=1): """ Takes a decimal and returns base91 char string. With optional parameter for fix with output """ text = [] if not isinstance(number, int_type): raise TypeError("Expected number to be int, got %s", type(number)) elif not isinstance(width, int_typ...
Takes a CALLSIGN and returns passcode
def passcode(callsign): """ Takes a CALLSIGN and returns passcode """ assert isinstance(callsign, str) callsign = callsign.split('-')[0].upper() code = 0x73e2 for i, char in enumerate(callsign): code ^= ord(char) << (8 if not i % 2 else 0) return code & 0x7fff
Parses the header part of packet Returns a dict
def parse_header(head): """ Parses the header part of packet Returns a dict """ try: (fromcall, path) = head.split('>', 1) except: raise ParseError("invalid packet header") if (not 1 <= len(fromcall) <= 9 or not re.findall(r"^[a-z0-9]{0,9}(\-[a-z0-9]{1,8})?$", fromcal...
Set a specified aprs - is filter for this connection
def set_filter(self, filter_text): """ Set a specified aprs-is filter for this connection """ self.filter = filter_text self.logger.info("Setting filter to: %s", self.filter) if self._connected: self._sendall("#filter %s\r\n" % self.filter)
Set callsign and password
def set_login(self, callsign, passwd="-1", skip_login=False): """ Set callsign and password """ self.__dict__.update(locals())
Initiate connection to APRS server and attempt to login
def connect(self, blocking=False, retry=30): """ Initiate connection to APRS server and attempt to login blocking = False - Should we block until connected and logged-in retry = 30 - Retry interval in seconds """ if self._connected: return ...
Closes the socket Called internally when Exceptions are raised
def close(self): """ Closes the socket Called internally when Exceptions are raised """ self._connected = False self.buf = b'' if self.sock is not None: self.sock.close()
Send a line or multiple lines sperapted by \\ r \\ n
def sendall(self, line): """ Send a line, or multiple lines sperapted by '\\r\\n' """ if isinstance(line, APRSPacket): line = str(line) elif not isinstance(line, string_type): raise TypeError("Expected line to be str or APRSPacket, got %s", type(line)) ...
When a position sentence is received it will be passed to the callback function
def consumer(self, callback, blocking=True, immortal=False, raw=False): """ When a position sentence is received, it will be passed to the callback function blocking: if true (default), runs forever, otherwise will return after one sentence You can still exit the loop, by rais...
Attemps connection to the server
def _connect(self): """ Attemps connection to the server """ self.logger.info("Attempting connection to %s:%s", self.server[0], self.server[1]) try: self._open_socket() peer = self.sock.getpeername() self.logger.info("Connected to %s", str(...
Sends login string to server
def _send_login(self): """ Sends login string to server """ login_str = "user {0} pass {1} vers aprslib {3}{2}\r\n" login_str = login_str.format( self.callsign, self.passwd, (" filter " + self.filter) if self.filter != "" else "", _...
Generator for complete lines received from the server
def _socket_readlines(self, blocking=False): """ Generator for complete lines, received from the server """ try: self.sock.setblocking(0) except socket.error as e: self.logger.error("socket error when setblocking(0): %s" % str(e)) raise Connect...
Convert UUID to binary blob
def db_value(self, value): """ Convert UUID to binary blob """ # ensure we have a valid UUID if not isinstance(value, UUID): value = UUID(value) # reconstruct for optimal indexing parts = str(value).split("-") reordered = ''.join([parts[2], p...
Convert binary blob to UUID instance
def python_value(self, value): """ Convert binary blob to UUID instance """ value = super(OrderedUUIDField, self).python_value(value) u = binascii.b2a_hex(value) value = u[8:16] + u[4:8] + u[0:4] + u[16:22] + u[22:32] return UUID(value.decode())
Convert the python value for storage in the database.
def db_value(self, value): """Convert the python value for storage in the database.""" value = self.transform_value(value) return self.hhash.encrypt(value, salt_size=self.salt_size, rounds=self.rounds)
Convert the database value to a pythonic value.
def python_value(self, value): """Convert the database value to a pythonic value.""" value = coerce_to_bytes(value) obj = HashValue(value) obj.field = self return obj
Register model ( s ) with app
def register(self, model_cls): """Register model(s) with app""" assert issubclass(model_cls, peewee.Model) assert not hasattr(model_cls._meta, 'database_manager') if model_cls in self: raise RuntimeError("Model already registered") self.append(model_cls) model...
Disconnect from all databases
def disconnect(self): """Disconnect from all databases""" for name, connection in self.items(): if not connection.is_closed(): connection.close()
Find matching database router
def get_database(self, model): """Find matching database router""" for router in self.routers: r = router.get_database(model) if r is not None: return r return self.get('default')
Returns dict of values to uniquely reference this item
def to_cursor_ref(self): """Returns dict of values to uniquely reference this item""" fields = self._meta.get_primary_keys() assert fields values = {field.name:self.__data__[field.name] for field in fields} return values
Apply pagination to query
def paginate_query(self, query, count, offset=None, sort=None): """ Apply pagination to query :attr query: Instance of `peewee.Query` :attr count: Max rows to return :attr offset: Pagination offset, str/int :attr sort: List of tuples, e.g. [('id', 'asc')] :retur...
Apply user specified filters to query
def apply_filters(self, query, filters): """ Apply user specified filters to query """ assert isinstance(query, peewee.Query) assert isinstance(filters, dict)
List items from query
def list(self, filters, cursor, count): """ List items from query """ assert isinstance(filters, dict), "expected filters type 'dict'" assert isinstance(cursor, dict), "expected cursor type 'dict'" # start with our base query query = self.get_query() asse...
Retrieve items from query
def retrieve(self, cursor): """ Retrieve items from query """ assert isinstance(cursor, dict), "expected cursor type 'dict'" # look for record in query query = self.get_query() assert isinstance(query, peewee.Query) query return query.get(**curso...
Regenerate the signing key for this instance. Store the new key in signing_key property.
def regenerate_signing_key(self, secret_key=None, region=None, service=None, date=None): """ Regenerate the signing key for this instance. Store the new key in signing_key property. Take scope elements of the new key from the equivalent properties ...
Try to pull a date from the request by looking first at the x - amz - date header and if that s not present then the Date header.
def get_request_date(cls, req): """ Try to pull a date from the request by looking first at the x-amz-date header, and if that's not present then the Date header. Return a datetime.date object, or None if neither date header is found or is in a recognisable format. req ...
Check if date_str is in a recognised format and return an ISO yyyy - mm - dd format version if so. Raise DateFormatError if not.
def parse_date(date_str): """ Check if date_str is in a recognised format and return an ISO yyyy-mm-dd format version if so. Raise DateFormatError if not. Recognised formats are: * RFC 7231 (e.g. Mon, 09 Sep 2011 23:36:00 GMT) * RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 G...
Handle a request whose date doesn t match the signing key scope date.
def handle_date_mismatch(self, req): """ Handle a request whose date doesn't match the signing key scope date. This AWS4Auth class implementation regenerates the signing key. See StrictAWS4Auth class if you would prefer an exception to be raised. req -- a requests prepared requ...
Encode body of request to bytes and update content - type if required.
def encode_body(req): """ Encode body of request to bytes and update content-type if required. If the body of req is Unicode then encode to the charset found in content-type header if present, otherwise UTF-8, or ASCII if content-type is application/x-www-form-urlencoded. If enc...
Create the AWS authentication Canonical Request string.
def get_canonical_request(self, req, cano_headers, signed_headers): """ Create the AWS authentication Canonical Request string. req -- Requests PreparedRequest object. Should already include an x-amz-content-sha256 header cano_headers -- Canonical ...
Generate the Canonical Headers section of the Canonical Request.
def get_canonical_headers(cls, req, include=None): """ Generate the Canonical Headers section of the Canonical Request. Return the Canonical Headers and the Signed Headers strs as a tuple (canonical_headers, signed_headers). req -- Requests PreparedRequest object in...
Generate the AWS4 auth string to sign for the request.
def get_sig_string(req, cano_req, scope): """ Generate the AWS4 auth string to sign for the request. req -- Requests PreparedRequest object. This should already include an x-amz-date header. cano_req -- The Canonical Request, as returned by g...
Generate the canonical path as per AWS4 auth requirements.
def amz_cano_path(self, path): """ Generate the canonical path as per AWS4 auth requirements. Not documented anywhere, determined from aws4_testsuite examples, problem reports and testing against the live services. path -- request path """ safe_chars = '/~' ...
Parse and format querystring as per AWS4 auth requirements.
def amz_cano_querystring(qs): """ Parse and format querystring as per AWS4 auth requirements. Perform percent quoting as needed. qs -- querystring """ safe_qs_amz_chars = '&=+' safe_qs_unresvd = '-_.~' # If Python 2, switch to working entirely in str ...
Generate the signing key string as bytes.
def generate_key(cls, secret_key, region, service, date, intermediates=False): """ Generate the signing key string as bytes. If intermediate is set to True, returns a 4-tuple containing the key and the intermediate keys: ( signing_key, date_key, region_key,...
Generate an SHA256 HMAC encoding msg to UTF - 8 if not already encoded.
def sign_sha256(key, msg): """ Generate an SHA256 HMAC, encoding msg to UTF-8 if not already encoded. key -- signing key. bytes. msg -- message to sign. unicode or bytes. """ if isinstance(msg, text_type): msg = msg.encode('utf-8') return hma...
Convert a datetime object into a valid STIX timestamp string.
def _format_datetime(dttm): """Convert a datetime object into a valid STIX timestamp string. 1. Convert to timezone-aware 2. Convert to UTC 3. Format in ISO format 4. Ensure correct precision a. Add subsecond value if non-zero and precision not defined 5. Add "Z" """ if dttm.tz...
If maybe_dttm is a datetime instance convert to a STIX - compliant string representation. Otherwise return the value unchanged.
def _ensure_datetime_to_string(maybe_dttm): """If maybe_dttm is a datetime instance, convert to a STIX-compliant string representation. Otherwise return the value unchanged.""" if isinstance(maybe_dttm, datetime.datetime): maybe_dttm = _format_datetime(maybe_dttm) return maybe_dttm
Convert API keyword args to a mapping of URL query parameters. Except for added_after all keywords are mapped to match filters i. e. to a query parameter of the form match [ <kwarg > ]. added_after is left alone since it s a special filter as defined in the spec.
def _filter_kwargs_to_query_params(filter_kwargs): """ Convert API keyword args to a mapping of URL query parameters. Except for "added_after", all keywords are mapped to match filters, i.e. to a query parameter of the form "match[<kwarg>]". "added_after" is left alone, since it's a special filter...
Factors out some JSON parse code with error handling to hopefully improve error messages.
def _to_json(resp): """ Factors out some JSON parse code with error handling, to hopefully improve error messages. :param resp: A "requests" library response :return: Parsed JSON. :raises: InvalidJSONError If JSON parsing failed. """ try: return resp.json() except ValueError...
Updates Status information
def refresh(self, accept=MEDIA_TYPE_TAXII_V20): """Updates Status information""" response = self.__raw = self._conn.get(self.url, headers={"Accept": accept}) self._populate_fields(**response)
It will poll the URL to grab the latest status resource in a given timeout and time interval.
def wait_until_final(self, poll_interval=1, timeout=60): """It will poll the URL to grab the latest status resource in a given timeout and time interval. Args: poll_interval (int): how often to poll the status service. timeout (int): how long to poll the URL until giving...
Validates Status information. Raises errors for required properties.
def _validate_status(self): """Validates Status information. Raises errors for required properties.""" if not self.id: msg = "No 'id' in Status for request '{}'" raise ValidationError(msg.format(self.url)) if not self.status: msg = "No 'status' in Sta...
Validates Collection information. Raises errors for required properties.
def _validate_collection(self): """Validates Collection information. Raises errors for required properties.""" if not self._id: msg = "No 'id' in Collection for request '{}'" raise ValidationError(msg.format(self.url)) if not self._title: msg = "No 't...
Implement the Get Objects endpoint ( section 5. 3 )
def get_objects(self, accept=MEDIA_TYPE_STIX_V20, **filter_kwargs): """Implement the ``Get Objects`` endpoint (section 5.3)""" self._verify_can_read() query_params = _filter_kwargs_to_query_params(filter_kwargs) return self._conn.get(self.objects_url, headers={"Accept": accept}, ...
Implement the Get an Object endpoint ( section 5. 5 )
def get_object(self, obj_id, version=None, accept=MEDIA_TYPE_STIX_V20): """Implement the ``Get an Object`` endpoint (section 5.5)""" self._verify_can_read() url = self.objects_url + str(obj_id) + "/" query_params = None if version: query_params = _filter_kwargs_to_que...
Implement the Add Objects endpoint ( section 5. 4 )
def add_objects(self, bundle, wait_for_completion=True, poll_interval=1, timeout=60, accept=MEDIA_TYPE_TAXII_V20, content_type=MEDIA_TYPE_STIX_V20): """Implement the ``Add Objects`` endpoint (section 5.4) Add objects to the collection. This may be performed eith...
Implement the Get Object Manifests endpoint ( section 5. 6 ).
def get_manifest(self, accept=MEDIA_TYPE_TAXII_V20, **filter_kwargs): """Implement the ``Get Object Manifests`` endpoint (section 5.6).""" self._verify_can_read() query_params = _filter_kwargs_to_query_params(filter_kwargs) return self._conn.get(self.url + "manifest/", ...
Validates API Root information. Raises errors for required properties.
def _validate_api_root(self): """Validates API Root information. Raises errors for required properties.""" if not self._title: msg = "No 'title' in API Root for request '{}'" raise ValidationError(msg.format(self.url)) if not self._versions: msg = "No...
Update the API Root s information and list of Collections
def refresh(self, accept=MEDIA_TYPE_TAXII_V20): """Update the API Root's information and list of Collections""" self.refresh_information(accept) self.refresh_collections(accept)
Update the properties of this API Root.
def refresh_information(self, accept=MEDIA_TYPE_TAXII_V20): """Update the properties of this API Root. This invokes the ``Get API Root Information`` endpoint. """ response = self.__raw = self._conn.get(self.url, headers={"Accept": accept}) ...
Update the list of Collections contained by this API Root.
def refresh_collections(self, accept=MEDIA_TYPE_TAXII_V20): """Update the list of Collections contained by this API Root. This invokes the ``Get Collections`` endpoint. """ url = self.url + "collections/" response = self._conn.get(url, headers={"Accept": accept}) self._...
Validates server information. Raises errors for required properties.
def _validate_server(self): """Validates server information. Raises errors for required properties. """ if not self._title: msg = "No 'title' in Server Discovery for request '{}'" raise ValidationError(msg.format(self.url))
Update the Server information and list of API Roots
def refresh(self): """Update the Server information and list of API Roots""" response = self.__raw = self._conn.get(self.url) self._populate_fields(**response) self._loaded = True
Check that the server is returning a valid Content - Type
def valid_content_type(self, content_type, accept): """Check that the server is returning a valid Content-Type Args: content_type (str): ``Content-Type:`` header value accept (str): media type to include in the ``Accept:`` header. """ accept_tokens = accept.repl...
Perform an HTTP GET using the saved requests. Session and auth info. If Accept isn t one of the given headers a default TAXII mime type is used. Regardless the response type is checked against the accept header value and an exception is raised if they don t match.
def get(self, url, headers=None, params=None): """Perform an HTTP GET, using the saved requests.Session and auth info. If "Accept" isn't one of the given headers, a default TAXII mime type is used. Regardless, the response type is checked against the accept header value, and an exceptio...
Send a JSON POST request with the given request headers additional URL query parameters and the given JSON in the request body. The extra query parameters are merged with any which already exist in the URL. The json and data parameters may not both be given.
def post(self, url, headers=None, params=None, **kwargs): """Send a JSON POST request with the given request headers, additional URL query parameters, and the given JSON in the request body. The extra query parameters are merged with any which already exist in the URL. The 'json' and '...
Merge headers from different sources together. Headers passed to the post/ get methods have highest priority then headers associated with the connection object itself have next priority.
def _merge_headers(self, call_specific_headers): """ Merge headers from different sources together. Headers passed to the post/get methods have highest priority, then headers associated with the connection object itself have next priority. :param call_specific_headers: A header...
Returns the the amount of memory available for use.
def total_memory(): """ Returns the the amount of memory available for use. The memory is obtained from MemTotal entry in /proc/meminfo. Notes ===== This function is not very useful and not very portable. """ with file('/proc/meminfo', 'r') as f: for line ...
Returns the default number of slave processes to be spawned.
def cpu_count(): """ Returns the default number of slave processes to be spawned. The default value is the number of physical cpu cores seen by python. :code:`OMP_NUM_THREADS` environment variable overrides it. On PBS/torque systems if OMP_NUM_THREADS is empty, we try to use the va...
Create a shared memory array from the shape of array.
def empty_like(array, dtype=None): """ Create a shared memory array from the shape of array. """ array = numpy.asarray(array) if dtype is None: dtype = array.dtype return anonymousmemmap(array.shape, dtype)
Create a shared memory array with the same shape and type as a given array filled with value.
def full_like(array, value, dtype=None): """ Create a shared memory array with the same shape and type as a given array, filled with `value`. """ shared = empty_like(array, dtype) shared[:] = value return shared
Create a shared memory array of given shape and type filled with value.
def full(shape, value, dtype='f8'): """ Create a shared memory array of given shape and type, filled with `value`. """ shared = empty(shape, dtype) shared[:] = value return shared
Copy an array to the shared memory.
def copy(a): """ Copy an array to the shared memory. Notes ----- copy is not always necessary because the private memory is always copy-on-write. Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory """ shared = anonymousmemmap(a.shape, dtype=a....
Protected get. Get an item from Q. Will block. but if the process group has errors raise an StopProcessGroup exception.
def get(self, Q): """ Protected get. Get an item from Q. Will block. but if the process group has errors, raise an StopProcessGroup exception. A slave process will terminate upon StopProcessGroup. The master process shall read the error from the process group. ...
Wait and join the child process. The return value of the function call is returned. If any exception occurred it is wrapped and raised.
def wait(self): """ Wait and join the child process. The return value of the function call is returned. If any exception occurred it is wrapped and raised. """ e, r = self.result.get() self.slave.join() self.slave = None self.result = None ...
Map - reduce with multile processes.
def map(self, func, sequence, reduce=None, star=False, minlength=0): """ Map-reduce with multile processes. Apply func to each item on the sequence, in parallel. As the results are collected, reduce is called on the result. The reduced result is returned as a list. ...
format of table header:
def savetxt2(fname, X, delimiter=' ', newline='\n', comment_character='#', header='', save_dtype=False, fmt={}): """ format of table header: # ID [type]:name(index) .... * number of items user's header is not prefixed by comment_character name of nested dtype elements are split b...
Known issues delimiter and newline is not respected. string quotation with space is broken.
def loadtxt2(fname, dtype=None, delimiter=' ', newline='\n', comment_character='#', skiplines=0): """ Known issues delimiter and newline is not respected. string quotation with space is broken. """ dtypert = [None, None, None] def preparedtype(dtype): dtypert[0] = dtype ...
Unpack a structured data - type.
def flatten_dtype(dtype, _next=None): """ Unpack a structured data-type. """ types = [] if _next is None: _next = [0, ''] primary = True else: primary = False prefix = _next[1] if dtype.names is None: for i in numpy.ndindex(dtype.shape): if dtype.b...
meta class for Ordered construct.
def MetaOrdered(parallel, done, turnstile): """meta class for Ordered construct.""" class Ordered: def __init__(self, iterref): if parallel.master: done[...] = 0 self.iterref = iterref parallel.barrier() @classmethod def abort(self): ...
kill all slaves and reap the monitor
def kill_all(self): """kill all slaves and reap the monitor """ for pid in self.children: try: os.kill(pid, signal.SIGTRAP) except OSError: continue self.join()
master only
def join(self): """ master only """ try: self.pipe.put('Q') self.thread.join() except: pass finally: self.thread = None
slave only
def slaveraise(self, type, error, traceback): """ slave only """ message = 'E' * 1 + pickle.dumps((type, ''.join(tb.format_exception(type, error, traceback)))) if self.pipe is not None: self.pipe.put(message)
schedule can be ( sch chunk ) or sch ; sch is static dynamic or guided.
def forloop(self, range, ordered=False, schedule=('static', 1)): """ schedule can be (sch, chunk) or sch; sch is 'static', 'dynamic' or 'guided'. chunk defaults to 1 if ordered, create an ordred """ if isinstance(schedule, tuple): sc...
ensure the master exit from Barrier
def abort(self): """ ensure the master exit from Barrier """ self.mutex.release() self.turnstile.release() self.mutex.release() self.turnstile2.release()
return at most n array items move the cursor.
def read(self, n): """ return at most n array items, move the cursor. """ while len(self.pool) < n: self.cur = self.files.next() self.pool = numpy.append(self.pool, self.fetch(self.cur), axis=0) rt = self.pool[:n] if n == len(self.poo...
axis is the axis to chop it off. if self. altreduce is set the results will be reduced with altreduce and returned otherwise will be saved to out then return out.
def call(self, args, axis=0, out=None, chunksize=1024 * 1024, **kwargs): """ axis is the axis to chop it off. if self.altreduce is set, the results will be reduced with altreduce and returned otherwise will be saved to out, then return out. """ if self.altredu...
adapt source to a packarray according to the layout of template
def adapt(cls, source, template): """ adapt source to a packarray according to the layout of template """ if not isinstance(template, packarray): raise TypeError('template must be a packarray') return cls(source, template.start, template.end)
parallel argsort like numpy. argsort
def argsort(data, out=None, chunksize=None, baseargsort=None, argmerge=None, np=None): """ parallel argsort, like numpy.argsort use sizeof(intp) * len(data) as scratch space use baseargsort for serial sort ind = baseargsort(data) use argmerge to merge def ...
Return a random ( abbreviated if abbr ) day of week name.
def day_of_week(abbr=False): """Return a random (abbreviated if `abbr`) day of week name.""" if abbr: return random.choice(DAYS_ABBR) else: return random.choice(DAYS)
Return a random ( abbreviated if abbr ) month name or month number if numerical.
def month(abbr=False, numerical=False): """Return a random (abbreviated if `abbr`) month name or month number if `numerical`. """ if numerical: return random.randint(1, 12) else: if abbr: return random.choice(MONTHS_ABBR) else: return random.choice(MON...
Return a random year.
def year(past=False, min_delta=0, max_delta=20): """Return a random year.""" return dt.date.today().year + _delta(past, min_delta, max_delta)
Return a random dt. date object. Delta args are days.
def date(past=False, min_delta=0, max_delta=20): """Return a random `dt.date` object. Delta args are days.""" timedelta = dt.timedelta(days=_delta(past, min_delta, max_delta)) return dt.date.today() + timedelta
Load a dictionary file dict_name ( if it s not cached ) and return its contents as an array of strings.
def get_dictionary(dict_name): """ Load a dictionary file ``dict_name`` (if it's not cached) and return its contents as an array of strings. """ global dictionaries_cache if dict_name not in dictionaries_cache: try: dictionary_file = codecs.open( join(DICTION...
Return a check digit of the given credit card number.
def check_digit(num): """Return a check digit of the given credit card number. Check digit calculated using Luhn algorithm ("modulus 10") See: http://www.darkcoding.net/credit-card/luhn-formula/ """ sum = 0 # drop last digit, then reverse the number digits = str(num)[:-1][::-1] for i,...
Return a random credit card number.
def number(type=None, length=None, prefixes=None): """ Return a random credit card number. :param type: credit card type. Defaults to a random selection. :param length: length of the credit card number. Defaults to the length for the selected card type. :param prefixes: allowed p...
Return a random street number.
def street_number(): """Return a random street number.""" length = int(random.choice(string.digits[1:6])) return ''.join(random.sample(string.digits, length))
Return a random ZIP code either in ##### or ##### - #### format.
def zip_code(): """Return a random ZIP code, either in `#####` or `#####-####` format.""" format = '#####' if random.random() >= 0.5: format = '#####-####' result = '' for item in format: if item == '#': result += str(random.randint(0, 9)) else: resul...
Return a random phone number in # - ( ### ) ### - #### format.
def phone(): """Return a random phone number in `#-(###)###-####` format.""" format = '#-(###)###-####' result = '' for item in format: if item == '#': result += str(random.randint(0, 9)) else: result += item return result
Return a random job title.
def job_title(): """Return a random job title.""" result = random.choice(get_dictionary('job_titles')).strip() result = result.replace('#{N}', job_title_suffix()) return result
Return a random email text.
def body(quantity=2, separator='\n\n', wrap_start='', wrap_end='', html=False, sentences_quantity=3, as_list=False): """Return a random email text.""" return lorem_ipsum.paragraphs(quantity=quantity, separator=separator, wrap_start=wrap_start, wrap_end=wrap_end, ...
Return a str of decimal with two digits after a decimal mark.
def money(min=0, max=10): """Return a str of decimal with two digits after a decimal mark.""" value = random.choice(range(min * 100, max * 100)) return "%1.2f" % (float(value) / 100)
Return random words.
def words(quantity=10, as_list=False): """Return random words.""" global _words if not _words: _words = ' '.join(get_dictionary('lorem_ipsum')).lower().\ replace('\n', '') _words = re.sub(r'\.|,|;/', '', _words) _words = _words.split(' ') result = random.sample(_wor...
Return a random sentence to be used as e. g. an e - mail subject.
def title(words_quantity=4): """Return a random sentence to be used as e.g. an e-mail subject.""" result = words(quantity=words_quantity) result += random.choice('?.!') return result.capitalize()