text stringlengths 18 773k |
|---|
def normal_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
The normal cover operation as described in :meth:`~.cover`.
Equivalent to calling::
dataset.cover("normal", ...)
"""
return self.cover(minAcc, maxAc... |
def flat_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns the union of all the regions
which contribute to the COVER. More precisely, it returns the contiguous regions
that start fro... |
def summit_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns only those portions of the COVER
result where the maximum number of regions overlap (this is done by returning only
regions ... |
def histogram_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns all regions contributing to
the COVER divided in different (contiguous) parts according to their accumulation
index val... |
def join(self, experiment, genometric_predicate, output="LEFT", joinBy=None,
refName="REF", expName="EXP", left_on=None, right_on=None):
"""
*Wrapper of* ``JOIN``
The JOIN operator takes in input two datasets, respectively known as anchor
(the first/left one) and experiment... |
def map(self, experiment, new_reg_fields=None, joinBy=None, refName="REF", expName="EXP"):
"""
*Wrapper of* ``MAP``
MAP is a non-symmetric operator over two datasets, respectively called
reference and experiment. The operation computes, for each sample in
the experiment dataset... |
def order(self, meta=None, meta_ascending=None, meta_top=None, meta_k=None,
regs=None, regs_ascending=None, region_top=None, region_k=None):
"""
*Wrapper of* ``ORDER``
The ORDER operator is used to order either samples, sample regions, or both,
in a dataset according to a ... |
def difference(self, other, joinBy=None, exact=False):
"""
*Wrapper of* ``DIFFERENCE``
DIFFERENCE is a binary, non-symmetric operator that produces one sample
in the result for each sample of the first operand, by keeping the same
metadata of the first operand sample and only th... |
def union(self, other, left_name="LEFT", right_name="RIGHT"):
"""
*Wrapper of* ``UNION``
The UNION operation is used to integrate homogeneous or heterogeneous samples of two
datasets within a single dataset; for each sample of either one of the input datasets, a
sample is create... |
def merge(self, groupBy=None):
"""
*Wrapper of* ``MERGE``
The MERGE operator builds a new dataset consisting of a single sample having
* as regions all the regions of all the input samples, with the
same attributes and values
* as metadata the uni... |
def group(self, meta=None, meta_aggregates=None, regs=None,
regs_aggregates=None, meta_group_name="_group"):
"""
*Wrapper of* ``GROUP``
The GROUP operator is used for grouping both regions and/or metadata of input
dataset samples according to distinct values of certain att... |
def meta_group(self, meta, meta_aggregates=None):
"""
*Wrapper of* ``GROUP``
Group operation only for metadata. For further information check :meth:`~.group`
"""
return self.group(meta=meta, meta_aggregates=meta_aggregates) |
def regs_group(self, regs, regs_aggregates=None):
"""
*Wrapper of* ``GROUP``
Group operation only for region data. For further information check :meth:`~.group`
"""
return self.group(regs=regs, regs_aggregates=regs_aggregates) |
def materialize(self, output_path=None, output_name=None, all_load=True):
"""
*Wrapper of* ``MATERIALIZE``
Starts the execution of the operations for the GMQLDataset. PyGMQL implements lazy execution
and no operation is performed until the materialization of the results is requestd.
... |
def step(self):
"""Grab a new message and dispatch it to the handler.
This method should not be extended or overwritten. Instead,
implementations of this daemon should implement the 'get_message()'
and 'handle_message()' methods.
"""
message = self.get_message()
... |
def init_app(self, app=None):
"""Initialize application configuration"""
config = getattr(app, 'config', app)
self.team_id = config.get('TEAM_ID') |
def command(self, command, token, team_id=None, methods=['GET'], **kwargs):
"""A decorator used to register a command.
Example::
@slack.command('your_command', token='your_token',
team_id='your_team_id', methods=['POST'])
def your_method(**kwargs):
... |
def dispatch(self):
"""Dispatch http request to registerd commands.
Example::
slack = Slack(app)
app.add_url_rule('/', view_func=slack.dispatch)
"""
from flask import request
method = request.method
data = request.args
if method == 'POST... |
def validate(self, command, token, team_id, method):
"""Validate request queries with registerd commands
:param command: command parameter from request
:param token: token parameter from request
:param team_id: team_id parameter from request
:param method: the request method
... |
def response(self, text, response_type='ephemeral', attachments=None):
"""Return a response with json format
:param text: the text returned to the client
:param response_type: optional. When `in_channel` is assigned,
both the response message and the initial
... |
def pid(self):
"""Get the pid which represents a daemonized process.
The result should be None if the process is not running.
"""
try:
with open(self.pidfile, 'r') as pidfile:
try:
pid = int(pidfile.read().strip())
exce... |
def pid(self, pidnum):
"""Set the pid for a running process."""
try:
with open(self.pidfile, "w+") as pidfile:
pidfile.write("{0}\n".format(pidnum))
except IOError:
LOG.exception("Failed to write pidfile {0}).".format(self.pidfile))
sys.exi... |
def pid(self):
"""Stop managing the current pid."""
try:
os.remove(self.pidfile)
except IOError:
if not os.path.isfile(self.pidfile):
return None
LOG.exception("Failed to clear pidfile {0}).".format(self.pidfile))
sys.exit(exit... |
def pool(self):
"""Get an gevent pool used to dispatch requests."""
self._pool = self._pool or gevent.pool.Pool(size=self.pool_size)
return self._pool |
def set_essid(interface, essid):
"""
Set the ESSID of a given interface
Arguments:
interface - device to work on (e.g. eth1, wlan0).
essid - ESSID to set. Must be no longer than IW_ESSID_MAX_SIZE (typically 32 characters).
"""
interface = _get_bytes(interface)
essid = _get_byte... |
def read_adjacency_matrix(file_path, separator):
"""
Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
Outp... |
def read_node_label_matrix(file_path, separator, number_of_nodes):
"""
Reads node-label pairs in csv format and returns a list of tuples and a node-label matrix.
Inputs: - file_path: The path where the node-label matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
... |
def ensure_data():
'''
Ensure that the Garuda directory and files
'''
if not os.path.exists(GARUDA_DIR):
os.makedirs(GARUDA_DIR)
Path(f'{GARUDA_DIR}/__init__.py').touch() |
def protoc_arguments():
'''
Construct protobuf compiler arguments
'''
proto_include = resource_filename('grpc_tools', '_proto')
return [
protoc.__file__, '-I', GARUDA_DIR, f'--python_out={GARUDA_DIR}',
f'--grpc_python_out={GARUDA_DIR}', GARUDA_PROTO_PATH,
f'-I{proto_include}'... |
def fix_grpc_import():
'''
Snippet to fix the gRPC import path
'''
with open(GARUDA_GRPC_PATH, 'r') as f:
filedata = f.read()
filedata = filedata.replace(
'import garuda_pb2 as garuda__pb2',
f'import {GARUDA_DIR}.garuda_pb2 as garuda__pb2')
with open(GARUDA_GRPC_PATH, 'w'... |
def write_average_score_row(fp, score_name, scores):
"""
Simple utility function that writes an average score row in a file designated by a file pointer.
Inputs: - fp: A file pointer.
- score_name: What it says on the tin.
- scores: An array of average score values corresponding ... |
def catch_errors(f):
"""
Catches specific errors in admin actions and shows a friendly error.
"""
@functools.wraps(f)
def wrapper(self, request, *args, **kwargs):
try:
return f(self, request, *args, **kwargs)
except exceptions.CertificateExpired:
self.message... |
def augmented_tf_idf(attribute_matrix):
"""
Performs augmented TF-IDF normalization on a bag-of-words vector representation of data.
Augmented TF-IDF introduced in: Manning, C. D., Raghavan, P., & Schütze, H. (2008).
Introduction to information retrieval (Vol. 1, p. 6).
... |
def get_file_row_generator(file_path, separator, encoding=None):
"""
Reads an separated value file row by row.
Inputs: - file_path: The path of the separated value format file.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- encoding: The encoding used in the stored ... |
def store_pickle(file_path, data):
"""
Pickle some data to a given path.
Inputs: - file_path: Target file path.
- data: The python object to be serialized via pickle.
"""
pkl_file = open(file_path, 'wb')
pickle.dump(data, pkl_file)
pkl_file.close() |
def load_pickle(file_path):
"""
Unpickle some data from a given path.
Input: - file_path: Target file path.
Output: - data: The python object that was serialized and stored in disk.
"""
pkl_file = open(file_path, 'rb')
data = pickle.load(pkl_file)
pkl_file.close()
return data |
def makeServoIDPacket(curr_id, new_id):
"""
Given the current ID, returns a packet to set the servo to a new ID
"""
pkt = Packet.makeWritePacket(curr_id, xl320.XL320_ID, [new_id])
return pkt |
def normalize_rows(features):
"""
This performs row normalization to 1 of community embedding features.
Input: - X in R^(nxC_n): The community indicator matrix.
Output: - X_norm in R^(nxC_n): The row normalized community indicator matrix.
"""
# Normalize each row of term frequencies to 1
... |
def normalize_columns(features):
"""
This performs column normalization of community embedding features.
Input: - X in R^(nxC_n): The community indicator matrix.
Output: - X_norm in R^(nxC_n): The tf-idf + row normalized community indicator matrix.
"""
# Calculate inverse document frequency.
... |
def pagerank_limit_push(s, r, w_i, a_i, push_node, rho):
"""
Performs a random step without a self-loop.
"""
# Calculate the A and B quantities to infinity
A_inf = rho*r[push_node]
B_inf = (1-rho)*r[push_node]
# Update approximate Pagerank and residual vectors
s[push_node] += A_inf
... |
def pagerank_lazy_push(s, r, w_i, a_i, push_node, rho, lazy):
"""
Performs a random step with a self-loop.
Introduced in: Andersen, R., Chung, F., & Lang, K. (2006, October).
Local graph partitioning using pagerank vectors.
In Foundations of Computer Science, 2006. FOC... |
def cumulative_pagerank_difference_limit_push(s, r, w_i, a_i, push_node, rho):
"""
Performs a random step without a self-loop.
Inputs: - s: A NumPy array that contains the approximate absorbing random walk cumulative probabilities.
- r: A NumPy array that contains the residual probability dis... |
def includeme(config):
"""Include pyramid_multiauth into a pyramid configurator.
This function provides a hook for pyramid to include the default settings
for auth via pyramid_multiauth. Activate it like so:
config.include("pyramid_multiauth")
This will pull the list of registered authn poli... |
def policy_factory_from_module(config, module):
"""Create a policy factory that works by config.include()'ing a module.
This function does some trickery with the Pyramid config system. Loosely,
it does config.include(module), and then sucks out information about the
authn policy that was registered. I... |
def get_policy_definitions(settings):
"""Find all multiauth policy definitions from the settings dict.
This function processes the paster deployment settings looking for items
that start with "multiauth.policy.<policyname>.". It pulls them all out
into a dict indexed by the policy name.
"""
po... |
def load_file(filename):
"""Read file to memory.
For stdin sourced files, this function does something super duper incredibly hacky and shameful. So so shameful. I'm
obtaining the original source code of the target module from the only instance of pycodestyle.Checker through the
Python garbage collecto... |
def ignore(code):
"""Should this code be ignored.
:param str code: Error code (e.g. D201).
:return: True if code should be ignored, False otherwise.
:rtype: bool
"""
if code in Main.options['ignore']:
return True
if any(c in code for c in Main.options['ignore']):
return Tru... |
def add_options(cls, parser):
"""Add options to flake8.
:param parser: optparse.OptionParser from pycodestyle.
"""
parser.add_option('--show-pydocstyle', action='store_true', help='show explanation of each PEP 257 error')
parser.config_options.append('show-pydocstyle') |
def parse_options(cls, options):
"""Read parsed options from flake8.
:param options: Options to add to flake8's command line options.
"""
# Handle flake8 options.
cls.options['explain'] = bool(options.show_pydocstyle)
cls.options['ignore'] = options.ignore
# Han... |
def run(self):
"""Run analysis on a single file."""
pydocstyle.Error.explain = self.options['explain']
filename, source = load_file(self.filename)
for error in pydocstyle.PEP257Checker().check_source(source, filename):
if not hasattr(error, 'code') or ignore(error.code):
... |
def numbers(self):
""""
Returns the barcode's number without the verification digit.
:return: list(int)
"""
numstring = '{:011d}{:02d}{:04d}{}{}'.format(
self._receipt.point_of_sales.owner.cuit, # 11 digits
int(self._receipt.receipt_type.code), # 2 digi... |
def verification_digit(numbers):
"""
Returns the verification digit for a given numbre.
The verification digit is calculated as follows:
* A = sum of all even-positioned numbers
* B = A * 3
* C = sum of all odd-positioned numbers
* D = B + C
* The result... |
def full_number(self):
"""
Returns the full number including the verification digit.
:return: str
"""
return '{}{}'.format(
''.join(str(n) for n in self.numbers),
ReceiptBarcodeGenerator.verification_digit(self.numbers),
) |
def read_adjacency_matrix(file_path, separator, numbering="matlab"):
"""
Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", ... |
def read_node_label_matrix(file_path, separator, numbering="matlab"):
"""
Reads node-label pairs in csv format and returns a list of tuples and a node-label matrix.
Inputs: - file_path: The path where the node-label matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ... |
def write_screen_name_to_topics(filepath, user_label_matrix, node_to_id, id_to_name, label_to_lemma, lemma_to_keyword, separator=","):
"""
Writes a user name and associated topic names per row.
"""
user_label_matrix = spsp.coo_matrix(user_label_matrix)
shape = user_label_matrix.shape
nnz = user... |
def packetToDict(pkt):
"""
Given a packet, this turns it into a dictionary ... is this useful?
in: packet, array of numbers
out: dictionary (key, value)
"""
d = {
'id': pkt[4],
# 'instruction': xl320.InstrToStr[pkt[7]],
# 'length': (pkt[6] << 8) + pkt[5],
# 'params': pkt[8:-2],
'Model Number': (pkt[10... |
def sweep(port, rate, ID, retry=3):
"""
Sends a ping packet to ID's from 0 to maximum and prints out any returned
messages.
Actually send a broadcast and will retry (resend) the ping 3 times ...
"""
if port == 'dummy':
s = ServoSerial(port, rate, fake=True)
else:
s = ServoSerial(port, rate)
if ID < 0:
I... |
def calculate_epsilon_effective(rho, epsilon, seed_degree, neighbor_degrees, mean_degree):
"""
Semi-automatic effective epsilon threshold calculation.
"""
# Calculate a weighted neighborhood degree average.
# neighborhood_degree = rho*seed_degree + (1-rho)*neighbor_degrees.mean()
neighborhood_de... |
def arcte_with_lazy_pagerank(adjacency_matrix, rho, epsilon, number_of_threads=None):
"""
Extracts local community features for all graph nodes based on the partitioning of node-centric similarity vectors.
Inputs: - A in R^(nxn): Adjacency matrix of an undirected network represented as a SciPy Sparse COOr... |
def get_folds_generator(node_label_matrix,
labelled_node_indices,
number_of_categories,
dataset_memory_folder,
percentage,
number_of_folds=10):
"""
Read or form and store the seed nodes for tr... |
def generate_folds(node_label_matrix, labelled_node_indices, number_of_categories, percentage, number_of_folds=10):
"""
Form the seed nodes for training and testing.
Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format.
- labelled_node_indices: A NumPy arra... |
def iterative_stratification(node_label_matrix, training_set_size, number_of_categories, random_seed=0):
"""
Iterative data fold stratification/balancing for two folds.
Based on: Sechidis, K., Tsoumakas, G., & Vlahavas, I. (2011).
On the stratification of multi-label data.
In Ma... |
def form_node_label_prediction_matrix(y_pred, y_test):
"""
Given the discriminator distances, this function forms the node-label prediction matrix.
It is assumed that the number of true labels is known.
Inputs: - y_pred: A NumPy array that contains the distance from the discriminator for each label f... |
def calculate_measures(y_pred, y_test):
"""
Calculates the F-scores and F-score averages given a classification result and a ground truth.
Inputs: - y_pred: The node-label prediction for the test set in a SciPy sparse CSR matrix format.
- y_test: The node-label ground truth for the test set i... |
def decode(buff):
"""
Transforms the raw buffer data read in into a list of bytes
"""
pp = list(map(ord, buff))
if 0 == len(pp) == 1:
pp = []
return pp |
def read(self, how_much=128): # FIXME: 128 might be too much ... what is largest?
"""
This toggles the RTS pin and reads in data. It also converts the buffer
back into a list of bytes and searches through the list to find valid
packets of info. If there is more than one packet, this returns an
array of valid... |
def read2(self, how_much=128): # FIXME: 128 might be too much ... what is largest?
"""
This toggles the RTS pin and reads in data. It also converts the buffer
back into a list of bytes and searches through the list to find valid
packets of info. If there is more than one packet, this returns an
array of vali... |
def write(self, pkt):
"""
This is a simple serial write command. It toggles the RTS pin and formats
all of the data into bytes before it writes.
"""
self.setRTS(self.DD_WRITE)
self.flushInput()
# prep data array for transmition
pkt = bytearray(pkt)
pkt = bytes(pkt)
num = self.serial.write(pkt)
# ... |
def sendPkt(self, pkt, retry=5, sleep_time=0.01):
"""
Sends a packet and waits for a return. If no return is given, then it
resends the packet. If an error occurs, it also resends the packet.
in:
pkt - command packet to send to servo
cnt - how many retries should this do? default = 5
out:
array of p... |
def scipy_sparse_to_csv(filepath, matrix, separator=",", directed=False, numbering="matlab"):
"""
Writes sparse matrix in separated value format.
"""
matrix = spsp.coo_matrix(matrix)
shape = matrix.shape
nnz = matrix.getnnz()
if numbering == "matlab":
row = matrix.row + 1
c... |
def read_adjacency_matrix(file_path, separator, undirected):
"""
Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ... |
def publish(build):
""" publish the package itself """
build.packages.install("wheel")
build.packages.install("twine")
build.executables.run([
"python", "setup.py",
"sdist", "bdist_wheel", "--universal", "--release"
])
build.executables.run([
"twine", "upload", "dist/*"
... |
def fast_approximate_personalized_pagerank(s,
r,
w_i,
a_i,
out_degree,
in_degree,
... |
def lazy_approximate_personalized_pagerank(s,
r,
w_i,
a_i,
out_degree,
in_degree,
... |
def read_matlab_features(array_paths, number_of_nodes, dimensionality):
"""
Returns a sparse feature matrix as calculated by a Matlab routine.
"""
# Read the data array
file_row_gen = get_file_row_generator(array_paths[0], "\t")
data = list()
append_data = data.append
for file_row in fil... |
def mroc(adjacency_matrix, alpha):
"""
Extracts hierarchical community features using the MROC method.
Introduced in: Wang, X., Tang, L., Liu, H., & Wang, L. (2013).
Learning with multi-resolution overlapping communities.
Knowledge and information systems, 36(2), 517-5... |
def community_neighbors(c_j, reverse_index_rows, unavailable_communities, unavailable_communities_counter):
"""
Finds communities with shared nodes to a seed community. Called by mroc.
Inputs: - c_j: The seed community for which we want to find which communities overlap.
- reverse_index_rows:... |
def jaccard(c_1, c_2):
"""
Calculates the Jaccard similarity between two sets of nodes. Called by mroc.
Inputs: - c_1: Community (set of nodes) 1.
- c_2: Community (set of nodes) 2.
Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.
"""
nom = np.inter... |
def louvain(adjacency_matrix):
"""
Performs community embedding using the LOUVAIN method.
Introduced in: Blondel, V. D., Guillaume, J. L., Lambiotte, R., & Lefebvre, E. (2008).
Fast unfolding of communities in large networks.
Journal of Statistical Mechanics: Theory an... |
def laplacian_eigenmaps(adjacency_matrix, k):
"""
Performs spectral graph embedding using the graph symmetric normalized Laplacian matrix.
Introduced in: Belkin, M., & Niyogi, P. (2003).
Laplacian eigenmaps for dimensionality reduction and data representation.
Neural c... |
def replicator_eigenmaps(adjacency_matrix, k):
"""
Performs spectral graph embedding on the centrality reweighted adjacency matrix
Inputs: - A in R^(nxn): Adjacency matrix of an undirected network represented as a scipy.sparse.coo_matrix
- k: The number of social dimensions/eigenve... |
def base_communities(adjacency_matrix):
"""
Forms the community indicator normalized feature matrix for any graph.
Inputs: - A in R^(nxn): Adjacency matrix of an undirected network represented as a SciPy Sparse COOrdinate matrix.
Outputs: - X in R^(nxC_n): The latent space embedding represented as a ... |
def create_embeded_pkcs7_signature(data, cert, key):
"""
Creates an embeded ("nodetached") pkcs7 signature.
This is equivalent to the output of::
openssl smime -sign -signer cert -inkey key -outform DER -nodetach < data
:type data: bytes
:type cert: str
:type key: str
""" # noqa:... |
def create_key(file_):
"""
Create a key and save it into ``file_``.
Note that ``file`` must be opened in binary mode.
"""
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 2048)
file_.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
file_.flush() |
def create_csr(key_file, organization_name, common_name, serial_number, file_):
"""Create a CSR for a key, and save it into ``file``."""
key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_file.read())
req = crypto.X509Req()
subj = req.get_subject()
subj.O = organization_name # noqa: E741 (we c... |
def model_fit(X_train, y_train, svm_hardness, fit_intercept, number_of_threads, classifier_type="LinearSVC"):
"""
Fits a Linear Support Vector Classifier to the labelled graph-based features using the LIBLINEAR library.
One-vs-All: http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRe... |
def meta_model_fit(X_train, y_train, svm_hardness, fit_intercept, number_of_threads, regressor_type="LinearSVR"):
"""
Trains meta-labeler for predicting number of labels for each user.
Based on: Tang, L., Rajan, S., & Narayanan, V. K. (2009, April).
Large scale multi-label classification via ... |
def weigh_users(X_test, model, classifier_type="LinearSVC"):
"""
Uses a trained model and the unlabelled features to produce a user-to-label distance matrix.
Inputs: - feature_matrix: The graph based-features in either NumPy or SciPy sparse array format.
- model: A trained scikit-learn One-vs... |
def classify_users(X_test, model, classifier_type, meta_model, upper_cutoff):
"""
Uses a trained model and the unlabelled features to associate users with labels.
The decision is done as per scikit-learn:
http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html
h... |
def get_client(service_name, sandbox=False):
"""
Returns a client for a given service.
The `sandbox` argument should only be necessary if a the client will be
used to make a request. If it will only be used to serialize objects, it is
irrelevant. Avoid the overhead of determining the sandbox mode ... |
def _extract_seq(extractor, seq):
"""Convert a sequence to primitive equivalents."""
subtype = Any
if seq.__args__ and seq.__args__[0] is not Any:
subtype = seq.__args__[0]
return _array_type(extractor.extract(subtype)) |
def _is_sequence(typ):
"""
returns True if the type in question
is a Sequence[] object from the typing module.
"""
# PEP_560 deprecates issubclass for
# List types, for the time being
# we'll support a specific escape hatch.
if PEP_560: # pragma: no cover
return isinstance(typ, ... |
def extract(cls, extractor, typ):
"""
take an attrs based class, and convert it
to jsonschema.
"""
schema = {
"title": typ.__name__,
"type": "object",
"properties": {},
"required": []
}
for attribute in attr.fields(t... |
def readme():
"""Try to read README.rst or return empty string if failed.
:return: File contents.
:rtype: str
"""
path = os.path.realpath(os.path.join(os.path.dirname(__file__), 'README.rst'))
handle = None
url_prefix = 'https://raw.githubusercontent.com/Robpol86/{name}/v{version}/'.format(... |
def listSerialPorts():
"""
http://pyserial.readthedocs.io/en/latest/shortintro.html
This calls the command line tool from pyserial to list the available
serial ports.
"""
cmd = 'python -m serial.tools.list_ports'
err, ret = commands.getstatusoutput(cmd)
if not err:
r = ret.split('\n')
ret = []
for line i... |
def prettyPrintPacket(ctrl_table):
"""
This will pretty print out a packet's fields.
in: dictionary of a packet
out: nothing ... everything is printed to screen
"""
print('---------------------------------------')
print("{:.<29} {}".format('id', ctrl_table['id']))
ctrl_table.pop('id')
for key, value in ctrl_t... |
def read(fname):
"""
Reads a Json file
in: file name
out: length of file, dictionary
"""
try:
with open(fname, 'r') as f:
data = json.load(f)
return data
except IOError:
raise Exception('Could not open {0!s} for reading'.format((fname))) |
def write(fname, data):
"""
Writes a Json file
in: fname - file name
data - dictionary of data to put into the file
out: nothing, everything is written to a file
"""
try:
with open(fname, 'w') as f:
json.dump(data, f)
except IOError:
raise Exception('Could not open {0!s} for writing'.forma... |
def makePacket(ID, instr, reg=None, params=None):
"""
This makes a generic packet.
TODO: look a struct ... does that add value using it?
0xFF, 0xFF, 0xFD, 0x00, ID, LEN_L, LEN_H, INST, PARAM 1, PARAM 2, ..., PARAM N, CRC_L, CRC_H]
in:
ID - servo id
instr - instruction
reg - register
params - instruction ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.