code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
flux_result = self.solve_fba(objective)
return flux_result.get_value(self._v_wt[objective]) | def get_fba_obj_flux(self, objective) | Return the maximum objective flux solved by FBA. | 10.793064 | 9.845366 | 1.096258 |
reactions = set(self._adjustment_reactions())
z_diff = self._z_diff
v = self._v
with self.constraints() as constr:
for f_reaction, f_value in iteritems(wt_fluxes):
if f_reaction in reactions:
# Add the constraint that finds the o... | def lin_moma(self, wt_fluxes) | Minimize the redistribution of fluxes using a linear objective.
The change in flux distribution is mimimized by minimizing the sum
of the absolute values of the differences of wild type FBA solution
and the knockout strain flux solution.
This formulation bases the solution on the wild ... | 8.195283 | 7.418822 | 1.104661 |
reactions = set(self._adjustment_reactions())
z_diff = self._z_diff
v = self._v
v_wt = self._v_wt
with self.constraints() as constr:
for f_reaction in reactions:
# Add the constraint that finds the optimal solution, such
# th... | def lin_moma2(self, objective, wt_obj) | Find the smallest redistribution vector using a linear objective.
The change in flux distribution is mimimized by minimizing the sum
of the absolute values of the differences of wild type FBA solution
and the knockout strain flux solution.
Creates the constraint that the we select the ... | 6.830615 | 5.822847 | 1.173071 |
reactions = set(self._adjustment_reactions())
v = self._v
obj_expr = 0
for f_reaction, f_value in iteritems(wt_fluxes):
if f_reaction in reactions:
# Minimize the Euclidean distance between the two vectors
obj_expr += (f_value - v[f_r... | def moma(self, wt_fluxes) | Minimize the redistribution of fluxes using Euclidean distance.
Minimizing the redistribution of fluxes using a quadratic objective
function. The distance is minimized by minimizing the sum of
(wild type - knockout)^2.
Args:
wt_fluxes: Dictionary of all the wild type fluxes... | 6.312294 | 6.099494 | 1.034888 |
obj_expr = 0
for reaction in self._adjustment_reactions():
v_wt = self._v_wt[reaction]
v = self._v[reaction]
obj_expr += (v_wt - v)**2
self._prob.set_objective(obj_expr)
with self.constraints(self._v_wt[objective] >= wt_obj):
sel... | def moma2(self, objective, wt_obj) | Find the smallest redistribution vector using Euclidean distance.
Minimizing the redistribution of fluxes using a quadratic objective
function. The distance is minimized by minimizing the sum of
(wild type - knockout)^2.
Creates the constraint that the we select the optimal flux vector... | 6.968281 | 6.508629 | 1.070622 |
# Set up logging for the command line interface
if 'PSAMM_DEBUG' in os.environ:
level = getattr(logging, os.environ['PSAMM_DEBUG'].upper(), None)
if level is not None:
logging.basicConfig(level=level)
else:
logging.basicConfig(level=logging.INFO)
base_logger... | def main(command_class=None, args=None) | Run the command line interface with the given :class:`Command`.
If no command class is specified the user will be able to select a specific
command through the first command line argument. If the ``args`` are
provided, these should be a list of strings that will be used instead of
``sys.argv[1:]``. Thi... | 2.571637 | 2.580286 | 0.996648 |
solver_args = dict(kwargs)
solver_args.update(self._solver_args)
return generic.Solver(**solver_args) | def _get_solver(self, **kwargs) | Return a new :class:`psamm.lpsolver.lp.Solver` instance | 4.528869 | 4.577941 | 0.989281 |
if self._args.parallel > 0:
workers = self._args.parallel
else:
try:
workers = mp.cpu_count() // cpus_per_worker
except NotImplementedError:
workers = 1
if workers != 1:
logger.info('Using {} parallel worke... | def _create_executor(self, handler, args, cpus_per_worker=1) | Return a new :class:`.Executor` instance. | 3.118651 | 2.978059 | 1.047209 |
"Parse an error response"
error_code = response.split(' ')[0]
if error_code in self.EXCEPTION_CLASSES:
response = response[len(error_code) + 1:]
return self.EXCEPTION_CLASSES[error_code](response)
return ResponseError(response) | def parse_error(self, response) | Parse an error response | 3.715353 | 3.740424 | 0.993297 |
self._sock = connection._sock
self._buffer = SocketBuffer(self._sock, self.socket_read_size)
if connection.decode_responses:
self.encoding = connection.encoding | def on_connect(self, connection) | Called when the socket connects | 6.677376 | 6.436263 | 1.037462 |
"Called when the socket disconnects"
if self._sock is not None:
self._sock.close()
self._sock = None
if self._buffer is not None:
self._buffer.close()
self._buffer = None
self.encoding = None | def on_disconnect(self) | Called when the socket disconnects | 3.307456 | 3.31138 | 0.998815 |
if self._sock:
return
try:
sock = self._connect()
except socket.error:
e = sys.exc_info()[1]
raise ConnectionError(self._error_message(e))
self._sock = sock
try:
self.on_connect()
except SSDBError:
... | def connect(self) | Connects to the SSDB server if not already connected | 5.950853 | 5.130455 | 1.159907 |
# we want to mimic what socket.create_connection does to support
# ipv4/ipv6, but we want to set options prior to calling
# socket.connect()
err = None
for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
... | def _connect(self) | Create a TCP socket connection | 2.43226 | 2.387649 | 1.018684 |
self._parser.on_disconnect()
if self._sock is None:
return
try:
self._sock.shutdown(socket.SHUT_RDWR)
self._sock.close()
except socket.error:
pass
self._sock = None | def disconnect(self) | Disconnects from the SSDB server | 2.617731 | 2.554041 | 1.024937 |
"Poll the socket to see if there's data that can be read."
sock = self._sock
if not sock:
self.connect()
sock = self._sock
return self._parser.can_read() or \
bool(select([sock], [], [], timeout)[0]) | def can_read(self, timeout=0) | Poll the socket to see if there's data that can be read. | 5.624446 | 4.228645 | 1.330082 |
try:
response = self._parser.read_response()
except:
self.disconnect()
raise
if isinstance(response, ResponseError):
raise response
#print(response)
return response | def read_response(self) | Read the response from a previously sent command | 4.379668 | 4.381404 | 0.999604 |
if isinstance(value, Token):
return b(value.value)
if isinstance(value, bytes):
return value
elif isinstance(value, (int, long)):
value = b(str(value))
elif isinstance(value, float):
value = repr(value)
elif... | def encode(self, value) | Return a bytestring representation of the value | 2.604183 | 2.582304 | 1.008473 |
# the client might have included 1 or more literal arguments in
# the command name, e.g., 'CONFIG GET'. The SSDB server expects
# these arguments to be sent separately, so split the first
# argument manually. All of these arguements get wrapped
# in the Token class to pr... | def pack_command(self, *args) | Pack a series of arguments into a value SSDB command | 6.745545 | 6.465482 | 1.043317 |
# Make sure we haven't changed process.
self._checkpid()
# Try and get a connection from the pool. If one isn't available within
# self.timeout then raise a ``ConnectionError``.
connection = None
try:
connection = self.pool.get(block=True,timeout=se... | def get_connection(self, command_name, *keys, **options) | Get a connection, blocking for ``self.timeout`` until a connection
is available from the pool.
If the connection returned is ``None`` then creates a new connection.
Because we use a last-in first-out queue, the existing connections
(having been returned to the pool after the ini... | 6.902891 | 6.200978 | 1.113194 |
val = loader.construct_scalar(node)
return lazy_once(env_get, val) | def expand_env_lazy(loader, node) | Substitutes a variable read from a YAML node with the value stored in Fabric's ``env`` dictionary. Creates an
object for late resolution.
:param loader: YAML loader.
:type loader: yaml.loader.SafeLoader
:param node: Document node.
:type node: ScalarNode
:return: Corresponding value stored in th... | 7.705925 | 13.287591 | 0.579934 |
if not options:
options = DiffOptions()
if not options.duck_type and type(a) != type(b) and not (
a is _nothing or b is _nothing
):
raise TypeError(
"cannot compare %s with %s" % (type(a).__name__, type(b).__name__)
)
if fs_a is None:
fs_a = Fie... | def compare_record_iter(a, b, fs_a=None, fs_b=None, options=None) | This generator function compares a record, slot by slot, and yields
differences found as ``DiffInfo`` objects.
args:
``a=``\ *Record*
The base object
``b=``\ *Record*\ \|\ *object*
The 'other' object, which must be the same type as ``a``, unless
``options.d... | 2.292977 | 2.156928 | 1.063075 |
if collection is _nothing:
def generator():
if False:
yield any
elif hasattr(collection, "itertuples"):
return collection.itertuples()
elif hasattr(collection, "keys"):
def generator():
for key in collection.keys():
yiel... | def collection_generator(collection) | This function returns a generator which iterates over the collection,
similar to Collection.itertuples(). Collections are viewed by this module,
regardless of type, as a mapping from an index to the value. For sets, the
"index" is the value itself (ie, (V, V)). For dicts, it's a string, and
for lists... | 2.418831 | 2.391887 | 1.011265 |
if fs_a is None:
fs_a = FieldSelector(tuple())
fs_b = FieldSelector(tuple())
if not options:
options = DiffOptions()
propvals = dict(a=propval_a, b=propval_b)
values = dict()
indices = dict()
for x in "a", "b":
propval_x = propvals[x]
vals = values[x]... | def compare_list_iter(propval_a, propval_b, fs_a=None, fs_b=None,
options=None) | Generator for comparing 'simple' lists when they are encountered. This
does not currently recurse further. Arguments are as per other
``compare_``\ *X* functions. | 2.270983 | 2.264897 | 1.002687 |
if fs_a is None:
fs_a = FieldSelector(tuple())
fs_b = FieldSelector(tuple())
if not options:
options = DiffOptions()
propvals = dict(a=propval_a, b=propval_b)
values = dict()
rev_keys = dict()
for x in "a", "b":
propval_x = propvals[x]
vals = values[x... | def compare_dict_iter(propval_a, propval_b, fs_a=None, fs_b=None,
options=None) | Generator for comparing 'simple' dicts when they are encountered. This
does not currently recurse further. Arguments are as per other
``compare_``\ *X* functions. | 2.141291 | 2.151088 | 0.995446 |
if options is None:
options = DiffOptions(**kwargs)
elif len(kwargs):
raise exc.DiffOptionsException()
null_fs = FieldSelector(tuple())
return _diff_iter(base, other, null_fs, null_fs, options) | def diff_iter(base, other, options=None, **kwargs) | Compare a Record with another object (usually a record of the same
type), and yield differences as :py:class:`DiffInfo` instances.
args:
``base=``\ *Record*
The 'base' object to compare against. The enumeration in
:py:class:`DiffTypes` is relative to this object.
``oth... | 6.342559 | 6.567944 | 0.965684 |
return Diff(diff_iter(base, other, **kwargs),
base_type_name=type(base).__name__,
other_type_name=type(other).__name__) | def diff(base, other, **kwargs) | Eager version of :py:func:`diff_iter`, which takes all the same options
and returns a :py:class:`Diff` instance. | 4.017357 | 3.408437 | 1.178651 |
if isinstance(value, unicode):
return u" ".join(
x for x in re.split(r'\s+', value, flags=re.UNICODE) if
len(x)
)
else:
return " ".join(value.split()) | def normalize_whitespace(self, value) | Normalizes whitespace; called if ``ignore_ws`` is true. | 3.249213 | 3.104067 | 1.04676 |
if isinstance(value, unicode):
return unicodedata.normalize('NFC', value)
else:
return value | def normalize_unf(self, value) | Normalizes Unicode Normal Form (to NFC); called if
``unicode_normal`` is true. | 2.928582 | 2.804911 | 1.044091 |
if self.ignore_ws:
value = self.normalize_whitespace(value)
if self.ignore_case:
value = self.normalize_case(value)
if self.unicode_normal:
value = self.normalize_unf(value)
return value | def normalize_text(self, value) | This hook is called by :py:meth:`DiffOptions.normalize_val` if the
value (after slot/item normalization) is a string, and is responsible
for calling the various ``normalize_``\ foo methods which act on text. | 3.477442 | 3.298528 | 1.054241 |
if isinstance(value, basestring):
value = self.normalize_text(value)
if self.ignore_empty_slots and self.value_is_empty(value):
value = _nothing
return value | def normalize_val(self, value=_nothing) | Hook which is called on every value before comparison, and should
return the scrubbed value or ``self._nothing`` to indicate that the
value is not set. | 4.196757 | 4.691689 | 0.894509 |
if value is not _nothing and hasattr(prop, "compare_as"):
method, nargs = getattr(prop, "compare_as_info", (False, 1))
args = []
if method:
args.append(obj)
if nargs:
args.append(value)
value = prop.compare_as(*... | def normalize_object_slot(self, value=_nothing, prop=None, obj=None) | This hook wraps ``normalize_slot``, and performs clean-ups which
require access to the object the slot is in as well as the value. | 4.030938 | 4.103472 | 0.982324 |
if value is not _nothing and hasattr(coll, "compare_item_as"):
value = coll.compare_item_as(value)
return self.normalize_val(value) | def normalize_item(self, value=_nothing, coll=None, index=None) | Hook which is called on every *collection item*; this is a way to
perform context-aware clean-ups.
args:
``value=``\ *nothing*\ \|\ *anything*
The value in the collection slot. *nothing* can be detected in
sub-class methods as ``self._nothing``.
... | 5.937177 | 4.182699 | 1.419461 |
pk = record_id(record, type_, selector, self.normalize_object_slot)
return pk | def record_id(self, record, type_=None, selector=None) | Retrieve an object identifier from the given record; if it is an
alien class, and the type is provided, then use duck typing to get the
corresponding fields of the alien class. | 17.777842 | 20.962025 | 0.848098 |
reaction_set = set(model.reactions)
subset = set(reaction_id for reaction_id in reaction_set
if model.limits[reaction_id].lower >= 0)
logger.info('Checking {} irreversible reactions...'.format(len(subset)))
logger.debug('|J| = {}, J = {}'.format(len(subset), subset))
p = Fast... | def fastcc(model, epsilon, solver) | Check consistency of model reactions.
Yield all reactions in the model that are not part of the consistent
subset.
Args:
model: :class:`MetabolicModel` to solve.
epsilon: Flux threshold value.
solver: LP solver instance to use. | 3.463292 | 3.358974 | 1.031056 |
for reaction in fastcc(model, epsilon, solver):
return False
return True | def fastcc_is_consistent(model, epsilon, solver) | Quickly check whether model is consistent
Return true if the model is consistent. If it is only necessary to know
whether a model is consistent, this function is fast as it will return
the result as soon as it finds a single inconsistent reaction.
Args:
model: :class:`MetabolicModel` to solve.... | 10.072978 | 14.202061 | 0.709262 |
reaction_set = set(model.reactions)
return reaction_set.difference(fastcc(model, epsilon, solver)) | def fastcc_consistent_subset(model, epsilon, solver) | Return consistent subset of model.
The largest consistent subset is returned as
a set of reaction names.
Args:
model: :class:`MetabolicModel` to solve.
epsilon: Flux threshold value.
solver: LP solver instance to use.
Returns:
Set of reaction IDs in the consistent reac... | 5.767191 | 8.326535 | 0.692628 |
consistent_subset = set()
reaction_set = set(model.reactions)
subset = core - model.reversible
logger.debug('|J| = {}, J = {}'.format(len(subset), subset))
penalty_set = reaction_set - core
logger.debug('|P| = {}, P = {}'.format(len(penalty_set), penalty_set))
p = FastcoreProblem(mod... | def fastcore(model, core, epsilon, solver, scaling=1e5, weights={}) | Find a flux consistent subnetwork containing the core subset.
The result will contain the core subset and as few of the additional
reactions as possible.
Args:
model: :class:`MetabolicModel` to solve.
core: Set of core reaction IDs.
epsilon: Flux threshold value.
solver: LP... | 3.271911 | 3.272491 | 0.999823 |
if self._zl is None:
self._add_maximization_vars()
positive = set(reaction_subset) - self._flipped
negative = set(reaction_subset) & self._flipped
v = self._v.set(positive)
zl = self._zl.set(positive)
cs = self._prob.add_linear_constraints(v >= zl)... | def lp7(self, reaction_subset) | Approximately maximize the number of reaction with flux.
This is similar to FBA but approximately maximizing the number of
reactions in subset with flux > epsilon, instead of just maximizing the
flux of one particular reaction. LP7 prefers "flux splitting" over
"flux concentrating". | 3.666463 | 3.727013 | 0.983754 |
if self._z is None:
self._add_minimization_vars()
positive = set(subset_k) - self._flipped
negative = set(subset_k) & self._flipped
v = self._v.set(positive)
cs = self._prob.add_linear_constraints(v >= self._epsilon)
self._temp_constr.extend(cs)
... | def lp10(self, subset_k, subset_p, weights={}) | Force reactions in K above epsilon while minimizing support of P.
This program forces reactions in subset K to attain flux > epsilon
while minimizing the sum of absolute flux values for reactions
in subset P (L1-regularization). | 4.722232 | 4.50776 | 1.047578 |
if len(core) == 0:
return
self.lp7(core)
k = set()
for reaction_id in core:
flux = self.get_flux(reaction_id)
if self.is_flipped(reaction_id):
flux *= -1
if flux >= self._epsilon:
k.add(reaction_id... | def find_sparse_mode(self, core, additional, scaling, weights={}) | Find a sparse mode containing reactions of the core subset.
Return an iterator of the support of a sparse mode that contains as
many reactions from core as possible, and as few reactions from
additional as possible (approximately). A dictionary of weights can be
supplied which gives fur... | 3.747714 | 3.405573 | 1.100465 |
for reaction in reactions:
if reaction in self._flipped:
self._flipped.remove(reaction)
else:
self._flipped.add(reaction) | def flip(self, reactions) | Flip the specified reactions. | 2.437372 | 2.219277 | 1.098273 |
elements = set(f1)
elements.update(f2)
count, w_count, w_total = 0, 0, 0
for element in elements:
mi = min(f1.get(element, 0), f2.get(element, 0))
mx = max(f1.get(element, 0), f2.get(element, 0))
count += mi
w = weight_func(element)
w_count += w * mi
... | def _jaccard_similarity(f1, f2, weight_func) | Calculate generalized Jaccard similarity of formulas.
Returns the weighted similarity value or None if there is no overlap
at all. If the union of the formulas has a weight of zero (i.e. the
denominator in the Jaccard similarity is zero), a value of zero is
returned. | 2.375452 | 2.432616 | 0.976501 |
def dict_from_iter_sum(it, div):
d = {}
for k, v in it:
if k not in d:
d[k] = 0
d[k] += int(v / div)
return d
div = reduce(gcd, (abs(v) for _, v in reaction.compounds), 0)
if div == 0:
raise ValueError('Empty reaction')
left ... | def _reaction_to_dicts(reaction) | Convert a reaction to reduced left, right dictionaries.
Returns a pair of (left, right) dictionaries mapping compounds to
normalized integer stoichiometric values. If a compound occurs multiple
times on one side, the occurences are combined into a single entry in the
dictionary. | 3.762825 | 3.153222 | 1.193327 |
prior_alpha, prior_beta = prior
reactions = dict(reactions)
pair_reactions = {}
possible_pairs = Counter()
for reaction_id, equation in iteritems(reactions):
for (c1, _), (c2, _) in product(equation.left, equation.right):
spair = tuple(sorted([c1.name, c2.name]))
... | def predict_compound_pairs_iterated(
reactions, formulas, prior=(1, 43), max_iterations=None,
element_weight=element_weight) | Predict reaction pairs using iterated method.
Returns a tuple containing a dictionary of predictions keyed by the
reaction IDs, and the final number of iterations. Each reaction prediction
entry contains a tuple with a dictionary of transfers and a dictionary of
unbalanced compounds. The dictionary of ... | 2.826322 | 2.754518 | 1.026068 |
uninstantiated_left, uninstantiated_right = _reaction_to_dicts(reaction)
def compound_instances(uninstantiated):
instances = []
for compound, value in iteritems(uninstantiated):
if value > 0:
f = compound_formula[compound.name]
instances.append(_... | def _match_greedily(reaction, compound_formula, score_func) | Match compounds greedily based on score function.
Args:
reaction: Reaction equation :class:`psamm.reaction.Reaction`.
compound_formula: Dictionary mapping compound IDs to
:class:`psamm.formula.Formula`. Formulas must be flattened.
score_func: Function that takes two :class:`_Com... | 2.160592 | 2.143857 | 1.007806 |
def score_func(inst1, inst2):
score = _jaccard_similarity(
inst1.formula, inst2.formula, weight_func)
if score is None:
return None
pair = inst1.compound.name, inst2.compound.name
pair_weight = pair_weights.get(pair, 1.0)
return pair_weight * scor... | def predict_compound_pairs(reaction, compound_formula, pair_weights={},
weight_func=element_weight) | Predict compound pairs for a single reaction.
Performs greedy matching on reaction compounds using a scoring function
that uses generalized Jaccard similarity corrected by the weights in the
given dictionary. Returns a tuple of a transfer dictionary and a dictionary
of unbalanced compounds. The diction... | 3.686196 | 3.372036 | 1.093166 |
try:
raw = subprocess.check_output(['config-get', option_name, '--format=yaml'])
return yaml.load(raw.decode('UTF-8'))
except ValueError:
return None | def config_get(option_name) | Helper to access a Juju config option when charmhelpers is not available.
:param str option_name: Name of the config option to get the value of | 4.111848 | 5.404721 | 0.760788 |
resources = _load(resources_yaml, None)
if reporthook is None:
reporthook = lambda r: juju_log('Fetching %s' % r, level='INFO')
_fetch(resources, which, mirror_url, force, reporthook)
failed = _invalid(resources, which)
if failed:
juju_log('Failed to fetch resource%s: %s' % (
... | def fetch(which=None, mirror_url=None, resources_yaml='resources.yaml',
force=False, reporthook=None) | Attempt to fetch all resources for a charm.
:param list which: A name, or a list of one or more resource names, to
fetch. If ommitted, all non-optional resources are fetched.
You can also pass ``jujuresources.ALL`` to fetch all optional *and*
required resources.
:param str mirror_url: ... | 2.904453 | 2.803696 | 1.035937 |
resources = _load(resources_yaml, None)
return _install(resources, which, mirror_url, destination, skip_top_level) | def install(which=None, mirror_url=None, destination=None, skip_top_level=False,
resources_yaml='resources.yaml') | Install one or more resources.
The resource(s) will be fetched, if necessary, and different resource
types are handled appropriately (e.g., PyPI resources are installed
with ``pip``, archive file resources are extracted, non-archive file
resources are copied, etc).
For PyPI resources, this is roug... | 3.972406 | 6.779014 | 0.585986 |
from limitlessled.group.commands.legacy import (
CommandSetWhiteLegacy, CommandSetRgbwLegacy)
from limitlessled.group.commands.v6 import (
CommandSetBridgeLightV6, CommandSetWhiteV6,
CommandSetDimmerV6, CommandSetRgbwV6,
CommandSetRgbwwV6, CommandSetWrgbV6)
command_sets... | def command_set_factory(bridge, group_number, led_type) | Create command set for controlling a specific led group.
:param bridge: The bridge the leds are connected to.
:param group_number: The group number.
:param led_type: The type of the leds.
:return: The created command set. | 3.045207 | 3.166592 | 0.961667 |
style = color_style()
verbosity = int(options['verbosity'])
host = '%s:%s' % (options['livereload_host'],
options['livereload_port'])
try:
urlopen('http://%s/changed?files=.' % host)
self.message('LiveReload request emitted.\n',
... | def livereload_request(self, **options) | Performs the LiveReload request. | 4.791131 | 4.528118 | 1.058084 |
handler = super(Command, self).get_handler(*args, **options)
if options['use_livereload']:
self.livereload_request(**options)
return handler | def get_handler(self, *args, **options) | Entry point to plug the LiveReload feature. | 4.35332 | 3.538678 | 1.230211 |
def decorator(function):
def wrapper(self, *args, **kwargs):
saved_wait = self.wait
saved_reps = self.reps
self.wait = wait
self.reps = reps
function(self, *args, **kwargs)
self.wait = saved_wait
s... | def rate(wait=MIN_WAIT, reps=REPS) | Rate limit a command function.
:param wait: How long to wait between commands.
:param reps: How many times to send a command.
:returns: Decorator. | 2.16563 | 2.264225 | 0.956456 |
self._on = state
cmd = self.command_set.off()
if state:
cmd = self.command_set.on()
self.send(cmd) | def on(self, state) | Turn on or off.
:param state: True (on) or False (off). | 5.011065 | 5.374918 | 0.932305 |
for _ in range(2):
self.on = not self.on
time.sleep(duration) | def flash(self, duration=0.0) | Flash a group.
:param duration: How quickly to flash (in seconds). | 5.150898 | 7.088552 | 0.72665 |
self._bridge.send(cmd, wait=self.wait, reps=self.reps) | def send(self, cmd) | Send a command to the bridge.
:param cmd: List of command bytes. | 11.401579 | 10.712909 | 1.064284 |
copied = Pipeline().append(pipeline)
copied.group = self
self._queue.put(copied) | def enqueue(self, pipeline) | Start a pipeline.
:param pipeline: Start this pipeline. | 14.506814 | 20.26811 | 0.715746 |
wait = ((duration - self.wait * self.reps * commands) / steps) - \
(self.wait * self.reps * self._bridge.active)
return max(0, wait) | def _wait(self, duration, steps, commands) | Compute wait time.
:param duration: Total time (in seconds).
:param steps: Number of steps.
:param commands: Number of commands.
:returns: Wait in seconds. | 11.530541 | 12.97368 | 0.888764 |
factor = duration / ((self.wait * self.reps * commands) - \
(self.wait * self.reps * self._bridge.active))
steps = [math.ceil(factor * step) for step in steps]
if len(steps) == 1:
return steps[0]
else:
return steps | def _scale_steps(self, duration, commands, *steps) | Scale steps
:param duration: Total time (in seconds)
:param commands: Number of commands to be executed.
:param steps: Steps for one or many properties to take.
:return: Steps scaled to time and total. | 5.743152 | 5.979075 | 0.960542 |
if 'url' in definition:
return URLResource(name, definition, output_dir)
elif 'pypi' in definition:
return PyPIResource(name, definition, output_dir)
else:
return Resource(name, definition, output_dir) | def get(cls, name, definition, output_dir) | Dispatch to the right subclass based on the definition. | 2.609699 | 2.344984 | 1.112885 |
try:
output = subprocess.check_output(['file', '-z', self.destination]).decode('utf8')
return 'tar archive' in output and 'gzip compressed data' in output
except subprocess.CalledProcessError:
return False | def _is_bugged_tarfile(self) | Check for tar file that tarfile library mistakenly reports as invalid.
Happens with tar files created on FAT systems. See:
http://stackoverflow.com/questions/25552162/tarfile-readerror-file-could-not-be-opened-successfully | 5.384777 | 4.720463 | 1.140731 |
args = ['tar', '-xzf', self.destination, '-C', destination]
if skip_top_level:
args.extend(['--strip-components', '1'])
subprocess.check_call(args) | def _handle_bugged_tarfile(self, destination, skip_top_level) | Handle tar file that tarfile library mistakenly reports as invalid.
Happens with tar files created on FAT systems. See:
http://stackoverflow.com/questions/25552162/tarfile-readerror-file-could-not-be-opened-successfully | 2.883374 | 2.81935 | 1.022709 |
def orig_func_wraper(msg, *args):
# Take the callers name and snap it in two, result is log
# level, e.g.: log_debug is DEBUG level.
log_level = origfunc.__name__.split("_")[1]
import Log
if getattr(Log, "LOG_%s" % log_level.upper()) <= \
Log.LOG_LEVEL_C... | def log_wrap(origfunc) | DRY: Use magic instead of code to get a string for the correct log
level when calling ``print_log_msg``. Because writing the same
boilerplate code in each log_XXX def was too painful to commit. | 11.247169 | 10.331948 | 1.088582 |
while True:
self._event.clear()
self._queue.get().run(self._event) | def run(self) | Run the pipeline queue.
The pipeline queue will run forever. | 7.950383 | 7.427623 | 1.07038 |
_LOGGER.info("Starting a new pipeline on group %s", self._group)
self._group.bridge.incr_active()
for i, stage in enumerate(self._pipe):
self._execute_stage(i, stage, stop)
_LOGGER.info("Finished pipeline on group %s", self._group)
self._group.bridge.decr_act... | def run(self, stop) | Run the pipeline.
:param stop: Stop event | 5.005745 | 4.961233 | 1.008972 |
for stage in pipeline.pipe:
self._pipe.append(stage)
return self | def append(self, pipeline) | Append a pipeline to this pipeline.
:param pipeline: Pipeline to append.
:returns: This pipeline. | 8.885029 | 14.893166 | 0.596584 |
def stage_func(self, *args, **kwargs):
self._pipe.append(Stage(name, args, kwargs))
return self
setattr(Pipeline, name, stage_func) | def _add_stage(self, name) | Add stage methods at runtime.
Stage methods all follow the same pattern.
:param name: Stage name. | 4.751809 | 6.149905 | 0.772664 |
if stop.is_set():
_LOGGER.info("Stopped pipeline on group %s", self._group)
return
_LOGGER.info(" -> Running stage '%s' on group %s", stage, self._group)
if stage.name == 'on':
self._group.on = True
elif stage.name == 'off':
self._... | def _execute_stage(self, index, stage, stop) | Execute a pipeline stage.
:param index: Stage index.
:param stage: Stage object. | 1.702225 | 1.74594 | 0.974962 |
times = None
if 'iterations' in stage.kwargs:
times = stage.kwargs['iterations'] - 1
stages_back = 1
if 'stages' in stage.kwargs:
stages_back = stage.kwargs['stages']
i = 0
while i != times:
if stop.is_set():
br... | def _repeat(self, index, stage, stop) | Repeat a stage.
:param index: Stage index.
:param stage: Stage object to repeat.
:param iterations: Number of iterations (default infinite).
:param stages: Stages back to repeat (default 1). | 3.32327 | 3.245961 | 1.023817 |
try:
cmd = self.command_set.brightness(brightness)
self.send(cmd)
self._brightness = brightness
except AttributeError:
self._setter('_brightness', brightness,
self._dimmest, self._brightest,
self._... | def brightness(self, brightness) | Set the brightness.
:param brightness: Value to set (0.0-1.0). | 6.801426 | 7.888702 | 0.862173 |
if duration == 0:
if brightness is not None:
self.brightness = brightness
return
if brightness != self.brightness:
self._transition(duration, brightness) | def transition(self, duration, brightness=None) | Transition wrapper.
Short-circuit transition if necessary.
:param duration: Duration of transition.
:param brightness: Transition to this brightness. | 3.582458 | 4.2666 | 0.839652 |
# Set initial value.
b_start = self.brightness
# Compute ideal step amount.
b_steps = 0
if brightness is not None:
b_steps = steps(self.brightness, brightness,
self.command_set.brightness_steps)
# Compute ideal step amount ... | def _transition(self, duration, brightness) | Complete a transition.
:param duration: Duration of transition.
:param brightness: Transition to this brightness. | 4.946831 | 5.207524 | 0.949939 |
if value < 0 or value > 1:
raise ValueError("out of range")
if value == 0.0:
bottom()
elif value == 1.0:
top()
else:
to_step(value)
setattr(self, attr, value) | def _setter(self, attr, value, bottom, top, to_step) | Set a value.
:param attr: Attribute to set.
:param value: Value to use.
:param bottom: Get to bottom value.
:param top: Get to top value.
:param to_step: Get to intermediary value. | 2.801615 | 3.471635 | 0.807001 |
self._to_value(self._brightness, brightness,
self.command_set.brightness_steps,
self._dimmer, self._brighter) | def _to_brightness(self, brightness) | Step to a given brightness.
:param brightness: Get to this brightness. | 11.703838 | 12.595442 | 0.929212 |
for _ in range(steps(current, target, max_steps)):
if (current - target) > 0:
step_down()
else:
step_up() | def _to_value(self, current, target, max_steps, step_down, step_up) | Step to a value
:param current: Current value.
:param target: Target value.
:param max_steps: Maximum number of steps.
:param step_down: Down function.
:param step_up: Up function. | 3.624548 | 4.220792 | 0.858737 |
for _ in range(steps(self.brightness, 0.0,
self.command_set.brightness_steps)):
self._dimmer() | def _dimmest(self) | Group brightness as dim as possible. | 19.197584 | 14.160848 | 1.35568 |
if isinstance(in_bytes, str):
raise TypeError('Unicode-objects must be encoded as bytes first')
in_bytes_mv = _get_buffer_view(in_bytes)
out_bytes = bytearray()
idx = 0
search_start_idx = 0
for in_char in in_bytes_mv:
if idx - search_start_idx == 0xFE:
out_bytes.... | def encode(in_bytes) | Encode a string using Consistent Overhead Byte Stuffing/Reduced (COBS/R).
Input is any byte string. Output is also a byte string.
Encoding guarantees no zero bytes in the output. The output
string may be expanded slightly, by a predictable amount.
An empty string is encoded to '\\x01 | 2.95894 | 2.76783 | 1.069047 |
juicer.utils.Log.log_debug("[CART:%s] Adding %s items to repo '%s'" % \
(self.cart_name, len(items), repo_name))
# We can't just straight-away add all of `items` to the
# repo. `items` may be composed of a mix of local files, local
# direct... | def add_repo(self, repo_name, items) | Build up repos
`name` - Name of this repo.
`items` - List of paths to rpm. | 5.170861 | 5.381905 | 0.960786 |
cart_file = os.path.join(CART_LOCATION, json_file)
try:
cart_body = juicer.utils.read_json_document(cart_file)
except IOError as e:
juicer.utils.Log.log_error('an error occured while accessing %s:' %
cart_file)
raise JuicerError(e.... | def load(self, json_file) | Build a cart from a json file | 4.970376 | 4.718658 | 1.053345 |
for repo, items in self.repo_items_hash.iteritems():
if items:
yield (repo, items) | def iterrepos(self) | A generator function that yields a (repo, [items]) tuple for
each non-empty repo. | 7.85034 | 4.866769 | 1.61305 |
cart_items = self.items()
item_paths = [item.path for item in cart_items]
sign_with(item_paths)
for item in cart_items:
item.refresh() | def sign_items(self, sign_with) | Sign the items in the cart with a GPG key.
After everything is collected and signed all the cart items
are issued a refresh() to sync their is_signed attributes.
`sign_with` is a reference to the method that implements
juicer.common.RpmSignPlugin. | 4.585836 | 4.474385 | 1.024909 |
connectors = juicer.utils.get_login_info()[0]
for repo, items in self.iterrepos():
repoid = "%s-%s" % (repo, self.current_env)
for rpm in items:
# don't bother syncing down if it's already in the pulp repo it needs to go to
if not rpm.path... | def sync_remotes(self, force=False) | Pull down all non-local items and save them into remotes_storage. | 7.43396 | 6.688896 | 1.111388 |
cart_items = []
for repo, items in self.iterrepos():
cart_items.extend(items)
return cart_items | def items(self) | Build and return a list of all items in this cart | 7.428958 | 5.333325 | 1.392932 |
juicer.utils.Log.log_debug("imploding %s" % self.cart_name)
# rm -r self.remotes_storage()
if os.path.exists(self.remotes_storage):
for item in os.listdir(self.remotes_storage):
ipath = os.path.expanduser(self.remotes_storage + '/' + item)
if... | def implode(self, env) | remove all trace of this cart: delete the file(s) on the local
filesystem and delete the entry from the database | 2.92566 | 2.655743 | 1.101635 |
url = self.base_url + "/status/"
juicer.utils.Log.log_debug("[REST:GET:%s]", url)
_r = requests.get(url, auth=self.auth, headers=self.headers,
verify=False)
if _r.status_code == Constants.PULP_GET_OK: # server is up, cool.
version = juice... | def check_api_version(self) | Self check that the client expects the api version used by the
server. /status/ is available without authentication so it
will not interfere with hello. | 7.661996 | 6.88459 | 1.11292 |
def _arg(f):
if not hasattr(f, '_subcommand_args'):
f._subcommand_args = []
f._subcommand_args.append((args, kwargs))
return f
return _arg | def arg(*args, **kwargs) | Decorator to add args to subcommands. | 2.692966 | 2.005889 | 1.34253 |
def _arg(f):
if not hasattr(f, '_subcommand_argsets'):
f._subcommand_argsets = {}
f._subcommand_argsets.setdefault(name, []).append((args, kwargs))
return f
return _arg | def argset(name, *args, **kwargs) | Decorator to add sets of required mutually exclusive args to subcommands. | 2.758671 | 2.322449 | 1.187828 |
eps = iter_entry_points('jujuresources.subcommands')
ep_map = {ep.name: ep.load() for ep in eps}
parser = argparse.ArgumentParser()
if '--description' in argv:
print('Manage and mirror charm resources')
return 0
subparsers = {}
subparser_factory = parser.add_subparsers()
... | def resources(argv=sys.argv[1:]) | Juju CLI subcommand for dispatching resources subcommands. | 2.502442 | 2.372284 | 1.054866 |
resources = _load(opts.resources, opts.output_dir)
if opts.all:
opts.resource_names = ALL
reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name))
if opts.verbose:
backend.VERBOSE = True
_fetch(resources, opts.resource_names, opts.mirror_url, opts.f... | def fetch(opts) | Create a local mirror of one or more resources. | 6.867695 | 6.187965 | 1.109847 |
resources = _load(opts.resources, opts.output_dir)
if opts.all:
opts.resource_names = ALL
invalid = _invalid(resources, opts.resource_names)
if not invalid:
if not opts.quiet:
print("All resources successfully downloaded")
return 0
else:
if not opts.q... | def verify(opts) | Verify that one or more resources were downloaded successfully. | 4.18011 | 3.634086 | 1.150251 |
resources = _load(opts.resources, opts.output_dir)
if opts.all:
opts.resource_names = ALL
success = _install(resources, opts.resource_names, opts.mirror_url,
opts.destination, opts.skip_top_level)
if success:
if not opts.quiet:
print("All resources... | def install(opts) | Install one or more resources. | 4.227495 | 3.960735 | 1.067351 |
resources = _load(opts.resources, opts.output_dir)
if opts.resource_name not in resources:
sys.stderr.write('Invalid resource name: {}\n'.format(opts.resource_name))
return 1
print(resources[opts.resource_name].destination) | def resource_path(opts) | Return the full path to a named resource. | 3.758953 | 3.472101 | 1.082616 |
resources = _load(opts.resources, opts.output_dir)
if opts.resource_name not in resources:
sys.stderr.write('Invalid resource name: {}\n'.format(opts.resource_name))
return 1
print(resources[opts.resource_name].spec) | def resource_spec(opts) | Return the spec (URL, package spec, file, etc) for a named resource. | 3.618279 | 3.16955 | 1.141575 |
resources = _load(opts.resources, opts.output_dir)
opts.output_dir = resources.output_dir # allow resources.yaml to set default output_dir
if not os.path.exists(opts.output_dir):
sys.stderr.write("Resources dir '{}' not found. Did you fetch?\n".format(opts.output_dir))
return 1
ba... | def serve(opts) | Run a light-weight HTTP server hosting previously mirrored resources | 3.296652 | 3.198211 | 1.03078 |
if isinstance(in_bytes, str):
raise TypeError('Unicode-objects must be encoded as bytes first')
in_bytes_mv = _get_buffer_view(in_bytes)
final_zero = True
out_bytes = bytearray()
idx = 0
search_start_idx = 0
for in_char in in_bytes_mv:
if in_char == b'\x00':
... | def encode(in_bytes) | Encode a string using Consistent Overhead Byte Stuffing (COBS).
Input is any byte string. Output is also a byte string.
Encoding guarantees no zero bytes in the output. The output
string will be expanded slightly, by a predictable amount.
An empty string is encoded to '\\x01 | 2.388772 | 2.489397 | 0.959578 |
if isinstance(in_bytes, str):
raise TypeError('Unicode-objects are not supported; byte buffer objects only')
in_bytes_mv = _get_buffer_view(in_bytes)
out_bytes = bytearray()
idx = 0
if len(in_bytes_mv) > 0:
while True:
length = ord(in_bytes_mv[idx])
if l... | def decode(in_bytes) | Decode a string using Consistent Overhead Byte Stuffing (COBS).
Input should be a byte string that has been COBS encoded. Output
is also a byte string.
A cobs.DecodeError exception will be raised if the encoded data
is invalid. | 3.274986 | 3.24618 | 1.008874 |
try:
cmd = self.command_set.temperature(temperature)
self.send(cmd)
self._temperature = temperature
except AttributeError:
self._setter('_temperature', temperature,
self._warmest, self._coolest,
se... | def temperature(self, temperature) | Set the temperature.
:param temperature: Value to set (0.0-1.0). | 8.047592 | 9.513314 | 0.845929 |
# Transition immediately if duration is zero.
if duration == 0:
if brightness is not None:
self.brightness = brightness
if temperature is not None:
self.temperature = temperature
return
if brightness != self.brightness ... | def transition(self, duration, brightness=None, temperature=None) | Transition wrapper.
Short-circuit transition if necessary.
:param duration: Duration of transition.
:param brightness: Transition to this brightness.
:param temperature: Transition to this temperature. | 2.620492 | 2.69903 | 0.970902 |
# Set initial value.
b_start = self.brightness
t_start = self.temperature
# Compute ideal step amount.
b_steps = 0
if brightness is not None:
b_steps = steps(self.brightness, brightness,
self.command_set.brightness_steps)
... | def _transition(self, duration, brightness, temperature) | Complete a transition.
:param duration: Duration of transition.
:param brightness: Transition to this brightness.
:param temperature: Transition to this temperature. | 2.652389 | 2.715299 | 0.976831 |
self._to_value(self._temperature, temperature,
self.command_set.temperature_steps,
self._warmer, self._cooler) | def _to_temperature(self, temperature) | Step to a given temperature.
:param temperature: Get to this temperature. | 13.642234 | 14.222188 | 0.959222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.