INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Add a valid set of credentials to be accepted for authentication. Calling this function will automatically enable requiring authentication. Passwords can be provided in either plaintext or as a hash by specifying the hash type in the * pwtype * argument. | def auth_add_creds(self, username, password, pwtype='plain'):
"""
Add a valid set of credentials to be accepted for authentication.
Calling this function will automatically enable requiring
authentication. Passwords can be provided in either plaintext or
as a hash by specifying the hash type in the *pwtype* a... |
Context manager to temporarily change the values of object attributes while executing a function. | def setattr_context(obj, **kwargs):
"""
Context manager to temporarily change the values of object attributes
while executing a function.
Example
-------
>>> class Foo: pass
>>> f = Foo(); f.attr = 'hello'
>>> with setattr_context(f, attr='goodbye'):
... print(f.attr)
goodby... |
Validate input arrays | def validate_inputs(*arrays, **kwargs):
"""Validate input arrays
This checks that
- Arrays are mutually broadcastable
- Broadcasted arrays are one-dimensional
Optionally, arrays are sorted according to the ``sort_by`` argument.
Parameters
----------
*args : ndarrays
All non-ke... |
Private function to prepare & check variables for smooth utilities | def _prep_smooth(t, y, dy, span, t_out, span_out, period):
"""Private function to prepare & check variables for smooth utilities"""
# If period is provided, sort by phases. Otherwise sort by t
if period:
t = t % period
if t_out is not None:
t_out = t_out % period
t, y, dy =... |
Perform a moving - average smooth of the data | def moving_average_smooth(t, y, dy, span=None, cv=True,
t_out=None, span_out=None, period=None):
"""Perform a moving-average smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
t... |
Perform a linear smooth of the data | def linear_smooth(t, y, dy, span=None, cv=True,
t_out=None, span_out=None, period=None):
"""Perform a linear smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
the integer spans of the ... |
Multiple linear interpolations | def multinterp(x, y, xquery, slow=False):
"""Multiple linear interpolations
Parameters
----------
x : array_like, shape=(N,)
sorted array of x values
y : array_like, shape=(N, M)
array of y values corresponding to each x value
xquery : array_like, shape=(M,)
array of que... |
Create a consulate. session object and query for its leader to ensure that the connection is made. | def _create_session(self, test_connection=False):
"""
Create a consulate.session object, and query for its leader to ensure
that the connection is made.
:param test_connection: call .leader() to ensure that the connection
is valid
:type test_connection: bool
... |
Applies all config values defined in consul s kv store to self. app. | def apply_remote_config(self, namespace=None):
"""
Applies all config values defined in consul's kv store to self.app.
There is no guarantee that these values will not be overwritten later
elsewhere.
:param namespace: kv namespace/directory. Defaults to
DEFAULT_... |
register this service with consul kwargs passed to Consul. agent. service. register | def register_service(self, **kwargs):
"""
register this service with consul
kwargs passed to Consul.agent.service.register
"""
kwargs.setdefault('name', self.app.name)
self.session.agent.service.register(**kwargs) |
Query the consul DNS server for the service IP and port | def _resolve(self):
"""
Query the consul DNS server for the service IP and port
"""
endpoints = {}
r = self.resolver.query(self.service, 'SRV')
for rec in r.response.additional:
name = rec.name.to_text()
addr = rec.items[0].address
endp... |
Proxy to requests. request: param method: str formatted http method: param endpoint: service endpoint: param kwargs: kwargs passed directly to requests. request: return: | def request(self, method, endpoint, **kwargs):
"""
Proxy to requests.request
:param method: str formatted http method
:param endpoint: service endpoint
:param kwargs: kwargs passed directly to requests.request
:return:
"""
kwargs.setdefault('timeout', (1, ... |
Decorator that wraps an entire function in a try/ except clause. On requests. exceptions. ConnectionError will re - run the function code until success or max_tries is reached. | def with_retry_connections(max_tries=3, sleep=0.05):
"""
Decorator that wraps an entire function in a try/except clause. On
requests.exceptions.ConnectionError, will re-run the function code
until success or max_tries is reached.
:param max_tries: maximum number of attempts before giving up
:pa... |
Crop the generator to a finite number of frames | def crop(gens, seconds=5, cropper=None):
'''
Crop the generator to a finite number of frames
Return a generator which outputs the provided generator limited
to enough samples to produce seconds seconds of audio (default 5s)
at the provided frame rate.
'''
if hasattr(gens, "next"):
# single generator
gens = ... |
Crop the generator ending at a zero - crossing | def crop_at_zero_crossing(gen, seconds=5, error=0.1):
'''
Crop the generator, ending at a zero-crossing
Crop the generator to produce approximately seconds seconds
(default 5s) of audio at the provided FRAME_RATE, attempting
to end the clip at a zero crossing point to avoid clicking.
'''
source = iter(gen)
... |
Change the volume of gen by dB decibles | def volume(gen, dB=0):
'''Change the volume of gen by dB decibles'''
if not hasattr(dB, 'next'):
# not a generator
scale = 10 ** (dB / 20.)
else:
def scale_gen():
while True:
yield 10 ** (next(dB) / 20.)
scale = scale_gen()
return envelope(gen, scale) |
Mix inputs together based on mix tuple | def mixer(inputs, mix=None):
'''
Mix `inputs` together based on `mix` tuple
`inputs` should be a tuple of *n* generators.
`mix` should be a tuple of *m* tuples, one per desired
output channel. Each of the *m* tuples should contain
*n* generators, corresponding to the time-sequence of
the desired mix levels f... |
Break multi - channel generator into one sub - generator per channel | def channelize(gen, channels):
'''
Break multi-channel generator into one sub-generator per channel
Takes a generator producing n-tuples of samples and returns n generators,
each producing samples for a single channel.
Since multi-channel generators are the only reasonable way to synchronize samples
across chan... |
Returns True if file f is seekable and False if not Useful to determine for example if f is STDOUT to a pipe. | def file_is_seekable(f):
'''
Returns True if file `f` is seekable, and False if not
Useful to determine, for example, if `f` is STDOUT to
a pipe.
'''
try:
f.tell()
logger.info("File is seekable!")
except IOError, e:
if e.errno == errno.ESPIPE:
return False
else:
raise
return True |
Convert audio waveform generator into packed sample generator. | def sample(generator, min=-1, max=1, width=SAMPLE_WIDTH):
'''Convert audio waveform generator into packed sample generator.'''
# select signed char, short, or in based on sample width
fmt = { 1: '<B', 2: '<h', 4: '<i' }[width]
return (struct.pack(fmt, int(sample)) for sample in \
normalize(hard_clip(generator, m... |
Convert list of audio waveform generators into list of packed sample generators. | def sample_all(generators, *args, **kwargs):
'''Convert list of audio waveform generators into list of packed sample generators.'''
return [sample(gen, *args, **kwargs) for gen in generators] |
Buffer the generator into byte strings of buffer_size samples | def buffer(stream, buffer_size=BUFFER_SIZE):
'''
Buffer the generator into byte strings of buffer_size samples
Return a generator that outputs reasonably sized byte strings
containing buffer_size samples from the generator stream.
This allows us to outputing big chunks of the audio stream to
disk at once for ... |
True if wave module can write data size of 0xFFFFFFFF False otherwise. | def wave_module_patched():
'''True if wave module can write data size of 0xFFFFFFFF, False otherwise.'''
f = StringIO()
w = wave.open(f, "wb")
w.setparams((1, 2, 44100, 0, "NONE", "no compression"))
patched = True
try:
w.setnframes((0xFFFFFFFF - 36) / w.getnchannels() / w.getsampwidth())
w._ensure_header_writ... |
Decorator to cache audio samples produced by the wrapped generator. | def cache_finite_samples(f):
'''Decorator to cache audio samples produced by the wrapped generator.'''
cache = {}
def wrap(*args):
key = FRAME_RATE, args
if key not in cache:
cache[key] = [sample for sample in f(*args)]
return (sample for sample in cache[key])
return wrap |
Play the contents of the generator using PyAudio | def play(channels, blocking=True, raw_samples=False):
'''
Play the contents of the generator using PyAudio
Play to the system soundcard using PyAudio. PyAudio, an otherwise optional
depenency, must be installed for this feature to work.
'''
if not pyaudio_loaded:
raise Exception("Soundcard playback requires P... |
Compute the windowed sum of the given arrays. | def windowed_sum_slow(arrays, span, t=None, indices=None, tpowers=0,
period=None, subtract_mid=False):
"""Compute the windowed sum of the given arrays.
This is a slow function, used primarily for testing and validation
of the faster version of ``windowed_sum()``
Parameters
--... |
Compute the windowed sum of the given arrays. | def windowed_sum(arrays, span, t=None, indices=None, tpowers=0,
period=None, subtract_mid=False):
"""Compute the windowed sum of the given arrays.
Parameters
----------
arrays : tuple of arrays
arrays to window
span : int or array of ints
The span to use for the sum... |
Internal routine to pad arrays for periodic models. | def _pad_arrays(t, arrays, indices, span, period):
"""Internal routine to pad arrays for periodic models."""
N = len(t)
if indices is None:
indices = np.arange(N)
pad_left = max(0, 0 - np.min(indices - span // 2))
pad_right = max(0, np.max(indices + span - span // 2) - (N - 1))
if pad_... |
Search all the available I2C devices in the system | def get_i2c_bus_numbers(glober = glob.glob):
"""Search all the available I2C devices in the system"""
res = []
for device in glober("/dev/i2c-*"):
r = re.match("/dev/i2c-([\d]){1,2}", device)
res.append(int(r.group(1)))
return res |
Parse the name for led number | def get_led_register_from_name(self, name):
"""Parse the name for led number
:param name: attribute name, like: led_1
"""
res = re.match('^led_([0-9]{1,2})$', name)
if res is None:
raise AttributeError("Unknown attribute: '%s'" % name)
led_num = int(res.group... |
Set PWM value for the specified LED | def set_pwm(self, led_num, value):
"""Set PWM value for the specified LED
:param led_num: LED number (0-15)
:param value: the 12 bit value (0-4095)
"""
self.__check_range('led_number', led_num)
self.__check_range('led_value', value)
register_low = self.calc_led_... |
Generic getter for all LED PWM value | def get_pwm(self, led_num):
"""Generic getter for all LED PWM value"""
self.__check_range('led_number', led_num)
register_low = self.calc_led_register(led_num)
return self.__get_led_value(register_low) |
Send the controller to sleep | def sleep(self):
"""Send the controller to sleep"""
logger.debug("Sleep the controller")
self.write(Registers.MODE_1, self.mode_1 | (1 << Mode1.SLEEP)) |
Write raw byte value to the specified register | def write(self, reg, value):
"""Write raw byte value to the specified register
:param reg: the register number (0-69, 250-255)
:param value: byte value
"""
# TODO: check reg: 0-69, 250-255
self.__check_range('register_value', value)
logger.debug("Write '%s' to re... |
Set the frequency for all PWM output | def set_pwm_frequency(self, value):
"""Set the frequency for all PWM output
:param value: the frequency in Hz
"""
self.__check_range('pwm_frequency', value)
reg_val = self.calc_pre_scale(value)
logger.debug("Calculated prescale value is %s" % reg_val)
self.sleep(... |
Calculates the normalized Levenshtein distance between two string arguments. The result will be a float in the range [ 0. 0 1. 0 ] with 1. 0 signifying the biggest possible distance between strings with these lengths | def levenshtein_norm(source, target):
"""Calculates the normalized Levenshtein distance between two string
arguments. The result will be a float in the range [0.0, 1.0], with 1.0
signifying the biggest possible distance between strings with these lengths
"""
# Compute Levenshtein distance using hel... |
Check if the color provided by the user is valid. | def check_valid_color(color):
"""Check if the color provided by the user is valid.
If color is invalid the default is returned.
"""
if color in list(mcolors.CSS4_COLORS.keys()) + ["#4CB391"]:
logging.info("Nanoplotter: Valid color {}.".format(color))
return color
else:
loggi... |
Check if the specified figure format is valid. | def check_valid_format(figformat):
"""Check if the specified figure format is valid.
If format is invalid the default is returned.
Probably installation-dependent
"""
fig = plt.figure()
if figformat in list(fig.canvas.get_supported_filetypes().keys()):
logging.info("Nanoplotter: valid o... |
Create bivariate plots. | def scatter(x, y, names, path, plots, color="#4CB391", figformat="png",
stat=None, log=False, minvalx=0, minvaly=0, title=None, plot_settings=None):
"""Create bivariate plots.
Create four types of bivariate plots of x vs y, containing marginal summaries
-A scatter plot with histograms on axes
... |
Make sure both arrays for bivariate ( scatter ) plot have a stddev > 0 | def contains_variance(arrays, names):
"""
Make sure both arrays for bivariate ("scatter") plot have a stddev > 0
"""
for ar, name in zip(arrays, names):
if np.std(ar) == 0:
sys.stderr.write(
"No variation in '{}', skipping bivariate plots.\n".format(name.lower()))
... |
Create histogram of normal and log transformed read lengths. | def length_plots(array, name, path, title=None, n50=None, color="#4CB391", figformat="png"):
"""Create histogram of normal and log transformed read lengths."""
logging.info("Nanoplotter: Creating length plots for {}.".format(name))
maxvalx = np.amax(array)
if n50:
logging.info("Nanoplotter: Usin... |
Make the physical layout of the MinION flowcell. based on https:// bioinformatics. stackexchange. com/ a/ 749/ 681 returned as a numpy array | def make_layout(maxval):
"""Make the physical layout of the MinION flowcell.
based on https://bioinformatics.stackexchange.com/a/749/681
returned as a numpy array
"""
if maxval > 512:
return Layout(
structure=np.concatenate([np.array([list(range(10 * i + 1, i * 10 + 11))
... |
Taking channel information and creating post run channel activity plots. | def spatial_heatmap(array, path, title=None, color="Greens", figformat="png"):
"""Taking channel information and creating post run channel activity plots."""
logging.info("Nanoplotter: Creating heatmap of reads per channel using {} reads."
.format(array.size))
activity_map = Plot(
p... |
Generate CSV files from a CronosPro/ CronosPlus database. | def main(database_dir, target_dir):
"""Generate CSV files from a CronosPro/CronosPlus database."""
if not os.path.isdir(database_dir):
raise click.ClickException("Database directory does not exist!")
try:
os.makedirs(target_dir)
except:
pass
try:
parse(database_dir, t... |
Check if the data contains reads created within the same days timeframe. | def check_valid_time_and_sort(df, timescol, days=5, warning=True):
"""Check if the data contains reads created within the same `days` timeframe.
if not, print warning and only return part of the data which is within `days` days
Resetting the index twice to get also an "index" column for plotting the cum_yi... |
Making plots of time vs read length time vs quality and cumulative yield. | def time_plots(df, path, title=None, color="#4CB391", figformat="png",
log_length=False, plot_settings=None):
"""Making plots of time vs read length, time vs quality and cumulative yield."""
dfs = check_valid_time_and_sort(df, "start_time")
logging.info("Nanoplotter: Creating timeplots using ... |
Create a violin or boxplot from the received DataFrame. | def violin_or_box_plot(df, y, figformat, path, y_name,
title=None, plot="violin", log=False, palette=None):
"""Create a violin or boxplot from the received DataFrame.
The x-axis should be divided based on the 'dataset' column,
the y-axis is specified in the arguments
"""
comp... |
Create barplots based on number of reads and total sum of nucleotides sequenced. | def output_barplot(df, figformat, path, title=None, palette=None):
"""Create barplots based on number of reads and total sum of nucleotides sequenced."""
logging.info("Nanoplotter: Creating barplots for number of reads and total throughput.")
read_count = Plot(path=path + "NanoComp_number_of_reads." + figfo... |
Use plotly to create an overlay of length histograms Return html code but also save as png | def overlay_histogram(df, path, palette=None):
"""
Use plotly to create an overlay of length histograms
Return html code, but also save as png
Only has 10 colors, which get recycled up to 5 times.
"""
if palette is None:
palette = plotly.colors.DEFAULT_PLOTLY_COLORS * 5
hist = Plot... |
Plot overlaying histograms with log transformation of length Return both html and fig for png | def plot_log_histogram(df, palette, title, histnorm=""):
"""
Plot overlaying histograms with log transformation of length
Return both html and fig for png
"""
data = [go.Histogram(x=np.log10(df.loc[df["dataset"] == d, "lengths"]),
opacity=0.4,
name=d... |
Glob for the poor. | def get_file(db_folder, file_name):
"""Glob for the poor."""
if not os.path.isdir(db_folder):
return
file_name = file_name.lower().strip()
for cand_name in os.listdir(db_folder):
if cand_name.lower().strip() == file_name:
return os.path.join(db_folder, cand_name) |
Parse a cronos database. | def parse(db_folder, out_folder):
"""
Parse a cronos database.
Convert the database located in ``db_folder`` into CSV files in the
directory ``out_folder``.
"""
# The database structure, containing table and column definitions as
# well as other data.
stru_dat = get_file(db_folder, 'Cro... |
Return the base64 encoding of the figure file and insert in html image tag. | def encode1(self):
"""Return the base64 encoding of the figure file and insert in html image tag."""
data_uri = b64encode(open(self.path, 'rb').read()).decode('utf-8').replace('\n', '')
return '<img src="data:image/png;base64,{0}">'.format(data_uri) |
Return the base64 encoding of the fig attribute and insert in html image tag. | def encode2(self):
"""Return the base64 encoding of the fig attribute and insert in html image tag."""
buf = BytesIO()
self.fig.savefig(buf, format='png', bbox_inches='tight', dpi=100)
buf.seek(0)
string = b64encode(buf.read())
return '<img src="data:image/png;base64,{0}"... |
Calculates the normalized restricted Damerau - Levenshtein distance ( a. k. a. the normalized optimal string alignment distance ) between two string arguments. The result will be a float in the range [ 0. 0 1. 0 ] with 1. 0 signifying the maximum distance between strings with these lengths | def rdlevenshtein_norm(source, target):
"""Calculates the normalized restricted Damerau-Levenshtein distance
(a.k.a. the normalized optimal string alignment distance) between two
string arguments. The result will be a float in the range [0.0, 1.0], with
1.0 signifying the maximum distance between string... |
Computes the Levenshtein ( https:// en. wikipedia. org/ wiki/ Levenshtein_distance ) and restricted Damerau - Levenshtein ( https:// en. wikipedia. org/ wiki/ Damerau%E2%80%93Levenshtein_distance ) distances between two Unicode strings with given lengths using the Wagner - Fischer algorithm ( https:// en. wikipedia. or... | def _levenshtein_compute(source, target, rd_flag):
"""Computes the Levenshtein
(https://en.wikipedia.org/wiki/Levenshtein_distance)
and restricted Damerau-Levenshtein
(https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
distances between two Unicode strings with given lengths using t... |
The main entry point. | def main():
"""The main entry point."""
if sys.version_info < (2, 7):
sys.exit('crispy requires at least Python 2.7')
elif sys.version_info[0] == 3 and sys.version_info < (3, 4):
sys.exit('crispy requires at least Python 3.4')
kwargs = dict(
name='crispy',
version=get_ve... |
Read the spectra from the files generated by Quanty and store them as a list of spectum objects. | def loadFromDisk(self, calculation):
"""
Read the spectra from the files generated by Quanty and store them
as a list of spectum objects.
"""
suffixes = {
'Isotropic': 'iso',
'Circular Dichroism (R-L)': 'cd',
'Right Polarized (R)': 'r',
... |
Populate the widget using data stored in the state object. The order in which the individual widgets are populated follows their arrangment. | def populateWidget(self):
"""
Populate the widget using data stored in the state
object. The order in which the individual widgets are populated
follows their arrangment.
The models are recreated every time the function is called.
This might seem to be an overkill, but i... |
Update the selection to contain only the result specified by the index. This should be the last index of the model. Finally updade the context menu. | def updateResultsView(self, index):
"""
Update the selection to contain only the result specified by
the index. This should be the last index of the model. Finally updade
the context menu.
The selectionChanged signal is used to trigger the update of
the Quanty dock widge... |
Updating the plotting widget should not require any information about the current state of the widget. | def updatePlotWidget(self):
"""Updating the plotting widget should not require any information
about the current state of the widget."""
pw = self.getPlotWidget()
pw.reset()
results = self.resultsModel.getCheckedItems()
for result in results:
if isinstance(r... |
Return the row of the child. | def row(self):
"""Return the row of the child."""
if self.parent is not None:
children = self.parent.getChildren()
# The index method of the list object.
return children.index(self)
else:
return 0 |
Return the index of the item in the model specified by the given row column and parent index. | def index(self, row, column, parent=QModelIndex()):
"""Return the index of the item in the model specified by the
given row, column, and parent index.
"""
if parent is not None and not parent.isValid():
parentItem = self.rootItem
else:
parentItem = self.it... |
Return the index of the parent for a given index of the child. Unfortunately the name of the method has to be parent even though a more verbose name like parentIndex would avoid confusion about what parent actually is - an index or an item. | def parent(self, index):
"""Return the index of the parent for a given index of the
child. Unfortunately, the name of the method has to be parent,
even though a more verbose name like parentIndex, would avoid
confusion about what parent actually is - an index or an item.
"""
... |
Return the number of rows under the given parent. When the parentIndex is valid rowCount () returns the number of children of the parent. For this it uses item () method to extract the parentItem from the parentIndex and calls the childCount () of the item to get number of children. | def rowCount(self, parentIndex):
"""Return the number of rows under the given parent. When the
parentIndex is valid, rowCount() returns the number of children
of the parent. For this it uses item() method to extract the
parentItem from the parentIndex, and calls the childCount() of
... |
Return role specific data for the item referred by index. column (). | def data(self, index, role):
"""Return role specific data for the item referred by
index.column()."""
if not index.isValid():
return
item = self.item(index)
column = index.column()
value = item.getItemData(column)
if role == Qt.DisplayRole:
... |
Set the role data for the item at index to value. | def setData(self, index, value, role):
"""Set the role data for the item at index to value."""
if not index.isValid():
return False
item = self.item(index)
column = index.column()
if role == Qt.EditRole:
items = list()
items.append(item)
... |
Return the active flags for the given index. Add editable flag to items other than the first column. | def flags(self, index):
"""Return the active flags for the given index. Add editable
flag to items other than the first column.
"""
activeFlags = (Qt.ItemIsEnabled | Qt.ItemIsSelectable |
Qt.ItemIsUserCheckable)
item = self.item(index)
column = ind... |
Return the data contained in the model. | def _getModelData(self, modelData, parentItem=None):
"""Return the data contained in the model."""
if parentItem is None:
parentItem = self.rootItem
for item in parentItem.getChildren():
key = item.getItemData(0)
if item.childCount():
modelDat... |
Return the check state ( disabled tristate enable ) of all items belonging to a parent. | def getNodesCheckState(self, parentItem=None):
"""Return the check state (disabled, tristate, enable) of all items
belonging to a parent.
"""
if parentItem is None:
parentItem = self.rootItem
checkStates = odict()
children = parentItem.getChildren()
... |
Calculate the hexadecimal version number from the tuple version_info: | def calc_hexversion(major=0, minor=0, micro=0, releaselevel='dev', serial=0):
"""Calculate the hexadecimal version number from the tuple version_info:
:param major: integer
:param minor: integer
:param micro: integer
:param relev: integer or string
:param serial: integer
:return: integerm a... |
Handle plot area customContextMenuRequested signal. | def _contextMenu(self, pos):
"""Handle plot area customContextMenuRequested signal.
:param QPoint pos: Mouse position relative to plot area
"""
# Create the context menu.
menu = QMenu(self)
menu.addAction(self._zoomBackAction)
# Displaying the context menu at th... |
Convolve an array with a kernel using FFT. Implemntation based on the convolve_fft function from astropy. | def convolve_fft(array, kernel):
"""
Convolve an array with a kernel using FFT.
Implemntation based on the convolve_fft function from astropy.
https://github.com/astropy/astropy/blob/master/astropy/convolution/convolve.py
"""
array = np.asarray(array, dtype=np.complex)
kernel = np.asarray(... |
Diagonalize the tensor. | def diagonalize(self):
'''Diagonalize the tensor.'''
self.eigvals, self.eigvecs = np.linalg.eig(
(self.tensor.transpose() + self.tensor) / 2.0)
self.eigvals = np.diag(np.dot(
np.dot(self.eigvecs.transpose(), self.tensor), self.eigvecs)) |
Calculate the Euler angles only if the rotation matrix ( eigenframe ) has positive determinant. | def euler_angles_and_eigenframes(self):
'''Calculate the Euler angles only if the rotation matrix
(eigenframe) has positive determinant.'''
signs = np.array([[1, 1, 1], [-1, 1, 1], [1, -1, 1],
[1, 1, -1], [-1, -1, 1], [-1, 1, -1],
[1, -1, -1... |
Skip a number of lines from the output. | def _skip_lines(self, n):
'''Skip a number of lines from the output.'''
for i in range(n):
self.line = next(self.output)
return self.line |
Parse a tensor. | def _parse_tensor(self, indices=False):
'''Parse a tensor.'''
if indices:
self.line = self._skip_lines(1)
tensor = np.zeros((3, 3))
for i in range(3):
tokens = self.line.split()
if indices:
tensor[i][0] = float(tokens[1])
... |
Iterate over the lines and extract the required data. | def parse(self):
'''Iterate over the lines and extract the required data.'''
for self.line in self.output:
# Parse general data: charge, multiplicity, coordinates, etc.
self.index = 0
if self.line[1:13] == 'Total Charge':
tokens = self.line.split()
... |
Method executed when the event set is triggered. | def __validate(self, target, value, oldvalue, initiator):
""" Method executed when the event 'set' is triggered.
:param target: Object triggered
:param value: New value
:param oldvalue: Previous value
:param initiator: Column modified
:return: :raise ValidateError:
... |
Create an SQLAlchemy event listening the set in a particular column. | def __create_event(self):
""" Create an SQLAlchemy event listening the 'set' in a particular column.
:rtype : object
"""
if not event.contains(self.field, 'set', self.__validate):
event.listen(self.field, 'set', self.__validate, retval=True) |
Remove the listener to stop the validation | def stop(self):
""" Remove the listener to stop the validation
"""
if event.contains(self.field, 'set', self.__validate):
event.remove(self.field, 'set', self.__validate) |
Restart the listener | def start(self):
""" Restart the listener
"""
if not event.contains(self.field, 'set', self.__validate):
self.__create_event() |
Nhap dai han | def nhapDaiHan(self, cucSo, gioiTinh):
"""Nhap dai han
Args:
cucSo (TYPE): Description
gioiTinh (TYPE): Description
Returns:
TYPE: Description
"""
for cung in self.thapNhiCung:
khoangCach = khoangCachCung(cung.cungSo, self.cungMen... |
A very easy - to - use version of GFL solver that just requires the data and the edges. | def solve_gfl(data, edges=None, weights=None,
minlam=0.2, maxlam=1000.0, numlam=30,
alpha=0.2, inflate=2., converge=1e-6,
maxsteps=1000000, lam=None, verbose=0,
missing_val=None, full_path=False,
loss='normal'):
'''A very easy-to-use version of G... |
Summary | def ngayThangNam(nn, tt, nnnn, duongLich=True, timeZone=7):
"""Summary
Args:
nn (TYPE): ngay
tt (TYPE): thang
nnnn (TYPE): nam
duongLich (bool, optional): bool
timeZone (int, optional): +7 Vietnam
Returns:
TYPE: Description
Raises:
Exception: De... |
Summary | def canChiNgay(nn, tt, nnnn, duongLich=True, timeZone=7, thangNhuan=False):
"""Summary
Args:
nn (int): ngày
tt (int): tháng
nnnn (int): năm
duongLich (bool, optional): True nếu là dương lịch, False âm lịch
timeZone (int, optional): Múi giờ
thangNhuan (bool, optio... |
chuyển đổi năm tháng âm/ dương lịch sang Can Chi trong tiếng Việt. Không tính đến can ngày vì phải chuyển đổi qua lịch Julius. | def ngayThangNamCanChi(nn, tt, nnnn, duongLich=True, timeZone=7):
"""chuyển đổi năm, tháng âm/dương lịch sang Can, Chi trong tiếng Việt.
Không tính đến can ngày vì phải chuyển đổi qua lịch Julius.
Hàm tìm can ngày là hàm canChiNgay(nn, tt, nnnn, duongLich=True,\
timeZone... |
Args: tenHanh ( string ): Tên Hành trong ngũ hành Kim hoặc K Moc hoặc M Thuy hoặc T Hoa hoặc H Tho hoặc O | def nguHanh(tenHanh):
"""
Args:
tenHanh (string): Tên Hành trong ngũ hành, Kim hoặc K, Moc hoặc M,
Thuy hoặc T, Hoa hoặc H, Tho hoặc O
Returns:
Dictionary: ID của Hành, tên đầy đủ của Hành, số Cục của Hành
Raises:
Exception: Description
"""
if tenHanh in ["Kim",... |
Sử dụng Ngũ Hành nạp âm để tính Hành của năm. | def nguHanhNapAm(diaChi, thienCan, xuatBanMenh=False):
"""Sử dụng Ngũ Hành nạp âm để tính Hành của năm.
Args:
diaChi (integer): Số thứ tự của địa chi (Tý=1, Sửu=2,...)
thienCan (integer): Số thứ tự của thiên can (Giáp=1, Ất=2,...)
Returns:
Trả về chữ viết tắt Hành của năm (K, T, H,... |
Tìm vị trí của sao Tử vi | def timTuVi(cuc, ngaySinhAmLich):
"""Tìm vị trí của sao Tử vi
Args:
cuc (TYPE): Description
ngaySinhAmLich (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description
"""
cungDan = 3 # Vị trí cung Dần ban đầu là 3
cucBanDau = cuc
if c... |
Translate a nucleotide sequence into an amino acid sequence. | def nt2aa(ntseq):
"""Translate a nucleotide sequence into an amino acid sequence.
Parameters
----------
ntseq : str
Nucleotide sequence composed of A, C, G, or T (uppercase or lowercase)
Returns
-------
aaseq : str
Amino acid sequence
Example
--------
>>> n... |
Represent nucleotide sequence by sequence of codon symbols. | def nt2codon_rep(ntseq):
"""Represent nucleotide sequence by sequence of codon symbols.
'Translates' the nucleotide sequence into a symbolic representation of
'amino acids' where each codon gets its own unique character symbol. These
characters should be reserved only for representing the 64 individua... |
Cut genomic sequence from the right. | def cutR_seq(seq, cutR, max_palindrome):
"""Cut genomic sequence from the right.
Parameters
----------
seq : str
Nucleotide sequence to be cut from the right
cutR : int
cutR - max_palindrome = how many nucleotides to cut from the right.
Negative cutR implies complementary pa... |
Cut genomic sequence from the left. | def cutL_seq(seq, cutL, max_palindrome):
"""Cut genomic sequence from the left.
Parameters
----------
seq : str
Nucleotide sequence to be cut from the right
cutL : int
cutL - max_palindrome = how many nucleotides to cut from the left.
Negative cutL implies complementary pali... |
Generate the sub_codons_right dictionary of codon suffixes. | def construct_codons_dict(alphabet_file = None):
"""Generate the sub_codons_right dictionary of codon suffixes.
syntax of custom alphabet_files:
char: list,of,amino,acids,or,codons,separated,by,commas
Parameters
----------
alphabet_file : str
File name for a custom al... |
Generate the sub_codons_left dictionary of codon prefixes. | def generate_sub_codons_left(codons_dict):
"""Generate the sub_codons_left dictionary of codon prefixes.
Parameters
----------
codons_dict : dict
Dictionary, keyed by the allowed 'amino acid' symbols with the values
being lists of codons corresponding to the symbol.
Returns
--... |
Generate the sub_codons_right dictionary of codon suffixes. | def generate_sub_codons_right(codons_dict):
"""Generate the sub_codons_right dictionary of codon suffixes.
Parameters
----------
codons_dict : dict
Dictionary, keyed by the allowed 'amino acid' symbols with the values
being lists of codons corresponding to the symbol.
Returns
... |
Determine the type of a sequence. Parameters ---------- | def determine_seq_type(seq, aa_alphabet):
"""Determine the type of a sequence.
Parameters
----------
seq : str
Sequence to be typed.
aa_alphabet : str
String of all characters recoginized as 'amino acids'. (i.e. the keys
of codons_dict: aa_alphabet = ''.join(codons_dict... |
Calculate the steady state dist of a 4 state markov transition matrix. | def calc_steady_state_dist(R):
"""Calculate the steady state dist of a 4 state markov transition matrix.
Parameters
----------
R : ndarray
Markov transition matrix
Returns
-------
p_ss : ndarray
Steady state probability distribution
"""
#Calc steady state d... |
Generate a random insertion nucleotide sequence of length ins_len. | def rnd_ins_seq(ins_len, C_R, CP_first_nt):
"""Generate a random insertion nucleotide sequence of length ins_len.
Draws the sequence identity (for a set length) from the distribution
defined by the dinucleotide markov model of transition matrix R.
Parameters
----------
ins_len : int
Le... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.