code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def thread_work(targets, function, params = {}, num_threads = 0):
q = Queue(maxsize=0)
if not num_threads:
num_threads = len(targets)
for i in range(num_threads):
worker = Thread(target=function, args=(q, params))
worker.setDaemon(True)
worker.start()
for target in t... | Generic multithreading helper
:param targets:
:param function:
:param params:
:param num_threads:
:return: |
def threaded_per_region(q, params):
while True:
try:
params['region'] = q.get()
method = params['method']
method(params)
except Exception as e:
printException(e)
finally:
q.task_done() | Helper for multithreading on a per-region basis
:param q:
:param params:
:return: |
def location(self, x=None, y=None):
''' Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!')
'''
stream = self._stream
stream.write(self.save_p... | Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!') |
def fullscreen(self):
''' Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!')
'''
stream = self._stream
stream.write(self.alt_screen_enable)
... | Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!') |
def hidden_cursor(self):
''' Context Manager that hides the cursor and restores it on exit.
::
with screen.hidden_cursor():
print('Clandestine activity…')
'''
stream = self._stream
stream.write(self.hide_cursor)
stream.flush()
... | Context Manager that hides the cursor and restores it on exit.
::
with screen.hidden_cursor():
print('Clandestine activity…') |
def undecorated(o):
# class decorator
if type(o) is type:
return o
try:
# python2
closure = o.func_closure
except AttributeError:
pass
try:
# python3
closure = o.__closure__
except AttributeError:
return
if closure:
for ... | Remove all decorators from a function, method or class |
def assume_role(role_name, credentials, role_arn, role_session_name, silent = False):
external_id = credentials.pop('ExternalId') if 'ExternalId' in credentials else None
# Connect to STS
sts_client = connect_service('sts', credentials, silent = silent)
# Set required arguments for assume role call... | Assume role and save credentials
:param role_name:
:param credentials:
:param role_arn:
:param role_session_name:
:param silent:
:return: |
def get_cached_credentials_filename(role_name, role_arn):
filename_p1 = role_name.replace('/','-')
filename_p2 = role_arn.replace('/', '-').replace(':', '_')
return os.path.join(os.path.join(os.path.expanduser('~'), '.aws'), 'cli/cache/%s--%s.json' %
(filename_p1, filename_p2)) | Construct filepath for cached credentials (AWS CLI scheme)
:param role_name:
:param role_arn:
:return: |
def generate_password(length=16):
chars = string.ascii_letters + string.digits + '!@#$%^&*()_+-=[]{};:,<.>?|'
modulus = len(chars)
pchars = os.urandom(16)
if type(pchars) == str:
return ''.join(chars[i % modulus] for i in map(ord, pchars))
else:
return ''.join(chars[i % modulus]... | Generate a password using random characters from uppercase, lowercase, digits, and symbols
:param length: Length of the password to be generated
:return: The random password |
def init_sts_session(profile_name, credentials, duration = 28800, session_name = None, save_creds = True):
# Set STS arguments
sts_args = {
'DurationSeconds': duration
}
# Prompt for MFA code if MFA serial present
if 'SerialNumber' in credentials and credentials['SerialNumber']:
... | Fetch STS credentials
:param profile_name:
:param credentials:
:param duration:
:param session_name:
:param save_creds:
:return: |
def read_creds_from_aws_credentials_file(profile_name, credentials_file = aws_credentials_file):
credentials = init_creds()
profile_found = False
try:
# Make sure the ~.aws folder exists
if not os.path.exists(aws_config_dir):
os.makedirs(aws_config_dir)
with open(cre... | Read credentials from AWS config file
:param profile_name:
:param credentials_file:
:return: |
def read_creds_from_csv(filename):
key_id = None
secret = None
mfa_serial = None
secret_next = False
with open(filename, 'rt') as csvfile:
for i, line in enumerate(csvfile):
values = line.split(',')
for v in values:
if v.startswith('AKIA'):
... | Read credentials from a CSV file
:param filename:
:return: |
def read_creds_from_ec2_instance_metadata():
creds = init_creds()
try:
has_role = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials', timeout = 1)
if has_role.status_code == 200:
iam_role = has_role.text
credentials = requests.get('http:/... | Read credentials from EC2 instance metadata (IAM role)
:return: |
def read_creds_from_ecs_container_metadata():
creds = init_creds()
try:
ecs_metadata_relative_uri = os.environ['AWS_CONTAINER_CREDENTIALS_RELATIVE_URI']
credentials = requests.get('http://169.254.170.2' + ecs_metadata_relative_uri, timeout = 1).json()
for c in ['AccessKeyId', 'Secre... | Read credentials from ECS instance metadata (IAM role)
:return: |
def read_creds_from_environment_variables():
creds = init_creds()
# Check environment variables
if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ:
creds['AccessKeyId'] = os.environ['AWS_ACCESS_KEY_ID']
creds['SecretAccessKey'] = os.environ['AWS_SECRET_ACCESS... | Read credentials from environment variables
:return: |
def read_profile_from_environment_variables():
role_arn = os.environ.get('AWS_ROLE_ARN', None)
external_id = os.environ.get('AWS_EXTERNAL_ID', None)
return role_arn, external_id | Read profiles from env
:return: |
def read_profile_from_aws_config_file(profile_name, config_file = aws_config_file):
role_arn = None
source_profile = 'default'
mfa_serial = None
profile_found = False
external_id = None
try:
with open(config_file, 'rt') as config:
for line in config:
prof... | Read profiles from AWS config file
:param profile_name:
:param config_file:
:return: |
def show_profiles_from_aws_credentials_file(credentials_files = [aws_credentials_file, aws_config_file]):
profiles = get_profiles_from_aws_credentials_file(credentials_files)
for profile in set(profiles):
printInfo(' * %s' % profile) | Show profile names from ~/.aws/credentials
:param credentials_files:
:return: |
def complete_profile(f, credentials, session_token_written, mfa_serial_written):
session_token = credentials['SessionToken'] if 'SessionToken' in credentials else None
mfa_serial = credentials['SerialNumber'] if 'SerialNumber' in credentials else None
if session_token and not session_token_written:
... | Append session token and mfa serial if needed
:param f:
:param credentials:
:param session_token_written:
:param mfa_serial_written:
:return: |
def get_stackset_ready_accounts(credentials, account_ids, quiet=True):
api_client = connect_service('sts', credentials, silent=True)
configured_account_ids = []
for account_id in account_ids:
try:
role_arn = 'arn:aws:iam::%s:role/AWSCloudFormationStackSetExecutionRole' % account_id
... | Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_account_ids: List of AWS accounts to check for Stackset configuration
... |
def fetch(self, url):
try:
r = requests.get(url, timeout=self.timeout)
except requests.exceptions.Timeout:
if not self.safe:
raise
else:
return None
# Raise 404/500 error if any
if r and not self.safe:
... | Get the feed content using 'requests' |
def parse(self, content):
if content is None:
return None
feed = feedparser.parse(content)
# When feed is malformed
if feed['bozo']:
# keep track of the parsing error exception but as string
# infos, not an exception object
... | Parse the fetched feed content
Feedparser returned dict contain a 'bozo' key which can be '1' if the feed
is malformed.
Return None if the feed is malformed and 'bozo_accept'
is 'False', else return the feed content dict.
If the feed is malformed but ... |
def _hash_url(self, url):
if isinstance(url, six.text_type):
url = url.encode('utf-8')
return hashlib.md5(url).hexdigest() | Hash the URL to an md5sum. |
def get(self, url, expiration):
# Hash url to have a shorter key and add it expiration time to avoid clash for
# other url usage with different expiration
cache_key = self.cache_key.format(**{
'id': self._hash_url(url),
'expire': str(expiration)
})
... | Fetch the feed if no cache exist or if cache is stale |
def get_context(self, url, expiration):
self._feed = self.get(url, expiration)
return {
self.feed_context_name: self.format_feed_content(self._feed),
} | Build template context with formatted feed content |
def render(self, url, template=None, expiration=0):
template = template or self.default_template
return render_to_string(template, self.get_context(url, expiration)) | Render feed template |
def is_ansi_capable():
''' Check to see whether this version of Windows is recent enough to
support "ANSI VT"" processing.
'''
BUILD_ANSI_AVAIL = 10586 # Win10 TH2
CURRENT_VERS = sys.getwindowsversion()[:3]
if CURRENT_VERS[2] > BUILD_ANSI_AVAIL:
result = True
else:
resu... | Check to see whether this version of Windows is recent enough to
support "ANSI VT"" processing. |
def get_position(stream=STD_OUTPUT_HANDLE):
''' Returns current position of cursor, starts at 1. '''
stream = kernel32.GetStdHandle(stream)
csbi = CONSOLE_SCREEN_BUFFER_INFO()
kernel32.GetConsoleScreenBufferInfo(stream, byref(csbi))
pos = csbi.dwCursorPosition
# zero based, add ones for compati... | Returns current position of cursor, starts at 1. |
def set_position(x, y, stream=STD_OUTPUT_HANDLE):
''' Sets current position of the cursor. '''
stream = kernel32.GetStdHandle(stream)
value = x + (y << 16)
kernel32.SetConsoleCursorPosition(stream, c_long(value)f set_position(x, y, stream=STD_OUTPUT_HANDLE):
''' Sets current position of the cursor. ... | Sets current position of the cursor. |
def get_title():
''' Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle
'''
MAX_LEN = 256
buffer_ = create_unicode_buffer(MAX_LEN)
kernel32.GetConsoleTitleW(buffer_, MAX_LEN)
log.debug('%s', buffer_.value)
return buffer_.valuf get_title():... | Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle |
def read_header(self):
def read_mpq_header(offset=None):
if offset:
self.file.seek(offset)
data = self.file.read(32)
header = MPQFileHeader._make(
struct.unpack(MPQFileHeader.struct_format, data))
header = header._asdict()... | Read the header of a MPQ archive. |
def read_table(self, table_type):
if table_type == 'hash':
entry_class = MPQHashTableEntry
elif table_type == 'block':
entry_class = MPQBlockTableEntry
else:
raise ValueError("Invalid table type.")
table_offset = self.header['%s_table_offset... | Read either the hash or block table of a MPQ archive. |
def get_hash_table_entry(self, filename):
hash_a = self._hash(filename, 'HASH_A')
hash_b = self._hash(filename, 'HASH_B')
for entry in self.hash_table:
if (entry.hash_a == hash_a and entry.hash_b == hash_b):
return entry | Get the hash table entry corresponding to a given filename. |
def extract(self):
if self.files:
return dict((f, self.read_file(f)) for f in self.files)
else:
raise RuntimeError("Can't extract whole archive without listfile.") | Extract all the files inside the MPQ archive in memory. |
def extract_to_disk(self):
archive_name, extension = os.path.splitext(os.path.basename(self.file.name))
if not os.path.isdir(os.path.join(os.getcwd(), archive_name)):
os.mkdir(archive_name)
os.chdir(archive_name)
for filename, data in self.extract().items():
... | Extract all files and write them to disk. |
def extract_files(self, *filenames):
for filename in filenames:
data = self.read_file(filename)
f = open(filename, 'wb')
f.write(data or b'')
f.close() | Extract given files from the archive to disk. |
def _hash(self, string, hash_type):
hash_types = {
'TABLE_OFFSET': 0,
'HASH_A': 1,
'HASH_B': 2,
'TABLE': 3
}
seed1 = 0x7FED7FED
seed2 = 0xEEEEEEEE
for ch in string.upper():
if not isinstance(ch, int): ch = ord(... | Hash a string using MPQ's hash function. |
def _decrypt(self, data, key):
seed1 = key
seed2 = 0xEEEEEEEE
result = BytesIO()
for i in range(len(data) // 4):
seed2 += self.encryption_table[0x400 + (seed1 & 0xFF)]
seed2 &= 0xFFFFFFFF
value = struct.unpack("<I", data[i*4:i*4+4])[0]
... | Decrypt hash or block table or a sector. |
def _prepare_encryption_table():
seed = 0x00100001
crypt_table = {}
for i in range(256):
index = i
for j in range(5):
seed = (seed * 125 + 3) % 0x2AAAAB
temp1 = (seed & 0xFFFF) << 0x10
seed = (seed * 125 + 3) % 0x... | Prepare encryption table for MPQ hash function. |
def key_for_request(self, method, url, **kwargs):
if method != 'get':
return None
return requests.Request(url=url, params=kwargs.get('params', {})).prepare().url | Return a cache key from a given set of request parameters.
Default behavior is to return a complete URL for all GET
requests, and None otherwise.
Can be overriden if caching of non-get requests is desired. |
def request(self, method, url, **kwargs):
# short circuit if cache isn't configured
if not self.cache_storage:
resp = super(CachingSession, self).request(method, url, **kwargs)
resp.fromcache = False
return resp
resp = None
method = method.lo... | Override, wraps Session.request in caching.
Cache is only used if key_for_request returns a valid key
and should_cache_response was true as well. |
def get(self, orig_key):
resp = requests.Response()
key = self._clean_key(orig_key)
path = os.path.join(self.cache_dir, key)
try:
with open(path, 'rb') as f:
# read lines one at a time
while True:
line = f.readlin... | Get cache entry for key, or return None. |
def set(self, key, response):
key = self._clean_key(key)
path = os.path.join(self.cache_dir, key)
with open(path, 'wb') as f:
status_str = 'status: {0}\n'.format(response.status_code)
f.write(status_str.encode('utf8'))
encoding_str = 'encoding: {0}\n... | Set cache entry for key with contents of response. |
def set(self, key, response):
mod = response.headers.pop('last-modified', None)
status = int(response.status_code)
rec = (key, status, mod, response.encoding, response.content,
json.dumps(dict(response.headers)))
with self._conn:
self._conn.execute("DE... | Set cache entry for key with contents of response. |
def get(self, key):
query = self._conn.execute("SELECT * FROM cache WHERE key=?", (key,))
rec = query.fetchone()
if rec is None:
return None
rec = dict(zip(self._columns, rec))
if self.check_last_modified:
if rec['modified'] is None:
... | Get cache entry for key, or return None. |
def _make_destination_callable(dest):
if callable(dest):
return dest
elif hasattr(dest, 'write') or isinstance(dest, string_types):
return _use_filehandle_to_save(dest)
else:
raise TypeError("Destination must be a string, writable or callable object.") | Creates a callable out of the destination. If it's already callable,
the destination is returned. Instead, if the object is a string or a
writable object, it's wrapped in a closure to be used later. |
def _validate(self, filehandle, metadata, catch_all_errors=False):
errors = []
DEFAULT_ERROR_MSG = '{0!r}({1!r}, {2!r}) returned False'
for validator in self._validators:
try:
if not validator(filehandle, metadata):
msg = DEFAULT_ERROR_MS... | Runs all attached validators on the provided filehandle.
In the base implmentation of Transfer, the result of `_validate` isn't
checked. Rather validators are expected to raise UploadError to report
failure.
`_validate` can optionally catch all UploadErrors that occur or bail out
... |
def _preprocess(self, filehandle, metadata):
"Runs all attached preprocessors on the provided filehandle."
for process in self._preprocessors:
filehandle = process(filehandle, metadata)
return filehandlf _preprocess(self, filehandle, metadata):
"Runs all attached preprocessor... | Runs all attached preprocessors on the provided filehandle. |
def _postprocess(self, filehandle, metadata):
"Runs all attached postprocessors on the provided filehandle."
for process in self._postprocessors:
filehandle = process(filehandle, metadata)
return filehandlf _postprocess(self, filehandle, metadata):
"Runs all attached postproc... | Runs all attached postprocessors on the provided filehandle. |
def save(self, filehandle, destination=None, metadata=None,
validate=True, catch_all_errors=False, *args, **kwargs):
destination = destination or self._destination
if destination is None:
raise RuntimeError("Destination for filehandle must be provided.")
elif d... | Saves the filehandle to the provided destination or the attached
default destination. Allows passing arbitrary positional and keyword
arguments to the saving mechanism
:param filehandle: werkzeug.FileStorage instance
:param dest: String path, callable or writable destination to pass the... |
def urlretrieve(self, url, filename=None, method='GET', body=None, dir=None, **kwargs):
result = self.request(method, url, data=body, **kwargs)
result.code = result.status_code # backwards compat
if not filename:
fd, filename = tempfile.mkstemp(dir=dir)
f = o... | Save result of a request to a file, similarly to
:func:`urllib.urlretrieve`.
If an error is encountered may raise any of the scrapelib
`exceptions`_.
A filename may be provided or :meth:`urlretrieve` will safely create a
temporary file. If a directory is provided, a file will b... |
def color_is_allowed():
''' Look for clues in environment, e.g.:
- https://bixense.com/clicolors/
- http://no-color.org/
Returns:
Bool: Allowed
'''
result = True # generally yes - env.CLICOLOR != '0'
if color_is_disabled():
result = False
log.debug('... | Look for clues in environment, e.g.:
- https://bixense.com/clicolors/
- http://no-color.org/
Returns:
Bool: Allowed |
def color_is_forced(**envars):
''' Look for clues in environment, e.g.:
- https://bixense.com/clicolors/
Arguments:
envars: Additional environment variables to check for
equality, i.e. ``MYAPP_COLOR_FORCED='1'``
Returns:
Bool: Forced
... | Look for clues in environment, e.g.:
- https://bixense.com/clicolors/
Arguments:
envars: Additional environment variables to check for
equality, i.e. ``MYAPP_COLOR_FORCED='1'``
Returns:
Bool: Forced |
def get_available_palettes(chosen_palette):
''' Given a chosen palette, returns tuple of those available,
or None when not found.
Because palette support of a particular level is almost always a
superset of lower levels, this should return all available palettes.
Returns:
... | Given a chosen palette, returns tuple of those available,
or None when not found.
Because palette support of a particular level is almost always a
superset of lower levels, this should return all available palettes.
Returns:
Boolean, None: is tty or None if not found. |
def is_a_tty(stream=sys.stdout):
''' Detect terminal or something else, such as output redirection.
Returns:
Boolean, None: is tty or None if not found.
'''
result = stream.isatty() if hasattr(stream, 'isatty') else None
log.debug(result)
return resulf is_a_tty(stream=sys.stdout... | Detect terminal or something else, such as output redirection.
Returns:
Boolean, None: is tty or None if not found. |
def parse_vtrgb(path='/etc/vtrgb'):
''' Parse the color table for the Linux console. '''
palette = ()
table = []
try:
with open(path) as infile:
for i, line in enumerate(infile):
row = tuple(int(val) for val in line.split(','))
table.append(row)
... | Parse the color table for the Linux console. |
def _getch():
''' POSIX implementation of get char/key. '''
import tty
with TermStack() as fd:
tty.setraw(fd)
return sys.stdin.read(1f _getch():
''' POSIX implementation of get char/key. '''
import tty
with TermStack() as fd:
tty.setraw(fd)
return sys.stdin.read... | POSIX implementation of get char/key. |
def _read_until(infile=sys.stdin, maxchars=20, end=RS):
''' Read a terminal response of up to a few characters from stdin. '''
chars = []
read = infile.read
if not isinstance(end, tuple):
end = (end,)
# count down, stopping at 0
while maxchars:
char = read(1)
if char in... | Read a terminal response of up to a few characters from stdin. |
def really_bad_du(path):
"Don't actually use this, it's just an example."
return sum([os.path.getsize(fp) for fp in list_files(path)]f really_bad_du(path):
"Don't actually use this, it's just an example."
return sum([os.path.getsize(fp) for fp in list_files(path)]) | Don't actually use this, it's just an example. |
def check_disk_usage(filehandle, meta):
# limit it at twenty kilobytes if no default is provided
MAX_DISK_USAGE = current_app.config.get('MAX_DISK_USAGE', 20 * 1024)
CURRENT_USAGE = really_bad_du(current_app.config['UPLOAD_PATH'])
filehandle.seek(0, os.SEEK_END)
if CURRENT_USAGE + filehandle.t... | Checks the upload directory to see if the uploaded file would exceed
the total disk allotment. Meant as a quick and dirty example. |
def get_version(filename, version='1.00'):
''' Read version as text to avoid machinations at import time. '''
with open(filename) as infile:
for line in infile:
if line.startswith('__version__'):
try:
version = line.split("'")[1]
except Ind... | Read version as text to avoid machinations at import time. |
def parse_range_header(self, header, resource_size):
if not header or '=' not in header:
return None
ranges = []
units, range_ = header.split('=', 1)
units = units.strip().lower()
if units != 'bytes':
return None
for val in range_.split... | Parses a range header into a list of two-tuples (start, stop) where
`start` is the starting byte of the range (inclusive) and
`stop` is the ending byte position of the range (exclusive).
Args:
header (str): The HTTP_RANGE request header.
resource_size (int): The size of ... |
def add_range_headers(self, range_header):
self['Accept-Ranges'] = 'bytes'
size = self.ranged_file.size
try:
ranges = self.ranged_file.parse_range_header(range_header, size)
except ValueError:
ranges = None
# Only handle syntactically valid header... | Adds several headers that are necessary for a streaming file
response, in order for Safari to play audio files. Also
sets the HTTP status_code to 206 (partial content).
Args:
range_header (str): Browser HTTP_RANGE request header. |
def build_color_tables(base=color_tables.vga_palette4):
'''
Create the color tables for palette downgrade support,
starting with the platform-specific 16 from the color tables module.
Save as global state. :-/
'''
base = [] if base is None else base
# make sure we have them befo... | Create the color tables for palette downgrade support,
starting with the platform-specific 16 from the color tables module.
Save as global state. :-/ |
def add_interval(self, start, end, data=None):
'''
Inserts an interval to the tree.
Note that when inserting we do not maintain appropriate sorting of the "mid" data structure.
This should be done after all intervals are inserted.
'''
# Ignore intervals of 0 or negative ... | Inserts an interval to the tree.
Note that when inserting we do not maintain appropriate sorting of the "mid" data structure.
This should be done after all intervals are inserted. |
def sort(self):
'''
Must be invoked after all intevals have been added to sort mid_** arrays.
'''
if self.single_interval is None or self.single_interval != 0:
return # Nothing to do for empty and leaf trees.
self.mid_sorted_by_start.sort(key = lambda x: x[0])
... | Must be invoked after all intevals have been added to sort mid_** arrays. |
def dfa_word_acceptance(dfa: dict, word: list) -> bool:
current_state = dfa['initial_state']
for action in word:
if (current_state, action) in dfa['transitions']:
current_state = dfa['transitions'][current_state, action]
else:
return False
if current_state in df... | Checks if a given **word** is accepted by a DFA,
returning True/false.
The word w is accepted by a DFA if DFA has an accepting run
on w. Since A is deterministic,
:math:`w ∈ L(A)` if and only if :math:`ρ(s_0 , w) ∈ F` .
:param dict dfa: input DFA;
:param list word: list of actions ∈ dfa['alpha... |
def dfa_completion(dfa: dict) -> dict:
dfa['states'].add('sink')
for state in dfa['states']:
for action in dfa['alphabet']:
if (state, action) not in dfa['transitions']:
dfa['transitions'][state, action] = 'sink'
return dfa | Side effects on input! Completes the DFA assigning to
each state a transition for each letter in the alphabet (if
not already defined).
We say that a DFA is complete if its transition function
:math:`ρ:S×Σ→S` is a total function, that is,
for all :math:`s ∈ S` and all :math:`a ∈ Σ` we have that
... |
def dfa_complementation(dfa: dict) -> dict:
dfa_complement = dfa_completion(deepcopy(dfa))
dfa_complement['accepting_states'] = \
dfa_complement['states'].difference(dfa_complement['accepting_states'])
return dfa_complement | Returns a DFA that accepts any word but he ones accepted
by the input DFA.
Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )`
is the DFA that runs A but accepts whatever word A does not.
:param dict dfa: input DFA.
:return: *(dict)* representing the complement of the input DFA. |
def dfa_reachable(dfa: dict) -> dict:
reachable_states = set() # set of reachable states from root
boundary = set()
reachable_states.add(dfa['initial_state'])
boundary.add(dfa['initial_state'])
while boundary:
s = boundary.pop()
for a in dfa['alphabet']:
if (s, a) ... | Side effects on input! Removes unreachable states from a
DFA and returns the pruned DFA.
It is possible to remove from a DFA A all unreachable states
from the initial state without altering the language.
The reachable DFA :math:`A_R` corresponding to A is defined as:
:math:`A_R = (Σ, S_R , s_0 , ρ... |
def dfa_co_reachable(dfa: dict) -> dict:
co_reachable_states = dfa['accepting_states'].copy()
boundary = co_reachable_states.copy()
# inverse transition function
inverse_transitions = dict()
for key, value in dfa['transitions'].items():
inverse_transitions.setdefault(value, set()).add... | Side effects on input! Removes from the DFA all states that
do not reach a final state and returns the pruned DFA.
It is possible to remove from a DFA A all states that do not
reach a final state without altering the language.
The co-reachable dfa :math:`A_F` corresponding to A is
defined as:
... |
def dfa_trimming(dfa: dict) -> dict:
# Reachable DFA
dfa = dfa_reachable(dfa)
# Co-reachable DFA
dfa = dfa_co_reachable(dfa)
# trimmed DFA
return dfa | Side effects on input! Returns the DFA in input trimmed,
so both reachable and co-reachable.
Given a DFA A, the corresponding trimmed DFA contains only
those states that are reachable from the initial state
and that lead to a final state.
The trimmed dfa :math:`A_{RF}` corresponding to A is defined... |
def dfa_nonemptiness_check(dfa: dict) -> bool:
# BFS
queue = [dfa['initial_state']]
visited = set()
visited.add(dfa['initial_state'])
while queue:
state = queue.pop(0) # TODO note that this pop is applied to a list
# not like in sets
visited.add(state)
for a in ... | Checks if the input DFA is nonempty (i.e. if it recognizes a
language except the empty one), returning True/False.
An automaton A is nonempty if :math:`L(A) ≠ ∅`. L(A) is
nonempty iff there are states :math:`s_0 and t ∈ F` such
that t is connected to :math:`s_0`. Thus, automata
nonemptiness is equi... |
def rename_dfa_states(dfa: dict, suffix: str):
conversion_dict = dict()
new_states = set()
new_accepting = set()
for state in dfa['states']:
conversion_dict[state] = '' + suffix + state
new_states.add('' + suffix + state)
if state in dfa['accepting_states']:
new_... | Side effect on input! Renames all the states of the DFA
adding a **suffix**.
It is an utility function to be used to avoid automata to have
states with names in common.
Avoid suffix that can lead to special name like "as", "and",...
:param dict dfa: input DFA.
:param str suffix: string to be ... |
def _load_chains(f):
'''
Loads all LiftOverChain objects from a file into an array. Returns the result.
'''
chains = []
while True:
line = f.readline()
if not line:
break
if line.startswith(b'#') or line.startswith(b'\n') or lin... | Loads all LiftOverChain objects from a file into an array. Returns the result. |
def monitor(stop, offset=0, limit=10, city='Dresden', *, raw=False):
try:
r = requests.get(
url='http://widgets.vvo-online.de/abfahrtsmonitor/Abfahrten.do',
params={
'ort': city,
'hst': stop,
'vz': offset,
'lim': li... | VVO Online Monitor
(GET http://widgets.vvo-online.de/abfahrtsmonitor/Abfahrten.do)
:param stop: Name of Stop
:param offset: Minimum time of arrival
:param limit: Count of returned results
:param city: Name of City
:param raw: Return raw response
:return: Dict of stops |
def find(search, eduroam=False, *, raw=False):
url = 'http://efa.faplino.de/dvb/XML_STOPFINDER_REQUEST' if eduroam \
else 'http://efa.vvo-online.de:8080/dvb/XML_STOPFINDER_REQUEST'
try:
r = requests.get(
url=url,
params={
'locationServerActive': '1'... | VVO Online EFA Stopfinder
(GET http://efa.vvo-online.de:8080/dvb/XML_STOPFINDER_REQUEST)
:param search: Stop to find
:param eduroam: Request from eduroam
:param raw: Return raw response
:return: All matching stops |
def pins(swlat, swlng, nelat, nelng, pintypes='stop', *, raw=False):
try:
swlat, swlng = wgs_to_gk4(swlat, swlng)
nelat, nelng = wgs_to_gk4(nelat, nelng)
r = requests.get(
url='https://www.dvb.de/apps/map/pins',
params={
'showlines': 'true',
... | DVB Map Pins
(GET https://www.dvb.de/apps/map/pins)
:param swlat: South-West Bounding Box Latitude
:param swlng: South-West Bounding Box Longitude
:param nelat: North-East Bounding Box Latitude
:param nelng: North-East Bounding Box Longitude
:param pintypes: Types to search for, defaults to 'st... |
def poi_coords(poi_id, *, raw=False):
try:
r = requests.get(
url='https://www.dvb.de/apps/map/coordinates',
params={
'id': poi_id,
},
)
if r.status_code == 200:
response = json.loads(r.content.decode('utf-8'))
else:... | DVB Map Coordinates
(GET https://www.dvb.de/apps/map/coordinates)
:param poi_id: Id of poi
:param raw: Return raw response
:return: Coordinates of poi |
def address(lat, lng, *, raw=False):
try:
lat, lng = wgs_to_gk4(lat, lng)
r = requests.get(
url='https://www.dvb.de/apps/map/address',
params={
'lat': lat,
'lng': lng,
},
)
if r.status_code == 200:
r... | DVB Map Address
(GET https://www.dvb.de/apps/map/address)
:param lat: Latitude
:param lng: Longitude
:param raw: Return raw response
:return: Dict of address |
def checksum(string):
digits = list(map(int, string))
odd_sum = sum(digits[-1::-2])
even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]])
return (odd_sum + even_sum) % 10 | Compute the Luhn checksum for the provided string of digits. Note this
assumes the check digit is in place. |
def is_blocked(self, ip):
blocked = True
if ip in self.allowed_admin_ips:
blocked = False
for allowed_range in self.allowed_admin_ip_ranges:
if ipaddress.ip_address(ip) in ipaddress.ip_network(allowed_range):
blocked = False
return bloc... | Determine if an IP address should be considered blocked. |
def train(self, X_train, Y_train, X_test, Y_test):
while True:
print(1)
time.sleep(1)
if random.randint(0, 9) >= 5:
break | Train and validate the LR on a train and test dataset
Args:
X_train (np.array): Training data
Y_train (np.array): Training labels
X_test (np.array): Test data
Y_test (np.array): Test labels |
def _convert_url_to_downloadable(url):
if 'drive.google.com' in url:
# For future support of google drive
file_id = url.split('d/')[1].split('/')[0]
base_url = 'https://drive.google.com/uc?export=download&id='
out = '{}{}'.format(base_url, file_id)
elif 'dropbox.com' in url... | Convert a url to the proper style depending on its website. |
def _get_ftp(url, temp_file_name, initial_size, file_size, verbose_bool,
progressbar, ncols=80):
# Adapted from: https://pypi.python.org/pypi/fileDownloader.py
# but with changes
parsed_url = urllib.parse.urlparse(url)
file_name = os.path.basename(parsed_url.path)
server_path = pa... | Safely (resume a) download to a file from FTP. |
def _get_http(url, temp_file_name, initial_size, file_size, verbose_bool,
progressbar, ncols=80):
# Actually do the reading
req = urllib.request.Request(url)
if initial_size > 0:
req.headers['Range'] = 'bytes=%s-' % (initial_size,)
try:
response = urllib.request.urlope... | Safely (resume a) download to a file from http(s). |
def md5sum(fname, block_size=1048576): # 2 ** 20
md5 = hashlib.md5()
with open(fname, 'rb') as fid:
while True:
data = fid.read(block_size)
if not data:
break
md5.update(data)
return md5.hexdigest() | Calculate the md5sum for a file.
Parameters
----------
fname : str
Filename.
block_size : int
Block size to use when reading.
Returns
-------
hash_ : str
The hexadecimal digest of the hash. |
def _chunk_write(chunk, local_file, progress):
local_file.write(chunk)
if progress is not None:
progress.update(len(chunk)) | Write a chunk to file and update the progress bar. |
def sizeof_fmt(num):
units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB']
decimals = [0, 0, 1, 2, 2, 2]
if num > 1:
exponent = min(int(log(num, 1024)), len(units) - 1)
quotient = float(num) / 1024 ** exponent
unit = units[exponent]
num_decimals = decimals[exponent]
fo... | Turn number of bytes into human-readable str.
Parameters
----------
num : int
The number of bytes.
Returns
-------
size : str
The size in human-readable format. |
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None,
retry_log_level=logging.INFO,
retry_log_message="Connection broken in '{f}' (error: '{e}'); "
"retrying with new connection.",
max_failures=None, interval=0,
max_failure_log_level=logging.ERROR... | Decorator to automatically reexecute a function if the connection is
broken for any reason. |
def get(self):
self.lock.acquire()
try:
c = self.conn.popleft()
yield c
except self.exc_classes:
# The current connection has failed, drop it and create a new one
gevent.spawn_later(1, self._addOne)
raise
except:
... | Get a connection from the pool, to make and receive traffic.
If the connection fails for any reason (socket.error), it is dropped
and a new one is scheduled. Please use @retry as a way to automatically
retry whatever operation you were performing. |
def eff_default_transformer(fills=EFF_DEFAULT_FILLS):
def _transformer(vals):
if len(vals) == 0:
return fills
else:
# ignore all but first effect
match_eff_main = _prog_eff_main.match(vals[0])
if match_eff_main is None:
logging.war... | Return a simple transformer function for parsing EFF annotations. N.B.,
ignores all but the first effect. |
def ann_default_transformer(fills=ANN_DEFAULT_FILLS):
def _transformer(vals):
if len(vals) == 0:
return fills
else:
# ignore all but first effect
ann = vals[0].split(b'|')
ann = ann[:11] + _ann_split2(ann[11]) + _ann_split2(ann[12]) + \
... | Return a simple transformer function for parsing ANN annotations. N.B.,
ignores all but the first effect. |
def overload(func):
if sys.version_info < (3, 3):
raise OverloadingError("The 'overload' syntax requires Python version 3.3 or higher.")
fn = unwrap(func)
ensure_function(fn)
fname = get_full_name(fn)
if fname.find('<locals>') >= 0:
raise OverloadingError("The 'overload' syntax ... | May be used as a shortcut for ``overloaded`` and ``overloads(f)``
when the overloaded function `f` can be automatically identified. |
def get_signature(func):
code = func.__code__
# Names of regular parameters
parameters = tuple(code.co_varnames[:code.co_argcount])
# Flags
has_varargs = bool(code.co_flags & inspect.CO_VARARGS)
has_varkw = bool(code.co_flags & inspect.CO_VARKEYWORDS)
has_kwonly = bool(code.co_kwonlya... | Gathers information about the call signature of `func`. |
def normalize_type(type_, level=0):
if not typing or not isinstance(type_, typing.TypingMeta) or type_ is AnyType:
return type_
if isinstance(type_, typing.TypeVar):
if type_.__constraints__ or type_.__bound__:
return type_
else:
return AnyType
if issubcl... | Reduces an arbitrarily complex type declaration into something manageable. |
def type_complexity(type_):
if (not typing
or not isinstance(type_, (typing.TypingMeta, GenericWrapperMeta))
or type_ is AnyType):
return 0
if issubclass(type_, typing.Union):
return reduce(operator.or_, map(type_complexity, type_.__union_params__))
if issubclass(type_, typi... | Computes an indicator for the complexity of `type_`.
If the return value is 0, the supplied type is not parameterizable.
Otherwise, set bits in the return value denote the following features:
- bit 0: The type could be parameterized but is not.
- bit 1: The type represents an iterable container with 1 ... |
def find_base_generic(type_):
for t in type_.__mro__:
if t.__module__ == typing.__name__:
return first_origin(t) | Locates the underlying generic whose structure and behavior are known.
For example, the base generic of a type that inherits from `typing.Mapping[T, int]`
is `typing.Mapping`. |
def iter_generic_bases(type_):
for t in type_.__mro__:
if not isinstance(t, typing.GenericMeta):
continue
yield t
t = t.__origin__
while t:
yield t
t = t.__origin__ | Iterates over all generics `type_` derives from, including origins.
This function is only necessary because, in typing 3.5.0, a generic doesn't
get included in the list of bases when it constructs a parameterized version
of itself. This was fixed in aab2c59; now it would be enough to just iterate
over ... |
def sig_cmp(sig1, sig2):
types1 = sig1.required
types2 = sig2.required
if len(types1) != len(types2):
return False
dup_pos = []
dup_kw = {}
for t1, t2 in zip(types1, types2):
match = type_cmp(t1, t2)
if match:
dup_pos.append(match)
else:
... | Compares two normalized type signatures for validation purposes. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.