text stringlengths 81 112k |
|---|
Extract tilting planes basing on distance map
def get_tiltplanes(self, sequence):
'''
Extract tilting planes basing on distance map
'''
tilting_planes = []
distance_map = []
for i in range(1, len(sequence)):
distance_map.append([ sequence[i], self.virtual_at... |
Main procedure
def get_tilting(self, oplane):
'''
Main procedure
'''
surf_atom1, surf_atom2, surf_atom3, surf_atom4 = oplane
# divide surface atoms into groups by distance between them
compare = [surf_atom2, surf_atom3, surf_atom4]
distance_map = []
for... |
Returns dict of help_context keys (description texts used in `EmailRegistry.register()` method).
def get_help_keys(self):
"""
Returns dict of help_context keys (description texts used in `EmailRegistry.register()` method).
"""
help_keys = {}
for k, v in self.help_context.items()... |
Returns dict of help_context values (example values submitted in `EmailRegistry.register()` method).
def get_help_values(self):
"""
Returns dict of help_context values (example values submitted in `EmailRegistry.register()` method).
"""
help_values = {}
for k, v in self.help_con... |
Registers email template.
Example usage:
email_templates.register('hello_template.html', help_text=u'Hello template',
help_context={'username': u'Name of user in hello expression'})
:param path: Template file path. It will become immutable registry lookup key.
:para... |
Returns registration item for specified path.
If an email template is not registered, this will raise NotRegistered.
def get_registration(self, path):
"""
Returns registration item for specified path.
If an email template is not registered, this will raise NotRegistered.
"""
... |
Returns text that can be used as form help text for creating email templates.
def get_form_help_text(self, path):
"""
Returns text that can be used as form help text for creating email templates.
"""
try:
form_help_text = self.get_registration(path).as_form_help_text()
... |
Analyzes the parsed results from Flake8 or PEP 8 output and creates FileResult instances
:param output_file: If specified, output will be written to this file instead of stdout.
def analyze(self, output_file=None):
"""
Analyzes the parsed results from Flake8 or PEP 8 output and creates FileResu... |
Generates an HTML file based on data from the Parser object and Jinja2 templates
:param output_file: If specified, output will be written to this file instead of stdout.
def generate(self, output_file=None):
"""
Generates an HTML file based on data from the Parser object and Jinja2 templates
... |
Reads the data from a FileResult and updates overall statistics
:param file_result: A FileResult instance
def update_stats(self, file_result):
"""
Reads the data from a FileResult and updates overall statistics
:param file_result: A FileResult instance
"""
for code, cou... |
Checks environment variables to see whether pepper8 is run under a build agent such as TeamCity
and performs the adequate actions to report statistics.
Will not perform any action if HTML output is written to OUTPUT_FILE and not stdout.
Currently only supports TeamCity.
:return: A list... |
Returns a phase transformation theta_i.
The phase transformation is defined in a way such that
theta1 + omega_level1 = 0.
>>> xi = np.zeros((1, 2, 2))
>>> xi[0, 1, 0] = 1.0
>>> xi[0, 0, 1] = 1.0
>>> rm = np.zeros((3, 2, 2))
>>> rm[0, 1, 0] = 1.0
>>> rm[1, 1, 0] = 1.0
>>> rm[2, ... |
Return a simplifying function, its inverse, and simplified frequencies.
This implements an index iu that labels energies in a non-degenerate
way.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, Ne))
>>> coup = [[(1, 0), (2, 0)], [... |
r"""Find the smallest transition frequency for each field.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, Ne))
>>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]]
>>> for l in range(Nl):
... for pair in coup[l]:
... ... |
r"""Get the indices of the transitions of all fields.
They are returned in the form
[[(i1, j1), (i2, j2)], ...,[(i1, j1)]].
that is, one list of pairs of indices for each field.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, Ne))... |
r"""Get the code to calculate the simplified detunings.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, Ne))
>>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]]
>>> for l in range(Nl):
... for pair in coup[l]:
... ... |
r"""Return all combinations of detunings.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, Ne))
>>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]]
>>> for l in range(Nl):
... for pair in coup[l]:
... xi[l, pair[... |
r"""Rewrite a symbolic expression in terms of allowed transition detunings.
>>> Ne = 6
>>> Nl = 2
>>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0]
>>> xi = np.zeros((Nl, Ne, Ne))
>>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]]
>>> for l in range(Nl):
... for pair in co... |
r"""Return a fast function that returns a Hamiltonian as an array.
INPUT:
- ``Ep`` - A list with the electric field amplitudes (real or complex).
- ``epsilonp`` - A list of the polarization vectors of the fields \
(real or complex).
- ``detuning_knob`` - A list of the detunings of each field (r... |
r"""Get the indices mu, nu, and term coefficients for linear terms.
>>> from fast.symbolic import define_density_matrix
>>> Ne = 2
>>> coef = 1+2j
>>> rhouv = define_density_matrix(Ne)[1, 1]
>>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1)
>>> unfolding = Unfolding(Ne, real=True, normalized=True)
... |
r"""Get the indices mu, nu, and term coefficients for linear terms.
We determine mu and nu, the indices labeling the density matrix components
d rho[mu] /dt = sum_nu A[mu, nu]*rho[nu]
for this complex and rho_u,v.
>>> from fast.symbolic import define_density_matrix
>>> Ne = 2
>>> coef = ... |
r"""Get code to calculate a linear term.
>>> term_code(1, 0, 33, False, False, True)
' rhs[1] += (33)*rho[0]\n'
def term_code(mu, nu, coef, matrix_form, rhouv_isconjugated, linear=True):
r"""Get code to calculate a linear term.
>>> term_code(1, 0, 33, False, False, True)
' rhs[1] += (33)*rh... |
r"""Return a fast function that returns the Rabi frequency terms.
We test a basic two-level system.
>>> import numpy as np
>>> from scipy.constants import physical_constants
>>> from sympy import Matrix
>>> from fast.electric_field import electric_field_amplitude_top
>>> from fast.symbolic imp... |
r"""Return a fast function that returns the Lindblad terms.
We test a basic two-level system.
>>> import numpy as np
>>> Ne = 2
>>> gamma21 = 2*np.pi*6e6
>>> gamma = np.array([[0.0, -gamma21],
... [gamma21, 0.0]])
>>> rhos = np.array([[0.6, 3+2j],
... ... |
r"""Return a fast function that returns the Hamiltonian terms.
We test a basic two-level system.
>>> import numpy as np
>>> from scipy.constants import physical_constants
>>> from sympy import Matrix, symbols
>>> from fast.electric_field import electric_field_amplitude_top
>>> from fast.symbol... |
r"""Return a fast function that returns a steady state.
We test a basic two-level system.
>>> import numpy as np
>>> from scipy.constants import physical_constants
>>> from sympy import Matrix, symbols
>>> from fast.electric_field import electric_field_amplitude_top
>>> from fast.symbolic impo... |
r"""Return a time-averaged density matrix (using trapezium rule).
We test a basic two-level system.
>>> import numpy as np
>>> from scipy.constants import physical_constants
>>> from sympy import Matrix, symbols
>>> from fast.electric_field import electric_field_amplitude_top
>>> from fast.sym... |
r"""Return an spectrum of density matrices in the steady state.
We test a basic two-level system.
>>> import numpy as np
>>> from sympy import symbols
>>> from scipy.constants import physical_constants
>>> e_num = physical_constants["elementary charge"][0]
>>> hbar_num = physical_constants["P... |
r"""Return a spectrum of time evolutions of the density matrix.
We test a basic two-level system.
>>> import numpy as np
>>> from sympy import symbols
>>> from scipy.constants import physical_constants
>>> e_num = physical_constants["elementary charge"][0]
>>> hbar_num = physical_constants["P... |
r"""Return an observable ammount.
INPUT:
- ``operator`` - An square matrix representing a hermitian operator \
in thesame basis as the density matrix.
- ``rho`` - A density matrix in unfolded format, or a list of such \
density matrices.
- ``unfolding`` - A mapping from matrix element indic... |
r"""Return the electric succeptibility for a given field.
INPUT:
- ``l`` - The index labeling the probe field.
- ``Ep`` - A list of the amplitudes of all pump fields.
- ``epsilonp`` - The polarization vector of the probe field.
- ``rm`` - The below-diagonal components of the position opera... |
r"""Return the radiated intensity in a given direction.
>>> from fast import State, Integer, split_hyperfine_to_magnetic
>>> g = State("Rb", 87, 5, 1, 3/Integer(2), 0)
>>> e = State("Rb", 87, 4, 2, 5/Integer(2), 1)
>>> magnetic_states = split_hyperfine_to_magnetic([g, e])
>>> omega0 = magnetic_stat... |
r"""Fold a vector into a matrix.
The input of this function can be a numpy array or a sympy Matrix.
If the input is understood to represent the time derivative of a
density matrix, then the flag time_derivative must be set to True.
>>> unfolding = Unfolding(2, real=True, lower_triangu... |
bdplotter is based on the fact that phonon DOS/bands and
electron DOS/bands are the objects of the same kind.
1) DOS is formatted precomputed / smeared according to a normal distribution
2) bands are formatted precomputed / interpolated through natural cubic spline function
def bdplotter(task, **kwargs):
... |
eplotter is like bdplotter but less complicated
def eplotter(task, data): # CRYSTAL, VASP, EXCITING
'''
eplotter is like bdplotter but less complicated
'''
results, color, fdata = [], None, []
if task == 'optstory':
color = '#CC0000'
clickable = True
for n, i in enumerate(d... |
r"""Return the Lande g-factors for a given atom or level.
>>> element = "Rb"
>>> isotope = 87
>>> print(lande_g_factors(element, isotope))
[ 9.9999e-01 2.0023e+00 -9.9514e-04]
The spin-orbit g-factor for a certain J
>>> print(lande_g_factors(element, isotope, L=0, J=1/Integer(2)))
... |
r"""Return Zeeman effect energies for a given fine state and\
magnetic field.
>>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2))
>>> Bz = 200.0
>>> Bz = Bz/10000
>>> for f_group in zeeman_energies(ground_state, Bz):
... print(f_group)
[-2.73736448508248e-24 -2.83044285506388... |
r"""Return Paschen-Back regime energies for a given fine state and\
magnetic field.
>>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2))
>>> Bz = 200.0
>>> Bz = Bz/10000
>>> for f_group in paschen_back_energies(ground_state, Bz):
... print(f_group)
[1.51284728917866e-24 3.8048... |
Restricts parsing
**name** is a name of the parser class
NB: this is the PUBLIC method
@procedure
def assign_parser(self, name):
'''
Restricts parsing
**name** is a name of the parser class
NB: this is the PUBLIC method
@procedure
'''
for ... |
Constructs standardized chemical formula
NB: this is the PUBLIC method
@returns formula_str
def formula(self, atom_sequence):
'''
Constructs standardized chemical formula
NB: this is the PUBLIC method
@returns formula_str
'''
labels = {}
types = [... |
Determines which files should be processed
NB: this is the PUBLIC method
@returns filenames_list
def savvyize(self, input_string, recursive=False, stemma=False):
'''
Determines which files should be processed
NB: this is the PUBLIC method
@returns filenames_list
... |
Low-level parsing
NB: this is the PRIVATE method
@returns tilde_obj, error
def _parse(self, parsable, parser_name):
'''
Low-level parsing
NB: this is the PRIVATE method
@returns tilde_obj, error
'''
calc, error = None, None
try:
for ca... |
High-level parsing:
determines the data format
and combines parent-children outputs
NB: this is the PUBLIC method
@returns tilde_obj, error
def parse(self, parsable):
'''
High-level parsing:
determines the data format
and combines parent-children outputs
... |
Reasons on normalization, invokes hierarchy API and prepares calc for saving
NB: this is the PUBLIC method
@returns tilde_obj, error
def classify(self, calc, symprec=None):
'''
Reasons on normalization, invokes hierarchy API and prepares calc for saving
NB: this is the PUBLIC me... |
Invokes module(s) API
NB: this is the PUBLIC method
@returns apps_dict
def postprocess(self, calc, with_module=None, dry_run=None):
'''
Invokes module(s) API
NB: this is the PUBLIC method
@returns apps_dict
'''
for appname, appclass in self.Apps.items():
... |
Saves tilde_obj into the database
NB: this is the PUBLIC method
@returns checksum, error
def save(self, calc, session):
'''
Saves tilde_obj into the database
NB: this is the PUBLIC method
@returns checksum, error
'''
checksum = calc.get_checksum()
... |
Deletes calc entry by checksum entirely from the database
NB source files on disk are not deleted
NB: this is the PUBLIC method
@returns error
def purge(self, session, checksum):
'''
Deletes calc entry by checksum entirely from the database
NB source files on disk are no... |
Merges calcs into a new calc called DATASET
NB: this is the PUBLIC method
@returns DATASET, error
def merge(self, session, checksums, title):
'''
Merges calcs into a new calc called DATASET
NB: this is the PUBLIC method
@returns DATASET, error
'''
calc = ... |
Augments a DATASET with some calcs
NB: this is the PUBLIC method
@returns error
def augment(self, session, parent, addendum):
'''
Augments a DATASET with some calcs
NB: this is the PUBLIC method
@returns error
'''
parent_calc = session.query(model.Calcula... |
Test whether given `filePath` is an executable. Does not really
check whether the executable is a CLI (e.g. whether it supports
--xml), but can be used to filter out non-executables within a
directory with CLI modules.
def isCLIExecutable(filePath):
"""Test whether given `filePath` is an executable. ... |
Return list of paths to valid CLI executables within baseDir (non-recursively).
This calls `isCLIExecutable()` on all files within `baseDir`.
def listCLIExecutables(baseDir):
"""Return list of paths to valid CLI executables within baseDir (non-recursively).
This calls `isCLIExecutable()` on all files withi... |
Wrapper around subprocess.Popen constructor that tries to
detect Slicer CLI modules and launches them through the Slicer
launcher in order to prevent potential DLL dependency issues.
Any kwargs are passed on to subprocess.Popen().
If you ever try to use this function to run a CLI, you might want to
... |
Call given cliExecutable with --xml and return xml ElementTree
representation of standard output.
Any kwargs are passed on to subprocess.Popen() (via popenCLIExecutable()).
def getXMLDescription(cliExecutable, **kwargs):
"""Call given cliExecutable with --xml and return xml ElementTree
representation ... |
Generates filenames of the form 'specktre_123AB.png'.
The random noise is five characters long, which allows for
62^5 = 916 million possible filenames.
def _candidate_filenames():
"""Generates filenames of the form 'specktre_123AB.png'.
The random noise is five characters long, which allows for
6... |
Given a coordinate generator and a filename, render those coordinates in
a new image and save them to the file.
def draw_tiling(coord_generator, filename):
"""Given a coordinate generator and a filename, render those coordinates in
a new image and save them to the file."""
im = Image.new('L', size=(CAN... |
Log 'msg % args' with severity 'TRACE'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.trace("Houston, we have a %s", "thorny problem", exc_info=1)
def trace(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'TRACE'.
To pass exce... |
Registers an error for this container with code on line at char.
:param code: The PEP 8 error code
:param line: The line number of the reported error
:param char: Line location of first offending character
:param description: The human readable description of the thrown error/warning
de... |
Simple utility method to ensure an argument provided is a list. If the
provider argument is not an instance of `list`, then we return [arg], else
arg is returned.
:type arg: list
:rtype: list
def listify(arg):
"""
Simple utility method to ensure an argument provided is a list. If the
provi... |
Resolves a setting for a configuration option. The winning value is chosen
from multiple methods of configuration, in the following order of priority
(top first):
- Explicitly passed argument
- Environment variable
- Configuration file entry
- Default
:param arg_value: Explicitly passed va... |
Retrieve the state of a given Class.
:param clz: types.ClassType
:return: Class state.
:rtype: dict
def get_state(cls, clz):
"""
Retrieve the state of a given Class.
:param clz: types.ClassType
:return: Class state.
:rtype: dict
"""
if c... |
https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/UniqueObject
Checks if ORM entity exists according to criteria,
if yes, returns it, if no, creates
def _unique(session, cls, queryfunc, constructor, arg, kw):
'''
https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/UniqueObject
Checks ... |
Checks if ORM entity exists according to criteria,
if yes, returns it, if no, returns dict representation
(required for further DB replication and syncing)
def _unique_todict(session, cls, queryfunc, arg, kw):
'''
Checks if ORM entity exists according to criteria,
if yes, returns it, if no, returns... |
r"""Return a symbolic density matrix.
The arguments are
Ne (integer):
The number of atomic states.
explicitly_hermitian (boolean):
Whether to make $\rho_{ij}=\bar{\rho}_{ij}$ for $i<j$
normalized (boolean):
Whether to make $\rho_{11}=1-\sum_{i>1} \rho_{ii}$
A very simple e... |
r"""Return the amplitudes and frequencies of Nl fields.
>>> E0, omega_laser = define_laser_variables(2)
>>> E0, omega_laser
([E_0^1, E_0^2], [varpi_1, varpi_2])
The amplitudes are complex by default:
>>> conjugate(E0[0])
conjugate(E_0^1)
But they can optionally be made real:
>>> E0, o... |
r"""This function returns a unitary vector describing the polarization
of plane waves. It recieves as arguments:
phi .- The spherical coordinates azimuthal angle of the wave vector k.
theta .- The spherical coordinates polar angle of the wave vector k.
alpha .- The rotation of a half-wave plate.
... |
r"""This function returns the action of a Lindblad operator A on a density
matrix rho. This is defined as :
L(A,rho) = A*rho*A.adjoint()
- (A.adjoint()*A*rho + rho*A.adjoint()*A)/2.
>>> rho=define_density_matrix(3)
>>> lindblad_operator( ketbra(1,2,3) ,rho )
Matrix([
[ rh... |
Returns iterable of all mass email recipients.
Default behavior will be to return list of all active users' emails.
This can be changed by providing callback in settings return some other list of users,
when user emails are stored in many, non default models.
To accomplish that add constant MASS_EMAIL_R... |
r"""A function to plot complex matrices.
def complex_matrix_plot(A, logA=False, normalize=False, plot=True, **kwds):
r"""A function to plot complex matrices."""
N = len(A[0])
if logA:
Anew = []
for i in range(N):
row = []
for j in range(N):
if... |
Make a bar chart for data on MF quantities.
def bar_chart_mf(data, path_name):
"""Make a bar chart for data on MF quantities."""
N = len(data)
ind = np.arange(N) # the x locations for the groups
width = 0.8 # the width of the bars
fig, ax = pyplot.subplots()
rects1 = ax.bar(ind... |
Draw the polarization of a plane wave.
def draw_plane_wave_3d(ax, beam, dist_to_center=0):
"""Draw the polarization of a plane wave."""
Ex = []; Ey = []; Ez = []
k = [cos(beam.phi)*sin(beam.theta),
sin(beam.phi)*sin(beam.theta),
cos(beam.theta)]
kx, ky, kz = k
Nt = 1000... |
Draw MOT lasers in 3d.
def draw_lasers_3d(ax, lasers, name=None, distances=None, lim=None):
"""Draw MOT lasers in 3d."""
if distances is None: distances = [1.0 for i in range(len(lasers))]
for i in range(len(lasers)):
if type(lasers[i]) == PlaneWave:
draw_plane_wave_3d(ax, lasers[i... |
r"""Plot the populations of a density matrix.
def plot_populations(path, name, Ne, states=None, filename='a.png',
fontsize=12, absolute_frequency=True,
save_path='', use_netcdf=True):
r"""Plot the populations of a density matrix."""
pyplot.close("all")
dat = r... |
r"""Rotate and translate a curve.
def rotate_and_traslate(cur, alpha, v0):
r"""Rotate and translate a curve."""
if len(cur) > 2 or (type(cur[0][0]) in [list, tuple]):
cur_list = cur[:]
for i in range(len(cur_list)):
curi = cur_list[i]
curi = rotate_and_traslate(cur... |
r"""Draw a mirror.
def mirror(ax, p0, alpha=0, size=2.54, width=0.5, format=None):
r"""Draw a mirror."""
if format is None: format = 'k-'
x0 = [size/2, -size/2, -size/2, size/2, size/2]
y0 = [0, 0, -width, -width, 0]
x1 = [size/2, size/2-width]; y1 = [0, -width]
x2 = [-size/2+width, -... |
r"""Draw an eye.
def eye(ax, p0, size=1.0, alpha=0, format=None, **kwds):
r"""Draw an eye."""
if format is None: format = 'k-'
N = 100
ang0 = pi-3*pi/16; angf = pi+3*pi/16
angstep = (angf-ang0)/(N-1)
x1 = [size*(cos(i*angstep+ang0)+1) for i in range(N)]
y1 = [size*sin(i*angstep+ang... |
r"""Draw a beam splitter.
def beam_splitter(ax, p0, size=2.54, alpha=0, format=None, **kwds):
r"""Draw a beam splitter."""
if format is None: format = 'k-'
a = size/2
x0 = [a, -a, -a, a, a, -a]
y0 = [a, a, -a, -a, a, -a]
cur_list = [(x0, y0)]
cur_list = rotate_and_traslate(cur_list... |
r"""Draw a laser beam.
def draw_beam(ax, p1, p2, width=0, beta1=None, beta2=None,
format=None, **kwds):
r"""Draw a laser beam."""
if format is None: format = 'k-'
if width == 0:
x0 = [p1[0], p2[0]]
y0 = [p1[1], p2[1]]
ax.plot(x0, y0, format, **kwds)
else:... |
r"""Draw a simple beam splitter.
def simple_beam_splitter(ax, p0, size=2.54, width=0.1, alpha=0,
format=None, **kwds):
r"""Draw a simple beam splitter."""
if format is None: format = 'k-'
a = size/2
b = width/2
x0 = [a, -a, -a, a, a]
y0 = [b, b, -b, -b, b]
... |
r"""Draw an arithmetic operator.
def draw_arith(ax, p0, size=1, alpha=0, arith=None, format=None,
fontsize=10, **kwds):
r"""Draw an arithmetic operator."""
if format is None: format = 'k-'
a = size/2.0
x0 = [0, 2.5*a, 0, 0]
y0 = [a, 0, -a, a]
cur_list = [(x0, y0)]
c... |
r"""Draw a quantum state for energy level diagrams.
def draw_state(ax, p, text='', l=0.5, alignment='left', label_displacement=1.0,
fontsize=25, atoms=None, atoms_h=0.125, atoms_size=5, **kwds):
r"""Draw a quantum state for energy level diagrams."""
ax.plot([p[0]-l/2.0, p[0]+l/2.0], [p[1], p[... |
r"""We draw a multiplet.
def draw_multiplet(ax, fine_state, p, hmin, w, fside='right',
label_separation=1, label_fontsize=15, fsize=10,
deltanu_fontsize=6, proportional=False, text='',
text_pos='top', magnetic_lines=False, **kwds):
r"""We draw a multiple... |
r"""Draw a spontaneous decay as a wavy line.
def decay(ax, p0, pf, A, n, format=None, **kwds):
r"""Draw a spontaneous decay as a wavy line."""
if format is None: format = 'k-'
T = sqrt((p0[0]-pf[0])**2+(p0[1]-pf[1])**2)
alpha = atan2(pf[1]-p0[1], pf[0]-p0[0])
x = [i*T/400.0 for i in range(40... |
Like os.dup2, but retry on EBUSY
def dup2(a, b, timeout=3):
"""Like os.dup2, but retry on EBUSY"""
dup_err = None
# give FDs 3 seconds to not be busy anymore
for i in range(int(10 * timeout)):
try:
return os.dup2(a, b)
except OSError as e:
dup_err = e
... |
Capture C-level stdout/stderr in a context manager.
The return value for the context manager is (stdout, stderr).
Examples
--------
>>> with capture() as (stdout, stderr):
... printf("C-level stdout")
... output = stdout.read()
def pipes(stdout=PIPE, stderr=PIPE, encoding=_default_encodi... |
Redirect C-level stdout/stderr to sys.stdout/stderr
This is useful of sys.sdout/stderr are already being forwarded somewhere.
DO NOT USE THIS if sys.stdout and sys.stderr are not already being forwarded.
def sys_pipes(encoding=_default_encoding):
"""Redirect C-level stdout/stderr to sys.stdout/st... |
Redirect all C output to sys.stdout/err
This is not a context manager; it turns on C-forwarding permanently.
def sys_pipes_forever(encoding=_default_encoding):
"""Redirect all C output to sys.stdout/err
This is not a context manager; it turns on C-forwarding permanently.
"""
global _might... |
Register me as an IPython extension
Captures all C output during execution and forwards to sys.
Does nothing on terminal IPython.
Use: %load_ext wurlitzer
def load_ipython_extension(ip):
"""Register me as an IPython extension
Captures all C output during execution and forwards t... |
Unload me as an IPython extension
Use: %unload_ext wurlitzer
def unload_ipython_extension(ip):
"""Unload me as an IPython extension
Use: %unload_ext wurlitzer
"""
if not getattr(ip, 'kernel'):
return
ip.events.unregister('pre_execute', sys_pipes_forever)
ip.events.unregist... |
Decode data, if any
Called before passing to stdout/stderr streams
def _decode(self, data):
"""Decode data, if any
Called before passing to stdout/stderr streams
"""
if self.encoding:
data = data.decode(self.encoding, 'replace')
return data |
Add a filter to the tokenizer chain.
def push_filters(self, new_filters):
"""Add a filter to the tokenizer chain.
"""
t = self.tokenizer
for f in new_filters:
t = f(t)
self.tokenizer = t |
Yields bad words and suggested alternate spellings.
def check(self, text):
"""Yields bad words and suggested alternate spellings.
"""
for word, pos in self.tokenizer(text):
correct = self.dictionary.check(word)
if correct:
continue
yield word,... |
Gets the name of the service from the port
all_services allows you to feed in the services to look through, pass
in a dict of service names to service information eg.
{
'service_name': {
'port': port_number
}
}
Returns the name of the service
def get_service_from_po... |
If run_only, returns only the services that are in the runs_on list.
If deploy_to_only, returns only the services in the deployed_to list.
If neither, both are returned, duplicates stripped.
Results are always sorted.
def all_nodes_that_receive(service, service_configuration=None, run_only=False, deploy_to... |
Returns all nodes that run in an environment. This needs
to be specified in field named 'env_runs_on' one level under services
in the configuration, and needs to contain an object which maps strings
to lists (environments to nodes).
:param service: A string specifying which service to look up nodes for... |
From a float, decide what precision and scale are needed to represent it.
>>> precision_and_scale(54.2)
(3, 1)
>>> precision_and_scale(9)
(1, 0)
Thanks to Mark Ransom,
http://stackoverflow.com/questions/3018758/determine-precision-and-scale-of-particular-number-in-python
def precision_and_sca... |
Coerces datum to the most specific data type possible
Order of preference: datetime, boolean, integer, decimal, float, string
>>> coerce_to_specific('-000000001854.60')
Decimal('-1854.60')
>>> coerce_to_specific(7.2)
Decimal('7.2')
>>> coerce_to_specific("Jan 17 2012")
datetime.datetime(201... |
>>> _places_b4_and_after_decimal(Decimal('54.212'))
(2, 3)
def _places_b4_and_after_decimal(d):
"""
>>> _places_b4_and_after_decimal(Decimal('54.212'))
(2, 3)
"""
tup = d.as_tuple()
return (len(tup.digits) + tup.exponent, max(-1*tup.exponent, 0)) |
Given two Decimals, return a 9-filled decimal representing both enough > 0 digits
and enough < 0 digits (scale) to accomodate numbers like either.
>>> worst_decimal(Decimal('762.1'), Decimal('-1.983'))
Decimal('999.999')
def worst_decimal(d1, d2):
"""
Given two Decimals, return a 9-filled decimal ... |
Pad new_worst with zeroes to prevent it being shorter than old_worst.
>>> set_worst(311920, '48-49')
'48-490'
>>> set_worst(98, -2)
-20
def set_worst(old_worst, new_worst):
"""
Pad new_worst with zeroes to prevent it being shorter than old_worst.
>>> set_worst(311920, '48-49')
... |
Given two objects each coerced to the most specific type possible, return the one
of the least restrictive type.
>>> best_representative(Decimal('-37.5'), Decimal('0.9999'))
Decimal('-99.9999')
>>> best_representative(None, Decimal('6.1'))
Decimal('6.1')
>>> best_representative(311920, '48-49')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.