Search is not available for this dataset
text stringlengths 75 104k |
|---|
def bitdepth(self):
"""The number of bits per sample in the audio encoding (an int).
Only available for certain file formats (zero where
unavailable).
"""
if hasattr(self.mgfile.info, 'bits_per_sample'):
return self.mgfile.info.bits_per_sample
return 0 |
def channels(self):
"""The number of channels in the audio (an int)."""
if hasattr(self.mgfile.info, 'channels'):
return self.mgfile.info.channels
return 0 |
def bitrate(self):
"""The number of bits per seconds used in the audio coding (an
int). If this is provided explicitly by the compressed file
format, this is a precise reflection of the encoding. Otherwise,
it is estimated from the on-disk file size. In this case, some
imprecisio... |
def fromfits(infilename, hdu = 0, verbose = True):
"""
Reads a FITS file and returns a 2D numpy array of the data.
Use hdu to specify which HDU you want (default = primary = 0)
"""
pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True)
pixelarray = np.asarray(pixelarray).transpose()... |
def tofits(outfilename, pixelarray, hdr = None, verbose = True):
"""
Takes a 2D numpy array and write it into a FITS file.
If you specify a header (pyfits format, as returned by fromfits()) it will be used for the image.
You can give me boolean numpy arrays, I will convert them into 8 bit integers.
... |
def subsample(a): # this is more a generic function then a method ...
"""
Returns a 2x2-subsampled version of array a (no interpolation, just cutting pixels in 4).
The version below is directly from the scipy cookbook on rebinning :
U{http://www.scipy.org/Cookbook/Rebinning}
There is ndimage.zoom(cu... |
def rebin2x2(a):
"""
Wrapper around rebin that actually rebins 2 by 2
"""
inshape = np.array(a.shape)
if not (inshape % 2 == np.zeros(2)).all(): # Modulo check to see if size is even
raise RuntimeError, "I want even image shapes !"
return rebin(a, inshape/2) |
def labelmask(self, verbose = None):
"""
Finds and labels the cosmic "islands" and returns a list of dicts containing their positions.
This is made on purpose for visualizations a la f2n.drawstarslist, but could be useful anyway.
"""
if verbose == None:
verbose = self... |
def getdilatedmask(self, size=3):
"""
Returns a morphologically dilated copy of the current mask.
size = 3 or 5 decides how to dilate.
"""
if size == 3:
dilmask = ndimage.morphology.binary_dilation(self.mask, structure=growkernel, iterations=1, mask=None, output=None,... |
def clean(self, mask = None, verbose = None):
"""
Given the mask, we replace the actual problematic pixels with the masked 5x5 median value.
This mimics what is done in L.A.Cosmic, but it's a bit harder to do in python, as there is no
readymade masked median. So for now we do a loop...
... |
def findsatstars(self, verbose = None):
"""
Uses the satlevel to find saturated stars (not cosmics !), and puts the result as a mask in self.satstars.
This can then be used to avoid these regions in cosmic detection and cleaning procedures.
Slow ...
"""
if verbose == None... |
def getsatstars(self, verbose = None):
"""
Returns the mask of saturated stars after finding them if not yet done.
Intended mainly for external use.
"""
if verbose == None:
verbose = self.verbose
if not self.satlevel > 0:
raise RuntimeError, "Canno... |
def guessbackgroundlevel(self):
"""
Estimates the background level. This could be used to fill pixels in large cosmics.
"""
if self.backgroundlevel == None:
self.backgroundlevel = np.median(self.rawarray.ravel())
return self.backgroundlevel |
def lacosmiciteration(self, verbose = None):
"""
Performs one iteration of the L.A.Cosmic algorithm.
It operates on self.cleanarray, and afterwards updates self.mask by adding the newly detected
cosmics to the existing self.mask. Cleaning is not made automatically ! You have to call
... |
def run(self, maxiter = 4, verbose = False):
"""
Full artillery :-)
- Find saturated stars
- Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found)
Stops if no cosmics are found or if maxiter is reached.
"""
if self.satlev... |
def search_project_root():
"""
Search your Django project root.
returns:
- path:string Django project root path
"""
while True:
current = os.getcwd()
if pathlib.Path("Miragefile.py").is_file() or pathlib.Path("Miragefile").is_file():
... |
def search_app_root():
"""
Search your Django application root
returns:
- (String) Django application root path
"""
while True:
current = os.getcwd()
if pathlib.Path("apps.py").is_file():
return current
elif pathl... |
def in_app() -> bool:
"""
Judge where current working directory is in Django application or not.
returns:
- (Bool) cwd is in app dir returns True
"""
try:
MirageEnvironment.set_import_root()
import apps
if os.path.isfile("apps.py")... |
def update_cached_fields(*args):
"""
Calls update_cached_fields() for each object passed in as argument.
Supports also iterable objects by checking __iter__ attribute.
:param args: List of objects
:return: None
"""
for a in args:
if a is not None:
if hasattr(a, '__iter__'... |
def update_cached_fields_pre_save(self, update_fields: list):
"""
Call on pre_save signal for objects (to automatically refresh on save).
:param update_fields: list of fields to update
"""
if self.id and update_fields is None:
self.update_cached_fields(commit=False, e... |
def start(name):
# type: (str) -> None
""" Start working on a new hotfix.
This will create a new branch off master called hotfix/<name>.
Args:
name (str):
The name of the new feature.
"""
hotfix_branch = 'hotfix/' + common.to_branch_name(name)
master = conf.get('git.mas... |
def finish():
# type: () -> None
""" Merge current feature into develop. """
pretend = context.get('pretend', False)
if not pretend and (git.staged() or git.unstaged()):
log.err(
"You have uncommitted changes in your repo!\n"
"You need to stash them before you merge the ... |
def merged():
# type: () -> None
""" Cleanup a remotely merged branch. """
develop = conf.get('git.devel_branch', 'develop')
master = conf.get('git.master_branch', 'master')
branch = git.current_branch(refresh=True)
common.assert_branch_type('hotfix')
# Pull master with the merged hotfix
... |
def run(self):
"""
Run the shell command
Returns:
ShellCommand: return this ShellCommand instance for chaining
"""
if not self.block:
self.output = []
self.error = []
self.thread = threading.Thread(target=self.run_non_blocking)
... |
def send(self, value):
"""
Send text to stdin. Can only be used on non blocking commands
Args:
value (str): the text to write on stdin
Raises:
TypeError: If command is blocking
Returns:
ShellCommand: return this ShellCommand instance for chain... |
def poll_output(self):
"""
Append lines from stdout to self.output.
Returns:
list: The lines added since last call
"""
if self.block:
return self.output
new_list = self.output[self.old_output_size:]
self.old_output_size += len(new_list)
... |
def poll_error(self):
"""
Append lines from stderr to self.errors.
Returns:
list: The lines added since last call
"""
if self.block:
return self.error
new_list = self.error[self.old_error_size:]
self.old_error_size += len(new_list)
... |
def kill(self):
"""
Kill the current non blocking command
Raises:
TypeError: If command is blocking
"""
if self.block:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE)
try:
self.process.kill()
except ProcessLookupError as exc:
... |
def wait_for(self, pattern, timeout=None):
"""
Block until a pattern have been found in stdout and stderr
Args:
pattern(:class:`~re.Pattern`): The pattern to search
timeout(int): Maximum number of second to wait. If None, wait infinitely
Raises:
Tim... |
def is_running(self):
"""
Check if the command is currently running
Returns:
bool: True if running, else False
"""
if self.block:
return False
return self.thread.is_alive() or self.process.poll() is None |
def print_live_output(self):
'''
Block and print the output of the command
Raises:
TypeError: If command is blocking
'''
if self.block:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE)
else:
while self.thread.is_alive() or self.old_output_s... |
def run(self, command, block=True, cwd=None, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
"""
Create an instance of :class:`~ShellCommand` and run it
Args:
command (str): :class:`~ShellCommand`
block (bool): See :class:`~ShellCommand`
... |
def bces(x1, x2, x1err=[], x2err=[], cerr=[], logify=True, model='yx', \
bootstrap=5000, verbose='normal', full_output=True):
"""
Bivariate, Correlated Errors and intrinsic Scatter (BCES)
translated from the FORTRAN code by Christina Bird and Matthew Bershady
(Akritas & Bershady, 1996)
Lin... |
def scatter(slope, zero, x1, x2, x1err=[], x2err=[]):
"""
Used mainly to measure scatter for the BCES best-fit
"""
n = len(x1)
x2pred = zero + slope * x1
s = sum((x2 - x2pred) ** 2) / (n - 1)
if len(x2err) == n:
s_obs = sum((x2err / x2) ** 2) / n
s0 = s - s_obs
print num... |
def kelly(x1, x2, x1err=[], x2err=[], cerr=[], logify=True,
miniter=5000, maxiter=1e5, metro=True,
silent=True):
"""
Python wrapper for the linear regression MCMC of Kelly (2007).
Requires pidly (http://astronomy.sussex.ac.uk/~anthonys/pidly/) and
an IDL license.
Parameters
... |
def mcmc(x1, x2, x1err=[], x2err=[], po=(1,1,0.5), logify=True,
nsteps=5000, nwalkers=100, nburn=500, output='full'):
"""
Use emcee to find the best-fit linear relation or power law
accounting for measurement uncertainties and intrinsic scatter
Parameters
----------
x1 : array... |
def mle(x1, x2, x1err=[], x2err=[], cerr=[], s_int=True,
po=(1,0,0.1), verbose=False, logify=True, full_output=False):
"""
Maximum Likelihood Estimation of best-fit parameters
Parameters
----------
x1, x2 : float arrays
the independent and dependent variables.
x... |
def to_log(x1, x2, x1err, x2err):
"""
Take linear measurements and uncertainties and transform to log values.
"""
logx1 = numpy.log10(numpy.array(x1))
logx2 = numpy.log10(numpy.array(x2))
x1err = numpy.log10(numpy.array(x1)+numpy.array(x1err)) - logx1
x2err = numpy.log10(numpy.array(x2)+num... |
def wrap_paths(paths):
# type: (list[str]) -> str
""" Put quotes around all paths and join them with space in-between. """
if isinstance(paths, string_types):
raise ValueError(
"paths cannot be a string. "
"Use array with one element instead."
)
return ' '.join('"... |
def filtered_walk(path, include=None, exclude=None):
# type: (str, List[str], List[str]) -> Generator[str]
""" Walk recursively starting at *path* excluding files matching *exclude*
Args:
path (str):
A starting path. This has to be an existing directory.
include (list[str]):
... |
def match_globs(path, patterns):
# type: (str, List[str]) -> bool
""" Test whether the given *path* matches any patterns in *patterns*
Args:
path (str):
A file path to test for matches.
patterns (list[str]):
A list of glob string patterns to test against. If *path* m... |
def search_globs(path, patterns):
# type: (str, List[str]) -> bool
""" Test whether the given *path* contains any patterns in *patterns*
Args:
path (str):
A file path to test for matches.
patterns (list[str]):
A list of glob string patterns to test against. If *path*... |
def write_file(path, content, mode='w'):
# type: (Text, Union[Text,bytes], Text) -> None
""" --pretend aware file writing.
You can always write files manually but you should always handle the
--pretend case.
Args:
path (str):
content (str):
mode (str):
"""
from pelt... |
def lint_cli(ctx, exclude, skip_untracked, commit_only):
# type: (click.Context, List[str], bool, bool) -> None
""" Run pep8 and pylint on all project files.
You can configure the linting paths using the lint.paths config variable.
This should be a list of paths that will be linted. If a path to a dire... |
def run_command(command, timeout_sec=3600.0, output=True):
"""Runs a command using the subprocess module
:param command: List containing the command and all args
:param timeout_sec (float) seconds to wait before killing
the command.
:param output (bool) True collects output, False ignores outpu... |
def get_ip_addresses():
"""Gets the ip addresses from ifconfig
:return: (dict) of devices and aliases with the IPv4 address
"""
log = logging.getLogger(mod_logger + '.get_ip_addresses')
command = ['/sbin/ifconfig']
try:
result = run_command(command)
except CommandError:
rai... |
def get_mac_address(device_index=0):
"""Returns the Mac Address given a device index
:param device_index: (int) Device index
:return: (str) Mac address or None
"""
log = logging.getLogger(mod_logger + '.get_mac_address')
command = ['ip', 'addr', 'show', 'eth{d}'.format(d=device_index)]
log.... |
def chmod(path, mode, recursive=False):
"""Emulates bash chmod command
This method sets the file permissions to the specified mode.
:param path: (str) Full path to the file or directory
:param mode: (str) Mode to be set (e.g. 0755)
:param recursive: (bool) Set True to make a recursive call
:re... |
def mkdir_p(path):
"""Emulates 'mkdir -p' in bash
:param path: (str) Path to create
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.mkdir_p')
if not isinstance(path, basestring):
msg = 'path argument is not a string'
log.error(msg)
raise... |
def source(script):
"""Emulates 'source' command in bash
:param script: (str) Full path to the script to source
:return: Updated environment
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.source')
if not isinstance(script, basestring):
msg = 'script argument must be... |
def yum_update(downloadonly=False, dest_dir='/tmp'):
"""Run a yum update on this system
This public method runs the yum -y update command to update
packages from yum. If downloadonly is set to true, the yum
updates will be downloaded to the specified dest_dir.
:param dest_dir: (str) Full path to t... |
def yum_install(packages, downloadonly=False, dest_dir='/tmp'):
"""Installs (or downloads) a list of packages from yum
This public method installs a list of packages from yum or
downloads the packages to the specified destination directory using
the yum-downloadonly yum plugin.
:param downloadonly... |
def rpm_install(install_dir):
"""This method installs all RPM files in a specific dir
:param install_dir: (str) Full path to the directory
:return int exit code form the rpm command
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.rpm_install')
# Type checks on the args
... |
def sed(file_path, pattern, replace_str, g=0):
"""Python impl of the bash sed command
This method emulates the functionality of a bash sed command.
:param file_path: (str) Full path to the file to be edited
:param pattern: (str) Search pattern to replace as a regex
:param replace_str: (str) String... |
def zip_dir(dir_path, zip_file):
"""Creates a zip file of a directory tree
This method creates a zip archive using the directory tree dir_path
and adds to zip_file output.
:param dir_path: (str) Full path to directory to be zipped
:param zip_file: (str) Full path to the output zip file
:return... |
def get_ip(interface=0):
"""This method return the IP address
:param interface: (int) Interface number (e.g. 0 for eth0)
:return: (str) IP address or None
"""
log = logging.getLogger(mod_logger + '.get_ip')
log.info('Getting the IP address for this system...')
ip_address = None
try:
... |
def update_hosts_file(ip, entry):
"""Updates the /etc/hosts file for the specified ip
This method updates the /etc/hosts file for the specified IP
address with the specified entry.
:param ip: (str) IP address to be added or updated
:param entry: (str) Hosts file entry to be added
:return: None... |
def set_hostname(new_hostname, pretty_hostname=None):
"""Sets this hosts hostname
This method updates /etc/sysconfig/network and calls the hostname
command to set a hostname on a Linux system.
:param new_hostname: (str) New hostname
:param pretty_hostname: (str) new pretty hostname, set to the sam... |
def set_ntp_server(server):
"""Sets the NTP server on Linux
:param server: (str) NTP server IP or hostname
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.set_ntp_server')
# Ensure the hostname is a str
if not isinstance(server, basestring):
msg = ... |
def copy_ifcfg_file(source_interface, dest_interface):
"""Copies an existing ifcfg network script to another
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises TypeError, OSError
"""
log = logging.getLogger(mod_logger + '.copy_ifcfg_file'... |
def remove_ifcfg_file(device_index='0'):
"""Removes the ifcfg file at the specified device index
and restarts the network service
:param device_index: (int) Device Index
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.remove_ifcfg_file')
if not isinstance(d... |
def add_nat_rule(port, source_interface, dest_interface):
"""Adds a NAT rule to iptables
:param port: String or int port number
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises: TypeError, OSError
"""
log = logging.getLogger(mod_log... |
def service_network_restart():
"""Restarts the network service on linux
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.service_network_restart')
command = ['service', 'network', 'restart']
time.sleep(5)
try:
result = run_command(command)
tim... |
def save_iptables(rules_file='/etc/sysconfig/iptables'):
"""Saves iptables rules to the provided rules file
:return: None
:raises OSError
"""
log = logging.getLogger(mod_logger + '.save_iptables')
# Run iptables-save to get the output
command = ['iptables-save']
log.debug('Running comm... |
def get_remote_host_environment_variable(host, environment_variable):
"""Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param environment_variable: (str) variable to query
:return: (str) value of the environment variable
:raises: TypeE... |
def set_remote_host_environment_variable(host, variable_name, variable_value, env_file='/etc/bashrc'):
"""Sets an environment variable on the remote host in the
specified environment file
:param host: (str) host to set environment variable on
:param variable_name: (str) name of the variable
:param ... |
def run_remote_command(host, command, timeout_sec=5.0):
"""Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param command: (str) command
:param timeout_sec (float) seconds to wait before killing the command.
:return: (str) command output... |
def check_remote_host_marker_file(host, file_path):
"""Queries a remote host over SSH to check for existence
of a marker file
:param host: (str) host to query
:param file_path: (str) path to the marker file
:return: (bool) True if the marker file exists
:raises: TypeError, CommandError
"""
... |
def restore_iptables(firewall_rules):
"""Restores and saves firewall rules from the firewall_rules file
:param firewall_rules: (str) Full path to the firewall rules file
:return: None
:raises OSError
"""
log = logging.getLogger(mod_logger + '.restore_iptables')
log.info('Restoring firewall ... |
def remove_default_gateway():
"""Removes Default Gateway configuration from /etc/sysconfig/network
and restarts networking
:return: None
:raises: OSError
"""
log = logging.getLogger(mod_logger + '.remove_default_gateway')
# Ensure the network script exists
network_script = '/etc/sy... |
def is_systemd():
"""Determines whether this system uses systemd
:return: (bool) True if this distro has systemd
"""
os_family = platform.system()
if os_family != 'Linux':
raise OSError('This method is only supported on Linux, found OS: {o}'.format(o=os_family))
linux_distro, linux_vers... |
def manage_service(service_name, service_action='status', systemd=None, output=True):
"""Use to run Linux sysv or systemd service commands
:param service_name (str) name of the service to start
:param service_action (str) action to perform on the service
:param systemd (bool) True if the command should... |
def system_reboot(wait_time_sec=20):
"""Reboots the system after a specified wait time. Must be run as root
:param wait_time_sec: (int) number of sec to wait before performing the reboot
:return: None
:raises: SystemRebootError, SystemRebootTimeoutError
"""
log = logging.getLogger(mod_logger +... |
def main():
"""Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None
"""
mkdir_p('/tmp/test/test')
source('/root/.bash_profile')
yum_install(['httpd', 'git'])
yum_install(['httpd', 'git'], dest_dir='/tmp/test/test... |
def log_event(name: str, request: Request=None, data=None, ip=None):
"""
Logs consistent event for easy parsing/analysis.
:param name: Name of the event. Will be logged as EVENT_XXX with XXX in capitals.
:param request: Django REST framework Request (optional)
:param data: Even data (optional)
:... |
def aes_b64_encrypt(value, secret, block_size=AES.block_size):
""" AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... |
def aes_b64_decrypt(value, secret, block_size=AES.block_size):
""" AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... |
def aes_encrypt(value, secret, block_size=AES.block_size):
""" AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#bytes) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... |
def aes_decrypt(value, secret, block_size=AES.block_size):
""" AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
ae... |
def aes_pad(s, block_size=32, padding='{'):
""" Adds padding to get the correct block sizes for AES encryption
@s: #str being AES encrypted or decrypted
@block_size: the AES block size
@padding: character to pad with
-> padded #str
..
from vital.security import... |
def lscmp(a, b):
""" Compares two strings in a cryptographically safe way:
Runtime is not affected by length of common prefix, so this
is helpful against timing attacks.
..
from vital.security import lscmp
lscmp("ringo", "starr")
# -> False
ls... |
def cookie(data, key_salt='', secret=None, digestmod=None):
""" Encodes or decodes a signed cookie.
@data: cookie data
@key_salt: HMAC key signing salt
@secret: HMAC signing secret key
@digestmod: hashing algorithm to sign with, recommended >=sha256
-> HMAC signed or unsigne... |
def strkey(val, chaffify=1, keyspace=string.ascii_letters + string.digits):
""" Converts integers to a sequence of strings, and reverse.
This is not intended to obfuscate numbers in any kind of
cryptographically secure way, in fact it's the opposite. It's
for predictable, reversable, obfusca... |
def chars_in(bits, keyspace):
""" ..
log2(keyspace^x_chars) = bits
log(keyspace^x_chars) = log(2) * bits
exp(log(keyspace^x_chars)) = exp(log(2) * bits)
x_chars = log(exp(log(2) * bits)) / log(keyspace)
..
-> (#int) number of characters in @bits of entropy given the @... |
def bits_in(length, keyspace):
""" |log2(keyspace^length) = bits|
-> (#float) number of bits of entropy in @length of characters for
a given a @keyspace
"""
keyspace = len(keyspace)
length_per_cycle = 64
if length > length_per_cycle:
bits = 0
length_processed = 0
... |
def iter_random_chars(bits,
keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Yields a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entr... |
def randkey(bits, keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable... |
def randstr(size, keyspace=string.ascii_letters + string.digits, rng=None):
""" Returns a cryptographically secure random string of desired @size
(in character length) within @keyspace using :class:random.SystemRandom
@size: (#int) number of random characters to generate
@keyspace: (#str) o... |
def parse_requirements(filename):
""" load requirements from a pip requirements file """
lineiter = (line.strip() for line in open(filename))
return (line for line in lineiter if line and not line.startswith("#")) |
def round_sig(x, n, scien_notation = False):
if x < 0:
x = x * -1
symbol = '-'
else:
symbol = ''
'''round floating point x to n significant figures'''
if type(n) is not types.IntType:
raise TypeError, "n must be an integer"
try:
x = float(x)
exce... |
def round_sig_error(x, ex, n, paren=False):
'''Find ex rounded to n sig-figs and make the floating point x
match the number of decimals. If [paren], the string is
returned as quantity(error) format'''
stex = round_sig(ex,n)
if stex.find('.') < 0:
extra_zeros = len(stex) - n
sigfigs ... |
def format_table(cols, errors, n, labels=None, headers=None, latex=False):
'''Format a table such that the errors have n significant
figures. [cols] and [errors] should be a list of 1D arrays
that correspond to data and errors in columns. [n] is the number of
significant figures to keep in the errors.... |
def round_sig_error2(x, ex1, ex2, n):
'''Find min(ex1,ex2) rounded to n sig-figs and make the floating point x
and max(ex,ex2) match the number of decimals.'''
minerr = min(ex1,ex2)
minstex = round_sig(minerr,n)
if minstex.find('.') < 0:
extra_zeros = len(minstex) - n
sigfigs = len(s... |
def send_to_azure_multi_threads(instance, data, nb_threads=4, replace=True, types=None, primary_key=(),
sub_commit=False):
"""
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_colum... |
def send_to_azure(instance, data, thread_number, sub_commit, table_info, nb_threads):
"""
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"rows" : [[... |
def create(self, items=[], taxes=[], custom_data=[]):
"""Adds the items to the invoice
Format of 'items':
[
InvoiceItem(
name="VIP Ticket",
quantity= 2,
unit_price= "3500",
total_price= "7000",
description= "VIP Tickets f... |
def confirm(self, token=None):
"""Returns the status of the invoice
STATUSES: pending, completed, cancelled
"""
_token = token if token else self._response.get("token")
return self._process('checkout-invoice/confirm/' + str(_token)) |
def add_taxes(self, taxes):
"""Appends the data to the 'taxes' key in the request object
'taxes' should be in format: [("tax_name", "tax_amount")]
For example:
[("Other TAX", 700), ("VAT", 5000)]
"""
# fixme: how to resolve duplicate tax names
_idx = len(self.tax... |
def add_item(self, item):
"""Updates the list of items in the current transaction"""
_idx = len(self.items)
self.items.update({"item_" + str(_idx + 1): item}) |
def _prepare_data(self):
"""Formats the data in the current transaction for processing"""
total_amount = self.total_amount or self.calculate_total_amt()
self._data = {
"invoice": {
"items": self.__encode_items(self.items),
"taxes": self.taxes,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.