Search is not available for this dataset
text stringlengths 75 104k |
|---|
def get(self, section, option, **kwargs):
"""
Get method that raises MissingSetting if the value was unset.
This differs from the SafeConfigParser which may raise either a
NoOptionError or a NoSectionError.
We take extra **kwargs because the Python 3.5 configparser extends the
... |
def set(self, section, option, value):
"""
Set method that (1) auto-saves if possible and (2) auto-creates
sections.
"""
try:
super(ExactOnlineConfig, self).set(section, option, value)
except NoSectionError:
self.add_section(section)
su... |
def _json_safe(data):
"""
json.loads wants an unistr in Python3. Convert it.
"""
if not hasattr(data, 'encode'):
try:
data = data.decode('utf-8')
except UnicodeDecodeError:
raise ValueError(
'Expected valid UTF8 for JSON data, got %r' % (data,))
... |
def http_post(url, data=None, opt=opt_default):
"""
Shortcut for urlopen (POST) + read. We'll probably want to add a
nice timeout here later too.
"""
return _http_request(url, method='POST', data=_marshalled(data), opt=opt) |
def http_put(url, data=None, opt=opt_default):
"""
Shortcut for urlopen (PUT) + read. We'll probably want to add a nice
timeout here later too.
"""
return _http_request(url, method='PUT', data=_marshalled(data), opt=opt) |
def connect(self):
"Connect to a host on a given (SSL) port."
sock = socket.create_connection((self.host, self.port),
self.timeout, self.source_address)
if self._tunnel_host:
self.sock = sock
self._tunnel()
# Python 2.7.9+
... |
def get_or_set_default(self, section, option, value):
"""
Base method to fetch values and to set defaults in case they
don't exist.
"""
try:
ret = self.get(section, option)
except MissingSetting:
self.set(section, option, value)
ret = v... |
def get_ledger_code_to_guid_map(self, codes):
"""
Convert set of human codes and to a dict of code to exactonline
guid mappings.
Example::
ret = inv.get_ledger_code_to_guid_map(['1234', '5555'])
ret == {'1234': '<guid1_from_exactonline_ledgeraccounts>',
... |
def get_vatcode_for_ledger_line(self, ledger_line):
"""
Get VATCode (up to three digit number) for the specified ledger line.
Can be as simple as:
return '0 ' # one VAT category only
Or more complicated, like:
if ledger_line['vat_percentage'] == 21:
... |
def get_divisions(self):
"""
Get the "current" division and return a dictionary of divisions
so the user can select the right one.
"""
ret = self.rest(GET('v1/current/Me?$select=CurrentDivision'))
current_division = ret[0]['CurrentDivision']
assert isinstance(curr... |
def set_division(self, division):
"""
Select the "current" division that we'll be working on/with.
"""
try:
division = int(division)
except (TypeError, ValueError):
raise V1DivisionError('Supplied division %r is not a number' %
... |
def map_exact2foreign_invoice_numbers(self, exact_invoice_numbers=None):
"""
Optionally supply a list of ExactOnline invoice numbers.
Returns a dictionary of ExactOnline invoice numbers to foreign
(YourRef) invoice numbers.
"""
# Quick, select all. Not the most nice to t... |
def map_foreign2exact_invoice_numbers(self, foreign_invoice_numbers=None):
"""
Optionally supply a list of foreign (your) invoice numbers.
Returns a dictionary of your invoice numbers (YourRef) to Exact
Online invoice numbers.
"""
# Quick, select all. Not the most nice t... |
def filter(self, relation_id=None, duedate__lt=None, duedate__gte=None,
**kwargs):
"""
A common query would be duedate__lt=date(2015, 1, 1) to get all
Receivables that are due in 2014 and earlier.
"""
if relation_id is not None:
# Filter by (relation) a... |
def sudoku_clauses():
"""
Create the (11745) Sudoku clauses, and return them as a list.
Note that these clauses are *independent* of the particular
Sudoku puzzle at hand.
"""
res = []
# for all cells, ensure that the each cell:
for i in range(1, 10):
for j in range(1, 10):
... |
def solve(grid):
"""
solve a Sudoku grid inplace
"""
clauses = sudoku_clauses()
for i in range(1, 10):
for j in range(1, 10):
d = grid[i - 1][j - 1]
# For each digit already known, a clause (with one literal).
# Note:
# We could also remove... |
def view(injector):
"""Create Django class-based view from injector class."""
handler = create_handler(View, injector)
apply_http_methods(handler, injector)
return injector.let(as_view=handler.as_view) |
def form_view(injector):
"""Create Django form processing class-based view from injector class."""
handler = create_handler(FormView, injector)
apply_form_methods(handler, injector)
return injector.let(as_view=handler.as_view) |
def method_view(injector):
"""Create Flask method based dispatching view from injector class."""
handler = create_handler(MethodView)
apply_http_methods(handler, injector)
return injector.let(as_view=handler.as_view) |
def api_view(injector):
"""Create DRF class-based API view from injector class."""
handler = create_handler(APIView, injector)
apply_http_methods(handler, injector)
apply_api_view_methods(handler, injector)
return injector.let(as_view=handler.as_view) |
def generic_api_view(injector):
"""Create DRF generic class-based API view from injector class."""
handler = create_handler(GenericAPIView, injector)
apply_http_methods(handler, injector)
apply_api_view_methods(handler, injector)
apply_generic_api_view_methods(handler, injector)
return injector... |
def model_view_set(injector):
"""Create DRF model view set from injector class."""
handler = create_handler(ModelViewSet, injector)
apply_api_view_methods(handler, injector)
apply_generic_api_view_methods(handler, injector)
apply_model_view_set_methods(handler, injector)
return injector.let(as_... |
def stream_from_fd(fd, loop):
"""Recieve a streamer for a given file descriptor."""
reader = asyncio.StreamReader(loop=loop)
protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
waiter = asyncio.futures.Future(loop=loop)
transport = UnixFileDescriptorTransport(
loop=loop,
file... |
def _read_ready(self):
"""Called by the event loop whenever the fd is ready for reading."""
try:
data = os.read(self._fileno, self.max_size)
except InterruptedError:
# No worries ;)
pass
except OSError as exc:
# Some OS-level problem, cras... |
def pause_reading(self):
"""Public API: pause reading the transport."""
self._loop.remove_reader(self._fileno)
self._active = False |
def resume_reading(self):
"""Public API: resume transport reading."""
self._loop.add_reader(self._fileno, self._read_ready)
self._active = True |
def _close(self, error=None):
"""Actual closing code, both from manual close and errors."""
self._closing = True
self.pause_reading()
self._loop.call_soon(self._call_connection_lost, error) |
def _call_connection_lost(self, error):
"""Finalize closing."""
try:
self._protocol.connection_lost(error)
finally:
os.close(self._fileno)
self._fileno = None
self._protocol = None
self._loop = None |
def watch(self, path, flags, *, alias=None):
"""Add a new watching rule."""
if alias is None:
alias = path
if alias in self.requests:
raise ValueError("A watch request is already scheduled for alias %s" % alias)
self.requests[alias] = (path, flags)
if self... |
def unwatch(self, alias):
"""Stop watching a given rule."""
if alias not in self.descriptors:
raise ValueError("Unknown watch alias %s; current set is %r" % (alias, list(self.descriptors.keys())))
wd = self.descriptors[alias]
errno = LibC.inotify_rm_watch(self._fd, wd)
... |
def _setup_watch(self, alias, path, flags):
"""Actual rule setup."""
assert alias not in self.descriptors, "Registering alias %s twice!" % alias
wd = LibC.inotify_add_watch(self._fd, path, flags)
if wd < 0:
raise IOError("Error setting up watch on %s with flags %s: wd=%s" % (... |
def setup(self, loop):
"""Start the watcher, registering new watches if any."""
self._loop = loop
self._fd = LibC.inotify_init()
for alias, (path, flags) in self.requests.items():
self._setup_watch(alias, path, flags)
# We pass ownership of the fd to the transport; ... |
def get_event(self):
"""Fetch an event.
This coroutine will swallow events for removed watches.
"""
while True:
prefix = yield from self._stream.readexactly(PREFIX.size)
if prefix == b'':
# We got closed, return None.
return
... |
def finish(self):
"""
Respond to ``nsqd`` that you've processed this message successfully (or would like
to silently discard it).
"""
assert not self._has_responded
self._has_responded = True
self.trigger(event.FINISH, message=self) |
def requeue(self, **kwargs):
"""
Respond to ``nsqd`` that you've failed to process this message successfully (and would
like it to be requeued).
:param backoff: whether or not :class:`nsq.Reader` should apply backoff handling
:type backoff: bool
:param delay: the amount... |
def touch(self):
"""
Respond to ``nsqd`` that you need more time to process the message.
"""
assert not self._has_responded
self.trigger(event.TOUCH, message=self) |
def run():
"""
Starts any instantiated :class:`nsq.Reader` or :class:`nsq.Writer`
"""
signal.signal(signal.SIGTERM, _handle_term_signal)
signal.signal(signal.SIGINT, _handle_term_signal)
tornado.ioloop.IOLoop.instance().start() |
def success(self):
"""Update the timer to reflect a successfull call"""
if self.interval == 0.0:
return
self.short_interval -= self.short_unit
self.long_interval -= self.long_unit
self.short_interval = max(self.short_interval, Decimal(0))
self.long_interval = ... |
def failure(self):
"""Update the timer to reflect a failed call"""
self.short_interval += self.short_unit
self.long_interval += self.long_unit
self.short_interval = min(self.short_interval, self.max_short_timer)
self.long_interval = min(self.long_interval, self.max_long_timer)
... |
def _utf8_params(params):
"""encode a dictionary of URL parameters (including iterables) as utf-8"""
assert isinstance(params, dict)
encoded_params = []
for k, v in params.items():
if v is None:
continue
if isinstance(v, integer_types + (float,)):
v = str(v)
... |
def close(self):
"""
Closes all connections stops all periodic callbacks
"""
for conn in self.conns.values():
conn.close()
self.redist_periodic.stop()
if self.query_periodic is not None:
self.query_periodic.stop() |
def is_starved(self):
"""
Used to identify when buffered messages should be processed and responded to.
When max_in_flight > 1 and you're batching messages together to perform work
is isn't possible to just compare the len of your list of buffered messages against
your configure... |
def connect_to_nsqd(self, host, port):
"""
Adds a connection to ``nsqd`` at the specified address.
:param host: the address to connect to
:param port: the port to connect to
"""
assert isinstance(host, string_types)
assert isinstance(port, int)
conn = As... |
def query_lookupd(self):
"""
Trigger a query of the configured ``nsq_lookupd_http_addresses``.
"""
endpoint = self.lookupd_http_addresses[self.lookupd_query_index]
self.lookupd_query_index = (self.lookupd_query_index + 1) % len(self.lookupd_http_addresses)
# urlsplit() i... |
def set_max_in_flight(self, max_in_flight):
"""Dynamically adjust the reader max_in_flight. Set to 0 to immediately disable a Reader"""
assert isinstance(max_in_flight, int)
self.max_in_flight = max_in_flight
if max_in_flight == 0:
# set RDY 0 to all connections
... |
def giving_up(self, message):
"""
Called when a message has been received where ``msg.attempts > max_tries``
This is useful to subclass and override to perform a task (such as writing to disk, etc.)
:param message: the :class:`nsq.Message` received
"""
logger.warning('[... |
def on(self, name, callback):
"""
Listen for the named event with the specified callback.
:param name: the name of the event
:type name: string
:param callback: the callback to execute when the event is triggered
:type callback: callable
"""
assert calla... |
def off(self, name, callback):
"""
Stop listening for the named event via the specified callback.
:param name: the name of the event
:type name: string
:param callback: the callback that was originally used
:type callback: callable
"""
if callback not in... |
def trigger(self, name, *args, **kwargs):
"""
Execute the callbacks for the listeners on the specified event with the
supplied arguments.
All extra arguments are passed through to each callback.
:param name: the name of the event
:type name: string
"""
f... |
def pub(self, topic, msg, callback=None):
"""
publish a message to nsq
:param topic: nsq topic
:param msg: message body (bytes)
:param callback: function which takes (conn, data) (data may be nsq.Error)
"""
self._pub('pub', topic, msg, callback=callback) |
def mpub(self, topic, msg, callback=None):
"""
publish multiple messages in one command (efficiently)
:param topic: nsq topic
:param msg: list of messages bodies (which are bytes)
:param callback: function which takes (conn, data) (data may be nsq.Error)
"""
if i... |
def dpub(self, topic, delay_ms, msg, callback=None):
"""
publish multiple messages in one command (efficiently)
:param topic: nsq topic
:param delay_ms: tell nsqd to delay delivery for this long (integer milliseconds)
:param msg: message body (bytes)
:param callback: fun... |
def score_function(self, x, W):
# need refector
'''
Score function to calculate score
'''
if (self.svm_kernel == 'polynomial_kernel' or self.svm_kernel == 'gaussian_kernel' or self.svm_kernel == 'soft_polynomial_kernel' or self.svm_kernel == 'soft_gaussian_kernel'):
... |
def score_function(self, x, W):
'''
Score function to calculate score
'''
score = super(BinaryClassifier, self).score_function(x, W)
if score >= 0.5:
score = 1.0
else:
score = -1.0
return score |
def train(self):
'''
Train Pocket Perceptron Learning Algorithm
From f(x) = WX
Find best h(x) = WX similar to f(x)
Output W
'''
if (self.status != 'init'):
print("Please load train data and init W first.")
return self.W
self.stat... |
def svm_score(self, x):
x = x[1:]
'''
original_X = self.svm_processor.train_X[:, 1:]
score = 0
for i in range(len(self.svm_processor.sv_alpha)):
score += self.svm_processor.sv_alpha[i] * self.svm_processor.sv_Y[i] * utility.Kernel.gaussian_kernel(self, original_X[se... |
def train(self):
'''
Train Linear Regression Algorithm
From f(x) = WX
Find best h(x) = WX similar to f(x)
Output W
'''
if (self.status != 'init'):
print("Please load train data and init W first.")
return self.W
self.status = 'tra... |
def score_function(self, x, W):
# need refector
'''
Score function to calculate score
'''
score = self.sign * np.sign(x[self.feature_index] - self.theta)
return score |
def train(self):
'''
Train Perceptron Learning Algorithm
From f(x) = WX
Find best h(x) = WX similar to f(x)
Output W
'''
if (self.status != 'init'):
print("Please load train data and init W first.")
return self.W
self.status = 't... |
def load(input_data_file='', data_type='float'):
"""load file"""
X = []
Y = []
if data_type == 'float':
with open(input_data_file) as f:
for line in f:
data = line.split()
x = [1] + [float(v) for v in data[:-1]]
... |
def kernel_matrix(svm_model, original_X):
if (svm_model.svm_kernel == 'polynomial_kernel' or svm_model.svm_kernel == 'soft_polynomial_kernel'):
K = (svm_model.zeta + svm_model.gamma * np.dot(original_X, original_X.T)) ** svm_model.Q
elif (svm_model.svm_kernel == 'gaussian_kernel' or svm_mod... |
def kernel_matrix_xX(svm_model, original_x, original_X):
if (svm_model.svm_kernel == 'polynomial_kernel' or svm_model.svm_kernel == 'soft_polynomial_kernel'):
K = (svm_model.zeta + svm_model.gamma * np.dot(original_x, original_X.T)) ** svm_model.Q
elif (svm_model.svm_kernel == 'gaussian_ker... |
def set_feature_transform(self, mode='polynomial', degree=1):
'''
Transform data feature to high level
'''
if self.status != 'load_train_data':
print("Please load train data first.")
return self.train_X
self.feature_transform_mode = mode
self.fe... |
def prediction(self, input_data='', mode='test_data'):
'''
Make prediction
input test data
output the prediction
'''
prediction = {}
if (self.status != 'train'):
print("Please load train data and init W then train the W first.")
return p... |
def theta(self, s):
'''
Theta sigmoid function
'''
s = np.where(s < -709, -709, s)
return 1 / (1 + np.exp((-1) * s)) |
def score_function(self, x, W):
# need refector
'''
Score function to calculate score
'''
score = self.theta(np.inner(x, W))
return score |
def error_function(self, x, y, W):
# need refector
'''
Error function to calculate error: cross entropy error
'''
error = np.log(1 + np.exp((-1) * y * np.inner(x, W)))
return error |
def parse_log(log_file):
"""Retrieves some statistics from a single Trimmomatic log file.
This function parses Trimmomatic's log file and stores some trimming
statistics in an :py:class:`OrderedDict` object. This object contains
the following keys:
- ``clean_len``: Total length after trimming.... |
def clean_up(fastq_pairs, clear):
"""Cleans the working directory of unwanted temporary files"""
# Find unpaired fastq files
unpaired_fastq = [f for f in os.listdir(".")
if f.endswith("_U.fastq.gz")]
# Remove unpaired fastq files, if any
for fpath in unpaired_fastq:
o... |
def merge_default_adapters():
"""Merges the default adapters file in the trimmomatic adapters directory
Returns
-------
str
Path with the merged adapters file.
"""
default_adapters = [os.path.join(ADAPTERS_PATH, x) for x in
os.listdir(ADAPTERS_PATH)]
filepat... |
def main(sample_id, fastq_pair, trim_range, trim_opts, phred, adapters_file,
clear):
""" Main executor of the trimmomatic template.
Parameters
----------
sample_id : str
Sample Identification string.
fastq_pair : list
Two element list containing the paired FastQ files.
... |
def depth_file_reader(depth_file):
"""
Function that parse samtools depth file and creates 3 dictionaries that
will be useful to make the outputs of this script, both the tabular file
and the json file that may be imported by pATLAS
Parameters
----------
depth_file: textIO
the path ... |
def main(depth_file, json_dict, cutoff, sample_id):
"""
Function that handles the inputs required to parse depth files from bowtie
and dumps a dict to a json file that can be imported into pATLAS.
Parameters
----------
depth_file: str
the path to depth file for each sample
json_dic... |
def _set_template(self, template):
"""Sets the path to the appropriate jinja template file
When a Process instance is initialized, this method will fetch
the location of the appropriate template file, based on the
``template`` argument. It will raise an exception is the template
... |
def set_main_channel_names(self, input_suffix, output_suffix, lane):
"""Sets the main channel names based on the provide input and
output channel suffixes. This is performed when connecting processes.
Parameters
----------
input_suffix : str
Suffix added to the input... |
def get_user_channel(self, input_channel, input_type=None):
"""Returns the main raw channel for the process
Provided with at least a channel name, this method returns the raw
channel name and specification (the nextflow string definition)
for the process. By default, it will fork from t... |
def render(template, context):
"""Wrapper to the jinja2 render method from a template file
Parameters
----------
template : str
Path to template file.
context : dict
Dictionary with kwargs context to populate the template
"""
path, filena... |
def template_str(self):
"""Class property that returns a populated template string
This property allows the template of a particular process to be
dynamically generated and returned when doing ``Process.template_str``.
Returns
-------
x : str
String with the... |
def set_channels(self, **kwargs):
""" General purpose method that sets the main channels
This method will take a variable number of keyword arguments to
set the :py:attr:`Process._context` attribute with the information
on the main channels for the process. This is done by appending
... |
def update_main_forks(self, sink):
"""Updates the forks attribute with the sink channel destination
Parameters
----------
sink : str
Channel onto which the main input will be forked to
"""
if not self.main_forks:
self.main_forks = [self.output_c... |
def set_secondary_channel(self, source, channel_list):
""" General purpose method for setting a secondary channel
This method allows a given source channel to be forked into one or
more channels and sets those forks in the :py:attr:`Process.forks`
attribute. Both the source and the chan... |
def update_attributes(self, attr_dict):
"""Updates the directives attribute from a dictionary object.
This will only update the directives for processes that have been
defined in the subclass.
Parameters
----------
attr_dict : dict
Dictionary containing the ... |
def set_compiler_channels(self, channel_list, operator="mix"):
"""General method for setting the input channels for the status process
Given a list of status channels that are gathered during the pipeline
construction, this method will automatically set the input channel
for the status ... |
def set_raw_inputs(self, raw_input):
"""Sets the main input channels of the pipeline and their forks.
The ``raw_input`` dictionary input should contain one entry for each
input type (fastq, fasta, etc). The corresponding value should be a
dictionary/json with the following key:values:
... |
def set_secondary_inputs(self, channel_dict):
""" Adds secondary inputs to the start of the pipeline.
This channels are inserted into the pipeline file as they are
provided in the values of the argument.
Parameters
----------
channel_dict : dict
Each entry s... |
def set_extra_inputs(self, channel_dict):
"""Sets the initial definition of the extra input channels.
The ``channel_dict`` argument should contain the input type and
destination channel of each parameter (which is the key)::
channel_dict = {
"param1": {
... |
def main(sample_id, assembly_file, minsize):
"""Main executor of the process_mapping template.
Parameters
----------
sample_id : str
Sample Identification string.
assembly: str
Path to the fatsa file generated by the assembler.
minsize: str
Min contig size to be consider... |
def _parse_coverage(header_str):
"""Attempts to retrieve the coverage value from the header string.
It splits the header by "_" and then screens the list backwards in
search of the first float value. This will be interpreted as the
coverage value. If it cannot find a float value, it ret... |
def _parse_assembly(self, assembly_file):
"""Parse an assembly fasta file.
This is a Fasta parsing method that populates the
:py:attr:`~Assembly.contigs` attribute with data for each contig in the
assembly.
The insertion of data on the self.contigs is done by the
:py:me... |
def _populate_contigs(self, contig_id, header, cov, sequence):
""" Inserts data from a single contig into\
:py:attr:`~Assembly.contigs`.
By providing a contig id, the original header, the coverage that
is parsed from the header and the sequence, this method will
populate the :p... |
def _get_gc_content(sequence, length):
"""Get GC content and proportions.
Parameters
----------
sequence : str
The complete sequence of the contig.
length : int
The length of the sequence contig.
Returns
-------
x : dict
... |
def filter_contigs(self, *comparisons):
"""Filters the contigs of the assembly according to user provided\
comparisons.
The comparisons must be a list of three elements with the
:py:attr:`~Assembly.contigs` key, operator and test value. For
example, to filter contigs with a mini... |
def get_assembly_length(self):
"""Returns the length of the assembly, without the filtered contigs.
Returns
-------
x : int
Total length of the assembly.
"""
return sum(
[vals["length"] for contig_id, vals in self.contigs.items()
if... |
def write_assembly(self, output_file, filtered=True):
"""Writes the assembly to a new file.
The ``filtered`` option controls whether the new assembly will be
filtered or not.
Parameters
----------
output_file : str
Name of the output assembly file.
f... |
def write_report(self, output_file):
"""Writes a report with the test results for the current assembly
Parameters
----------
output_file : str
Name of the output assembly file.
"""
logger.debug("Writing the assembly report into: {}".format(
outp... |
def guess_process(query_str, process_map):
"""
Function to guess processes based on strings that are not available in
process_map. If the string has typos and is somewhat similar (50%) to any
process available in flowcraft it will print info to the terminal,
suggesting the most similar processes ava... |
def remove_inner_forks(text):
"""Recursively removes nested brackets
This function is used to remove nested brackets from fork strings using
regular expressions
Parameters
----------
text: str
The string that contains brackets with inner forks to be removed
Returns
-------
... |
def brackets_insanity_check(p_string):
"""
This function performs a check for different number of '(' and ')'
characters, which indicates that some forks are poorly constructed.
Parameters
----------
p_string: str
String with the definition of the pipeline, e.g.::
'process... |
def fork_procs_insanity_check(p_string):
"""
This function checks if the pipeline string contains a process between
the fork start token or end token and the separator (lane) token. Checks for
the absence of processes in one of the branches of the fork ['|)' and '(|']
and for the existence of a proc... |
def inner_fork_insanity_checks(pipeline_string):
"""
This function performs two sanity checks in the pipeline string. The first
check, assures that each fork contains a lane token '|', while the second
check looks for duplicated processes within the same fork.
Parameters
----------
pipeline... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.