INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
A boolean matrix m [ i j ] == True if there is a relation term ( i ) - > term ( j ): return: a np. matrix ( len ( dictionary ) len ( dictionary )) of boolean | def connexity(self):
"""
A boolean matrix, m[i, j] == True if there is a relation term(i) -> term(j)
:return: a np.matrix (len(dictionary), len(dictionary)) of boolean
"""
return np.matrix(sum(self.relations.values()).todense(), dtype=bool) |
path is a mul of coord or a coord | def _resolve_path(obj, path):
"""path is a mul of coord or a coord"""
if obj.__class__ not in path.context.accept:
result = set()
for ctx in path.context.accept:
result |= {e for u in obj[ctx] for e in _resolve_path(u, path)}
return result
if isinstance(obj, Text):
... |
Resolve the context of the rules ( the type of this element ) and building the ieml element.: param rules:: return: | def _resolve_ctx(rules):
"""
Resolve the context of the rules (the type of this element), and building the ieml element.
:param rules:
:return:
"""
if not rules:
raise ResolveError("Missing node definition.")
# if rules == [(None, e)] --> e
if len(rules) == 1 and rules[0][0] is ... |
usls is an iterable of usl. | def project_usls_on_dictionary(usls, allowed_terms=None):
"""`usls` is an iterable of usl.
return a mapping term -> usl list
"""
cells_to_usls = defaultdict(set)
tables = set()
for u in usls:
for t in u.objects(Term):
for c in t.singular_sequences:
# This i... |
usls_data: usl = > data []: param usls_data:: return: | def project_usl_with_data(usls_data, metric=None):
"""
usls_data: usl => data[]
:param usls_data:
:return:
"""
projection = project_usls_on_dictionary(usls_data)
all_terms = set(c for u in usls_data for t in u.objects(Term) for c in t.singular_sequences)
if metric is None:
metri... |
script_lvl_0: PRIMITIVE LAYER0_MARK | REMARKABLE_ADDITION LAYER0_MARK | def p_script_lvl_0(self, p):
""" script_lvl_0 : PRIMITIVE LAYER0_MARK
| REMARKABLE_ADDITION LAYER0_MARK"""
if p[1] == 'E':
p[0] = NullScript(layer=0)
elif p[1] in REMARKABLE_ADDITION:
p[0] = AdditiveScript(character=p[1])
else:
... |
sum_lvl_0: script_lvl_0 | script_lvl_0 PLUS sum_lvl_0 | def p_sum_lvl_0(self, p):
""" sum_lvl_0 : script_lvl_0
| script_lvl_0 PLUS sum_lvl_0"""
if len(p) == 4:
p[3].append(p[1])
p[0] = p[3]
else:
p[0] = [p[1]] |
script_lvl_1: additive_script_lvl_0 LAYER1_MARK | additive_script_lvl_0 additive_script_lvl_0 LAYER1_MARK | additive_script_lvl_0 additive_script_lvl_0 additive_script_lvl_0 LAYER1_MARK | REMARKABLE_MULTIPLICATION LAYER1_MARK | def p_script_lvl_1(self, p):
""" script_lvl_1 : additive_script_lvl_0 LAYER1_MARK
| additive_script_lvl_0 additive_script_lvl_0 LAYER1_MARK
| additive_script_lvl_0 additive_script_lvl_0 additive_script_lvl_0 LAYER1_MARK
| REMARKABLE_MULTIPL... |
sum_lvl_1: script_lvl_1 | script_lvl_1 PLUS sum_lvl_1 | def p_sum_lvl_1(self, p):
""" sum_lvl_1 : script_lvl_1
| script_lvl_1 PLUS sum_lvl_1"""
if len(p) == 4:
p[3].append(p[1])
p[0] = p[3]
else:
p[0] = [p[1]] |
Compute the ordering of a list of usls from each usl and return the matrix m s. t. for each u in usl_list at index i [ usl_list [ j ] for j in m [ i: ]] is the list sorted by proximity from u. of the result: param usl_list: a list of usls: return: a ( len ( usl_list ) len ( usl_list )) np. array | def square_order_matrix(usl_list):
"""
Compute the ordering of a list of usls from each usl and return the matrix m s.t.
for each u in usl_list at index i, [usl_list[j] for j in m[i, :]] is the list sorted
by proximity from u.
of the result
:param usl_list: a list of usls
:return: a (len(us... |
True when the term is a subset of this term tables. If the parent of this term is already a TableSet return always false ( only one main tableset ): param term:: return: | def accept_script(self, script):
"""
True when the term is a subset of this term tables. If the parent of this term is already a TableSet,return
always false (only one main tableset)
:param term:
:return:
"""
if isinstance(self.parent, TableSet):
retur... |
Slow method retrieve all the terms from the database.: return: | def _build_pools(self):
"""
Slow method, retrieve all the terms from the database.
:return:
"""
if self.level >= Topic:
# words
self.topics_pool = set(self.topic() for i in range(self.pool_size))
if self.level >= Fact:
# sentences
... |
Returns the mean value. | def mean(self):
"""Returns the mean value."""
if self.counter.value > 0:
return self.sum.value / self.counter.value
return 0.0 |
Returns variance | def variance(self):
"""Returns variance"""
if self.counter.value <= 1:
return 0.0
return self.var.value[1] / (self.counter.value - 1) |
Record an event with the meter. By default it will record one event. | def mark(self, value=1):
"""Record an event with the meter. By default it will record one event.
:param value: number of event to record
"""
self.counter += value
self.m1_rate.update(value)
self.m5_rate.update(value)
self.m15_rate.update(value) |
Returns the mean rate of the events since the start of the process. | def mean_rate(self):
"""
Returns the mean rate of the events since the start of the process.
"""
if self.counter.value == 0:
return 0.0
else:
elapsed = time() - self.start_time
return self.counter.value / elapsed |
Record an event with the derive. | def mark(self, value=1):
"""Record an event with the derive.
:param value: counter value to record
"""
last = self.last.get_and_set(value)
if last <= value:
value = value - last
super(Derive, self).mark(value) |
Wrapper to make map () behave the same on Py2 and Py3. | def mmap(func, iterable):
"""Wrapper to make map() behave the same on Py2 and Py3."""
if sys.version_info[0] > 2:
return [i for i in map(func, iterable)]
else:
return map(func, iterable) |
Send metric and its snapshot. | def send_metric(self, name, metric):
"""Send metric and its snapshot."""
config = SERIALIZER_CONFIG[class_name(metric)]
mmap(
self._buffered_send_metric,
self.serialize_metric(
metric,
name,
config['keys'],
... |
Serialize and send available measures of a metric. | def serialize_metric(self, metric, m_name, keys, m_type):
"""Serialize and send available measures of a metric."""
return [
self.format_metric_string(m_name, getattr(metric, key), m_type)
for key in keys
] |
Compose a statsd compatible string for a metric s measurement. | def format_metric_string(self, name, value, m_type):
"""Compose a statsd compatible string for a metric's measurement."""
# NOTE(romcheg): This serialized metric template is based on
# statsd's documentation.
template = '{name}:{value}|{m_type}\n'
if self.prefix:... |
Add a metric to the buffer. | def _buffered_send_metric(self, metric_str):
"""Add a metric to the buffer."""
self.batch_count += 1
self.batch_buffer += metric_str
# NOTE(romcheg): Send metrics if the number of metrics in the buffer
# has reached the threshold for sending.
if self.bat... |
Get method that raises MissingSetting if the value was unset. | 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
... |
Set method that ( 1 ) auto - saves if possible and ( 2 ) auto - creates sections. | 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... |
json. loads wants an unistr in Python3. Convert it. | 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,))
... |
Shortcut for urlopen ( POST ) + read. We ll probably want to add a nice timeout here later too. | 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) |
Shortcut for urlopen ( PUT ) + read. We ll probably want to add a nice timeout here later too. | 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) |
Connect to a host on a given ( SSL ) port. | 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+
... |
Base method to fetch values and to set defaults in case they don t exist. | 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... |
Convert set of human codes and to a dict of code to exactonline guid mappings. | 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>',
... |
Get VATCode ( up to three digit number ) for the specified ledger line. | 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:
... |
Get the current division and return a dictionary of divisions so the user can select the right one. | 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... |
Select the current division that we ll be working on/ with. | 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' %
... |
Optionally supply a list of ExactOnline invoice numbers. | 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... |
Optionally supply a list of foreign ( your ) invoice numbers. | 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... |
A common query would be duedate__lt = date ( 2015 1 1 ) to get all Receivables that are due in 2014 and earlier. | 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... |
Create the ( 11745 ) Sudoku clauses and return them as a list. Note that these clauses are * independent * of the particular Sudoku puzzle at hand. | 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):
... |
solve a Sudoku grid inplace | 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... |
Create Django class - based view from injector class. | 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) |
Create Django form processing class - based view from injector class. | 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) |
Create Flask method based dispatching view from injector class. | 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) |
Create DRF class - based API view from injector class. | 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) |
Create DRF generic class - based API view from injector class. | 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... |
Create DRF model view set from injector class. | 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_... |
Recieve a streamer for a given file descriptor. | 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... |
Called by the event loop whenever the fd is ready for reading. | 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... |
Public API: pause reading the transport. | def pause_reading(self):
"""Public API: pause reading the transport."""
self._loop.remove_reader(self._fileno)
self._active = False |
Public API: resume transport reading. | def resume_reading(self):
"""Public API: resume transport reading."""
self._loop.add_reader(self._fileno, self._read_ready)
self._active = True |
Actual closing code both from manual close and errors. | 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) |
Finalize closing. | 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 |
Add a new watching rule. | 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... |
Stop watching a given rule. | 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)
... |
Actual rule setup. | 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" % (... |
Start the watcher registering new watches if any. | 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; ... |
Fetch an event. | 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
... |
Respond to nsqd that you ve processed this message successfully ( or would like to silently discard it ). | 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) |
Respond to nsqd that you ve failed to process this message successfully ( and would like it to be requeued ). | 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... |
Respond to nsqd that you need more time to process the message. | 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) |
Starts any instantiated: class: nsq. Reader or: class: nsq. Writer | 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() |
Update the timer to reflect a successfull call | 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 = ... |
Update the timer to reflect a failed call | 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)
... |
encode a dictionary of URL parameters ( including iterables ) as utf - 8 | 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)
... |
Closes all connections stops all periodic callbacks | 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() |
Used to identify when buffered messages should be processed and responded to. | 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... |
Adds a connection to nsqd at the specified address. | 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... |
Trigger a query of the configured nsq_lookupd_http_addresses. | 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... |
Dynamically adjust the reader max_in_flight. Set to 0 to immediately disable a Reader | 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
... |
Called when a message has been received where msg. attempts > max_tries | 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('[... |
Listen for the named event with the specified callback. | 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... |
Stop listening for the named event via the specified callback. | 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... |
Execute the callbacks for the listeners on the specified event with the supplied arguments. | 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... |
publish a message to nsq | 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) |
publish multiple messages in one command ( efficiently ) | 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... |
publish multiple messages in one command ( efficiently ) | 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... |
Score function to calculate score | 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'):
... |
Score function to calculate score | 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 |
Train Pocket Perceptron Learning Algorithm From f ( x ) = WX Find best h ( x ) = WX similar to f ( x ) Output W | 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... |
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 [ self. svm_processor. sv_index [ i ]] x ) score = score + self. svm_p... | 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... |
Train Linear Regression Algorithm From f ( x ) = WX Find best h ( x ) = WX similar to f ( x ) Output W | 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... |
Score function to calculate score | 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 |
Train Perceptron Learning Algorithm From f ( x ) = WX Find best h ( x ) = WX similar to f ( x ) Output W | 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... |
load file | 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]]
... |
K = np. zeros (( svm_model. data_num svm_model. data_num )) | 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... |
K = np. zeros (( svm_model. data_num svm_model. data_num )) | 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... |
Transform data feature to high level | 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... |
Make prediction input test data output the prediction | 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... |
Theta sigmoid function | def theta(self, s):
'''
Theta sigmoid function
'''
s = np.where(s < -709, -709, s)
return 1 / (1 + np.exp((-1) * s)) |
Score function to calculate score | def score_function(self, x, W):
# need refector
'''
Score function to calculate score
'''
score = self.theta(np.inner(x, W))
return score |
Error function to calculate error: cross entropy error | 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 |
Retrieves some statistics from a single Trimmomatic log file. | 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.... |
Cleans the working directory of unwanted temporary files | 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... |
Merges the default adapters file in the trimmomatic adapters directory | 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... |
Main executor of the trimmomatic template. | 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.
... |
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 | 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 ... |
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. | 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... |
Sets the path to the appropriate jinja template file | 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
... |
Sets the main channel names based on the provide input and output channel suffixes. This is performed when connecting processes. | 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... |
Returns the main raw channel for the process | 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... |
Wrapper to the jinja2 render method from a template file | 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... |
Class property that returns a populated template string | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.