content stringlengths 1 1.04M | input_ids listlengths 1 774k | ratio_char_token float64 0.38 22.9 | token_count int64 1 774k |
|---|---|---|---|
import csv
import datetime
import os
import shutil
import sys
import argparse
from mikrotik import Mikrotik
def compare_files(f1, f2):
"""
Compare two text files. Ignore lines with '#'.
:param f1: current_file
:param f2: previous_file
:return: True - if files identical, otherwise - False. If previous_file doesn't exist return False.
"""
if not os.path.exists(f2):
return False
with open(f1, 'r') as fp1, open(f2, 'r') as fp2:
while True:
# b1 = fp1.readline().rstrip()
# b2 = fp2.readline().rstrip()
b1 = fp1.readline()
b2 = fp2.readline()
# print(b1)
# print(b2)
# print("--------------------------------")
if b1.startswith('#') or b2.startswith('#'):
continue
if b1 != b2:
return False
if not b1:
return True
if __name__ == '__main__':
begin_time = datetime.datetime.now()
curr_date = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
# Parsing arguments
parser = argparse.ArgumentParser(description="Mikrotiks Backup")
parser.add_argument("-c", dest="command", help="Mikrotik terminal command (enclose in double quotes)")
args = parser.parse_args()
# print(args)
# If arguments is not set then execute backup_mikrotiks() as default method
if len(sys.argv) == 1:
result = backup_mikrotiks()
if args.command:
result = execute_command(args.command)
print_result(result)
print(f"Program completed")
print(f"Total time spent: {datetime.datetime.now() - begin_time} sec.")
| [
11748,
269,
21370,
198,
11748,
4818,
8079,
198,
11748,
28686,
198,
11748,
4423,
346,
198,
11748,
25064,
198,
11748,
1822,
29572,
198,
198,
6738,
285,
1134,
10599,
1134,
1330,
17722,
10599,
1134,
628,
198,
4299,
8996,
62,
16624,
7,
69,
1... | 2.251012 | 741 |
"""TensorFlow utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.backend as K
from time import time
import scope.lanczos as lanczos
KERAS_LEARNING_PHASE_TEST = 0
KERAS_LEARNING_PHASE_TRAIN = 1
class Timer:
"""A simple wallclock timer."""
@property
class NumpyPrintEverything:
"""Tell NumPy to print everything.
Synopsis:
with NumpyPrintEverything():
print(numpy_array)
"""
class NumpyPrintoptions:
"""Temporarily set NumPy printoptions.
Synopsis:
with NumpyPrintoptions(formatter={'float': '{:0.2f}'.format}):
print(numpy_array)
"""
class MiniBatchMaker:
"""Shuffle data and split it into batches."""
def at_start_of_epoch(self):
"""Are we starting a new epoch?"""
return self.i == 0
def create_iid_batch_generator(x, y, steps, batch_size, resample_prob=1):
"""Returns an IID mini-batch generator.
ds = Dataset.from_generator(
create_iid_batch_generator(x, y, batch_size), ...)
Args:
x: Input samples
y: Labels
steps: How many steps to run for
batch_size: Integer size of mini-batch
resample_prob: Probability of resampling a given sample at each step.
If a function, the function should return the current resampling
probability and will be called every time a batch is generated.
"""
N = len(x)
return gen
def keras_feed_dict(model,
x=None,
y=None,
feed_dict={},
learning_phase=KERAS_LEARNING_PHASE_TEST):
"""Return a feed dict with inputs and labels suitable for Keras.
Args:
model: A Keras Model
x: Model inputs, or None if inputs are not fed
y: Model targets (labels), or None if targets are not fed
feed_dict: Additional feed_dict to merge with (if given, updated in
place)
learning_phase: 0 for TEST, 1 for TRAIN
Returns:
The new feed_dict (equal to feed_dict if that was provided).
"""
new_feed_dict = dict(feed_dict)
if x is not None:
new_feed_dict[model.inputs[0]] = x
new_feed_dict[model.sample_weights[0]] = np.ones(x.shape[0])
if y is not None:
new_feed_dict[model.targets[0]] = y
new_feed_dict[K.learning_phase()] = learning_phase # TEST phase
return new_feed_dict
def keras_compute_tensors(model, x, y, tensors, feed_dict={}):
"""Compute the given tensors in Keras."""
new_feed_dict = keras_feed_dict(model, x, y, feed_dict)
return K.get_session().run(tensors, feed_dict=new_feed_dict)
def clone_keras_model_shared_weights(
model, input_tensor, target_tensor):
"""Clone a Keras model.
The new model shares its weights with the old model, but accepts different
inputs and targets. This is useful, for example, for evaluating a model
mid-training.
Args:
model: A compiled Keras model.
input_tensor: Tensor to use as input for the cloned model.
target_tensor: Tensor to be used as targets (labels) for the cloned model.
Returns:
The cloned Keras model.
"""
assert len(model.inputs) == 1
inputs = keras.layers.Input(tensor=input_tensor,
shape=model.inputs[0].shape[1:])
clone = keras.Model(
inputs=inputs,
outputs=model(input_tensor))
clone.compile(
loss=model.loss,
target_tensors=[target_tensor],
optimizer=model.optimizer,
metrics=model.metrics)
return clone
def flatten_array_list(arrays):
"""Flatten and concat a list of numpy arrays into a single rank 1 vector."""
return np.concatenate([np.reshape(a, [-1]) for a in arrays], axis=0)
def flatten_tensor_list(tensors):
"""Flatten and concat a list of tensors into a single rank 1 tensor."""
return tf.concat([tf.reshape(t, [-1]) for t in tensors], axis=0)
def unflatten_tensor_list(flat_tensor, orig_tensors):
"""Reshape a flattened tensor back to a list of tensors with their
original shapes.
Args:
flat_tensor: A tensor that was previously flattened using
flatten_tensor_list()
orig_tensor: A list of tensors with the original desired shapes.
"""
unflattened = []
offset = 0
for t in orig_tensors:
num_elems = t.shape.num_elements()
unflattened.append(
tf.reshape(flat_tensor[offset:offset + num_elems], t.shape))
offset += num_elems
return unflattened
def compute_sample_mean_tensor(model, batches, tensors, feed_dict={}):
"""Compute the sample mean of the given tensors.
Args:
model: Keras Model
batches: MiniBatchMaker
tensors: Tensor or list of Tensors to compute the mean of
feed_dict: Used when evaluating tensors
"""
sample_means = None
tensors_is_list = isinstance(tensors, (list, tuple))
tensors = _AsList(tensors)
while True:
x_batch, y_batch = batches.next_batch()
results = keras_compute_tensors(model, x_batch, y_batch, tensors, feed_dict)
for i in range(len(results)):
results[i] *= len(x_batch)
if sample_means is None:
sample_means = results
else:
for i in range(len(results)):
sample_means[i] += results[i]
if batches.at_start_of_epoch():
break
for i in range(len(sample_means)):
sample_means[i] /= batches.N
if tensors_is_list:
return sample_means
else:
assert len(sample_means) == 1
return sample_means[0]
def jacobian(y, x):
"""Compute the Jacobian tensor J_ij = dy_i/dx_j.
From https://github.com/tensorflow/tensorflow/issues/675, which is adapted
from tf.hessiangs().
:param Tensor y: A Tensor
:param Tensor x: A Tensor
:rtype: Tensor
:return: The Jacobian Tensor, whose shape is the concatenation of
the y_flat and x shapes.
"""
y_flat = tf.reshape(y, [-1])
# tf.shape() returns a Tensor, so this supports dynamic sizing
n = tf.shape(y_flat)[0]
loop_vars = [
tf.constant(0, tf.int32),
tf.TensorArray(tf.float32, size=n),
]
_, jacobian = tf.while_loop(
lambda j, _: j < n,
lambda j, result: (j+1,
result.write(j, tf.gradients(y_flat[j], x)[0])),
loop_vars)
jacobian_shape = tf.concat([tf.shape(y), tf.shape(x)], axis=0)
jacobian = tf.reshape(jacobian.stack(), jacobian_shape)
return jacobian
def jacobians(y, xs):
"""Compute the Jacobian tensors J_ij = dy_i/dx_j for each x in xs.
With this implementation, the gradient is computed for all xs in one
call, so if xs includes weights from different layers then back prop
is used.
:param Tensor y: A rank 1 Tensor
:param Tensor xs: A Tensor or list of Tensors
:rtype: list
:return: List of Jacobian tensors J_ij = dy_i/dx_j for each x in xs.
"""
if y.shape.ndims != 1:
raise ValueError('y must be a rank 1 Tensor')
xs = _AsList(xs)
# tf.shape() returns a Tensor, so this supports dynamic sizing
len_y = tf.shape(y)[0]
jacobians = []
# Outer loop runs over elements of y, computes gradients for each
loop_vars = [
tf.constant(0, tf.int32),
[tf.TensorArray(tf.float32, size=len_y) for x in xs]
]
def _compute_single_y_gradient(j, arrays):
"""Compute the gradient for a single y elem."""
grads = tf.gradients(y[j], xs)
for i, g in enumerate(grads):
arrays[i] = arrays[i].write(j, g)
return arrays
_, jacobians = tf.while_loop(
lambda j, _: j < len_y,
lambda j, arrays: (j + 1, _compute_single_y_gradient(j, arrays)),
loop_vars)
jacobians = [a.stack() for a in jacobians]
return jacobians
def hessians(y, xs):
"""The Hessian of y with respect to each x in xs.
:param y Tensor: A scalar Tensor.
:param xs Tensor: A Tensor or list of Tensors. Each Tensor can have any
rank.
:rtype: list
:return: List of Hessians d^2y/dx^2. The shape of a Hessian is
x.shape + y.shape.
"""
xs = _AsList(xs)
hessians = []
for x in xs:
# First derivative and flatten
grad = tf.gradients(y, x)[0]
grad_flat = tf.reshape(grad, [-1])
# Second derivative
n = tf.shape(grad_flat)[0]
loop_vars = [
tf.constant(0, tf.int32),
tf.TensorArray(tf.float32, size=n),
]
_, hessian = tf.while_loop(
lambda j, _: j < n,
lambda j, result: (j+1, result.write(
j, tf.gradients(grad_flat[j], x)[0])),
loop_vars)
hessian = hessian.stack()
x_shape = tf.shape(x)
hessian_shape = tf.concat([x_shape, x_shape], axis=0)
hessians.append(tf.reshape(hessian, hessian_shape))
return hessians
def num_weights(weights):
"""Number of weights in the given list of weight tensors."""
return sum([w.shape.num_elements() for w in weights])
def total_num_weights(model):
"""Total number of weights in the given Keras model."""
return num_weights(model.trainable_weights)
def total_tensor_elements(x):
"""Tensor containing the total number of elements of x.
:param x Tensor: A tensor.
:rtype: Tensor
:return: A scalar Tensor containing the total number of elements.
"""
return tf.reduce_prod(tf.shape(x))
def hessian_tensor_blocks(y, xs):
"""Compute the tensors that make up the full Hessian (d^2y / dxs dxs).
A full computation of the Hessian would look like this:
blocks = hessian_tensor_blocks(y, xs)
block_results = sess.run(blocks)
hessian = hessian_combine_blocks(block_results)
:param y Tensor: A scalar Tensor.
:param xs Tensor: A Tensor or list of Tensors. Each Tensor can have any
rank.
:rtype: list
:return: List of Tensors that should be evaluated, and the results
should be passed to hessian_combine_blocks() to get the full
gradient.
"""
xs = _AsList(xs)
hess_blocks = []
for i1, x1 in enumerate(xs):
# First derivative and flatten
grad_x1 = tf.gradients(y, x1)[0]
grad_x1_flat = tf.reshape(grad_x1, [-1])
x1_size = total_tensor_elements(x1)
# Second derivative: Only compute upper-triangular blocks
# because Hessian is symmetric
for x2 in xs[i1:]:
x2_size = total_tensor_elements(x2)
loop_vars = [
tf.constant(0, tf.int32),
tf.TensorArray(tf.float32, size=x1_size),
]
_, x1_x2_block = tf.while_loop(
lambda j, _: j < x1_size,
lambda j, result: (j+1, result.write(
j, tf.gradients(grad_x1_flat[j], x2)[0])),
loop_vars)
x1_x2_block = tf.reshape(x1_x2_block.stack(), [x1_size, x2_size])
hess_blocks.append(x1_x2_block)
return hess_blocks
def hessian_combine_blocks(blocks):
"""Combine the pieces obtained by evaluated the Tensors returned
by hessian_tensor_pieces(), and return the full Hessian matrix.
"""
# We only record upper-triangular blocks, and here we work out
# the number of blocks per row by solving a quadratic:
# len = n * (n+1) / 2
num_recorded_blocks = len(blocks)
blocks_per_row = int((np.sqrt(1 + 8 * num_recorded_blocks) - 1) / 2)
# Sum the column sizes
dims = [b.shape[1] for b in blocks[:blocks_per_row]]
total_dim = sum(dims)
H = np.zeros((total_dim, total_dim))
row = 0
col = 0
for i, b in enumerate(blocks):
row_start = sum(dims[:row])
row_end = sum(dims[:row + 1])
col_start = sum(dims[:col])
col_end = sum(dims[:col + 1])
H[row_start:row_end, col_start:col_end] = b
H[col_start:col_end, row_start:row_end] = b.transpose()
col += 1
if col >= blocks_per_row:
row += 1
col = row
return H
def trace_hessian(loss, logits, weights):
"""Compute the trace of the Hessian of loss with respect to weights.
We assume that loss = loss(logits(weights)), and that logits is a
piecewise-linear function of the weights (therefore d^2 logits / dw^2 = 0
for any w). This allows for a faster implementation that the naive one.
Note: This computes the Hessian of loss / logits, where logits is indexed
by sample and class, but all elements of the Hessian with two different
classes vanish. So this is still not the most efficient way to do it.
:param loss Tensor: A scalar Tensor
:param logits Tensor: The logits tensor.
:param weights Tensor: A Tensor or list of Tensors of model weights.
:rtype: Tensor
:return: The trace of the Hessian of loss with respect to all the weights.
"""
weights = _AsList(weights)
# Flatten logits with a well-specified dimension. This assumes any
# non-trivial dimension will resolve to 1.
# logits_flat = tf.reshape(logits, [-1])
loss_logits_hessian = hessians(loss, logits)[0]
tr_hessian_pieces = []
for w in weights:
J = jacobian(logits, w)
# Contract along the weight indices
# (first index is the logit index)
weight_axes = list(range(logits.shape.ndims, J.shape.ndims))
JJ = tf.tensordot(J, J, axes=[weight_axes, weight_axes])
# Doesn't work for dynamic shape
# assert loss_logits_hessian.shape == JJ.shape
all_axes = list(range(JJ.shape.ndims))
tr_hessian_pieces.append(
tf.tensordot(loss_logits_hessian, JJ, axes=[all_axes, all_axes]))
return tf.reduce_sum(tr_hessian_pieces)
def trace_hessian_softmax_crossentropy(logits, weights):
"""Compute the trace of the Hessian of loss with respect to weights.
The loss is assumed to be crossentropy(softmax(logits)), which allows
us to compute the loss/logits Hessian analytically, and it factorizes.
We also assume that logits is a piecewise-linear function of the weights
(therefore d^2 logits / dw^2 = 0 for any w).
Here we compute the Hessian of loss / logits analytically, which saves
some time, but only about 10%. It seems most time is spent just computing
the Jacobian.
:param loss Tensor: A scalar Tensor
:param logits Tensor: A Tensor with rank 2, indexed by [sample, class].
:param weights Tensor: A Tensor or list of Tensors of model weights.
:rtype: Tensor
:return: The trace of the Hessian of loss with respect to all the weights.
"""
weights = _AsList(weights)
if logits.shape.ndims != 2:
raise ValueError('logits tensor must have rank 2')
probs = tf.nn.softmax(logits)
tr_hessian_pieces = []
JdotP = tf.gradients(logits, weights, grad_ys=probs)
tf.logging.info('JdotP =', JdotP)
return tf.reduce_sum(tr_hessian_pieces)
def trace_hessian_reference(loss, weights):
"""Compute the whole Hessian for each layer, then take the trace.
This is a straightforward and slow implementation meant for testing.
"""
weights = _AsList(weights)
trace_terms = []
grads = tf.gradients(loss, weights)
for grad, weight in zip(grads, weights):
grad_unstacked = tf.unstack(tf.reshape(grad, [-1]))
for i, g in enumerate(grad_unstacked):
g2 = tf.reshape(tf.gradients(g, weight)[0], [-1])
diag_hessian_term = g2[i]
trace_terms.append(diag_hessian_term)
return tf.reduce_sum(trace_terms)
def hessian_vector_product(loss, weights, v):
"""Compute the tensor of the product H.v, where H is the loss Hessian with
respect to the weights. v is a vector (a rank 1 Tensor) of the same size as
the loss gradient. The ordering of elements in v is the same obtained from
flatten_tensor_list() acting on the gradient. Derivatives of dv/dweights
should vanish.
"""
grad = flatten_tensor_list(tf.gradients(loss, weights))
grad_v = tf.reduce_sum(grad * tf.stop_gradient(v))
H_v = flatten_tensor_list(tf.gradients(grad_v, weights))
return H_v
class TensorStatistics:
"""Collect statistics for a tensor over different mini-batches."""
def add_minibatch(self, value):
"""Add mean value over minibatch."""
self.running_sum += value
self.running_sum_of_squares += value * value
self.n += 1
@property
def mean(self):
"""The mean"""
return self.running_sum / self.n
@property
def var(self):
"""Variance of each tensor element"""
return self.running_sum_of_squares / self.n - self.mean**2
@property
def std(self):
"""Standard deviation of each tensor element"""
return np.sqrt(self.var)
@property
def norm_of_mean(self):
"""Norm of the mean"""
return np.linalg.norm(self.mean)
@property
def norm_of_std(self):
"""Norm of vector of standard deviations"""
return np.linalg.norm(self.std)
class TensorListStatistics(list):
"""Collect statistics for a list of tensors over different mini-batches.
Behaves as list where each element is a TensorStatistics object.
"""
def __init__(self, tensors):
"""tensors: list of Tensors"""
super().__init__([TensorStatistics(t) for t in tensors])
@property
def means(self):
"""List of tensor means"""
return [s.mean for s in self]
@property
def vars(self):
"""List of tensor variances"""
return [s.var for s in self]
@property
def stds(self):
"""List of tensor standard devs"""
return [s.std for s in self]
@property
def norm_of_mean(self):
"""The norm of the concatenated list of tensor means."""
norms = np.array([np.linalg.norm(s.mean) for s in self])
return np.sqrt(np.sum(norms * norms))
@property
def norm_of_std(self):
"""The norm of the concatenated list of tensor stds."""
norms = np.array([np.linalg.norm(s.std) for s in self])
return np.sqrt(np.sum(norms * norms))
class KerasHessianSpectrum:
"""Computes the partial Hessian spectrum of a Keras model using Lanczos."""
def __init__(self, model, x, y, batch_size=1024, stochastic=False,
weights=None, loss=None):
"""model is a keras sequential model.
Args:
model: A Keras Model
x: Training samples
y: Training labels
batch_size: Batch size for computing the Hessian. Does not affect the
result, only affects time and memory performance.
stochastic: If True, approximate the Hessian using batch_size samples,
chosen at random with each call to compute_spectrum().
weights: Weights with respect to which to compute the Hessian.
Can be a weight tensor or a list of tensors. If None,
all model weights are used.
loss: Can be specified separately for unit testing purposes.
"""
self.model = model
if weights is None:
self.weights = model.trainable_weights
else:
self.weights = _AsList(weights)
self.num_weights = num_weights(self.weights)
self.v = tf.placeholder(tf.float32, shape=(self.num_weights,))
# Delay looking at model because it may not be compiled yet
self._loss = loss
self._Hv = None
self.train_batches = MiniBatchMaker(x, y, batch_size)
self.batch_size = batch_size
self.stochastic = stochastic
@property
def loss(self):
"""The loss.
Evaluated lazily in case the model is not compiled at
first.
"""
if self._loss is None:
return self.model.total_loss
else:
return self._loss
@property
def Hv(self):
"""The Hessian-vector product tensor"""
if self._Hv is None:
self._Hv = hessian_vector_product(self.loss, self.weights, self.v)
return self._Hv
def compute_spectrum(self, k, v0=None, show_progress=False):
"""Compute k leading eigenvalues and eigenvectors.
Args:
v0: If specified, use as initial vector for Lanczos.
"""
timer = Timer()
if self.stochastic:
results = self._compute_stochastic_spectrum(k, v0, show_progress)
else:
results = self._compute_full_batch_spectrum(k, v0, show_progress)
self.lanczos_secs = timer.secs
if show_progress:
tf.logging.info('')
return results
def _compute_stochastic_spectrum(self, k, v0=None, show_progress=False):
"""Compute k leading eigenvalues and eigenvectors.
Each time this method is called, a new batch is selected to approximate
the Hessian.
"""
self.lanczos_iterations = 0
x_batch, y_batch = self.train_batches.next_batch()
if len(x_batch) < self.batch_size:
assert self.train_batches.at_start_of_epoch()
x_batch, y_batch = self.train_batches.next_batch()
if len(x_batch) < self.batch_size:
raise ValueError("Getting batches that are too small: {} < {}".format(
len(x_batch), self.batch_size))
evals, evecs = lanczos.eigsh(
n=self.num_weights, dtype=np.float32, matvec=compute_Hv, k=k, v0=v0)
return evals, evecs
| [
37811,
51,
22854,
37535,
20081,
526,
15931,
198,
198,
6738,
11593,
37443,
834,
1330,
4112,
62,
11748,
198,
6738,
11593,
37443,
834,
1330,
7297,
198,
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
198,
11748,
25064,
198,
11748,
299,
... | 2.567402 | 7,982 |
tipo = [
'Ação',
'FII',
'ETF'
] | [
22504,
78,
796,
685,
198,
220,
220,
220,
705,
32,
16175,
28749,
3256,
198,
220,
220,
220,
705,
37,
3978,
3256,
198,
220,
220,
220,
705,
22274,
6,
198,
60
] | 1.433333 | 30 |
import gym
import time
if __name__ == '__main__':
run()
| [
198,
11748,
11550,
198,
11748,
640,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
1057,
3419,
628,
198
] | 2.461538 | 26 |
from jiminy.gym.envs.mujoco.mujoco_env import MujocoEnv
# ^^^^^ so that user gets the correct error
# message if mujoco is not installed correctly
from jiminy.gym.envs.mujoco.ant import AntEnv
from jiminy.gym.envs.mujoco.half_cheetah import HalfCheetahEnv
from jiminy.gym.envs.mujoco.hopper import HopperEnv
from jiminy.gym.envs.mujoco.walker2d import Walker2dEnv
from jiminy.gym.envs.mujoco.humanoid import HumanoidEnv
from jiminy.gym.envs.mujoco.inverted_pendulum import InvertedPendulumEnv
from jiminy.gym.envs.mujoco.inverted_double_pendulum import InvertedDoublePendulumEnv
from jiminy.gym.envs.mujoco.reacher import ReacherEnv
from jiminy.gym.envs.mujoco.swimmer import SwimmerEnv
from jiminy.gym.envs.mujoco.humanoidstandup import HumanoidStandupEnv
from jiminy.gym.envs.mujoco.pusher import PusherEnv
from jiminy.gym.envs.mujoco.thrower import ThrowerEnv
from jiminy.gym.envs.mujoco.striker import StrikerEnv
| [
6738,
474,
320,
3541,
13,
1360,
76,
13,
268,
14259,
13,
76,
23577,
25634,
13,
76,
23577,
25634,
62,
24330,
1330,
8252,
73,
25634,
4834,
85,
198,
2,
10563,
39397,
523,
326,
2836,
3011,
262,
3376,
4049,
198,
2,
3275,
611,
285,
23577,
... | 2.465054 | 372 |
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
| [
6738,
42625,
14208,
13,
7295,
13,
6371,
411,
349,
690,
1330,
9575,
198,
6738,
42625,
14208,
13,
4023,
1330,
367,
29281,
31077,
7738,
1060,
198,
6738,
42625,
14208,
13,
33571,
13,
41357,
1330,
37350,
7680,
198,
6738,
42625,
14208,
13,
36... | 3.62963 | 54 |
#!/usr/bin/env python3
import os
import random
import string
from hashlib import sha256
from Toy_AE import Toy_AE
from secret import FLAG
if __name__ == "__main__":
ae = Toy_AE()
if not proof_of_work():
exit(-1)
for _ in range(4):
try:
menu()
except:
exit(-1) | [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
11748,
28686,
198,
11748,
4738,
198,
11748,
4731,
198,
6738,
12234,
8019,
1330,
427,
64,
11645,
198,
198,
6738,
10977,
62,
14242,
1330,
10977,
62,
14242,
198,
6738,
3200,
1330,
9977,... | 2.14 | 150 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from confspirator import groups as config_groups
from confspirator import fields as config_fields
from adjutant_moc.actions import base, operations
from adjutant_moc.actions import serializers
| [
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
743,
407,
779,
428,
2393,
2845,
287,
11846,
351,
262,
13789,
13,
198,
2,
921,
743,
7330,
257,
4866,
286,
262,
13789,
379,
198,
2,... | 3.889474 | 190 |
import uuid
from numpy import random
from clovis_points import ActivationFunctions as af
from clovis_points import TruthTables as tt
from clovis_points.Flutes import Flutes
from testing.TestUtilities import TestUtilities
from the_historical_record.Block import Block
from the_historical_record.BlockChain import BlockChain
| [
11748,
334,
27112,
198,
198,
6738,
299,
32152,
1330,
4738,
198,
198,
6738,
537,
709,
271,
62,
13033,
1330,
13144,
341,
24629,
2733,
355,
6580,
198,
6738,
537,
709,
271,
62,
13033,
1330,
14056,
51,
2977,
355,
256,
83,
198,
6738,
537,
... | 3.611111 | 90 |
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: sfp_tool_onesixtyone
# Purpose: SpiderFoot plug-in for using the onesixtyone tool.
# Tool: https://github.com/trailofbits/onesixtyone
#
# Author: <steve@binarypool.com>
#
# Created: 2022-04-02
# Copyright: (c) Steve Micallef 2022
# Licence: MIT
# -------------------------------------------------------------------------------
import sys
import os.path
import tempfile
from netaddr import IPNetwork
from subprocess import PIPE, Popen
from spiderfoot import SpiderFootPlugin, SpiderFootEvent, SpiderFootHelpers
# End of sfp_tool_onesixtyone class
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
16529,
24305,
198,
2,
6530,
25,
220,
220,
220,
220,
220,
220,
220,
264,
46428,
62,
25981,
62,
1952,
19404,
505,
198,
2,
32039,
25,
220,
220,
220,
220,
12648,
1757... | 3.25463 | 216 |
import os
from paraview import simple
# -----------------------------------------------------------------------------
MODULE_PATH = os.path.dirname(os.path.abspath(__file__))
PLUGINS = [
'parflow.py'
]
FULL_PATHS = [
'/Applications/ParaView-5.6.0-1626-g52acf2f741.app/Contents/Plugins/ParFlow.so',
]
# -----------------------------------------------------------------------------
# Load the plugins
# -----------------------------------------------------------------------------
for plugin in PLUGINS:
simple.LoadPlugin(os.path.join(MODULE_PATH, plugin))
for plugin in FULL_PATHS:
simple.LoadPlugin(plugin)
| [
11748,
28686,
198,
6738,
1582,
615,
769,
1330,
2829,
198,
198,
2,
16529,
32501,
198,
198,
33365,
24212,
62,
34219,
796,
28686,
13,
6978,
13,
15908,
3672,
7,
418,
13,
6978,
13,
397,
2777,
776,
7,
834,
7753,
834,
4008,
198,
198,
6489,... | 3.556818 | 176 |
from django.contrib.auth.models import User
from django.db import models
| [
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
27530,
1330,
11787,
198,
6738,
42625,
14208,
13,
9945,
1330,
4981,
628
] | 3.52381 | 21 |
# Generated by Django 3.2.3 on 2021-06-17 23:09
from django.db import migrations, models
| [
2,
2980,
515,
416,
37770,
513,
13,
17,
13,
18,
319,
33448,
12,
3312,
12,
1558,
2242,
25,
2931,
198,
198,
6738,
42625,
14208,
13,
9945,
1330,
15720,
602,
11,
4981,
628
] | 2.84375 | 32 |
# this file stores some constants regarding MIDI-handling, etc.
# for settings which MIDI-notes trigger what functionality see settings.py
import Live
#from Live import MidiMap
#from Live.MidiMap import MapMode
DEFAULT_CHANNEL = 0
STATUS_MASK = 0xF0
CHAN_MASK = 0x0F
CC_STATUS = 0xb0
NOTEON_STATUS = 0x90
NOTEOFF_STATUS = 0x80
STATUS_ON = 0x7f
STATUS_OFF = 0x00
STATUS_OFF2 = 0x40
# possible CC modes (always 7bit); RELATIVE: <increment> / <decrement>
ABSOLUTE = Live.MidiMap.MapMode.absolute # 0 - 127
RELATIVE_BINARY_OFFSET = Live.MidiMap.MapMode.relative_binary_offset # 065 - 127 / 063 - 001
RELATIVE_SIGNED_BIT = Live.MidiMap.MapMode.relative_signed_bit # 001 - 064 / 065 - 127
RELATIVE_SIGNED_BIT2 = Live.MidiMap.MapMode.relative_signed_bit2 # 065 - 127 / 001 - 064
RELATIVE_TWO_COMPLIMENT = Live.MidiMap.MapMode.relative_two_compliment # 001 - 064 / 127 - 65
relative_to_signed_int = {
ABSOLUTE: lambda value: value,
RELATIVE_BINARY_OFFSET: relativebinary_offset_to_signed_int,
RELATIVE_SIGNED_BIT: relative_signed_bit_to_signed_int,
RELATIVE_SIGNED_BIT2: relative_signed_bit2_to_signed_int,
RELATIVE_TWO_COMPLIMENT: relative_two_complement_to_signed_int
}
| [
2,
428,
2393,
7000,
617,
38491,
5115,
33439,
12,
4993,
1359,
11,
3503,
13,
198,
2,
329,
6460,
543,
33439,
12,
17815,
7616,
644,
11244,
766,
6460,
13,
9078,
198,
198,
11748,
7547,
198,
2,
6738,
7547,
1330,
7215,
72,
13912,
198,
2,
... | 2.585153 | 458 |
__all__ = [
"ATOMIC_RADII",
"KHOT_EMBEDDINGS",
"CONTINUOUS_EMBEDDINGS",
"QMOF_KHOT_EMBEDDINGS",
]
from .atomic_radii import ATOMIC_RADII
from .continuous_embeddings import CONTINUOUS_EMBEDDINGS
from .khot_embeddings import KHOT_EMBEDDINGS
from .qmof_khot_embeddings import QMOF_KHOT_EMBEDDINGS
| [
834,
439,
834,
796,
685,
198,
220,
220,
220,
366,
1404,
2662,
2149,
62,
49,
2885,
3978,
1600,
198,
220,
220,
220,
366,
42,
39,
2394,
62,
3620,
33,
1961,
35,
20754,
1600,
198,
220,
220,
220,
366,
37815,
1268,
52,
20958,
62,
3620,
... | 2.059603 | 151 |
from django import forms
| [
6738,
42625,
14208,
1330,
5107,
628
] | 4.333333 | 6 |
from builtins import hex
from builtins import str
from . import six
from . import api_requestor
from . import util
import json
| [
6738,
3170,
1040,
1330,
17910,
198,
6738,
3170,
1040,
1330,
965,
198,
198,
6738,
764,
1330,
2237,
198,
6738,
764,
1330,
40391,
62,
25927,
273,
198,
6738,
764,
1330,
7736,
198,
11748,
33918,
628
] | 3.794118 | 34 |
"""Rundown API Response Facades."""
from typing import Union
class LinesResponseFacade(dict):
"""TheRundown `GET events` response accessor."""
@property
def meta(self) -> dict:
"""Fetch `meta` key from LineResponse."""
return self.get("meta")
@property
def events(self) -> Union[list, None]:
"""Fetch `events` key from LineResponse."""
raw_events = self.get("events")
if not raw_events:
return None
events = []
for event in raw_events:
events.append(LinesEventFacade(event))
return events
class LinesEventFacade(dict):
"""TheRundown `GET events.line` response accessor."""
@property
def event_id(self) -> str:
"""Fetch `event_id` from LineEvent."""
return self.get("event_id")
@property
def sport_id(self) -> int:
"""Fetch `sport_id` from LineEvent."""
return self.get("sport_id")
@property
def event_date(self) -> str:
"""Fetch `event_date` from LineEvent."""
return self.get("event_date")
@property
def score(self) -> dict:
"""Fetch `score` from LineEvent."""
return self.get("score")
@property
def teams_normalized(self) -> list:
"""Fetch `teams_normalized` from LineEvent."""
return self.get("teams_normalized")
@property
def schedule(self) -> dict:
"""Fetch `schedule` from LineEvent."""
return self.get("schedule")
@property
def line_periods(self) -> dict:
"""Fetch `line_periods` from LineEvent."""
return self.get("line_periods")
| [
37811,
49,
41609,
7824,
18261,
13585,
2367,
526,
15931,
198,
6738,
19720,
1330,
4479,
628,
198,
4871,
26299,
31077,
47522,
671,
7,
11600,
2599,
198,
220,
220,
220,
37227,
464,
49,
41609,
4600,
18851,
2995,
63,
2882,
1895,
273,
526,
1593... | 2.408555 | 678 |
from __future__ import division, print_function
import unittest
import testing.mysqld
import testing.postgresql
from beam_nuggets.io.relational_db import SourceConfiguration
from .database import TestDatabase
| [
6738,
11593,
37443,
834,
1330,
7297,
11,
3601,
62,
8818,
198,
198,
11748,
555,
715,
395,
198,
198,
11748,
4856,
13,
28744,
80,
335,
198,
11748,
4856,
13,
7353,
34239,
13976,
198,
198,
6738,
15584,
62,
77,
26550,
13,
952,
13,
2411,
8... | 3.803571 | 56 |
import cv2
import sys
import pyprind
import torch
import numpy as np
import dl_modules.dataset as ds
import dl_modules.transforms as trf
import cm_modules.utils as utils
import skvideo.io as vio
from cm_modules.enhance import correct_colors
from cm_modules.utils import convert_to_cv_8bit
| [
11748,
269,
85,
17,
198,
11748,
25064,
198,
11748,
12972,
1050,
521,
198,
11748,
28034,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
288,
75,
62,
18170,
13,
19608,
292,
316,
355,
288,
82,
198,
11748,
288,
75,
62,
18170,
13,
7645,
... | 3.052632 | 95 |
from socket import * | [
6738,
17802,
1330,
1635
] | 5 | 4 |
from django.db.models import F
from bridger import display as dp
from bridger.pandas import fields as pf
from bridger.pandas.views import PandasAPIView
from bridger.serializers import decorator
from tests.filters import PandasFilterSet
from tests.models import ModelTest
from .display import PandasDisplayConfig
| [
6738,
42625,
14208,
13,
9945,
13,
27530,
1330,
376,
198,
198,
6738,
38265,
1362,
1330,
3359,
355,
288,
79,
198,
6738,
38265,
1362,
13,
79,
392,
292,
1330,
7032,
355,
279,
69,
198,
6738,
38265,
1362,
13,
79,
392,
292,
13,
33571,
1330... | 3.597701 | 87 |
__version__ = "0.18.2+melior1.1.6"
| [
834,
9641,
834,
796,
366,
15,
13,
1507,
13,
17,
10,
17694,
1504,
16,
13,
16,
13,
21,
1,
198
] | 1.75 | 20 |
'''
Created on 2016年8月4日
@author: Administrator
'''
from io import StringIO
# write to StringIO:
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())
# read from StringIO:
f = StringIO('水面细风生,\n菱歌慢慢声。\n客亭临小市,\n灯火夜妆明。')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
| [
7061,
6,
198,
41972,
319,
1584,
33176,
112,
23,
17312,
230,
19,
33768,
98,
198,
198,
31,
9800,
25,
22998,
198,
7061,
6,
198,
6738,
33245,
1330,
10903,
9399,
628,
198,
2,
3551,
284,
10903,
9399,
25,
198,
69,
796,
10903,
9399,
3419,
... | 1.764398 | 191 |
# -*- coding: utf-8 -*-
"""
"""
from __future__ import unicode_literals
from __future__ import print_function
import logging
from unittest import TestCase
from unittest.mock import MagicMock
from mock import call
from p2p0mq.app.local_peer import LocalPeer
from p2p0mq.peer import Peer
from enhterm import EnhTerm
from enhterm.command import Command
from enhterm.command.text import TextCommand
from enhterm.impl.p2p.p2p_concern import RemoteConcern
from enhterm.impl.p2p.p2p_runner import RemoteRunner
from enhterm.message import Message
logger = logging.getLogger('')
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
37811,
198,
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198,
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
198,
11748,
18931,
198,
6738,
... | 3.080214 | 187 |
"""portal URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from portal.views import (
HomeView,
)
urlpatterns = [
path('', include('webprovider.urls')),
path('', HomeView.as_view()),
path('account/', include('account.urls')),
path('blog/', include('blog.urls')),
path('upload/', include('upload.urls')),
path('sys_console/', include('setup.urls')),
# Provided application url
path('admin/', admin.site.urls),
path('markdownx/', include('markdownx.urls')),
path('', include('first_setup.urls')),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
path('__debug__/', include(debug_toolbar.urls)),
]
| [
37811,
634,
282,
10289,
28373,
198,
198,
464,
4600,
6371,
33279,
82,
63,
1351,
11926,
32336,
284,
5009,
13,
1114,
517,
1321,
3387,
766,
25,
198,
220,
220,
220,
3740,
1378,
31628,
13,
28241,
648,
404,
305,
752,
13,
785,
14,
268,
14,
... | 2.766393 | 488 |
import logging
import os
import requests
if __name__ == "__main__":
pass
| [
11748,
18931,
198,
11748,
28686,
198,
198,
11748,
7007,
628,
628,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
220,
1208,
198
] | 2.928571 | 28 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2020-04-19 07:57
from __future__ import unicode_literals
from django.db import migrations
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
2980,
515,
416,
37770,
352,
13,
1157,
13,
1238,
319,
12131,
12,
3023,
12,
1129,
8753,
25,
3553,
198,
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198... | 2.709091 | 55 |
"""
Sponge Knowledge Base
Processor inheritance
"""
| [
37811,
201,
198,
4561,
14220,
20414,
7308,
201,
198,
18709,
273,
24155,
201,
198,
37811,
201,
198
] | 3.294118 | 17 |
from dagster import PipelineDefinition, OutputDefinition, lambda_solid, types
| [
6738,
48924,
1706,
1330,
37709,
36621,
11,
25235,
36621,
11,
37456,
62,
39390,
11,
3858,
628
] | 4.9375 | 16 |
# import os
# import numpy as np
# import readprm
# import readxyz
# import katom
# # I use examples.py to play with code.
# path = '/Users/moseschung/Documents/Ponder/HIPPO/test/testitems'
# atom_dict, bond_dict, angle_dict, repel_dict, disp_dict, mpole_dict, chgpen_dict, polarize_dict, chgtrn_dict = readprm.readkeyfile('/Users/moseschung/Documents/Ponder/HIPPO/test/testitems/water21test.key')
# ATOM = katom.returnatom(atom_dict)
# BOND = katom.returnbond(bond_dict)
# ANGLE = katom.returnangle(angle_dict)
# REPEL = katom.returnrepulsion(repel_dict)
# DISP = katom.returndispersion(disp_dict)
# MPOLE = katom.returnmultipole(mpole_dict)
# CHGPEN = katom.returnchargepenetration(chgpen_dict)
# POLARIZE = katom.returnpolarization(polarize_dict)
# CHGTRN = katom.returnchargetransfer(chgtrn_dict)
# # print(CHGPEN)
# coordinates, atomtype, connectivity = readxyz.readxyz(f'{path}/waterwater.xyz')
# # print(coordinates[0])
# # print(atomtype[0])
# # print(connectivity[0])
# # print(atom_dict)
# # print(ATOM)
# ATOMID = katom.returnatomid(atomtype[0], coordinates[0], connectivity[0], ATOM, MPOLE, CHGPEN)
# for i in ATOMID:
# i.rotmat(ATOMID)
# i.rotsite()
# print(i.returnmscale(ATOMID))
# # coordinates, atomtype, connectivity = readxyz.readxyz(f'{path}/Nawater.xyz')
# # print(coordinates[0])
# # print(atomtype[0])
# # print(connectivity[0])
# print(3.3535788241877126E-002)
one, two, three = 1, 2, 3
print(one)
| [
2,
1330,
28686,
198,
2,
1330,
299,
32152,
355,
45941,
198,
2,
1330,
1100,
1050,
76,
198,
2,
1330,
1100,
5431,
89,
198,
2,
1330,
479,
37696,
198,
198,
2,
1303,
314,
779,
6096,
13,
9078,
284,
711,
351,
2438,
13,
198,
198,
2,
3108,... | 2.415 | 600 |
from hstest.common.reflection_utils import get_stacktrace
from hstest.exception.failure_handler import get_report
from hstest.exception.outcomes import UnexpectedError
from hstest.outcomes.outcome import Outcome
| [
6738,
289,
301,
395,
13,
11321,
13,
5420,
1564,
62,
26791,
1330,
651,
62,
25558,
40546,
198,
6738,
289,
301,
395,
13,
1069,
4516,
13,
32165,
495,
62,
30281,
1330,
651,
62,
13116,
198,
6738,
289,
301,
395,
13,
1069,
4516,
13,
448,
... | 3.380952 | 63 |
# write your silhouette score unit tests here
import numpy as np
from scipy.spatial.distance import cdist
import cluster
import pytest
from sklearn.metrics import silhouette_samples, silhouette_score
def test_silhouette():
"""
Unit test of silhouette scores for each of the observations.
NOTE: Using sklearn.metrics.silhouette_samples as ground truth. (NOT sklearn.metrics.silhouette_score)
References
----------
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.silhouette_samples.html
"""
# Generate cluster data
mat, labels = cluster.utils.make_clusters()
# Fit model and predict labels
k_model = cluster.KMeans(k=3)
k_model.fit(mat)
predicted_labels = k_model.predict(mat)
# Calculate silhouette scores and check against sklearn
bmi203_proj5_sihouette_values = cluster.Silhouette().score(mat, predicted_labels)
sklearn_silhouette_values = silhouette_samples(mat, predicted_labels)
assert np.allclose(bmi203_proj5_sihouette_values, sklearn_silhouette_values) | [
2,
3551,
534,
41834,
4776,
4326,
5254,
994,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
629,
541,
88,
13,
2777,
34961,
13,
30246,
1330,
269,
17080,
198,
11748,
13946,
198,
11748,
12972,
9288,
198,
198,
6738,
1341,
35720,
13,
4164,
... | 2.911846 | 363 |
"""MyST-NB package setup."""
from setuptools import find_packages, setup
# Manually finding the version so we don't need to import our module
text = open("./myst_nb/__init__.py").read()
for line in text.split("\n"):
if "__version__" in line:
break
version = line.split("= ")[-1].strip('"')
setup(
name="myst-nb",
version=version,
description=(
"A Jupyter Notebook Sphinx reader built on top of the MyST markdown parser."
),
long_description=open("README.md", encoding="utf8").read(),
long_description_content_type="text/markdown",
url="https://github.com/executablebooks/myst_nb",
author="ExecutableBookProject",
author_email="choldgraf@berkeley.edu",
license="BSD-3",
packages=find_packages(),
entry_points={"console_scripts": []},
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Text Processing :: Markup",
"Framework :: Sphinx :: Extension",
],
keywords="markdown lexer parser development docutils sphinx",
python_requires=">=3.6",
package_data={"myst_nb": ["_static/*"]},
install_requires=[
"myst-parser~=0.12.0",
"docutils>=0.15",
"sphinx>=2,<4",
"jupyter_sphinx~=0.2.4",
"jupyter-cache~=0.4.0",
"ipython",
"nbformat~=5.0",
"nbconvert~=5.6",
"pyyaml",
"sphinx-togglebutton~=0.2.2",
],
extras_require={
"code_style": ["flake8<3.8.0,>=3.7.0", "black", "pre-commit==1.17.0"],
"testing": [
"pytest~=5.4",
"pytest-cov~=2.8",
"coverage<5.0",
"pytest-regressions",
"matplotlib",
"numpy",
"sympy",
"pandas",
],
"rtd": [
"coconut~=1.4.3",
"sphinxcontrib-bibtex",
"ipywidgets",
"pandas",
"numpy",
"sympy",
"altair",
"alabaster",
"bokeh",
"plotly",
"matplotlib",
"sphinx-copybutton",
"sphinx-book-theme",
"sphinx-panels~=0.4.1",
],
},
zip_safe=True,
)
| [
37811,
3666,
2257,
12,
32819,
5301,
9058,
526,
15931,
198,
6738,
900,
37623,
10141,
1330,
1064,
62,
43789,
11,
9058,
198,
198,
2,
1869,
935,
4917,
262,
2196,
523,
356,
836,
470,
761,
284,
1330,
674,
8265,
198,
5239,
796,
1280,
7,
19... | 2.045079 | 1,331 |
"""
Author : Achintya Gupta
Date Created : 22-09-2020
"""
"""
Problem Statement
------------------------------------------------
Q) Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
"""
from utils import timing_decorator
import numpy as np
@timing_decorator
digit_n_power()
| [
37811,
198,
13838,
1058,
26219,
600,
3972,
42095,
198,
10430,
15622,
1058,
2534,
12,
2931,
12,
42334,
198,
37811,
198,
198,
37811,
198,
40781,
21983,
198,
47232,
198,
48,
8,
47183,
612,
389,
691,
1115,
3146,
326,
460,
307,
3194,
355,
... | 2.829167 | 240 |
#!/usr/bin/env python
#
#Copyright (C) 2011 by Venkata Pingali (pingali@gmail.com) & TCS
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
import os.path, sys
from config import Config, ConfigMerger
from optparse import OptionParser, SUPPRESS_HELP
import logging
import traceback
log=logging.getLogger('AuthConfig')
__author__ = "Venkata Pingali"
__copyright__ = "Copyright 2011,Venkata Pingali and TCS"
__credits__ = ["UIDAI", "MindTree", "GeoDesic", "Viral Shah"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Venkata Pingali"
__email__ = "pingali@gmail.com"
__status__ = "Pre-release"
class AuthConfig():
"""
Parse the command line
"""
def __init__(self,name="unknown", summary="Unknown commands",
cfg=None):
"""
Initialize command object with information about the target
configuration (e.g., 'request') and appropriate help text
(e.g., 'Processes authentication requests'
"""
self._name = name
self._summary = summary
self._cfg = cfg
def update_paths(self, cfg):
"""
Take relative paths of various files and make it absolute
"""
# first introduce a dir element
paths = ['common.private_key', 'common.public_cert',
'common.pkcs_path', 'common.uid_cert_path',
#'common.logfile',
#'request_demo.xml', 'request_demo.signedxml',
#'request_bio.xml', 'request_bio.signedxml',
'response_validate.xml',
'signature_default.xml', 'signature_default.signedxml',
'signature_verify.signedxml', 'validate_xml_only.xml',
'batch_default.json']
basedir = cfg.common.dir
for p in paths:
try:
old_path = eval("cfg.%s" % p)
if not old_path.startswith("/"):
new_path = basedir + "/" + old_path
else:
new_path = old_path
if not os.path.isfile(new_path):
log.warn("File %s does not exist" % new_path)
exec("cfg.%s = '%s'" % (p, new_path))
#log.debug("Updated path from %s to %s " % \
# (old_path, eval("cfg.%s" % p)))
except:
traceback.print_exc()
log.error("Could not update the path for cfg.%s" % p)
pass
# Treat the xsd paths specially. They are relative to the
# package
xsd_paths = ['common.request_xsd', 'common.response_xsd']
this_dir = os.path.dirname(os.path.realpath(__file__))
exec("cfg.common.request_xsd='%s/xsd/uid-auth-request.xsd'" % \
this_dir)
exec("cfg.common.response_xsd='%s/xsd/uid-auth-response.xsd'" % \
this_dir)
#log.debug("request_xsd path is %s " % cfg.common.request_xsd)
#log.debug("response_xsd path is %s " % cfg.common.response_xsd)
return
def update_config(self):
"""
Process each element of the command line and generate a target
configuration.
"""
logging.basicConfig()
usage = "usage: %prog [options] [<attrib=value> <attrib=value>...]\n" \
+ self._summary
parser = OptionParser(usage=usage)
if self._cfg == None:
default_config_file = "fixtures/auth.cfg"
else:
default_config_file = self._cfg
#=> Set the help text and other command line options.
parser.add_option("-c", "--config",
action="store", type="string", dest="config_file",
default=default_config_file,
help="Specify the input configuration file. " +
"(default: %s)" % default_config_file,
metavar="FILE")
parser.add_option("--show-example-config",
action="callback", callback=self.show_example_config,
help="Sample configuration file")
defaults = {
'data': 'request_demo',
'request': 'request_demo',
'response': 'response_validate',
'crypt': 'crypt_test',
'signature': 'signature_default',
'validate': 'validate_xml_only',
'batch': 'batch_default',
'unknown': 'unknown_default'
}
# => For a given command (e.g., response.py), enable the help
# text for that config element. For everything else, suppress
# help. Make the options secret.
for k, v in defaults.items():
if (k == self._name):
help_text=\
"""Specify the configuration instance to use for %s. For example, %s. See
available choices in config file. (default: %s)""" % (k, v, v)
else:
help_text=SUPPRESS_HELP
parser.add_option("--" + k,
action="store", type="string",
dest=k, default=v,
metavar="NAME",
help=help_text)
# parse the command line
(options, args) = parser.parse_args()
# Check if the configuration file exists
if (not os.path.isfile(options.config_file)):
raise Exception("Unknown config file %s " % (options.config_file))
# Read the configuration file
cfg = Config(options.config_file)
# => For the target configuration element (e.g., request or
# response) check whether the target configuration is valid
cmd = "cfg[options.%s]" % self._name
try:
target_config = eval(cmd)
except:
raise Exception("Invalid setting for parameter \'%s\'. Please check the configuration file." % self._name)
# => Update the configuration for the particular service
log.debug("Setting request configuration to %s " % \
(eval("options.%s" % self._name)))
cmd = "cfg.%s=cfg[options.%s]" % (self._name, self._name)
exec(cmd)
# => Update the paths
if options.config_file.startswith('/'):
config_path = options.config_file
else:
config_path = os.path.realpath(options.config_file)
cfg['common']['dir'] = os.path.dirname(config_path)
self.update_paths(cfg)
# python <command> --conf=auth.cfg a=x c.d=y Over ride
# individual parameters of the config file. Note that you can
# override pretty much any config element. If there is a '.'
# in the variable name, then it is assumed to refer to full
# path of the config element (e.g., batch.json). If there is
# no '.', it is assumed to refer to only the configuration
# element corresponding to the command (e.g., request).
param_hash = {}
for idx, arg in enumerate(args):
parts = arg.split('=', 1)
if len(parts) < 2:
# End of options, don't translate the rest.
# newargs.extend(sys.argv[idx+1:])
break
argname, argvalue = parts
param_hash[argname] = argvalue
log.debug("Command line parameter options = " + param_hash.__str__())
# Print the updated configuration element
log.debug("Configuration of target element '%s':\n%s " % (self._name, cfg[self._name]))
# Update the
for k,v in param_hash.items():
if "." not in k:
# here we are updating only the config element
# corresponding to the command.
cfg[self._name][k] = v
else:
cmd = "cfg.%s=\'%s\'" % (k, v)
exec(cmd)
cmd = "cfg.%s" % k
log.debug("Updated conf var %s to %s \n" % (cmd, eval(cmd)))
# Turn some strings in objects
cfg.common.loglevel = eval("logging.%s" % cfg.common.loglevel)
if (cfg.validate.signed):
cfg.validate.signed = eval("%s" % cfg.validate.signed)
log.debug("Final configuration:\n%s" % cfg)
return cfg
if __name__ == "__main__":
name = "request"
summary = "Issues authentication requests to the server"
logging.getLogger().setLevel(logging.DEBUG)
logging.basicConfig()#filename="execution.log")
c = AuthConfig(name, summary)
cfg = c.update_config()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
220,
198,
2,
198,
2,
15269,
357,
34,
8,
2813,
416,
9932,
74,
1045,
34263,
7344,
357,
13886,
7344,
31,
14816,
13,
785,
8,
1222,
309,
7902,
220,
198,
2,
198,
2,
5990,
3411,
318,
29376,
... | 2.152404 | 4,534 |
"""adam.adam_2
"""
# pylint: disable=C0111
import ctypes
import functools
import operator
@decorator
| [
37811,
324,
321,
13,
324,
321,
62,
17,
198,
37811,
198,
198,
2,
279,
2645,
600,
25,
15560,
28,
34,
486,
1157,
198,
198,
11748,
269,
19199,
198,
11748,
1257,
310,
10141,
198,
11748,
10088,
628,
628,
628,
198,
31,
12501,
273,
1352,
... | 2.5 | 44 |
import os
import subprocess as sp
"""batch convert videos to a 4x4 720p version"""
#VIDEO_DIRECTORY = '/media/taylor/external/robot/Rover/trail'
#VIDEO_DIRECTORY = '/media/taylor/feynman/rover_videos/trail_scan/Videos'
VIDEO_DIRECTORY = '/media/taylor/external/robot/Rover/trail/unprocessed'
video_groups = []
#{01_20_2020_20:49:06}_
files = os.listdir(VIDEO_DIRECTORY)
print(files)
idx = 0
for file in files:
match = False
for video in video_groups:
if video[:21] == file[:21]:
match = True
print('Match: {} {}'.format(video[:21], file[:21]))
if not match:
video_groups.append(files[idx])
idx+=1
print(video_groups)
#sys.exit()
for video in video_groups:
filename = os.path.join(VIDEO_DIRECTORY, video[:21])
output = "{}_merged".format(video[:21])
output = os.path.join(VIDEO_DIRECTORY, output)
if os.path.isfile("{}_720.mp4".format(output)):
print("Output file already exists and will be skipped: {}".format(output))
else:
#command = "ffmpeg -i {}_2.mkv -i {}_4.mkv -i {}_3.mkv -i {}_1.mkv -filter_complex '[0:v][1:v]hstack=inputs=2[top];[2:v][3:v]hstack=inputs=2[bottom];[top][bottom]vstack=inputs=2[v]' -vsync 0 -map '[v]' {}.mp4".format(filename,filename,filename,filename,output)
command = ("ffmpeg -vsync 0 -hwaccel cuvid -c:v h264_cuvid -i {}_2.mkv -hwaccel cuvid -c:v h264_cuvid -i {}_4.mkv -hwaccel cuvid -c:v h264_cuvid -i {}_3.mkv -hwaccel cuvid -c:v h264_cuvid -i {}_1.mkv ".format(filename,filename,filename,filename) +
"-filter_complex '[0:v] scale_npp=1280:720, hwdownload, format=nv12 [upperleft]; [1:v] scale_npp=1280:720, hwdownload, format=nv12 [lowerleft]; [2:v] scale_npp=1280:720, hwdownload, format=nv12 [upperright]; " +
"[3:v] scale_npp=1280:720, hwdownload, format=nv12 [lowerright]; [upperleft][upperright][lowerleft][lowerright]xstack=inputs=4:layout=0_0|0_h0|w0_0|w0_h0[mosaic]; [mosaic] hwupload_cuda' " +
"-c:v hevc_nvenc -preset slow -rc vbr_hq -b:v 20M -maxrate:v 30M -c:a aac -b:a 240k {}_720.mp4".format(output))
# command = ("ffmpeg -vsync 0 -hwaccel cuvid -c:v hevc_cuvid -i {}_1.mp4 -hwaccel cuvid -c:v hevc_cuvid -i {}_3.mp4 -hwaccel cuvid -c:v hevc_cuvid -i {}_2.mp4 -hwaccel cuvid -c:v hevc_cuvid -i {}_0.mp4 ".format(filename,filename,filename,filename) +
# "-filter_complex '[0:v] scale_npp=1280:720, hwdownload, format=nv12 [upperleft]; [1:v] scale_npp=1280:720, hwdownload, format=nv12 [lowerleft]; [2:v] scale_npp=1280:720, hwdownload, format=nv12 [upperright]; " +
# "[3:v] scale_npp=1280:720, hwdownload, format=nv12 [lowerright]; [upperleft][upperright][lowerleft][lowerright]xstack=inputs=4:layout=0_0|0_h0|w0_0|w0_h0[mosaic]; [mosaic] hwupload_cuda' " +
# "-c:v hevc_nvenc -preset slow -rc vbr_hq -b:v 20M -maxrate:v 30M -c:a aac -b:a 240k {}_720.mp4".format(output))
# command = ("ffmpeg -vsync 0 -hwaccel cuvid -c:v h264_cuvid -i {}_2.mkv -hwaccel cuvid -c:v h264_cuvid -i {}_4.mkv -hwaccel cuvid -c:v h264_cuvid -i {}_3.mkv -hwaccel cuvid -c:v h264_cuvid -i {}_1.mkv ".format(filename,filename,filename,filename) +
# "-filter_complex '[0:v] hwdownload, format=nv12 [upperleft]; [1:v] hwdownload, format=nv12 [lowerleft]; [2:v] hwdownload, format=nv12 [upperright]; " +
# "[3:v] hwdownload, format=nv12 [lowerright]; [upperleft][upperright][lowerleft][lowerright]xstack=inputs=4:layout=0_0|0_h0|w0_0|w0_h0[mosaic]; [mosaic] hwupload_cuda' " +
# "-c:v hevc_nvenc -preset slow -rc vbr_hq -b:v 20M -maxrate:v 30M -c:a aac -b:a 240k {}.mp4".format(output))
print("Running command: {}".format(command))
try:
output = sp.check_output(command, shell=True)
except sp.CalledProcessError as e:
print("Error with video {}. Proceeding to the next. Actual error was:")
print(e)
print("Output was: {}".format(output))
| [
11748,
28686,
198,
11748,
850,
14681,
355,
599,
628,
198,
37811,
43501,
10385,
5861,
284,
257,
604,
87,
19,
26250,
79,
2196,
37811,
628,
198,
2,
42937,
62,
17931,
23988,
15513,
796,
31051,
11431,
14,
83,
7167,
14,
22615,
14,
305,
1364... | 2.164835 | 1,820 |
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import abc
from amazon_kclpy.messages import ShutdownInput
class RecordProcessorBase(object):
"""
Base class for implementing a record processor. Each RecordProcessor processes a single shard in a stream.
The record processor represents a lifecycle where it will be initialized, possibly process records, and
finally be terminated.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def initialize(self, initialize_input):
"""
Called once by a the KCL to allow the record processor to configure itself before starting to process records.
:param amazon_kclpy.messages.InitializeInput initialize_input: Information about the
initialization request for the record processor
"""
raise NotImplementedError
@abc.abstractmethod
def process_records(self, process_records_input):
"""
This is called whenever records are received. The method will be provided the batch of records that were
received. A checkpointer is also supplied that allows the application to checkpoint its progress within the
shard.
:param amazon_kclpy.messages.ProcessRecordsInput process_records_input: the records, metadata about the
records, and a checkpointer.
"""
raise NotImplementedError
@abc.abstractmethod
def lease_lost(self, lease_lost_input):
"""
This is called whenever the record processor has lost the lease. After this returns the record processor will
be shutdown. Additionally once a lease has been lost checkpointing is no longer possible.
:param amazon_kclpy.messages.LeaseLostInput lease_lost_input: information about the lease loss (currently empty)
"""
raise NotImplementedError
@abc.abstractmethod
def shard_ended(self, shard_ended_input):
"""
This is called whenever the record processor has reached the end of the shard. The record processor needs to
checkpoint to notify the KCL that it's ok to start processing the child shard(s). Failing to checkpoint will
trigger a retry of the shard end
:param amazon_kclpy.messages.ShardEndedInput shard_ended_input: information about reaching the end of the shard.
"""
raise NotImplementedError
@abc.abstractmethod
def shutdown_requested(self, shutdown_requested_input):
"""
Called when the parent process is preparing to shutdown. This gives the record processor one more chance to
checkpoint before its lease will be released.
:param amazon_kclpy.messages.ShutdownRequestedInput shutdown_requested_input:
Information related to shutdown requested including the checkpointer.
"""
raise NotImplementedError
version = 3
class V2toV3Processor(RecordProcessorBase):
"""
Provides a bridge between the new v2 RecordProcessorBase, and the original RecordProcessorBase.
This handles the conversion of the new input types to the older expected forms. This normally shouldn't be used
directly by record processors, since it's just a compatibility layer.
The delegate should be a :py:class:`amazon_kclpy.kcl.RecordProcessorBase`:
"""
def __init__(self, delegate):
"""
Creates a new V2 to V3 record processor.
:param amazon_kclpy.kcl.v2.RecordProcessorBase delegate: the delegate where requests will be forwarded to
"""
self.delegate = delegate
def initialize(self, initialize_input):
"""
Initializes the record processor
:param amazon_kclpy.messages.InitializeInput initialize_input: the initialization request
:return: None
"""
self.delegate.initialize(initialize_input)
def process_records(self, process_records_input):
"""
Expands the requests, and hands it off to the delegate for processing
:param amazon_kclpy.messages.ProcessRecordsInput process_records_input: information about the records
to process
:return: None
"""
self.delegate.process_records(process_records_input)
def lease_lost(self, lease_lost_input):
"""
Translates the lease lost call to the older shutdown/shutdown input style that was used. In a special case the
checkpointer will not be set in this call, which is essentially fine as checkpointing would fail anyway
:param amazon_kclpy.messages.LeaseLostInput lease_lost_input: information about the lease loss
(currently this is empty)
:return: None
"""
self.delegate.shutdown(ShutdownInput.zombie())
def shard_ended(self, shard_ended_input):
"""
Translates the shard end message to a shutdown input with a reason of TERMINATE and the checkpointer
:param amazon_kclpy.messages.ShardEndedInput shard_ended_input: information, and checkpoint for the end of the
shard.
:return: None
"""
self.delegate.shutdown(ShutdownInput.terminate(shard_ended_input.checkpointer))
def shutdown_requested(self, shutdown_requested_input):
"""
Sends the shutdown request to the delegate
:param amazon_kclpy.messages.ShutdownRequested shutdown_requested_input: information related to the record processor shutdown
:return: None
"""
self.delegate.shutdown_requested(shutdown_requested_input)
| [
2,
15069,
2864,
6186,
13,
785,
11,
3457,
13,
393,
663,
29116,
13,
1439,
6923,
33876,
13,
198,
2,
30628,
55,
12,
34156,
12,
33234,
7483,
25,
24843,
12,
17,
13,
15,
198,
11748,
450,
66,
198,
198,
6738,
716,
5168,
62,
74,
565,
9078... | 2.919979 | 1,912 |
# Copyright 2015 The Switch Authors. All rights reserved.
# Licensed under the Apache License, Version 2, which is in the LICENSE file.
"""
Defines model components to describe transmission build-outs for the
SWITCH-Pyomo model.
SYNOPSIS
>>> from switch_mod.utilities import define_AbstractModel
>>> model = define_AbstractModel(
... 'timescales', 'financials', 'load_zones', 'trans_build')
>>> instance = model.load_inputs(inputs_dir='test_dat')
"""
import os
from pyomo.environ import *
from financials import capital_recovery_factor as crf
def define_components(mod):
"""
Adds components to a Pyomo abstract model object to describe bulk
transmission of an electric grid. This includes parameters, build
decisions and constraints. Unless otherwise stated, all power
capacity is specified in units of MW and all sets and parameters are
mandatory.
TRANSMISSION_LINES is the complete set of transmission pathways
connecting load zones. Each member of this set is a one dimensional
identifier such as "A-B". This set has no regard for directionality
of transmisison lines and will generate an error if you specify two
lines that move in opposite directions such as (A to B) and (B to
A). Another derived set - TRANS_LINES_DIRECTIONAL - stores
directional information. Transmission may be abbreviated as trans or
tx in parameter names or indexes.
trans_lz1[tx] and trans_lz2[tx] specify the load zones at either end
of a transmission line. The order of 1 and 2 is unimportant, but you
are encouraged to be consistent to simplify merging information back
into external databases.
trans_dbid[tx in TRANSMISSION_LINES] is an external database
identifier for each transmission line. This is an optional parameter
than defaults to the identifier of the transmission line.
trans_length_km[tx in TRANSMISSION_LINES] is the length of each
transmission line in kilometers.
trans_efficiency[tx in TRANSMISSION_LINES] is the proportion of
energy sent down a line that is delivered. If 2 percent of energy
sent down a line is lost, this value would be set to 0.98.
trans_new_build_allowed[tx in TRANSMISSION_LINES] is a binary value
indicating whether new transmission build-outs are allowed along a
transmission line. This optional parameter defaults to True.
TRANS_BUILD_YEARS is the set of transmission lines and years in
which they have been or could be built. This set includes past and
potential future builds. All future builds must come online in the
first year of an investment period. This set is composed of two
elements with members: (tx, build_year). For existing transmission
where the build years are not known, build_year is set to 'Legacy'.
EXISTING_TRANS_BLD_YRS is a subset of TRANS_BUILD_YEARS that lists
builds that happened before the first investment period. For most
datasets the build year is unknown, so is it always set to 'Legacy'.
existing_trans_cap[tx in TRANSMISSION_LINES] is a parameter that
describes how many MW of capacity has been installed before the
start of the study.
NEW_TRANS_BLD_YRS is a subset of TRANS_BUILD_YEARS that describes
potential builds.
BuildTrans[(tx, bld_yr) in TRANS_BUILD_YEARS] is a decision variable
that describes the transfer capacity in MW installed on a cooridor
in a given build year. For existing builds, this variable is locked
to the existing capacity.
TransCapacity[(tx, bld_yr) in TRANS_BUILD_YEARS] is an expression
that returns the total nameplate transfer capacity of a transmission
line in a given period. This is the sum of existing and newly-build
capacity.
trans_derating_factor[tx in TRANSMISSION_LINES] is an overall
derating factor for each transmission line that can reflect forced
outage rates, stability or contingency limitations. This parameter
is optional and defaults to 0.
TransCapacityAvailable[(tx, bld_yr) in TRANS_BUILD_YEARS] is an
expression that returns the available transfer capacity of a
transmission line in a given period, taking into account the
nameplate capacity and derating factor.
trans_terrain_multiplier[tx in TRANSMISSION_LINES] is
a cost adjuster applied to each transmission line that reflects the
additional costs that may be incurred for traversing that specific
terrain. Crossing mountains or cities will be more expensive than
crossing plains. This parameter is optional and defaults to 1. This
parameter should be in the range of 0.5 to 3.
trans_capital_cost_per_mw_km describes the generic costs of building
new transmission in units of $BASE_YEAR per MW transfer capacity per
km. This is optional and defaults to 1000.
trans_lifetime_yrs is the number of years in which a capital
construction loan for a new transmission line is repaid. This
optional parameter defaults to 20 years based on 2009 WREZ
transmission model transmission data. At the end of this time,
we assume transmission lines will be rebuilt at the same cost.
trans_fixed_o_m_fraction is describes the fixed Operations and
Maintenance costs as a fraction of capital costs. This optional
parameter defaults to 0.03 based on 2009 WREZ transmission model
transmission data costs for existing transmission maintenance.
trans_cost_hourly[tx TRANSMISSION_LINES] is the cost of building
transmission lines in units of $BASE_YEAR / MW- transfer-capacity /
hour. This derived parameter is based on the total annualized
capital and fixed O&M costs, then divides that by hours per year to
determine the portion of costs incurred hourly.
TRANS_DIRECTIONAL is a derived set of directional paths that
electricity can flow along transmission lines. Each element of this
set is a two-dimensional entry that describes the origin and
destination of the flow: (load_zone_from, load_zone_to). Every
transmission line will generate two entries in this set. Members of
this set are abbreviated as trans_d where possible, but may be
abbreviated as tx in situations where brevity is important and it is
unlikely to be confused with the overall transmission line.
trans_d_line[trans_d] is the transmission line associated with this
directional path.
PERIOD_RELEVANT_TRANS_BUILDS[p in PERIODS] is an indexed set that
describes which transmission builds will be operational in a given
period. Currently, transmission lines are kept online indefinitely,
with parts being replaced as they wear out.
PERIOD_RELEVANT_TRANS_BUILDS[p] will return a subset of (tx, bld_yr)
in TRANS_BUILD_YEARS.
--- Delayed implementation ---
is_dc_line ... Do I even need to implement this?
--- NOTES ---
The cost stream over time for transmission lines differs from the
SWITCH-WECC model. The SWITCH-WECC model assumed new transmission
had a financial lifetime of 20 years, which was the length of the
loan term. During this time, fixed operations & maintenance costs
were also incurred annually and these were estimated to be 3 percent
of the initial capital costs. These fixed O&M costs were obtained
from the 2009 WREZ transmission model transmission data costs for
existing transmission maintenance .. most of those lines were old
and their capital loans had been paid off, so the O&M were the costs
of keeping them operational. SWITCH-WECC basically assumed the lines
could be kept online indefinitely with that O&M budget, with
components of the lines being replaced as needed. This payment
schedule and lifetimes was assumed to hold for both existing and new
lines. This made the annual costs change over time, which could
create edge effects near the end of the study period. SWITCH-WECC
had different cost assumptions for local T&D; capital expenses and
fixed O&M expenses were rolled in together, and those were assumed
to continue indefinitely. This basically assumed that local T&D would
be replaced at the end of its financial lifetime.
SWITCH-Pyomo treats all transmission and distribution (long-
distance or local) the same. Any capacity that is built will be kept
online indefinitely. At the end of its financial lifetime, existing
capacity will be retired and rebuilt, so the annual cost of a line
upgrade will remain constant in every future year.
"""
mod.TRANSMISSION_LINES = Set()
mod.trans_lz1 = Param(mod.TRANSMISSION_LINES, within=mod.LOAD_ZONES)
mod.trans_lz2 = Param(mod.TRANSMISSION_LINES, within=mod.LOAD_ZONES)
mod.min_data_check('TRANSMISSION_LINES', 'trans_lz1', 'trans_lz2')
mod.trans_dbid = Param(mod.TRANSMISSION_LINES, default=lambda m, tx: tx)
mod.trans_length_km = Param(mod.TRANSMISSION_LINES, within=PositiveReals)
mod.trans_efficiency = Param(
mod.TRANSMISSION_LINES,
within=PositiveReals,
validate=lambda m, val, tx: val <= 1)
mod.EXISTING_TRANS_BLD_YRS = Set(
dimen=2,
initialize=lambda m: set(
(tx, 'Legacy') for tx in m.TRANSMISSION_LINES))
mod.existing_trans_cap = Param(
mod.TRANSMISSION_LINES,
within=PositiveReals)
mod.min_data_check(
'trans_length_km', 'trans_efficiency', 'EXISTING_TRANS_BLD_YRS',
'existing_trans_cap')
mod.trans_new_build_allowed = Param(
mod.TRANSMISSION_LINES, within=Boolean, default=True)
mod.NEW_TRANS_BLD_YRS = Set(
dimen=2,
initialize=lambda m: m.TRANSMISSION_LINES * m.PERIODS,
filter=lambda m, tx, p: m.trans_new_build_allowed[tx])
mod.TRANS_BUILD_YEARS = Set(
dimen=2,
initialize=lambda m: m.EXISTING_TRANS_BLD_YRS | m.NEW_TRANS_BLD_YRS)
mod.PERIOD_RELEVANT_TRANS_BUILDS = Set(
mod.PERIODS,
within=mod.TRANS_BUILD_YEARS,
initialize=lambda m, p: set(
(tx, bld_yr) for (tx, bld_yr) in m.TRANS_BUILD_YEARS
if bld_yr <= p))
mod.BuildTrans = Var(
mod.TRANS_BUILD_YEARS,
within=NonNegativeReals,
bounds=bounds_BuildTrans)
mod.TransCapacity = Expression(
mod.TRANSMISSION_LINES, mod.PERIODS,
initialize=lambda m, tx, period: sum(
m.BuildTrans[tx, bld_yr]
for (tx2, bld_yr) in m.TRANS_BUILD_YEARS
if tx2 == tx and (bld_yr == 'Legacy' or bld_yr <= period)))
mod.trans_derating_factor = Param(
mod.TRANSMISSION_LINES,
within=NonNegativeReals,
default=0,
validate=lambda m, val, tx: val <= 1)
mod.TransCapacityAvailable = Expression(
mod.TRANSMISSION_LINES, mod.PERIODS,
initialize=lambda m, tx, period: (
m.TransCapacity[tx, period] * m.trans_derating_factor[tx]))
mod.trans_terrain_multiplier = Param(
mod.TRANSMISSION_LINES,
within=Reals,
default=1,
validate=lambda m, val, tx: val >= 0.5 and val <= 3)
mod.trans_capital_cost_per_mw_km = Param(
within=PositiveReals,
default=1000)
mod.trans_lifetime_yrs = Param(
within=PositiveReals,
default=20)
mod.trans_fixed_o_m_fraction = Param(
within=PositiveReals,
default=0.03)
# Total annaul fixed costs for building new transmission lines...
# Multiply capital costs by capital recover factor to get annual
# payments. Add annual fixed O&M that are expressed as a fraction of
# overnight costs.
mod.trans_cost_annual = Param(
mod.TRANSMISSION_LINES,
within=PositiveReals,
initialize=lambda m, tx: (
m.trans_capital_cost_per_mw_km * m.trans_terrain_multiplier[tx] *
(crf(m.interest_rate, m.trans_lifetime_yrs) +
m.trans_fixed_o_m_fraction)))
# An expression to summarize annual costs for the objective
# function. Units should be total annual future costs in $base_year
# real dollars. The objective function will convert these to
# base_year Net Present Value in $base_year real dollars.
mod.Trans_Fixed_Costs_Annual = Expression(
mod.PERIODS,
initialize=lambda m, p: sum(
m.BuildTrans[tx, bld_yr] * m.trans_cost_annual[tx]
for (tx, bld_yr) in m.PERIOD_RELEVANT_TRANS_BUILDS[p]))
mod.cost_components_annual.append('Trans_Fixed_Costs_Annual')
mod.TRANS_DIRECTIONAL = Set(
dimen=2,
initialize=init_TRANS_DIRECTIONAL)
mod.trans_d_line = Param(
mod.TRANS_DIRECTIONAL,
within=mod.TRANSMISSION_LINES,
initialize=init_trans_d_line)
def load_inputs(mod, switch_data, inputs_dir):
"""
Import data related to transmission builds. The following files are
expected in the input directory:
transmission_lines.tab
TRANSMISSION_LINE, trans_lz1, trans_lz2, trans_length_km,
trans_efficiency, existing_trans_cap
The next files are optional. If they are not included or if any rows
are missing, those parameters will be set to default values as
described in documentation. If you only want to override some
columns and not others in trans_optional_params, put a dot . in the
columns that you don't want to override.
trans_optional_params.tab
TRANSMISSION_LINE, trans_dbid, trans_derating_factor,
trans_terrain_multiplier, trans_new_build_allowed
Note that the next file is formatted as .dat, not as .tab.
trans_params.dat
trans_capital_cost_per_mw_km, trans_lifetime_yrs,
trans_fixed_o_m_fraction, distribution_losses
"""
switch_data.load(
filename=os.path.join(inputs_dir, 'transmission_lines.tab'),
select=('TRANSMISSION_LINE', 'trans_lz1', 'trans_lz2',
'trans_length_km', 'trans_efficiency', 'existing_trans_cap'),
index=mod.TRANSMISSION_LINES,
param=(mod.trans_lz1, mod.trans_lz2, mod.trans_length_km,
mod.trans_efficiency, mod.existing_trans_cap))
trans_optional_params_path = os.path.join(
inputs_dir, 'trans_optional_params.tab')
if os.path.isfile(trans_optional_params_path):
switch_data.load(
filename=trans_optional_params_path,
select=('TRANSMISSION_LINE', 'trans_dbid', 'trans_derating_factor',
'trans_terrain_multiplier', 'trans_new_build_allowed'),
param=(mod.trans_dbid, mod.trans_derating_factor,
mod.trans_terrain_multiplier, mod.trans_new_build_allowed))
trans_params_path = os.path.join(inputs_dir, 'trans_params.dat')
if os.path.isfile(trans_params_path):
switch_data.load(filename=trans_params_path)
| [
2,
15069,
1853,
383,
14645,
46665,
13,
1439,
2489,
10395,
13,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
11,
543,
318,
287,
262,
38559,
24290,
2393,
13,
198,
198,
37811,
198,
198,
7469,
1127,
2746,
6805,
284,
6901,
11478,
... | 2.883744 | 5,118 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Release File wrapper.
The ReleaseFile is the overall meta data file of a :class:apt.repo.Distribution
"""
from typing import Dict, Optional, List
from .tagblock import TagBlock
from .filehash import FileHash
class ReleaseFile(TagBlock):
"""
Release File wrapper.
The ReleaseFile is the overall meta data file of a :class:apt.repo.Distribution
"""
files: Dict[str, FileHash]
def components(self) -> List[str]:
"""
Returns the list of components as a python List
:return List[str]:
"""
return self['Components'].split(' ')
def architectures(self) -> List[str]:
"""
Returns the list of architectures as a python List
:return List[str]:
"""
return self['Architectures'].split(' ')
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
37811,
198,
26362,
9220,
29908,
13,
198,
198,
464,
13868,
8979,
318,
262,
4045,
13634,
1366,
2393,
286,
257,
... | 2.68038 | 316 |
#!/usr/bin/env python3
import asyncio
from mavsdk import System
from mavsdk.offboard import OffboardError, VelocityNedYaw
async def run():
""" Does Offboard control using velocity NED coordinates. """
drone = System()
await drone.connect(system_address="udp://:14540")
print("Waiting for drone to connect...")
async for state in drone.core.connection_state():
if state.is_connected:
print(f"Drone discovered!")
break
print("-- Arming")
await drone.action.arm()
print("-- Setting initial setpoint")
await drone.offboard.set_velocity_ned(VelocityNedYaw(0.0, 0.0, 0.0, 0.0))
print("-- Starting offboard")
try:
await drone.offboard.start()
except OffboardError as error:
print(
f"Starting offboard mode failed with error code: \
{error._result.result}"
)
print("-- Disarming")
await drone.action.disarm()
return
print("-- Go up 2 m/s")
await drone.offboard.set_velocity_ned(VelocityNedYaw(0.0, 0.0, -2.0, 0.0))
await asyncio.sleep(4)
print("-- Go North 2 m/s, turn to face East")
await drone.offboard.set_velocity_ned(VelocityNedYaw(2.0, 0.0, 0.0, 90.0))
await asyncio.sleep(4)
print("-- Go South 2 m/s, turn to face West")
await drone.offboard.set_velocity_ned(VelocityNedYaw(-2.0, 0.0, 0.0, 270.0))
await asyncio.sleep(4)
print("-- Go West 2 m/s, turn to face East")
await drone.offboard.set_velocity_ned(VelocityNedYaw(0.0, -2.0, 0.0, 90.0))
await asyncio.sleep(4)
print("-- Go East 2 m/s")
await drone.offboard.set_velocity_ned(VelocityNedYaw(0.0, 2.0, 0.0, 90.0))
await asyncio.sleep(4)
print("-- Turn to face South")
await drone.offboard.set_velocity_ned(VelocityNedYaw(0.0, 0.0, 0.0, 180.0))
await asyncio.sleep(2)
print("-- Go down 1 m/s, turn to face North")
await drone.offboard.set_velocity_ned(VelocityNedYaw(0.0, 0.0, 1.0, 0.0))
await asyncio.sleep(4)
print("-- Stopping offboard")
try:
await drone.offboard.stop()
except OffboardError as error:
print(
f"Stopping offboard mode failed with error code: \
{error._result.result}"
)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
628,
198,
11748,
30351,
952,
198,
198,
6738,
285,
615,
21282,
74,
1330,
4482,
198,
6738,
285,
615,
21282,
74,
13,
2364,
3526,
1330,
3242,
3526,
12331,
11,
43137,
45,
276,
56,
707,
628... | 2.297271 | 1,026 |
#coding: utf-8
#----------------------------------------------------------------
# Um programa que abre e reproduz o áudio de um arquivo MP3.
#----------------------------------------------------------------
# Tocando um MP3 - Exercício #021
#----------------------------------------------------------------
import pygame, mutagen.mp3
opc = str(input('\n\033[35mDigite bora, para curtir um GreenDayzinho <3: \033[m')).lower()[0]
if opc == 'b':
#linha colorida com frase centralizada(not important)
print('\033[2;35;45m>>>{:^60}<<<\033[m'.format('BOM SOM'))
#instrução para parar com código de cor(opcional)
print('\033[35m>> Qualquer botão para parar <<\033[m\n')
mp3file = 'task021guns.mp3'
pygame.mixer.init(frequency=mutagen.mp3.MP3(mp3file).info.sample_rate)
pygame.mixer.music.load(mp3file)
pygame.mixer.music.play()
pygame.init()
pygame.event.wait()
print('Thanks for listening.')
| [
2,
66,
7656,
25,
3384,
69,
12,
23,
198,
2,
10097,
198,
2,
220,
21039,
1430,
64,
8358,
450,
260,
304,
8186,
89,
267,
6184,
94,
463,
952,
390,
23781,
610,
421,
23593,
4904,
18,
13,
198,
2,
10097,
198,
2,
220,
309,
420,
25440,
23... | 2.819876 | 322 |
from Circle import Circle
from Item import Item
import Constant as c
from GeometryMath import sub, norm
| [
6738,
16291,
1330,
16291,
198,
6738,
9097,
1330,
9097,
198,
11748,
20217,
355,
269,
198,
6738,
2269,
15748,
37372,
1330,
850,
11,
2593,
628
] | 4.375 | 24 |
from displayarray.effects import lens
from displayarray import display
from examples.videos import test_video
# Move the mouse to center the image, scroll to increase/decrease barrel, ctrl+scroll to increase/decrease zoom
m = lens.Barrel(use_bleed=False)
m.enable_mouse_control()
display(test_video, callbacks=m, blocking=True)
| [
6738,
3359,
18747,
13,
34435,
1330,
10317,
198,
6738,
3359,
18747,
1330,
3359,
198,
6738,
6096,
13,
32861,
1330,
1332,
62,
15588,
198,
198,
2,
10028,
262,
10211,
284,
3641,
262,
2939,
11,
10743,
284,
2620,
14,
12501,
260,
589,
9036,
1... | 3.473684 | 95 |
"""Provides the abstract class Expression"""
from abc import ABC, abstractmethod
from functools import partialmethod
from typing import Any
from .context import ContextBase
class Expression(ABC):
"""The abstract Expression class"""
def __hash__(self) -> int:
"""Make it hashable"""
return hash(id(self))
def __getattr__(self, name: str) -> "Expression":
"""Whenever `expr.attr` is encountered,
return a ReferenceAttr object"""
# for dispatch
from .symbolic import ReferenceAttr
return ReferenceAttr(self, name)
def __getitem__(self, item: Any) -> "Expression":
"""Whenever `expr[item]` is encountered,
return a ReferenceAttr object"""
from .symbolic import ReferenceItem
return ReferenceItem(self, item)
def _op_handler(self, op: str, *args: Any, **kwargs: Any) -> "Expression":
"""Handle the operators"""
from .operator import Operator
return Operator.REGISTERED(op, (self, *args), kwargs)
def __rshift__(self, other):
"""Allow to use the right shift operator,"""
from .verb import Verb
if isinstance(other, Verb):
return Verb(
other._pipda_func,
(self, *other._pipda_args),
other._pipda_kwargs,
dataarg=False,
)
return self._op_handler("rshift", other)
# Make sure the operators connect all expressions into one
__add__ = partialmethod(_op_handler, "add")
__radd__ = partialmethod(_op_handler, "radd")
__sub__ = partialmethod(_op_handler, "sub")
__rsub__ = partialmethod(_op_handler, "rsub")
__mul__ = partialmethod(_op_handler, "mul")
__rmul__ = partialmethod(_op_handler, "rmul")
__matmul__ = partialmethod(_op_handler, "matmul")
__rmatmul__ = partialmethod(_op_handler, "rmatmul")
__truediv__ = partialmethod(_op_handler, "truediv")
__rtruediv__ = partialmethod(_op_handler, "rtruediv")
__floordiv__ = partialmethod(_op_handler, "floordiv")
__rfloordiv__ = partialmethod(_op_handler, "rfloordiv")
__mod__ = partialmethod(_op_handler, "mod")
__rmod__ = partialmethod(_op_handler, "rmod")
__lshift__ = partialmethod(_op_handler, "lshift")
__rlshift__ = partialmethod(_op_handler, "rlshift")
# __rshift__ = partialmethod(_op_handler, "rshift")
__rrshift__ = partialmethod(_op_handler, "rrshift")
__and__ = partialmethod(_op_handler, "and_")
__rand__ = partialmethod(_op_handler, "rand_")
__xor__ = partialmethod(_op_handler, "xor")
__rxor__ = partialmethod(_op_handler, "rxor")
__or__ = partialmethod(_op_handler, "or_")
__ror__ = partialmethod(_op_handler, "ror_")
__pow__ = partialmethod(_op_handler, "pow")
__rpow__ = partialmethod(_op_handler, "rpow")
# __contains__() is forced into bool
# __contains__ = partialmethod(_op_handler, 'contains')
__lt__ = partialmethod(_op_handler, "lt") # type: ignore
__le__ = partialmethod(_op_handler, "le")
__eq__ = partialmethod(_op_handler, "eq") # type: ignore
__ne__ = partialmethod(_op_handler, "ne") # type: ignore
__gt__ = partialmethod(_op_handler, "gt")
__ge__ = partialmethod(_op_handler, "ge")
__neg__ = partialmethod(_op_handler, "neg")
__pos__ = partialmethod(_op_handler, "pos")
__invert__ = partialmethod(_op_handler, "invert")
def __index__(self):
"""Allow Expression object to work as indexes"""
return None
def __iter__(self):
"""Forbiden iterating on Expression objects
If it is happening, probably wrong usage of functions/verbs
"""
raise TypeError(
"Expression object is not iterable.\n"
"If you are expecting the evaluated results of the object, try "
"using the piping syntax or writing it in a independent statement, "
"instead of an argument of a regular function call."
)
@abstractmethod
def _pipda_eval(
self,
data: Any,
context: ContextBase = None,
) -> Any:
"""Evaluate the expression using given data"""
| [
37811,
15946,
1460,
262,
12531,
1398,
41986,
37811,
198,
198,
6738,
450,
66,
1330,
9738,
11,
12531,
24396,
198,
6738,
1257,
310,
10141,
1330,
13027,
24396,
198,
6738,
19720,
1330,
4377,
198,
198,
6738,
764,
22866,
1330,
30532,
14881,
628,... | 2.549908 | 1,633 |
"""building.py build frameworks from mission files
"""
from __future__ import division
#print("module {0}".format(__name__))
import time
import re
import importlib
import os
from collections import deque
try:
from itertools import izip
except ImportError: #python 3 zip is same as izip
izip = zip
from ..aid.sixing import *
from ..aid.odicting import odict
from .globaling import *
from . import excepting
from . import registering
from . import storing
from . import housing
from . import acting
from . import poking
from . import needing
from . import goaling
from . import doing
from . import traiting
from . import fiating
from . import wanting
from . import completing
from . import tasking
from . import framing
from . import logging
from . import serving
from .. import trim
from ..aid.consoling import getConsole
console = getConsole()
from ..trim import exterior
def Convert2Num(text):
"""converts text to python type in order
Int, hex, Float, Complex
ValueError if can't
"""
#convert to number if possible
try:
value = int(text, 10)
return value
except ValueError as ex:
pass
try:
value = int(text, 16)
return value
except ValueError as ex:
pass
try:
value = float(text)
return value
except ValueError as ex:
pass
try:
value = complex(text)
return value
except ValueError as ex:
pass
raise ValueError("Expected Number got '{0}'".format(text))
# return None
def Convert2CoordNum(text):
"""converts text to python type in order
FracDeg, Int, hex, Float, Complex
ValueError if can't
"""
#convert to FracDeg Coord if possible
dm = REO_LatLonNE.findall(text) #returns list of tuples of groups [(deg,min)]
if dm:
deg = float(dm[0][0])
min_ = float(dm[0][1])
return (deg + min_/60.0)
dm = REO_LatLonSW.findall(text) #returns list of tuples of groups [(deg,min)]
if dm:
deg = float(dm[0][0])
min_ = float(dm[0][1])
return (-(deg + min_/60.0))
try:
return (Convert2Num(text))
except ValueError:
raise ValueError("Expected CoordPointNum got '{0}'".format(text))
def Convert2BoolCoordNum(text):
"""converts text to python type in order
None, Boolean, Int, Float, Complex
ValueError if can't
"""
#convert to None if possible
if text.lower() == 'none':
return None
#convert to boolean if possible
if text.lower() in ['true', 'yes']:
return (True)
if text.lower() in ['false', 'no']:
return (False)
try:
return (Convert2CoordNum(text))
except ValueError:
raise ValueError("Expected BoolCoordPointNum got '{0}'".format(text))
return None
def Convert2StrBoolCoordNum(text):
"""converts text to python type in order
Boolean, Int, Float, complex or double quoted string
ValueError if can't
Need goal wants unitary type not path or point
"""
if REO_Quoted.match(text): #text is double quoted string
return text.strip('"') #strip off quotes
if REO_QuotedSingle.match(text): #text is single quoted string
return text.strip("'") #strip off quotes
try:
return (Convert2BoolCoordNum(text))
except ValueError:
raise ValueError("Expected StrBoolCoordNum got '{0}'".format(text))
return None
def Convert2PointNum(text):
"""
Converts text to python type in order
Pxy, Pne,Pfs,Pxyz,Pned,Pfsb, Int, hex, Float, Complex
ValueError if can't
"""
# convert to on of the Point classes if possible
match = REO_PointXY.findall(text)
if match:
x, y = match[0]
return Pxy(x=float(x), y=float(y))
match = REO_PointNE.findall(text)
if match:
n, e = match[0]
return Pne(n=float(n), e=float(e))
match = REO_PointFS.findall(text)
if match:
f, s = match[0]
return Pfs(f=float(f), s=float(s))
match = REO_PointXYZ.findall(text)
if match:
x, y, z = match[0]
return Pxyz(x=float(x), y=float(y), z=float(z))
match = REO_PointNED.findall(text)
if match:
n, e, d = match[0]
return Pned(n=float(n), e=float(e), d=float(d))
match = REO_PointFSB.findall(text)
if match:
f, s, b = match[0]
return Pfsb(f=float(f), s=float(s), b=float(b))
try:
return (Convert2Num(text))
except ValueError:
raise ValueError("Expected PointNum got '{0}'".format(text))
def Convert2CoordPointNum(text):
"""converts text to python type in order
FracDeg, Int, hex, Float, Complex
ValueError if can't
"""
#convert to FracDeg Coord if possible
dm = REO_LatLonNE.findall(text) #returns list of tuples of groups [(deg,min)]
if dm:
deg = float(dm[0][0])
min_ = float(dm[0][1])
return (deg + min_/60.0)
dm = REO_LatLonSW.findall(text) #returns list of tuples of groups [(deg,min)]
if dm:
deg = float(dm[0][0])
min_ = float(dm[0][1])
return (-(deg + min_/60.0))
try:
return (Convert2PointNum(text))
except ValueError:
raise ValueError("Expected CoordPointNum got '{0}'".format(text))
def Convert2BoolCoordPointNum(text):
"""converts text to python type in order
None, Boolean, Int, Float, Complex
ValueError if can't
"""
#convert to None if possible
if text.lower() == 'none':
return None
#convert to boolean if possible
if text.lower() in ['true', 'yes']:
return (True)
if text.lower() in ['false', 'no']:
return (False)
try:
return (Convert2CoordPointNum(text))
except ValueError:
raise ValueError("Expected BoolCoordPointNum got '{0}'".format(text))
return None
def Convert2PathCoordPointNum(text):
"""converts text to python type in order
Boolean, Int, Float, Complex
ValueError if can't
"""
#convert to path string if possible
if REO_PathNode.match(text):
return (text)
try:
return (Convert2CoordPointNum(text))
except ValueError:
raise ValueError("Expected PathCoordPointNum got '{0}'".format(text))
return None
def Convert2BoolPathCoordPointNum(text):
"""converts text to python type in order
Boolean, Int, Float, Complex
ValueError if can't
"""
#convert to None if possible
if text.lower() == 'none':
return None
#convert to boolean if possible
if text.lower() in ['true', 'yes']:
return (True)
if text.lower() in ['false', 'no']:
return (False)
try:
return (Convert2PathCoordPointNum(text))
except ValueError:
raise ValueError("Expected PathBoolCoordPointNum got '{0}'".format(text))
return None
def Convert2StrBoolPathCoordPointNum(text):
"""converts text to python type in order
Boolean, Int, Float, complex or double quoted string
ValueError if can't
"""
if REO_Quoted.match(text): #text is double quoted string
return text.strip('"') #strip off quotes
if REO_QuotedSingle.match(text): #text is single quoted string
return text.strip("'") #strip off quotes
try:
return (Convert2BoolPathCoordPointNum(text))
except ValueError:
raise ValueError("Expected StrBoolPathCoordPointNum got '{0}'".format(text))
return None
def StripQuotes(text):
"""
Returns text with leading and following quotes (singe or double) stripped
off if any Otherwise return as is
"""
if REO_Quoted.match(text): #text is double quoted string
return text.strip('"') #strip off quotes
if REO_QuotedSingle.match(text): #text is single quoted string
return text.strip("'") #strip off quotes
return text
VerbList = ['load', 'house', 'init',
'server',
'logger', 'log', 'loggee',
'framer', 'first',
'frame', 'over', 'under', 'next', 'done', 'timeout', 'repeat',
'native', 'benter', 'enter', 'recur', 'exit', 'precur', 'renter', 'rexit',
'print', 'put', 'inc', 'copy', 'set',
'aux', 'rear', 'raze',
'go', 'let',
'do',
'bid', 'ready', 'start', 'stop', 'run', 'abort',
'use', 'flo', 'give', 'take' ]
#reserved tokens
Comparisons = ['==', '<', '<=', '>=', '>', '!=']
Connectives = ['to', 'by', 'with', 'from', 'per', 'for', 'cum', 'qua', 'via',
'as', 'at', 'in', 'of', 'on', 're', 'is',
'if', 'be', 'into', 'and', 'not', '+-', ]
Reserved = Connectives + Comparisons #concatenate to get reserved words
ReservedFrameNames = ['next', 'prev'] # frame names with special meaning as target of goto
class Builder(object):
"""
"""
def __init__(self, fileName='', mode=None, metas=None, preloads=None, behaviors=None):
"""
"""
self.fileName = fileName #initial name of file to start building from
self.mode = mode or []
self.metas = metas or []
self.preloads = preloads or []
self.behaviors = behaviors or []
self.files = [] #list of open file objects, appended to by load commands
self.counts = [] #list of linectr s for open file objects
self.houses = [] #list of houses
self.currentFile = None
self.currentCount = 0
self.currentHuman = '' # human friendly version of current line
self.currentMode = None # None is any
self.currentHouse = None
self.currentStore = None
self.currentLogger = None
self.currentLog = None
self.currentFramer = None
self.currentFrame = None # current frame
self.currentContext = NATIVE
def tokenize(self, line):
"""
Parse line and read and parse continuation lines if any and return tokens list.
"""
saveLines = []
saveLineViews = []
while line.endswith('\\\n'): # escaped newline continuation
line = line.rstrip()
saveLineViews.append("%04d %s" % (self.currentCount, line))
saveLines.append(line.rstrip('\\').strip())
line = self.currentFile.readline() #empty if end of file
self.currentCount += 1 #inc line counter
# process last line read as either only line or continuation line
line = line.rstrip()
saveLineViews.append("%04d %s" % (self.currentCount, line))
saveLines.append(line)
# join all saved into one line
lineView = "\n".join(saveLineViews)
line = " ".join(saveLines)
console.concise(lineView + '\n')
line = line.strip() #strips white space both ends
chunks = REO_Chunks.findall(line) # also chunks trailing comments
tokens = []
for chunk in chunks:
if chunk[0] == '#': # throw away chunk as comment
break
else:
tokens.append(chunk)
return tokens
def build(self, fileName='', mode=None, metas=None, preloads=None, behaviors=None):
"""
Allows building from multiple files. Essentially files list is stack of files
fileName is name of first file. Load commands in any files push (append) file onto files
until file completed loaded and then popped off
Each house's store is inited with the meta data in metas
"""
#overwrite default if truthy argument
if fileName:
self.fileName = fileName
if mode:
self.mode.extend[mode]
if metas:
self.metas.extend[metas]
if preloads:
self.preloads.extend[preloads]
if behaviors:
self.behaviors.extend[behaviors]
if self.behaviors: #import behavior package/module
for behavior in self.behaviors:
mod = importlib.import_module(behavior)
housing.House.Clear() #clear house registry
housing.ClearRegistries() #clear all the other registries
try: #IOError
self.fileName = os.path.abspath(self.fileName)
self.currentFile = open(self.fileName,"r")
self.currentCount = 0
try: #ResolveError
while self.currentFile:
line = self.currentFile.readline() # empty if end of file
self.currentCount += 1 # inc line counter
nextTokens = [] # for connective continuation
while (line):
if nextTokens: # parsed ahead but not continuation
tokens = nextTokens
nextTokens = []
else:
tokens = self.tokenize(line) # line and any continuations
if (not tokens): #empty line or comment only
line = self.currentFile.readline() # empty if end of file
self.currentCount += 1 # inc line counter
continue # guarantees at least 1 token
# verbs like load which change file context can not be continued
if tokens[0] not in ('load'): # verb allows connective continuation
while True: # iteratively attempt connective continuation
# Connective continuation
# adds lines that start with connective
# skips empty or comment lines
# stops on line starting with non connective verb
line = self.currentFile.readline() # empty if end of file
self.currentCount += 1 # inc line counter
if not line: # end of file
break
nextTokens = self.tokenize(line) # parse ahead
if nextTokens and nextTokens[0] not in Reserved: # not connective
break # do not continue
if nextTokens:
tokens.extend(nextTokens) # add continuation
nextTokens = []
self.currentHuman = ' '.join(tokens)
try: #ParseError ParseWarning
if not self.dispatch(tokens): # catches dispatches the return unexpectedly
console.terse("Script Parsing stopped at line {0} in file {1}\n".format(
self.currentCount, self.currentFile.name))
console.terse(self.currentHuman + '\n')
return False
except excepting.ParseError as ex:
console.terse("\n{0}\n\n".format(ex))
console.terse("Script line {0} in file {1}\n".format(
self.currentCount, self.currentFile.name))
console.terse(self.currentHuman + '\n')
raise
#dispatch evals commands. self.currentFile may be changed by load command
if not nextTokens:
line = self.currentFile.readline() #empty if end of file
self.currentCount += 1 #inc line counter
self.currentFile.close()
if self.files:
self.currentFile = self.files.pop()
self.currentCount = self.counts.pop()
console.terse("Resume loading from file {0}.\n".format(self.currentFile.name))
else:
self.currentFile = None
#building done so now resolve links and collect actives inactives
for house in self.houses:
house.orderTaskables()
house.resolve()
if console._verbosity >= console.Wordage.concise:
house.showAllTaskers()
#show framework hierarchiy
for framer in house.framers:
framer.showHierarchy()
#show hierarchy of each house's store
console.concise( "\nData Store for {0}\n".format(house.name))
house.store.expose(valued=(console._verbosity >= console.Wordage.terse))
return True
except excepting.ResolveError as ex:
console.terse("{0}\n".format(ex))
return False
except IOError as ex:
console.terse("Error opening mission file {0}\n".format(ex))
return False
finally:
for f in self.files:
if not f.closed:
f.close()
def dispatch(self, tokens):
"""
Converts declaration verb into build method name and calls it
"""
verb = tokens[0]
index = 1
if verb not in VerbList:
msg = "ParseError: Building {0}. Unknown verb {1}, index = {2} tokens = {3}".format(
verb, verb, index, tokens)
raise excepting.ParseError(msg, tokens, index)
verbMethod = 'build' + verb.capitalize()
if hasattr(self, verbMethod):
return(getattr(self, verbMethod )(verb, tokens, index))
else:
return self.buildGeneric(verb, tokens, index)
def buildGeneric(self, verb, tokens, index):
"""
Called when no build method exists for a verb
"""
msg = "ParseError: No build method for verb {0}.".format(verb)
raise excepting.ParseError(msg, tokens, index)
def buildLoad(self, command, tokens, index):
"""
load filepathname
"""
try:
name = tokens[index]
index +=1
self.files.append(self.currentFile) #push currentFile
self.counts.append(self.currentCount) #push current line ct
cwd = os.getcwd() #save current working directory
os.chdir(os.path.split(self.currentFile.name)[0]) # set cwd to current file
name = os.path.abspath(os.path.expanduser(name)) # resolve name if relpath to cwd
os.chdir(cwd) #restore old cwd
self.currentFile = open(name,"r")
self.currentCount = 0
console.terse("Loading from file {0}.\n".format(self.currentFile.name))
except IndexError:
msg = "ParseError: Building verb '%s'. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "ParseError: Building verb '%s'. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
return True
#House specific builders
def buildHouse(self, command, tokens, index):
"""Create a new house and make it the current one
house dreams
"""
try:
name = tokens[index]
index +=1
self.verifyName(name, command, tokens, index)
self.currentHouse = housing.House(name = name) #also creates .store
self.houses.append(self.currentHouse)
self.currentStore = self.currentHouse.store
console.terse(" Created House '{0}'. Assigning registries and "
"creating instances ...\n".format(name))
self.currentHouse.assignRegistries()
console.profuse(" Clearing current Framer, Frame, Log etc.\n")
#changed store so need to make new frameworks and frames
self.currentFramer = None #current framer
self.currentFrame = None #current frame
self.currentLogger = None #current logger
self.currentLog = None #current log
#meta data in metas is list of triples of (name, path, data)
for name, path, data in self.metas:
self.currentHouse.metas[name] = self.initPathToData(path, data)
# set .meta.house to house.name
self.currentHouse.metas['house'] = self.initPathToData('.meta.house',
odict(value=self.currentHouse.name))
for path, data in self.preloads:
self.initPathToData(path, data)
except IndexError:
msg = "ParseError: Building verb '%s'. Not enough tokens." % (command, )
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "ParseError: Building verb '%s'. Unused tokens." % (command, )
raise excepting.ParseError(msg, tokens, index)
msg = " Built House '{0}' with meta:\n".format(self.currentHouse.name)
for name, share in self.currentHouse.metas.items():
msg += " {0}: {1!r}\n".format(name, share)
console.terse(msg)
msg = " Built House '{0}' with preload:\n".format(self.currentHouse.name)
for path, data in self.preloads:
share = self.currentHouse.store.fetch(path)
msg += " {0}: {1!r}\n".format(path, share)
console.terse(msg)
return True
# Convenience Functions
def initPathToData(self, path, data):
"""Convenience support function to preload meta data.
Initialize share given by path with data.
Assumes self.currentStore is valid
path is share path string
data is ordered dict of data
"""
share = self.currentStore.create(path)
self.verifyShareFields(share, data.keys(), None, None)
share.update(data)
return share
#Store specific builders
def buildInit(self, command, tokens, index):
"""Initialize share in current store
init destination with data
init indirect from source
destination:
absolute
path
data:
direct
indirect:
[(value, fields) in] absolute
[(value, fields) in] path
source:
[(value, fields) in] absolute
[(value, fields) in] path
"""
if not self.currentStore:
msg = "ParseError: Building verb '%s'. No current store" % (command)
raise excepting.ParseError(msg, tokens, index)
try:
destinationFields, index = self.parseFields(tokens, index)
destinationPath, index = self.parsePath(tokens, index)
if self.currentStore.fetchShare(destinationPath) is None:
console.terse(" Warning: Init of non-preexistent share {0} ..."
" creating anyway\n".format(destinationPath))
destination = self.currentStore.create(destinationPath)
connective = tokens[index]
index += 1
if connective in ('with', 'to'): # to form deprecated eventually remove
if connective == 'to':
console.terse("Warning: Connective 'to' in 'init' verb depricated. Use 'with' instead.\n")
if destinationFields: #fields not allowed so error
msg = "ParseError: Building verb '%s'. Unexpected fields '%s in' clause " %\
(command, destinationFields)
raise excepting.ParseError(msg, tokens, index)
data, index = self.parseDirect(tokens, index)
#prevent init value and non value fields in same share
self.verifyShareFields(destination, data.keys(), tokens, index)
destination.update(data)
console.profuse(" Inited share {0} to data = {1}\n".format(destination.name, data))
elif connective in ('from', ):
sourceFields, index = self.parseFields(tokens, index)
sourcePath, index = self.parsePath(tokens, index)
source = self.currentStore.fetchShare(sourcePath)
if source is None:
msg = "ParseError: Building verb '%s'. Nonexistent source share '%s'" %\
(command, sourcePath)
raise excepting.ParseError(msg, tokens, index)
sourceFields, destinationFields = self.prepareSrcDstFields(source,
sourceFields,
destination,
destinationFields,
tokens,
index)
data = odict()
for sf, df in izip(sourceFields, destinationFields):
data[df] = source[sf]
destination.update(data)
msg = " Inited share {0} from source {1} with data = {2}\n".format(
destination.name, source.name, data)
console.profuse(msg)
else:
msg = "ParseError: Building verb '%s'. Unexpected connective '%s'" %\
(command, connective)
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "ParseError: Building verb '%s'. Not enough tokens." % (command, )
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "ParseError: Building verb '%s'. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
return True
def buildServer(self, command, tokens, index):
"""create server tasker in current house
server has to have name so can ask stop
server name [at period] [be scheduled]
[rx shost:sport] [tx dhost:dport] [in order] [to prefix] [per data]
[for source]
scheduled: (active, inactive, slave)
rx:
(host:port, :port, host:, host, :)
tx:
(host:port, :port, host:, host, :)
order:
(front, mid, back)
prefix
filepath
data:
direct
source:
[(value, fields) in] indirect
"""
if not self.currentHouse:
msg = "ParseError: Building verb '%s'. No current house" % (command)
raise excepting.ParseError(msg, tokens, index)
if not self.currentStore:
msg = "ParseError: Building verb '%s'. No current store" % (command)
raise excepting.ParseError(msg, tokens, index)
try:
parms = {}
init = {}
name = ''
connective = None
period = 0.0
prefix = './'
schedule = ACTIVE #globaling.py
order = MID #globaling.py
rxa = ''
txa = ''
sha = ('', 54321) #empty host means any interface on local host
dha = ('localhost', 54321)
name = tokens[index]
index +=1
while index < len(tokens): #options
connective = tokens[index]
index += 1
if connective == 'at':
period = abs(Convert2Num(tokens[index]))
index +=1
elif connective == 'to':
prefix = tokens[index]
index +=1
elif connective == 'be':
option = tokens[index]
index +=1
if option not in ['active', 'inactive', 'slave']:
msg = "ParseError: Building verb '%s'. Bad server scheduled option got %s" % \
(command, option)
raise excepting.ParseError(msg, tokens, index)
schedule = ScheduleValues[option] #replace text with value
elif connective == 'in':
order = tokens[index]
index +=1
if order not in OrderValues:
msg = "ParseError: Building verb '%s'. Bad order option got %s" % \
(command, order)
raise excepting.ParseError(msg, tokens, index)
order = OrderValues[order] #convert to order value
elif connective == 'rx':
rxa = tokens[index]
index += 1
elif connective == 'tx':
txa = tokens[index]
index += 1
elif connective == 'per':
data, index = self.parseDirect(tokens, index)
init.update(data)
elif connective == 'for':
srcFields, index = self.parseFields(tokens, index)
srcPath, index = self.parsePath(tokens, index)
if self.currentStore.fetchShare(srcPath) is None:
console.terse(" Warning: Init 'with' non-existent share {0}"
" ... creating anyway".format(srcPath))
src = self.currentStore.create(srcPath)
#assumes src share inited before this line parsed
for field in srcFields:
init[field] = src[field]
else:
msg = "ParseError: Building verb '%s'. Bad connective got %s" % \
(command, connective)
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "ParseError: Building verb '%s'. Not enough tokens." % (command, )
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "ParseError: Building verb '%s'. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
prefix += '/' + self.currentHouse.name #extra slashes are ignored
if rxa:
if ':' in rxa:
host, port = rxa.split(':')
sha = (host, int(port))
else:
sha = (rxa, sha[1])
if txa:
if ':' in txa:
host, port = txa.split(':')
dha = (host, int(port))
else:
dha = (txa, dha[1])
server = serving.Server(name=name, store = self.currentStore,)
kw = dict(period=period, schedule=schedule, sha=sha, dha=dha, prefix=prefix,)
kw.update(init)
server.reinit(**kw)
self.currentHouse.taskers.append(server)
if schedule == SLAVE:
self.currentHouse.slaves.append(server)
else: #taskable active or inactive
if order == FRONT:
self.currentHouse.fronts.append(server)
elif order == BACK:
self.currentHouse.backs.append(server)
else:
self.currentHouse.mids.append(server)
msg = " Created server named {0} at period {2:0.4f} be {3}\n".format(
server.name, name, server.period, ScheduleNames[server.schedule])
console.profuse(msg)
return True
#Logger specific builders
def buildLogger(self, command, tokens, index):
"""
Create logger in current house
logger logname [to prefix] [at period] [be scheduled]
[flush interval] [keep copies] [cycle term] [size bytes]
scheduled: (active, inactive, slave)
period seconds
interval seconds
term seconds
copies integer
bytes bytes
logger basic at 0.125
logger basic
"""
if not self.currentHouse:
msg = "ParseError: Building verb '{0}'. No current house.".format(
command, index, tokens)
raise excepting.ParseError(msg, tokens, index)
if not self.currentStore:
msg = "ParseError: Building verb '{0}'. No current store.".format(
command, index, tokens)
raise excepting.ParseError(msg, tokens, index)
try:
name = tokens[index]
index +=1
period = 0.0 #default
schedule = ACTIVE #globaling.py
order = MID #globaling.py
interval = 30.0
prefix = './'
keep = 0
term = 3600.0
size = 1024 # default rotate size is 1024 bytes = 1KB
reuse = False # non-unique logger directory name if True
while index < len(tokens): #options
connective = tokens[index]
index += 1
if connective == 'at':
period = abs(Convert2Num(tokens[index]))
index +=1
elif connective == 'to': # base directory path for log files
prefix = tokens[index] # house name is post pended as sub directory
index +=1
elif connective == 'be':
option = tokens[index]
index +=1
if option not in ['active', 'inactive', 'slave']:
msg = "Error building %s. Bad logger scheduled option got %s." %\
(command, option)
raise excepting.ParseError(msg, tokens, index)
schedule = ScheduleValues[option] #replace text with value
elif connective == 'in':
order = tokens[index]
index +=1
if order not in OrderValues:
msg = "Error building %s. Bad order got %s." %\
(command, order)
raise excepting.ParseError(msg, tokens, index)
order = OrderValues[order] #convert to order value
elif connective == 'flush':
interval = max(1.0, abs(Convert2Num(tokens[index])))
index +=1
elif connective == 'keep':
keep = max(0, int(Convert2Num(tokens[index])))
index +=1
elif connective == 'cycle':
term = max(0.0, abs(Convert2Num(tokens[index])))
index +=1
elif connective == 'size':
size = max(0, abs(Convert2Num(tokens[index])))
index +=1
elif connective == 'reuse':
reuse = True
else:
msg = "Error building %s. Bad connective got %s." %\
(command, connective)
raise excepting.ParseError(msg, tokens, index)
if name in logging.Logger.Names:
msg = "Error building %s. Task %s already exists." %\
(command, name)
raise excepting.ParseError(msg, tokens, index)
logger = logging.Logger(name=name,
store=self.currentStore,
period=period,
flushPeriod=interval,
prefix=prefix,
keep=keep,
cyclePeriod=term,
fileSize=size,
reuse=reuse)
logger.schedule = schedule
self.currentHouse.taskers.append(logger)
if schedule == SLAVE:
self.currentHouse.slaves.append(logger)
else: #taskable active or inactive
if order == FRONT:
self.currentHouse.fronts.append(logger)
elif order == BACK:
self.currentHouse.backs.append(logger)
else:
self.currentHouse.mids.append(logger)
self.currentLogger = logger
console.profuse(" Created logger named {0} at period {1:0.4f} be {2}\n".format(
logger.name, logger.period, ScheduleNames[logger.schedule]))
except IndexError:
msg = "Error building %s. Not enough tokens." % (command, )
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
return True
def buildLog(self, command, tokens, index):
"""
Create log in current logger
log name [to fileName] [as (text, binary)] [on rule]
rule: (once, never, always, update, change, streak, deck)
default fileName is log's name
default type is text
default rule is never
for manual logging use tout command with rule once or never
log autopilot text to './logs/' on update
"""
if not self.currentLogger:
msg = "Error building %s. No current logger." % (command,)
raise excepting.ParseError(msg, tokens, index)
if not self.currentStore:
msg = "Error building %s. No current store." % (command,)
raise excepting.ParseError(msg, tokens, index)
try:
kind = 'text'
fileName = ''
rule = NEVER
name = tokens[index]
index +=1
while index < len(tokens): #options
connective = tokens[index]
index += 1
if connective == 'as':
kind = tokens[index]
index +=1
if kind not in ['text', 'binary']:
msg = "Error building %s. Bad kind = %s." %\
(command, kind)
raise excepting.ParseError(msg, tokens, index)
elif connective == 'to':
fileName = tokens[index]
index +=1
elif connective == 'on':
rule = tokens[index].capitalize()
index +=1
if rule not in LogRuleValues:
msg = "Error building %s. Bad rule = %s." %\
(command, rule)
raise excepting.ParseError(msg, tokens, index)
rule = LogRuleValues[rule]
else:
msg = "Error building %s. Bad connective got %s." %\
(command, connective)
raise excepting.ParseError(msg, tokens, index)
if name in logging.Log.Names: # check if instance name in Registrar
msg = "Error building %s. Log named %s already exists." %\
(command, name)
raise excepting.ParseError(msg, tokens, index)
if fileName:
for log in self.currentLogger.logs:
if fileName == log.baseFilename:
msg = ("Error building {0}. Log named {1} file named {2} "
"already exists.".format(command, name, fileName))
raise excepting.ParseError(msg, tokens, index)
log = logging.Log(name=name,
store=self.currentStore,
kind=kind,
baseFilename=fileName,
rule=rule)
self.currentLogger.addLog(log)
self.currentLog = log
console.profuse(" Created log named {0} kind {1} file {2} rule {3}\n".format(
name, kind, fileName, LogRuleNames[rule]))
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command, )
raise excepting.ParseError(msg, tokens, index)
return True
def buildLoggee(self, command, tokens, index):
"""
Add loggee(s) to current log
Syntax:
loggee [fields in] path [as tag] [[fields in] path [as tag]] ...
path: share path
fields: field list
If fields not provided use all fields
If tag not provide use last segment of path as tag
If log rule is streak then only one loggee per log is allowed and only
the first field from fields clause is used.
Syntax:
log name on streak
loggee [fields in] path [as tag]
If log rule is deck then only one loggee per log is allowed and
fields clause is required.
Syntax:
log name on deck
loggee fields in path [as tag]
"""
if not self.currentLog:
msg = "Error building %s. No current log." % (command,)
raise excepting.ParseError(msg, tokens, index)
if not self.currentStore:
msg = "Error building %s. No current store." % (command,)
raise excepting.ParseError(msg, tokens, index)
try:
while index < len(tokens):
tag = ""
fields, index = self.parseFields(tokens, index)
path = tokens[index]
index +=1
if path in Reserved:
msg = "ParseError: Invalid path '{0}' using reserved".format(path)
raise excepting.ParseError(msg, tokens, index)
if not (REO_DotPath.match(path) or REO_RelPath.match(path)):
#valid absolute or relative path segment without relation clause
msg = "ParseError: Invalid path format'{0}'".format(path)
raise excepting.ParseError(msg, tokens, index)
parts = path.split(".")
if "me" in parts:
msg = "ParseError: Invalid path format'{0}', 'me' undefined".format(path)
raise excepting.ParseError(msg, tokens, index)
if index < len(tokens):
connective = tokens[index]
if connective == 'as':
index += 1 # eat token
tag = tokens[index]
if tag in Reserved:
msg = "ParseError: Invalid tag '{0}' using reserved".format(tag)
raise excepting.ParseError(msg, tokens, index)
tag = StripQuotes(tag)
index += 1
if not tag:
tag = parts[-1]
share = self.currentStore.create(path) #create so no errors at runtime
if not isinstance(share, storing.Share): #verify path ends in share not node
msg = "Error building %s. Loggee path %s not Share." % (command, path)
raise excepting.ParseError(msg, tokens, index)
if tag in self.currentLog.loggees:
msg = "Error building %s. Loggee %s already exists in Log %s." %\
(command, tag, self.currentLog.name)
raise excepting.ParseError(msg, tokens, index)
if self.currentLog.rule in (STREAK, DECK) and self.currentLog.loggees:
# only one loggee allowed when rule is streak or deck
msg = ("Error building {0}. Only one loggee allowed when "
"rule is streak or deck.".format(command))
raise excepting.ParseError(msg, tokens, index)
self.currentLog.addLoggee(tag=tag, loggee=share, fields=fields)
console.profuse(" Added loggee {0} with tag {1} fields {2}\n".format(
share.name, tag, fields))
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
return True
#Framework specific builders
def buildFramer(self, command, tokens, index):
"""Create a new framer and make it the current one
framer framername [be (active, inactive, aux, slave)] [at period]
[first frame] [via inode]
framer framername be active at 0.0
framer framername
"""
if not self.currentHouse:
msg = "Error building %s. No current house." % (command,)
raise excepting.ParseError(msg, tokens, index)
if not self.currentStore:
msg = "Error building %s. No current store." % (command,)
raise excepting.ParseError(msg, tokens, index)
try:
name = tokens[index]
index +=1
self.verifyName(name, command, tokens, index)
schedule = INACTIVE #globaling.py
order = MID #globaling.py
period = 0.0
frame = ''
inode = ''
while index < len(tokens): #options
connective = tokens[index]
index += 1
if connective == 'at':
period = max(0.0, Convert2Num(tokens[index]))
index +=1
elif connective == 'be':
option = tokens[index]
index +=1
if option not in ScheduleValues:
msg = "Error building %s. Bad scheduled option got %s." %\
(command, option)
raise excepting.ParseError(msg, tokens, index)
schedule = ScheduleValues[option] #replace text with value
elif connective == 'in':
order = tokens[index]
index +=1
if order not in OrderValues:
msg = "Error building %s. Bad order got %s." %\
(command, order,)
raise excepting.ParseError(msg, tokens, index)
order = OrderValues[order] #convert to order value
elif connective == 'first':
frame = tokens[index]
index +=1
self.verifyName(frame, command, tokens, index)
elif connective == 'via':
inode, index = self.parseIndirect(tokens, index, node=True)
else:
msg = "Error building %s. Bad connective got %s." %\
(command, connective)
raise excepting.ParseError(msg, tokens, index)
if name in framing.Framer.Names:
msg = "Error building %s. Framer or Task %s already exists." %\
(command, name)
raise excepting.ParseError(msg, tokens, index)
else:
framer = framing.Framer(name = name,
store = self.currentStore,
period = period)
framer.schedule = schedule
framer.first = frame #need to resolve later
framer.inode = inode
self.currentHouse.taskers.append(framer)
self.currentHouse.framers.append(framer)
if schedule == SLAVE:
self.currentHouse.slaves.append(framer)
elif schedule == AUX:
self.currentHouse.auxes.append(framer)
elif schedule == MOOT:
self.currentHouse.moots.append(framer)
else: #taskable active or inactive
if order == FRONT:
self.currentHouse.fronts.append(framer)
elif order == BACK:
self.currentHouse.backs.append(framer)
else:
self.currentHouse.mids.append(framer)
self.currentFramer = framer
self.currentFramer.assignFrameRegistry()
self.currentFrame = None #changed current Framer so no current Frame
console.profuse(" Created Framer named '{0}' at period {1:0.4f} be {2} first {3}\n".format(
framer.name, framer.period, ScheduleNames[framer.schedule], framer.first))
console.profuse(" Added Framer '{0}' to House '{1}', Assigned frame registry\n".format(
framer.name, self.currentHouse.name))
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
return True
def buildFirst(self, command, tokens, index):
"""set first (starting) frame for current framer
first framename
"""
if not self.currentFramer:
msg = "Error building %s. No current framer." % (command,)
raise excepting.ParseError(msg, tokens, index)
try:
name = tokens[index]
index +=1
self.verifyName(name, command, tokens, index)
self.currentFramer.first = name #need to resolve later
console.profuse(" Assigned first frame {0} for framework {1}\n".format(
name, self.currentFramer.name))
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
return True
#Frame specific builders
def buildFrame(self, command, tokens, index):
"""Create frame and attach to over frame if indicated
frame framename [in over] [via inode]
framename cannot be "next" which is reserved
"""
if not self.currentStore:
msg = "Error building %s. No current store." % (command,)
raise excepting.ParseError(msg, tokens, index)
if not self.currentFramer:
msg = "Error building %s. No current framer." % (command,)
raise excepting.ParseError(msg, tokens, index)
inode = ''
try:
name = tokens[index]
index +=1
self.verifyName(name, command, tokens, index)
over = None
while index < len(tokens): #options
connective = tokens[index]
index += 1
if connective == 'in':
over = tokens[index]
index +=1
elif connective == 'via':
inode, index = self.parseIndirect(tokens, index, node=True)
else:
msg = "Error building %s. Bad connective got %s." % (command, connective)
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if name in ReservedFrameNames:
msg = "Error building %s in Framer %s. Frame name %s reserved." %\
(command, self.currentFramer.name, name)
raise excepting.ParseError(msg, tokens, index)
elif name in framing.Frame.Names: #could use Registry Retrieve function
msg = "Error building %s in Framer %s. Frame %s already exists." %\
(command, self.currentFramer.name, name)
raise excepting.ParseError(msg, tokens, index)
else:
frame = framing.Frame(name=name, store = self.currentStore,
framer=self.currentFramer.name,
inode=inode)
if over:
frame.over = over #need to resolve later
#if previous frame did not have explicit next frame then use this new frame
# ad next lexically
if self.currentFrame and not self.currentFrame.next_:
self.currentFrame.next_ = frame.name
#default first frame is first lexical frame if not assigned otherwise
#so if startFrame is none then we must be first lexical frame
if not self.currentFramer.first: #frame.framer.first:
self.currentFramer.first = frame.name #frame.framer.first = frame
self.currentFrame = frame
self.currentContext = NATIVE
console.profuse(" Created frame {0} with over {1}\n".format(frame.name, over))
return True
def buildOver(self, command, tokens, index):
"""Makes frame the over frame of the current frame
over frame
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
over = tokens[index]
index +=1
self.verifyName(over, command, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
self.currentFrame.over = over #need to resolve and attach later
console.profuse(" Assigned over {0} to frame {1}\n".format(
over,self.currentFrame.name))
return True
def buildUnder(self, command, tokens, index):
"""Makes frame the primary under frame of the current frame
under frame
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
under = tokens[index]
index +=1
self.verifyName(under, command, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
unders = self.currentFrame.unders
if not unders: #empty so just append
unders.append(under)
elif under != unders[0]: #not already primary
while under in unders: #remove under (in case multiple copies shouldnt be)
unders.remove(under)
if isinstance(unders[0], framing.Frame): #should not be but if valid don't overwrite
unders.insert(0, under)
else: #just name so overwrite
unders[0] = under
else: #under == unders[0] already so do nothing
pass
console.profuse(" Assigned primary under {0} for frame {1}\n".format(
under,self.currentFrame.name))
return True
def buildNext(self, command, tokens, index):
"""Explicitly assign next frame for timeouts and as target of go next
next frameName
next
blank frameName means use lexically next allows override if multiple
next commands to default of lexical
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
if index < len(tokens): #next frame optional
next_ = tokens[index]
index += 1
self.verifyName(next_, command, tokens, index)
else:
next_ = None
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
self.currentFrame.next_ = next_
console.profuse(" Assigned next frame {0} for frame {1}\n".format(
next_, self.currentFrame.name))
return True
def buildAux(self, command, tokens, index):
"""Parse 'aux' command for simple, cloned, or conditional aux of forms
Simple Auxiliary:
aux framername
Cloned Auxiliary:
aux framername as (mine, clonedauxname) [via (main, mine, inode)]
Simple Conditional Auxiliary:
aux framername if [not] need
aux framername if [not] need [and [not] need ...]
Cloned Conditional Auxiliary:
aux framername as (mine, clonedauxname) [via inode]
if [not] need
aux framername as (mine, clonedauxname) [via inode]
if [not] need [and [not] need ...]
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
needs = []
aux = None # original
connective = None
clone = None
inode = ''
insular = False
aux = tokens[index]
index +=1 #eat token
self.verifyName(aux, command, tokens, index)
while index < len(tokens): #options
connective = tokens[index]
index += 1
if connective == 'as':
clone = tokens[index]
index += 1
self.verifyName(clone, command, tokens, index)
elif connective == 'via':
inode, index = self.parseIndirect(tokens, index, node=True)
elif connective == 'if':
while (index < len(tokens)):
act, index = self.makeNeed(tokens, index)
if not act:
return False # something wrong do not know what
needs.append(act)
if index < len(tokens):
connective = tokens[index]
if connective not in ['and']:
msg = "ParseError: Building verb '%s'. Bad connective '%s'" % \
(command, connective)
raise excepting.ParseError(msg, tokens, index)
index += 1 #otherwise eat token
else:
msg = ("Error building {0}. Invalid connective"
" '{1}'.".format(command, connective))
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if clone and needs:
msg = "Error building %s. Conditional auxilary may not be clone." % (command,)
raise excepting.ParseError(msg, tokens, index)
if clone:
if clone == 'mine':
clone = self.currentFramer.newMootTag(base=aux)
insular = True
if clone in self.currentFramer.moots:
msg = ("Error building {0}. Aux/Clone tag '{1}' "
"already in use.".format(command, clone))
raise excepting.ParseError(msg, tokens, index)
data = odict(original=aux,
clone=clone,
schedule=AUX,
human=self.currentHuman,
count=self.currentCount,
inode=inode,
insular=insular)
self.currentFramer.moots[clone] = data # need to resolve early
aux = odict(tag=clone) # mapping indicates that its a clone
# assign aux to mapping with clone tag name as original aux is to be cloned
# named clone create clone when resolve framer.moots so may be referenced
# named clones must be resolved before any frames get resolved
# and are added to the class Framer.names so they can be referenced
# resolved by house.resolve -> house.presolvePresolvables
# -> framer.presolve -> framer.resolveMoots
# resolveMoots adds new resolveable framers to house.presolvables
# self.store.house.presolvables.append(clone)
if needs: # conditional auxiliary suspender preact
human = ' '.join(tokens) #recreate transition command string for debugging
#resolve aux link later
parms = dict(needs = needs, main = 'me', aux = aux, human = human)
act = acting.Act( actor='Suspender',
registrar=acting.Actor,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
self.currentFrame.addPreact(act)
console.profuse(" Added suspender preact, '{0}', with aux"
" {1} needs:\n".format(command, aux))
for need in needs:
console.profuse(" {0} with parms = {1}\n".format(need.actor, need.parms))
else: # simple auxiliary if aux is string then regular auz if aux is mapping then clone
self.currentFrame.addAux(aux) #need to resolve later
console.profuse(" Added aux framer {0}\n".format(aux))
return True
def buildRear(self, command, tokens, index):
"""
Parse 'rear' verb
Two Forms: only first form is currently supported
rear original [as mine] [be aux] in frame framename
framename cannot be me or in outline of me
rear original as clonename be schedule
schedule cannot be aux
clonename cannot be mine
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
original = None
connective = None
clone = 'mine' # default is insular clone
schedule = 'aux' # default schedule is aux
frame = 'me' # default frame is current
original = tokens[index]
index +=1 # eat token
self.verifyName(original, command, tokens, index)
while index < len(tokens): #options
connective = tokens[index]
index += 1
if connective == 'as':
clone = tokens[index]
index += 1
self.verifyName(clone, command, tokens, index)
elif connective == 'be':
schedule = tokens[index]
index += 1
elif connective == 'in': #optional in frame or in framer clause
place = tokens[index] #need to resolve
index += 1 # eat token
if place != 'frame':
msg = ("ParseError: Building verb '{0}'. Invalid "
" '{1}' clause. Expected 'frame' got "
"'{2}'".format(command, connective, place))
raise excepting.ParseError(msg, tokens, index)
if index < len(tokens):
frame = tokens[index]
index += 1
else:
msg = ("Error building {0}. Invalid connective"
" '{1}'.".format(command, connective))
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "Error building {0}. Not enough tokens.".format(command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building {0}. Unused tokens.".format(command,)
raise excepting.ParseError(msg, tokens, index)
# only allow schedule of aux for now
if schedule not in ScheduleValues or schedule not in ['aux']:
msg = "Error building {0}. Bad scheduled option got '{1}'.".format(command, schedule)
raise excepting.ParseError(msg, tokens, index)
schedule = ScheduleValues[schedule] #replace text with value
# when clone is insular and schedule is aux then frame cannot be
# current frames outline. This is validated in the actor resolve
if schedule == AUX:
if clone != 'mine':
msg = ("Error building {0}. Only insular clonename of"
" 'mine' allowed. Got '{1}'.".format(command, clone))
raise excepting.ParseError(msg, tokens, index)
if frame == 'me':
msg = ("Error building {0}. Frame clause required.".format(command, clone))
raise excepting.ParseError(msg, tokens, index)
parms = dict(original=original,
clone=clone,
schedule=schedule,
frame=frame)
actorName = 'Rearer'
if actorName not in acting.Actor.Registry:
msg = "Error building '{0}'. No actor named '{1}'.".format(command, actorName)
raise excepting.ParseError(msg, tokens, index)
act = acting.Act(actor=actorName,
registrar=acting.Actor,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
context = self.currentContext
if context == NATIVE:
context = ENTER # what is native for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Added {0} '{1}' with parms '{2}'\n".format(
ActionContextNames[context], act.actor, act.parms))
return True
def buildRaze(self, command, tokens, index):
"""
Parse 'raze' verb
raze (all, last, first) [in frame [(me, framename)]]
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
connective = None
who = None # default is insular clone
frame = 'me' # default frame is current
who = tokens[index]
index +=1 # eat token
if who not in ['all', 'first', 'last']:
msg = ("ParseError: Building verb '{0}'. Invalid target of"
" raze. Expected one of ['all', 'first', 'last'] but got "
"'{2}'".format(command, connective, who))
raise excepting.ParseError(msg, tokens, index)
while index < len(tokens): #options
connective = tokens[index]
index += 1
if connective == 'in': #optional in frame or in framer clause
place = tokens[index] #need to resolve
index += 1 # eat token
if place != 'frame':
msg = ("ParseError: Building verb '{0}'. Invalid "
" '{1}' clause. Expected 'frame' got "
"'{2}'".format(command, connective, place))
raise excepting.ParseError(msg, tokens, index)
if index < len(tokens):
frame = tokens[index]
index += 1
else:
msg = ("Error building {0}. Invalid connective"
" '{1}'.".format(command, connective))
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "Error building {0}. Not enough tokens.".format(command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building {0}. Unused tokens.".format(command,)
raise excepting.ParseError(msg, tokens, index)
parms = dict(who=who,
frame=frame)
actorName = 'Razer'
if actorName not in acting.Actor.Registry:
msg = "Error building '{0}'. No actor named '{1}'.".format(command, actorName)
raise excepting.ParseError(msg, tokens, index)
act = acting.Act(actor=actorName,
registrar=acting.Actor,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
context = self.currentContext
if context == NATIVE:
context = EXIT # what is native for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Added {0} '{1}' with parms '{2}'\n".format(
ActionContextNames[context], act.actor, act.parms))
return True
def buildDone(self, command, tokens, index):
"""
Creates complete action that indicates tasker(s) completed
by setting .done state to True
native context is enter
done tasker [tasker ...]
done [me]
tasker:
(taskername, me)
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
kind = 'Done'
taskers = []
while index < len(tokens):
tasker = tokens[index]
index +=1
self.verifyName(tasker, command, tokens, index)
taskers.append(tasker) #resolve later
if not taskers:
taskers.append('me')
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
actorName = 'Complete' + kind.capitalize()
if actorName not in completing.Complete.Registry:
msg = "Error building complete %s. No actor named %s." %\
(kind, actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['taskers'] = taskers #resolve later
act = acting.Act(actor=actorName,
registrar=completing.Complete,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
context = self.currentContext
if context == NATIVE:
context = ENTER #what is native for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Created done complete {0} with {1}\n".format(act.actor, act.parms))
return True
def buildTimeout(self, command, tokens, index):
"""creates implicit transition to next on elapsed >= value
timeout 5.0
"""
self.verifyCurrentContext(tokens, index)
try:
value = abs(Convert2Num(tokens[index])) #convert text to number if valid format
index +=1
if isinstance(value, str):
msg = "Error building %s. invalid timeout %s." %\
(command, value)
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
# build need act for transact
need = self.makeImplicitDirectFramerNeed( name="elapsed",
comparison='>=',
goal=float(value),
tolerance=0)
needs = []
needs.append(need)
# build transact
human = ' '.join(tokens) #recreate transition command string for debugging
far = 'next' #resolve far link later
parms = dict(needs = needs, near = 'me', far = far, human = human)
act = acting.Act(actor='Transiter',
registrar=acting.Actor,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
self.currentFrame.addPreact(act) #add transact as preact
console.profuse(" Added timeout transition preact, '{0}', with far {1} needs:\n".format(
command, far))
for act in needs:
console.profuse(" {0} with parms = {1}\n".format(act.actor, act.parms))
return True
def buildRepeat(self, command, tokens, index):
"""creates implicit transition to next on recurred >= value
repeat 2
go next if recurred >= 2
"""
self.verifyCurrentContext(tokens, index)
try:
value = abs(Convert2Num(tokens[index])) #convert text to number if valid format
index +=1
if isinstance(value, str):
msg = "Error building %s. invalid repeat %s." %\
(command, value)
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
# build need act for transact
need = self.makeImplicitDirectFramerNeed( name="recurred",
comparison='>=',
goal=int(value),
tolerance=0)
needs = []
needs.append(need)
# build transact
human = ' '.join(tokens) #recreate transition command string for debugging
far = 'next' #resolve far link later
parms = dict(needs = needs, near = 'me', far = far, human = human)
act = acting.Act( actor='Transiter',
registrar=acting.Actor,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
self.currentFrame.addPreact(act) #add transact as preact
console.profuse(" Added repeat transition preact, '{0}', with far {1} needs:\n".format(
command, far))
for act in needs:
console.profuse(" {0} with parms = {1}\n".format(act.actor, act.parms))
return True
def buildNative(self, command, tokens, index):
""" sets context for current frame to
native
"""
self.currentContext = NATIVE
console.profuse(" Changed context to {0}\n".format(
ActionContextNames[self.currentContext]))
return True
def buildBenter(self, command, tokens, index):
""" sets context for current frame to
benter
"""
self.currentContext = BENTER
console.profuse(" Changed context to {0}\n".format(
ActionContextNames[self.currentContext]))
return True
def buildEnter(self, command, tokens, index):
""" sets context for current frame to
enter
"""
self.currentContext = ENTER
console.profuse(" Changed context to {0}\n".format(
ActionContextNames[self.currentContext]))
return True
def buildRenter(self, command, tokens, index):
""" sets context for current frame to
renter
"""
self.currentContext = RENTER
console.profuse(" Changed context to {0}\n".format(
ActionContextNames[self.currentContext]))
return True
def buildPrecur(self, command, tokens, index):
""" sets context for current frame to
precur
"""
self.currentContext = PRECUR
console.profuse(" Changed context to {0}\n".format(
ActionContextNames[self.currentContext]))
return True
def buildRecur(self, command, tokens, index):
""" sets context for current frame to
recur
"""
self.currentContext = RECUR
console.profuse(" Changed context to {0}\n".format(
ActionContextNames[self.currentContext]))
return True
def buildExit(self, command, tokens, index):
""" sets context for current frame to
exit
"""
self.currentContext = EXIT
console.profuse(" Changed context to {0}\n".format(
ActionContextNames[self.currentContext]))
return True
def buildRexit(self, command, tokens, index):
""" sets context for current frame to
rexit
"""
self.currentContext = REXIT
console.profuse(" Changed context to {0}\n".format(
ActionContextNames[self.currentContext]))
return True
#Frame Action specific builders
def buildPrint(self, command, tokens, index):
"""prints a string consisting of space separated tokens
print message
print hello world
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
message = ' '.join(tokens[1:])
except IndexError:
message = ''
parms = dict(message = message)
act = acting.Act( actor='Printer',
registrar=acting.Actor,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
context = self.currentContext
if context == NATIVE:
context = ENTER #what is native for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Added {0} '{1}' with parms '{2}'\n".format(
ActionContextNames[context], act.actor, act.parms))
return True
def buildPut(self, command, tokens, index):
"""Build put command to put data into share
put data into destination
data:
direct
destination:
[(value, fields) in] indirect
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
srcData, index = self.parseDirect(tokens, index)
connective = tokens[index]
index += 1
if connective != 'into':
msg = "ParseError: Building verb '%s'. Unexpected connective '%s'" %\
(command, connective)
raise excepting.ParseError(msg, tokens, index)
dstFields, index = self.parseFields(tokens, index)
dstPath, index = self.parseIndirect(tokens, index)
except IndexError:
msg = "ParseError: Building verb '%s'. Not enough tokens." % (command, )
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "ParseError: Building verb '%s'. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
actorName = 'Poke' + 'Direct' #capitalize second word
if actorName not in poking.Poke.Registry:
msg = "ParseError: Can't find actor named '%s'" % (actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['sourceData'] = srcData # this is dict
parms['destination'] = dstPath # this is a share path
parms['destinationFields'] = dstFields # this is a list
act = acting.Act( actor=actorName,
registrar=poking.Poke,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
msg = " Created Actor {0} parms: data = {1} destination = {2} fields = {3} ".format(
actorName, srcData, dstPath, dstFields)
console.profuse(msg)
context = self.currentContext
if context == NATIVE:
context = ENTER #what is native for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Added {0} '{1}' with parms '{2}'\n".format(
ActionContextNames[context], act.actor, act.parms))
return True
def buildInc(self, command, tokens, index):
"""Build inc command to inc share by data or from source
inc destination with data
inc destination from source
destination:
[(value, field) in] indirect
data:
directone
source:
[(value, field) in] indirect
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
dstFields, index = self.parseFields(tokens, index)
dstPath, index = self.parseIndirect(tokens, index)
connective = tokens[index]
index += 1
if connective in ('with', ):
srcData, index = self.parseDirect(tokens, index)
for field, value in srcData.items():
if isinstance(value, str):
msg = "ParseError: Building verb '%s'. " % (command)
msg += "Data value = '%s' in field '%s' not a number" %\
(value, field)
raise excepting.ParseError(msg, tokens, index)
act = self.makeIncDirect(dstPath, dstFields, srcData)
elif connective in ('from', ):
srcFields, index = self.parseFields(tokens, index)
srcPath, index = self.parseIndirect(tokens, index)
act = self.makeIncIndirect(dstPath, dstFields, srcPath, srcFields)
else:
msg = "ParseError: Building verb '%s'. Unexpected connective '%s'" %\
(command, connective)
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "ParseError: Building verb '%s'. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "ParseError: Building verb '%s'. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
context = self.currentContext
if context == NATIVE:
context = ENTER #what is native for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Added {0} '{1}' with parms '{2}'\n".format(
ActionContextNames[context], act.actor, act.parms))
return True
def buildCopy(self, command, tokens, index):
"""Build copy command to copy from one share to another
copy source into destination
source:
[(value, fields) in] indirect
destination:
[(value, fields) in] indirect
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
srcFields, index = self.parseFields(tokens, index)
srcPath, index = self.parseIndirect(tokens, index)
connective = tokens[index]
index += 1
if connective != 'into':
msg = "ParseError: Building verb '%s'. Unexpected connective '%s'" %\
(command, connective)
raise excepting.ParseError(msg, tokens, index)
dstFields, index = self.parseFields(tokens, index)
dstPath, index = self.parseIndirect(tokens, index)
except IndexError:
msg = "ParseError: Building verb '%s'. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "ParseError: Building verb '%s'. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
actorName = 'Poke' + 'Indirect' #capitalize second word
if actorName not in poking.Poke.Registry:
msg = "ParseError: Can't find actor named '%s'" % (actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['source'] = srcPath #this is string
parms['sourceFields'] = srcFields #this is a list
parms['destination'] = dstPath #this is a string
parms['destinationFields'] = dstFields #this is a list
act = acting.Act( actor=actorName,
registrar=poking.Poke,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
msg = " Created Actor {0} parms: ".format(actorName)
for key, value in parms.items():
msg += " {0} = {1}".format(key, value)
console.profuse("{0}\n".format(msg))
context = self.currentContext
if context == NATIVE:
context = ENTER #what is native for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Added {0} '{1}' with parms '{2}'\n".format(
ActionContextNames[context], act.actor, act.parms))
return True
def buildSet(self, command, tokens, index):
"""Build set command to generate goal actions
set goal with data
set goal from source
goal:
elapsed
recurred
[(value, fields) in] absolute
[(value, fields) in] relativegoal
data:
direct
source:
indirect
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
kind = tokens[index]
if kind in ['elapsed', 'recurred']: #simple implicit framer relative goals, direct and indirect,
index +=1 #eat token
act, index = self.makeFramerGoal(kind, tokens, index)
else: #basic goals
#goal is destination dst
dstFields, index = self.parseFields(tokens, index)
dstPath, index = self.parseIndirect(tokens, index)
#required connective
connective = tokens[index]
index += 1
if connective in ('with', ): #data direct
srcData, index = self.parseDirect(tokens, index)
act = self.makeGoalDirect(dstPath, dstFields, srcData)
elif connective in ('from', ): #source indirect
srcFields, index = self.parseFields(tokens, index)
srcPath, index = self.parseIndirect(tokens, index)
act = self.makeGoalIndirect(dstPath, dstFields, srcPath, srcFields)
else:
msg = "ParseError: Building verb '%s'. Unexpected connective '%s'" %\
(command, connective)
raise excepting.ParseError(msg, tokens, index)
if not act:
return False
except IndexError:
msg = "ParseError: Building verb '%s'. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "ParseError: Building verb '%s'. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
context = self.currentContext
if context == NATIVE:
context = ENTER #what is native for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Added {0} '{1}' with parms '{2}'\n".format(
ActionContextNames[context], act.actor, act.parms))
return True
def buildGo(self, command, tokens, index):
"""Parse 'go' command transition with
transition conditions of forms
Transitions:
go far
go far if [not] need
go far if [not] need [and [not] need ...]
Far:
next
me
frame
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
needs = []
far = None
connective = None
far = tokens[index] #get target
index +=1 #eat token
self.verifyName(far, command, tokens, index)
if index < len(tokens): #check for optional if connective
connective = tokens[index]
if connective not in ['if']: #invalid connective
msg = "ParseError: Building verb '%s'. Bad connective '%s'" % \
(command, connective)
raise excepting.ParseError(msg, tokens, index)
index += 1 #otherwise eat token
while (index < len(tokens)):
act, index = self.makeNeed(tokens, index)
if not act:
return False #something wrong do not know what
needs.append(act)
if index < len(tokens):
connective = tokens[index]
if connective not in ['and']:
msg = "ParseError: Building verb '%s'. Bad connective '%s'" % \
(command, connective)
raise excepting.ParseError(msg, tokens, index)
index += 1 #otherwise eat token
except IndexError:
msg = "ParseError: Building verb '%s'. Not enough tokens." % (command, )
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "ParseError: Building verb '%s'. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if not needs and connective: #if but no needs
msg = "ParseError: Building verb '%s'. Connective %s but missing need(s)" %\
(command, connective)
raise excepting.ParseError(msg, tokens, index)
# build transact
human = ' '.join(tokens) #recreate transition command string for debugging
#resolve far link later
parms = dict(needs = needs, near = 'me', far = far, human = human)
act = acting.Act( actor='Transiter',
registrar=acting.Actor,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
self.currentFrame.addPreact(act)
console.profuse(" Added transition preact, '{0}', with far {1} needs:\n".format(
command, far))
for act in needs:
console.profuse(" {0} with parms = {1}\n".format(act.actor, act.parms))
return True
def buildLet(self, command, tokens, index):
"""Parse 'let' command benter action with entry conditions of forms
Before Enter:
let [me] if [not] need
let [me] if [not] need [and [not] need ...]
Far:
next
me
frame
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
needs = []
connective = None
connective = tokens[index] #get me or if
if connective not in ['me', 'if']: #invalid connective
msg = "ParseError: Building verb '%s'. Bad connective '%s'" % \
(command, connective)
raise excepting.ParseError(msg, tokens, index)
index += 1 #otherwise eat token
if connective == 'me':
connective = tokens[index] #check for if connective
if connective not in ['if']: #invalid connective
msg = "ParseError: Building verb '%s'. Bad connective '%s'" % \
(command, connective)
raise excepting.ParseError(msg, tokens, index)
index += 1 #otherwise eat token
while (index < len(tokens)):
act, index = self.makeNeed(tokens, index)
if not act:
return False # something wrong do know what
needs.append(act)
if index < len(tokens):
connective = tokens[index]
if connective not in ['and']:
msg = "ParseError: Building verb '%s'. Bad connective '%s'" % \
(command, connective)
raise excepting.ParseError(msg, tokens, index)
index += 1 #otherwise eat token
except IndexError:
msg = "ParseError: Building verb '%s'. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "ParseError: Building verb '%s'. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if not needs: # no needs
msg = "ParseError: Building verb '%s'. Missing need(s)" %\
(command)
raise excepting.ParseError(msg, tokens, index)
# build beact
for act in needs:
self.currentFrame.addBeact(act)
console.profuse(" Added beact, '{0}', with needs:\n".format(command))
for act in needs:
console.profuse(" {0} with {1}\n".format(act.actor, act.parms))
return True
def buildDo(self, command, tokens, index):
"""
Syntax:
do kind [part ...] [as name [part ...]] [at context] [via inode]
[with data]
[from source]
[per data]
[for source]
[cum data]
[qua source]
deed:
name [part ...]
kind:
name [part ...]
context:
(native, benter, enter, recur, exit, precur, renter, rexit)
inode:
indirect
data:
direct
source:
[(value, fields) in] indirect
do controller pid depth --> controllerPIDDepth
do arbiter switch heading --> arbiterSwitchHeading
do controller pid depth with foobar 1
do controller pid depth from value in .max.depth
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
kind = "" # deed class key in registry
name = "" #specific name of deed instance
inode = None
parts = []
parms = odict()
inits = odict()
ioinits = odict()
prerefs = odict([('inits', odict()),
('ioinits', odict()),
('parms', odict()) ])
connective = None
context = self.currentContext
while index < len(tokens):
if (tokens[index] in ['as', 'at', 'via', 'with', 'from',
'per', 'for', 'cum', 'qua' ]): # end of parts
break
parts.append(tokens[index])
index += 1 #eat token
if parts:
kind = "".join([part.capitalize() for part in parts]) #camel case
while index < len(tokens): #options
connective = tokens[index]
index += 1
if connective in ('as', ):
parts = []
while index < len(tokens): # kind parts end when connective
if tokens[index] in ['as', 'at', 'with', 'from' 'per',
'for', 'cum', 'qua' ]: # end of parts
break
parts.append(tokens[index])
index += 1 #eat token
name = "".join([part.capitalize() for part in parts]) #camel case
if not name:
msg = "ParseError: Building verb '%s'. Missing name for connective 'as'" % (command)
raise excepting.ParseError(msg, tokens, index)
elif connective in ('at', ):
context = tokens[index]
index += 1
if context not in ActionContextValues:
msg = ("ParseError: Building verb '{0}'. Invalid context"
" '{1} for connective 'as'".format(command, context))
raise excepting.ParseError(msg, tokens, index)
context = ActionContextValues[context]
elif connective in ('via', ):
inode, index = self.parseIndirect(tokens, index, node=True)
elif connective in ('with', ):
data, index = self.parseDirect(tokens, index)
parms.update(data)
elif connective in ('from', ):
srcFields, index = self.parseFields(tokens, index)
srcPath, index = self.parseIndirect(tokens, index)
prerefs['parms'][srcPath] = srcFields
elif connective in ('per', ):
data, index = self.parseDirect(tokens, index)
ioinits.update(data)
elif connective in ('for', ):
srcFields, index = self.parseFields(tokens, index)
srcPath, index = self.parseIndirect(tokens, index)
prerefs['ioinits'][srcPath] = srcFields
elif connective in ('cum', ):
data, index = self.parseDirect(tokens, index)
inits.update(data)
elif connective in ('qua', ):
srcFields, index = self.parseFields(tokens, index)
srcPath, index = self.parseIndirect(tokens, index)
prerefs['inits'][srcPath] = srcFields
else:
msg = ("Error building {0}. Invalid connective"
" '{1}'.".format(command, connective))
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if not kind:
msg = "ParseError: Building verb '%s'. Missing kind for Doer." %\
(command)
raise excepting.ParseError(msg, tokens, index)
if kind not in doing.Doer.Registry: # class registration not exist
msg = "ParseError: Building verb '%s'. No Deed of kind '%s' in registry" %\
(command, kind)
raise excepting.ParseError(msg, tokens, index)
if inode:
ioinits.update(inode=inode) # via argument takes precedence over others
if name:
inits['name'] = name
act = acting.Act( actor=kind,
registrar=doing.Doer,
inits=inits,
ioinits=ioinits,
parms=parms,
prerefs=prerefs,
human=self.currentHuman,
count=self.currentCount)
#context = self.currentContext
if context == NATIVE:
context = RECUR #what is native for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Added {0} '{1}' with parms '{2}'\n".format(
ActionContextNames[context], act.actor, act.parms))
return True
def buildBid(self, command, tokens, index):
"""
bid control tasker [tasker ...] [at period]
bid control [me] [at period]
bid control all [at period]
control:
(stop, start, run, abort, ready)
tasker:
(tasker, me, all)
period:
number
indirectOne
indirectOne:
sharepath [of relative]
(field, value) in sharepath [of relative]
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
period = None # no period provided
sourcePath = None
sourceField = None
parms = odict([('taskers', []), ('period', None), ('sources', odict())])
control = tokens[index]
index +=1
if control not in ['start', 'run', 'stop', 'abort', 'ready']:
msg = "Error building {0}. Bad control = {1}.".format(command, control)
raise excepting.ParseError(msg, tokens, index)
taskers = []
while index < len(tokens):
if (tokens[index] in ['at']):
break # end of taskers so do not eat yet
tasker = tokens[index]
index +=1
self.verifyName(tasker, command, tokens, index)
taskers.append(tasker) #resolve later
if not taskers:
taskers.append('me')
while index < len(tokens): # at option
connective = tokens[index]
index += 1
if connective in ['at']:
# parse period direct or indirect
try: #parse direct
period = max(0.0, Convert2Num(tokens[index])) # period is number
index += 1 # eat token
except ValueError: # parse indirect
sourceField, index = self.parseField(tokens, index)
sourcePath, index = self.parseIndirect(tokens, index)
else:
msg = ("Error building {0}. Invalid connective"
" '{1}'.".format(command, connective))
raise excepting.ParseError(msg, tokens, index)
actorName = 'Want' + control.capitalize()
if actorName not in wanting.Want.Registry:
msg = "Error building %s. No actor named %s." % (command, actorName)
raise excepting.ParseError(msg, tokens, index)
parms['taskers'] = taskers #resolve later
parms['period'] = period
parms['source'] = sourcePath
parms['sourceField'] = sourceField
act = acting.Act( actor=actorName,
registrar=wanting.Want,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
context = self.currentContext
if context == NATIVE:
context = ENTER #what is native for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Added {0} want '{1}' with parms '{2}'\n".format(
ActionContextNames[context], act.actor, act.parms))
return True
def buildReady(self, command, tokens, index):
"""
ready taskName
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
tasker = tokens[index]
index +=1
self.verifyName(tasker, command, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
native = BENTER
self.makeFiat(tasker, 'ready', native, command, tokens, index)
return True
def buildStart(self, command, tokens, index):
"""
start taskName
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
tasker = tokens[index]
index +=1
self.verifyName(tasker, command, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
native = ENTER
self.makeFiat(tasker, 'start', native, command, tokens, index)
return True
def buildStop(self, command, tokens, index):
"""
stop taskName
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
tasker = tokens[index]
index +=1
self.verifyName(tasker, command, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
native = EXIT
self.makeFiat(tasker, 'stop', native, command, tokens, index)
return True
def buildRun(self, command, tokens, index):
"""
run taskName
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
tasker = tokens[index]
index +=1
self.verifyName(tasker, command, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
native = RECUR
self.makeFiat(tasker, 'run', native, command, tokens, index)
return True
def buildAbort(self, command, tokens, index):
"""
abort taskName
"""
self.verifyCurrentContext(tokens, index) #currentStore, currentFramer, currentFrame exist
try:
tasker = tokens[index]
index +=1
self.verifyName(tasker, command, tokens, index)
except IndexError:
msg = "Error building %s. Not enough tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
if index != len(tokens):
msg = "Error building %s. Unused tokens." % (command,)
raise excepting.ParseError(msg, tokens, index)
native = ENTER
self.makeFiat(tasker, 'abort', native, command, tokens, index)
return True
def buildUse(self, command, tokens, index):
"""
Not implemented yet
"""
msg = " ".join(tokens)
console.concise("{0}\n")
return True
def buildFlo(self, command, tokens, index):
"""
Not implemented yet
"""
msg = " ".join(tokens)
console.concise("{0}\n")
return True
def buildTake(self, command, tokens, index):
"""
Not implemented yet
"""
msg = " ".join(tokens)
console.concise("{0}\n")
return True
def buildGive(self, command, tokens, index):
"""
Not implemented yet
"""
msg = " ".join(tokens)
console.concise("{0}\n")
return True
#------------------
def makeIncDirect(self, dstPath, dstFields, srcData):
"""Make IncDirect act
method must be wrapped in appropriate try excepts
"""
actorName = 'Inc' + 'Direct' #capitalize second word
if actorName not in poking.Poke.Registry:
msg = "ParseError: Can't find actor named '%s'" % (actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['destination'] = dstPath #this is string
parms['destinationFields'] = dstFields # this is a list
parms['sourceData'] = srcData #this is an ordered dictionary
act = acting.Act( actor=actorName,
registrar=poking.Poke,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
msg = " Created Actor {0} parms: ".format(actorName)
for key, value in parms.items():
msg += " {0} = {1}".format(key, value)
console.profuse("{0}\n".format(msg))
return act
def makeIncIndirect(self, dstPath, dstFields, srcPath, srcFields):
"""Make IncIndirect act
method must be wrapped in appropriate try excepts
"""
actorName = 'Inc' + 'Indirect' #capitalize second word
if actorName not in poking.Poke.Registry:
msg = "ParseError: Goal can't find actor named '%s'" % (actorName)
raise excepting.ParseError(msg, tokens, index)
#actor = poking.Poke.Names[actorName]
parms = {}
parms['destination'] = dstPath #this is a share
parms['destinationFields'] = dstFields #this is a list
parms['source'] = srcPath #this is a share
parms['sourceFields'] = srcFields #this is a list
act = acting.Act( actor=actorName,
registrar=poking.Poke,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
msg = " Created Actor {0} parms: ".format(actorName)
for key, value in parms.items():
msg += " {0} = {1}".format(key, value)
console.profuse("{0}\n".format(msg))
return act
def makeFramerGoal(self, name, tokens, index):
"""Goal to set goal name relative to current framer
method must be wrapped in appropriate try excepts
goal to data
goal from source
goal:
name
implied goal is framer.currentframer.goal.name value
data:
[value] value
field value [field value ...]
source:
[(value, fields) in] indirect
"""
#name is used as name of goal relative to current framer
#create goal relative to current framer destination is goal
dstPath = 'framer.' + 'me' + '.goal.' + name
dstField = 'value'
dstFields = [dstField]
#required connective
connective = tokens[index]
index += 1
if connective in ['to', 'with']: #data direct
srcData, index = self.parseDirect(tokens, index)
act = self.makeGoalDirect(dstPath, dstFields, srcData )
elif connective in ['by', 'from']: #source indirect
srcFields, index = self.parseFields(tokens, index)
srcPath, index = self.parseIndirect(tokens, index)
act = self.makeGoalIndirect(dstPath, dstFields, srcPath, srcFields)
else:
msg = "ParseError: Unexpected connective '%s'" %\
(connective)
raise excepting.ParseError(msg, tokens, index)
return act, index
def makeGoalDirect(self, dstPath, dstFields, srcData):
"""Make GoalDirect act
method must be wrapped in appropriate try excepts
"""
actorName = 'Goal' + 'Direct' #capitalize second word
if actorName not in goaling.Goal.Registry:
msg = "ParseError: Goal can't find actor named '%s'" % (actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['destination'] = dstPath #this is string
parms['destinationFields'] = dstFields #this is list
parms['sourceData'] = srcData #this is a dictionary
act = acting.Act( actor=actorName,
registrar=goaling.Goal,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
msg = " Created Actor {0} parms: ".format(actorName)
for key, value in parms.items():
msg += " {0} = {1}".format(key, value)
console.profuse("{0}\n".format(msg))
return act
def makeGoalIndirect(self, dstPath, dstFields, srcPath, srcFields):
"""Make GoalIndirect act
method must be wrapped in appropriate try excepts
"""
actorName = 'Goal' + 'Indirect' #capitalize second word
if actorName not in goaling.Goal.Registry:
msg = "ParseError: Goal can't find actor named '%s'" % (actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['destination'] = dstPath #this is string
parms['destinationFields'] = dstFields #this is a list
parms['source'] = srcPath #this is a string
parms['sourceFields'] = srcFields #this is a list
act = acting.Act( actor=actorName,
registrar=goaling.Goal,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
msg = " Created Actor {0} parms: ".format(actorName)
for key, value in parms.items():
msg += " {0} = {1}".format(key, value)
console.profuse("{0}\n".format(msg))
return act
def makeNeed(self, tokens, index):
"""
Parse a need
method must be wrapped in try except indexError
method assumes already checked for currentStore
method assumes already checked for currentFramer
method assumes already checked for currentFrame
Need forms:
[not] need
need:
basic need:
if state [comparison goal [+- tolerance]]
simple need:
if framerstate [re [(me, framername)]] comparison framergoal [+- tolerance]
if framerstate re [me] is TBD # not supported yet
special need:
if indirect is updated [in frame (me, framename)]
if taskername is (readied, started, running, stopped, aborted)
if taskername is done
if (aux auxname, any, all)
[in frame [(me, framename)][in framer [(me, framername)]]] is done
if (aux auxname, any, all)
[in framer [(me, framername)]] is done
if ([aux] auxname, any, all)
in frame [(me, framename)][in framer [(me, framername)]] is done
if ([aux] auxname, any, all)
in framer [(me, framername)] is done
state:
[(value, field) in] indirect
goal:
value
[(value, field) in] indirect
indirect:
path [[of relation] ...]
comparison:
(==, !=, <, <=, >=, >)
tolerance:
number (the absolute value is used)
framerstate:
(elapsed, recurred)
framergoal:
goal
value
[(value, field) in] indirect
"""
kind = None
negate = False
if tokens[index] == 'not':
negate = True
index += 1 #eat token
# find back end of current clause
if 'and' in tokens[index:]: # conjunction
back = tokens[index:].index('and') + index + 1
else:
back = len(tokens)
if 'is' in tokens[index:back]: # check for 'is participle' form, special needs
place = tokens[index:back].index('is') # is
participle = tokens[index + place + 1] # participle modifier to is
if participle in ('done', ):
kind = 'done'
act, index = self.makeDoneNeed(kind, tokens, index)
elif participle in ('readied', 'started', 'running', 'stopped', 'aborted'):
kind = 'status'
act, index = self.makeStatusNeed(kind, tokens, index)
elif participle in ('updated', 'changed'):
kind = participle[:-1] # remove 'd' suffix
act, index = self.makeMarkerNeed(kind, tokens, index)
else:
msg = "ParseError: Unexpected 'is' participle '%s' for need" %\
(participle)
raise excepting.ParseError(msg, tokens, index)
else: # either simple need or basic need
state, framer, index = self.parseFramerState(tokens, index)
if state is not None: # 're' clause present, simple need
if state not in ('elapsed', 'recurred'):
msg = "ParseError: Unsupported framer state '%s'" %\
(state)
raise excepting.ParseError(msg, tokens, index)
kind = state
act, index = self.makeFramerNeed(kind, tokens, index)
# in the future we could support framer need for a different framer
# not me or current framer
# currently ignoring framer, because only allow 'me' or currentFramer
else: # basic need with support for deprecated form of simple need
simple = False # found deprecated simple need form
stateField, index = self.parseField(tokens, index)
if stateField is None: # no 'in' clause
state = tokens[index] # look for bare framer state
if state in ('elapsed', 'recurred'): # deprecated
index += 1
kind = state
simple = True
act, index = self.makeFramerNeed(kind, tokens, index)
if not simple: # basic need either path not elapsed,recurred or 'in' clause
statePath, index = self.parseIndirect(tokens, index)
#parse optional comparison
comparison, index = self.parseComparisonOpt(tokens,index)
if not comparison: #no comparison so make a boolean need
act = self.makeBoolenNeed(statePath, stateField)
else: #valid comparison so required goal
#parse required goal
direct, goal, goalPath, goalField, index = \
self.parseNeedGoal(statePath, stateField, tokens, index)
#parse optional tolerance
tolerance, index = self.parseTolerance(tokens, index)
if direct: #make a direct need
act = self.makeDirectNeed(statePath,
stateField,
comparison,
goal,
tolerance)
else: #make an indirect need
act = self.makeIndirectNeed(statePath,
stateField,
comparison,
goalPath,
goalField,
tolerance)
if negate:
act = acting.Nact(actor=act.actor,
registrar=act.registrar,
parms=act.parms,
human=self.currentHuman,
count=self.currentCount)
return (act, index)
def makeDoneNeed(self, kind, tokens, index):
"""
Need to check if tasker completed by .done truthy
method must be wrapped in appropriate try excepts
Syntax:
if taskername is done
if (aux auxname, any, all)
[in frame [(me, framename)][in framer [(me, framername)]]] is done
if (aux auxname, any, all)
[in framer [(me, framername)]] is done
if ([aux] auxname, any, all)
in frame [(me, framename)][in framer [(me, framername)]] is done
if ([aux] auxname, any, all)
in framer [(me, framername)] is done
"""
frame = "" # name of frame where aux resides if applicable
framer = "" # name of framer where aux resides if applicable
auxed = False # one of the auxiliary forms
tasker = tokens[index]
if tasker in ('any', 'all'): # auxilary case applicable so default
index += 1
auxed = True
framer = 'me'
frame = 'me'
elif tasker == "aux":
index += 1
auxed = True
framer = 'me'
tasker = tokens[index]
self.verifyName(tasker, kind, tokens, index)
index += 1
else:
self.verifyName(tasker, kind, tokens, index)
index += 1
# in clause existence means auxilary case
# optional in clauses followed by is clause
connective = tokens[index]
if connective == 'in': # optional 'in frame [(me, framename)]' clause
index += 1 # eat 'in' connective
auxed = True
framer = 'me'
place = tokens[index] # required place frame or framer
index += 1 # eat place token
if place == 'framer':
connective = tokens[index]
if connective not in Reserved: # assume must be name
framer = connective
self.verifyName(framer, kind, tokens, index)
index += 1
connective = tokens[index] # set up for next clause
elif place == 'frame':
frame = 'me'
connective = tokens[index]
if connective not in Reserved: # assume must be name
frame = connective
self.verifyName(frame, kind, tokens, index)
index += 1
connective = tokens[index] # setup for next clause
if connective == 'in': # optional 'in framer [(me, framername)]' clause
index += 1 # eat 'in' connective
place = tokens[index] # required place framer
index += 1 # eat place token
if place != 'framer':
msg = ("ParseError: Expected 'framer' got "
"'{0}'".format(place))
raise excepting.ParseError(msg, tokens, index)
connective = tokens[index]
if connective not in Reserved: # assume must be name
framer = connective
self.verifyName(framer, kind, tokens, index)
index += 1
connective = tokens[index] # setup for next clause
else:
msg = ("ParseError: Expected 'framer' or frame' got "
"'{0}'".format(place))
raise excepting.ParseError(msg, tokens, index)
if connective not in ('is', ): # missing 'is'
msg = ("ParseError: Expected 'is' connective got "
"'{0}'".format(connective))
raise excepting.ParseError(msg, tokens, index)
index += 1 # eat 'is' connective token
participle = tokens[index]
index += 1
if participle not in ('done', ): # wrong 'participle'
msg = ("ParseError: Expected 'done' participle got "
"'{0}'".format(participle))
raise excepting.ParseError(msg, tokens, index)
# a frame of me is nonsensical if framer is not current framer
if (frame == 'me' and
not (framer == 'me' or framer == self.currentFramer.name)):
msg = ("Error: Frame '{0}' nonsensical given"
" Framer '{1}'.".format(frame, framer))
raise excepting.ParseError(msg, tokens, index)
actorName = 'Need' + kind.capitalize()
if auxed:
actorName += 'Aux'
if actorName not in needing.Need.Registry:
msg = "ParseError: Need '%s' can't find actor named '%s'" %\
( kind, actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['tasker'] = tasker
parms['framer'] = framer
parms['frame'] = frame
act = acting.Act(actor=actorName,
registrar=needing.Need,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
return (act, index)
def makeStatusNeed(self, kind, tokens, index):
"""
Need to check if tasker named tasker status' is status
method must be wrapped in appropriate try excepts
Syntax:
if taskername is (readied, started, running, stopped, aborted)
"""
tasker = tokens[index]
if not REO_IdentPub.match(tasker):
msg = "ParseError: Invalid format of tasker name '%s'" % (tasker)
raise excepting.ParseError(msg, tokens, index)
index += 1
connective = tokens[index]
index += 1
if connective not in ('is', ):
msg = "ParseError: Need status invalid connective '%s'" %\
(kind, connective)
raise excepting.ParseError(msg, tokens, index)
status = tokens[index] # participle
index += 1
if status.capitalize() not in StatusValues:
msg = "ParseError: Need status invalid status '%s'" %\
(kind, status)
raise excepting.ParseError(msg, tokens, index)
status = StatusValues[status.capitalize()] #replace name with value
actorName = 'Need' + kind.capitalize()
if actorName not in needing.Need.Registry:
msg = "ParseError: Need '%s' can't find actor named '%s'" %\
(kind, actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['tasker'] = tasker #need to resolve this
parms['status'] = status
act = acting.Act( actor=actorName,
registrar=needing.Need,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
return (act, index)
def makeUpdateNeed(self, kind, tokens, index):
"""
Need to check if share updated in frame
method must be wrapped in appropriate try excepts
Syntax:
if path [[of relation] ...] is updated [in frame [(me, framename)]]
[by marker]
"""
return (self.makeMarkerNeed(kind, tokens, index))
def makeChangeNeed(self, kind, tokens, index):
"""
Need to check if share updated in frame
method must be wrapped in appropriate try excepts
Syntax:
if path [[of relation] ...] is changed [in frame [(me, framename)]]
[by marker]
"""
return (self.makeMarkerNeed(kind, tokens, index))
def makeMarkerNeed(self, kind, tokens, index):
"""
Support method to make either NeedUpdate or NeedChange
as determined by kind
Syntax:
if path [[of relation] ...] is (updated, changed)
[in frame [(me, framename)]] [by marker]
sharepath:
path [[of relation] ...]
marker:
string
"""
frame = "" # name of marked frame when empty resolve uses "me"" but no enact
marker = ""
sharePath, index = self.parseIndirect(tokens, index)
connective = tokens[index]
if connective not in ('is', ):
msg = ("ParseError: Unexpected connective '{0}' not 'is', "
"while building need".format(connective))
raise excepting.ParseError(msg, tokens, index)
index += 1
participle = tokens[index]
if participle not in ('updated', 'changed' ):
msg = ("ParseError: Unexpected 'is' participle '{0}', "
" not 'updated' or 'changed', "
"while building need".format(participle))
raise excepting.ParseError(msg, tokens, index)
index += 1
# ensure kind and participle match
if participle[:-1] != kind: # remove 'd' suffix
msg = ("ParseError: Mismatching participle. Expected '{0}' got "
"'{1}'".format(kind + 'd', participle))
raise excepting.ParseError(msg, tokens, index)
while index < len(tokens): # optional 'in frame' clause
connective = tokens[index]
if connective not in ('in', 'by'): # next need clause started
break
index += 1 # eat token for connective
if connective == 'in':
place = tokens[index] #need to resolve
index += 1 # eat place token
if place != 'frame':
msg = ("ParseError: Invalid "
" '{0}' clause. Expected 'frame' got "
"'{1}'".format(connective, place))
raise excepting.ParseError(msg, tokens, index)
frame = "me" # default if just frame but no framename
if index < len(tokens): # frame name is optional
connective = tokens[index] #need to resolve
if connective not in Reserved: # assume must be name
frame = connective # only
if not REO_IdentPub.match(frame):
msg = "ParseError: Invalid format of frame name '%s'" % (frame)
raise excepting.ParseError(msg, tokens, index)
index += 1 # consume frame name token
elif connective == 'by':
marker = tokens[index]
index += 1 # eat marker token
marker = StripQuotes(marker)
# assign marker type actual marker Act created in need's resolve
markerKind = 'Marker' + kind.capitalize()
actorName = 'Need' + kind.capitalize()
if actorName not in needing.Need.Registry:
msg = "ParseError: Need '%s' can't find actor named '%s'" %\
(kind, actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['share'] = sharePath
parms['frame'] = frame # marked frame name resolved in resolvelinks
parms['kind'] = markerKind # marker kind resolved in resolvelinks
parms['marker'] = marker
act = acting.Act( actor=actorName,
registrar=needing.Need,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
return (act, index)
def makeImplicitDirectFramerNeed(self, name, comparison, goal, tolerance):
"""Make implicit need, ie the need is not parsed but implied by the command
such as timeout
method must be wrapped in appropriate try excepts
state comparison goal [+- tolerance]
goal:
value (direct number or string)
state:
name
implied state is framer.currentframer.state.name value
"""
console.profuse(" Making implicit direct framer need {0}\n".format(name))
#name is used as name of state relative to current framer
# and if implicit goal the name of goal relative to current framer
#create state relative to framer
statePath = 'framer.' + 'me' + '.state.' + name
stateField = 'value'
act = self.makeDirectNeed(statePath, stateField, comparison, goal, tolerance)
return act
def makeFramerNeed(self, name, tokens, index):
"""Need that checks if framer state name for current framer satisfies comparison
method must be wrapped in appropriate try excepts
state comparison goal [+- tolerance]
state:
name
implied state is framer.currentframer.state.name value
goal:
goal
from path [key]
value
dotpath [key]
elapsed >= 25.0
elapsed >= goal
elapsed == goal +- 0.1
"""
console.profuse(" Making framer need {0}\n".format(name))
#name is used as name of state relative to current framer
# and if implicit goal the name of goal relative to current framer
#create state relative to framer
statePath = 'framer.' + 'me' + '.state.' + name
stateField = 'value'
#parse required comparison
comparison, index = self.parseComparisonReq(tokens,index)
#parse required goal
direct, goal, goalPath, goalField, index = \
self.parseFramerNeedGoal(statePath, stateField, tokens, index)
#parse optional tolerance
tolerance, index = self.parseTolerance(tokens, index)
if direct: #make a direct need
act = self.makeDirectNeed(statePath,
stateField,
comparison,
goal,
tolerance)
else: #make an indirect need
act = self.makeIndirectNeed(statePath,
stateField,
comparison,
goalPath,
goalField,
tolerance)
return (act, index)
def makeBoolenNeed(self, statePath, stateField):
"""Make booleanNeed act
method must be wrapped in appropriate try excepts
"""
actorName = 'Need' + 'Boolean' #capitalize second word
if actorName not in needing.Need.Registry:
msg = "ParseError: Need can't find actor named '%s'" % (actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['state'] = statePath #this is a string
parms['stateField'] = stateField #this is string
act = acting.Act( actor=actorName,
registrar=needing.Need,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
msg = " Created Actor {0} parms: ".format(actorName)
for key, value in parms.items():
msg += " {0} = {1}".format(key, value)
console.profuse("{0}\n".format(msg))
return act
def makeDirectNeed(self, statePath, stateField, comparison, goal, tolerance):
"""Make directNeed act
method must be wrapped in appropriate try excepts
"""
actorName = 'Need' + 'Direct' #capitalize second word
if actorName not in needing.Need.Registry:
msg = "ParseError: Need can't find actor named '%s'" % (actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['state'] = statePath #this is a string
parms['stateField'] = stateField #this is a string
parms['comparison'] = comparison #this is a string
parms['goal'] = goal #this is a value: boolean number or string
parms['tolerance'] = tolerance #this is a number
act = acting.Act( actor=actorName,
registrar=needing.Need,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
msg = " Created Actor {0} parms: ".format(actorName)
for key, value in parms.items():
msg += " {0} = {1}".format(key, value)
console.profuse("{0}\n".format(msg))
return act
def makeIndirectNeed(self,
statePath,
stateField,
comparison,
goalPath,
goalField,
tolerance):
"""Make indirectNeed act
method must be wrapped in appropriate try excepts
"""
actorName = 'Need' + 'Indirect' #capitalize second word
if actorName not in needing.Need.Registry:
msg = "ParseError: Need can't find actor named '%s'" % (actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['state'] = statePath #this is string
parms['stateField'] = stateField #this is a string
parms['comparison'] = comparison #this is a string
parms['goal'] = goalPath #this is a string
parms['goalField'] = goalField #this is a string
parms['tolerance'] = tolerance #this is a number
msg = " Created Actor {0} parms: ".format(actorName)
for key, value in parms.items():
msg += " {0} = {1}".format(key, value)
console.profuse("{0}\n".format(msg))
act = acting.Act( actor=actorName,
registrar=needing.Need,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
return act
def makeFiat(self, name, kind, native, command, tokens, index):
"""
Assumes wrapped in currentFrame etc checks
make a fiat action given the tasker name and fiat kind
"""
actorName = 'Fiat' + kind.capitalize()
if actorName not in fiating.Fiat.Registry:
msg = "Error building fiat %s. No actor named %s." % (kind, actorName)
raise excepting.ParseError(msg, tokens, index)
parms = {}
parms['tasker'] = name #resolve later
act = acting.Act( actor=actorName,
registrar=fiating.Fiat,
parms=parms,
human=self.currentHuman,
count=self.currentCount)
context = self.currentContext
if context == NATIVE:
context = native #The native context for this command
if not self.currentFrame.addByContext(act, context):
msg = "Error building %s. Bad context '%s'." % (command, context)
raise excepting.ParseError(msg, tokens, index)
console.profuse(" Added {0} fiat '{1}' with parms '{2}'\n".format(
ActionContextNames[context], act.actor, act.parms))
return True
#----------------------------
def parseDirect(self, tokens, index):
"""Parse Direct data address
returns ordered dictionary of fields (keys) and values
if no field provided then uses default field = 'value'
parms:
tokens = list of tokens for command
index = current index into tokens
returns:
data ordered dict
index
method must be wrapped in appropriate try excepts
Syntax:
data:
[value] value
field value [field value ...]
possible parsing end conditions:
no more tokens (init, set)
token 'into' (put)
"""
data = odict()
if index == (len(tokens) - 1): #only one more token so it must be value
value = tokens[index]
if value in Reserved: # ending token not valid value
msg = "ParseError: Encountered reserved '{0}' instead of value." % (value)
raise excepting.ParseError(msg, tokens, index)
index +=1 #eat token
field = 'value' #default field
else: #more than one so first may be field and second token may be value
field = tokens[index]
if field in Reserved: # ending token not valid field
msg = "ParseError: Encountered reserved '{0}' instead of field." % (field)
raise excepting.ParseError(msg, tokens, index)
index += 1
value = tokens[index]
if value in Reserved: #second reserved token so first token was value
value = field
field = 'value' #default field
else: #first token was field and second value
field = StripQuotes(field)
index += 1 #eat token
data[field] = Convert2StrBoolPathCoordPointNum(value) #convert to BoolNumStr, load data
#parse rest if any
while index < len(tokens): #must be in pairs unless first is ending token
field = tokens[index]
if field in Reserved: #ending token so break
break
field = StripQuotes(field)
index += 1 #eat token
value = tokens[index]
if value in Reserved: # ending token before valid value
msg = "ParseError: Encountered reserved '{0}' instead of value." % (value)
raise excepting.ParseError(msg, tokens, index)
index += 1
data[field] = Convert2StrBoolPathCoordPointNum(value) #convert to BoolNumStr, load data
#prevent using multiple fields if one of them is 'value'
if (len(data) > 1) and ('value' in data):
msg = "ParseError: Direct data field = 'value' must be only field '%s'" % (data.keys)
raise excepting.ParseError(msg, tokens, index)
#prevent using incorrect format for fields
for field in data: # keys
if not REO_IdentPub.match(field): #invalid format
msg = "ParseError: Invalid field = '%s'" % (field)
raise excepting.ParseError(msg, tokens, index)
return (data, index)
def parseFields(self, tokens, index):
"""
Parse optional field list for Indirect address
parms:
tokens = list of tokens for command
index = current index into tokens
returns:
(fields,index)
method must be wrapped in appropriate try excepts
Syntax:
[(value, fields) in] indirect
fields:
field [field ...]
valid fields only when encounter token 'in' after fields
consumes fields and the 'in' so subsequent parsePath starts with indirect path
parsing end conditions that signify no fields
if encounter before 'in':
no more tokens
reserved token
"""
indexSave = index #save it since welookahead to see if "in"
fields = []
found = False #flag to indicate found 'in' wich indicates fields clause
while index < len(tokens): # provisionall parse for fields
field = tokens[index]
if field == 'in': #field list present and completed now we know
index +=1
found = True
break
if field in Reserved: #field list not present
break
index += 1 #eat token
field = StripQuotes(field)
fields.append(field) # provisional
if not found: # no fields clause so we ignore
index = indexSave #so restore index
fields = [] #empty fields list
#prevent using multiple fields if one of them is 'value'
if (len(fields) > 1) and ('value' in fields):
msg = "ParseError: Field = 'value' with multiple fields = '%s'" % (fields)
raise excepting.ParseError(msg, tokens, index)
for i, field in enumerate(fields): # now we check if valid format
if not REO_IdentPub.match(field):
msg = "ParseError: Invalid format of field '%s'" % (field)
raise excepting.ParseError(msg, tokens, index)
return (fields, index)
def parseField(self, tokens, index):
"""
Parse optional field for Indirect address
parms:
tokens = list of tokens for command
index = current index into tokens
returns:
(field, index)
method must be wrapped in appropriate try excepts
Syntax:
[(value, field) in] indirect
valid field only when encounter token 'in' after first field
consumes field and the 'in' so subsequent parsePath starts with indirect path
parsing end conditions that signify no fields
if encounter before 'in':
no more tokens
reserved token
"""
indexSave = index #save it since welookahead to see if "in"
fields = []
found = False #flag to indicate found 'in' which indicates fields clause
while index < len(tokens):
field = tokens[index]
if field == 'in': #field list present and completed
index +=1
found = True
break
if field in Reserved: #field list not present
break
index += 1 #eat token
field = StripQuotes(field)
fields.append(field)
if not found: #no fields clause
index = indexSave #so restore index
fields = [] #empty fields list
#prevent using multiple fields
if (len(fields) > 1):
msg = "ParseError: More than one field = '%s'" % (fields)
raise excepting.ParseError(msg, tokens, index)
if fields:
field = fields[0]
if not REO_IdentPub.match(field):
msg = "ParseError: Invalid format of field '%s'" % (field)
raise excepting.ParseError(msg, tokens, index)
else:
field = None
return (field, index)
def parsePath(self, tokens, index):
"""Parse required (path or dotpath) path
Does not support relative path processing for verbs such as init or
server which are not inside a framer context
method must be wrapped in appropriate try excepts
"""
path = tokens[index]
index +=1
if not REO_Path.match(path): #check if valid path
msg = "ParseError: Invalid path '%s'" % (path)
raise excepting.ParseError(msg, tokens, index)
#path = path.lstrip('.') #remove leading dot if any
return (path, index)
def parseIndirect(self, tokens, index, node=False):
"""
Parse Indirect data address
If node then allow trailing dot in path
parms:
tokens = list of tokens for command
index = current index into tokens
returns:
path
index
method must be wrapped in appropriate try excepts
Syntax:
indirect:
absolute
relative
absolute:
dotpath
relative:
root
inode
framer
frame
actor
root:
path [of root]
inode:
path of me
framer:
path of framer [name]
frame:
path of frame [name]
actor:
path of actor [name]
"""
if node:
reoDotPath = REO_DotPathNode
reoRelPath = REO_RelPathNode
else:
reoDotPath = REO_DotPath
reoRelPath = REO_RelPath
path = tokens[index]
index +=1
if path in Reserved:
msg = "ParseError: Invalid path '%s' using reserved" % (path)
raise excepting.ParseError(msg, tokens, index)
if reoDotPath.match(path): #valid absolute path segment
#check for optional relation clause
#if 'of relation' clause then allows relative but no
#implied relation clauses
relation, index = self.parseRelation(tokens, index)
# dotpath starts with '.' no need to add
elif reoRelPath.match(path): #valid relative path segment
#get optional relation clause, default is root
relation, index = self.parseRelation(tokens, index)
chunks = path.split('.')
if relation: # check for relation conflict
if chunks[0] in ['framer', 'frame', 'actor']:
if (chunks[0] == 'framer' or
(chunks[0] == 'frame' and '.frame.' in relation) or
(chunks[0] == 'actor' and '.actor.' in relation)):
msg = ("ParseError: Relation conflict in path '{0}'"
" with relation '{1}'".format(path, relation))
raise excepting.ParseError(msg, tokens, index)
if relation == 'me':
msg = ("ParseError: Relation conflict in path '{0}'"
" with relation '{1}'".format(path, relation))
raise excepting.ParseError(msg, tokens, index)
else: # prepend missing relations if partial relation in path
if chunks[0] == 'actor':
if len(chunks) < 3: # actor name or share name missing
msg = ("ParseError: Incomplete path '{0}'. Actor name"
" or Share name missing given inline actor "
"relation".format(path))
raise excepting.ParseError(msg, tokens, index)
relation = 'framer.me.frame.me'
elif chunks[0] == 'frame':
if len(chunks) < 3: # frame name or share name missing
msg = ("ParseError: Incomplete path '{0}'. Frame name"
" or Share name missing given inline frame "
"relation".format(path))
raise excepting.ParseError(msg, tokens, index)
framername = 'me'
if chunks[1] == 'main':
framername = 'main'
relation = 'framer.' + framername
if relation:
relation += '.' # add dot since not dotpath
else: #invalid path format
msg = "ParseError: Invalid path '{0}'".format(path)
raise excepting.ParseError(msg, tokens, index)
path = relation + path
return (path, index)
def parseRelation(self, tokens, index, framername=''):
"""
Parse optional relation clause of relative data address
parms:
tokens = list of tokens for command
index = current index into tokens
framername = default framer name if not provided such as 'main'
returns:
relation
index
method must be wrapped in appropriate try excepts
Syntax:
relative:
root
inode
framer
frame
actor
root:
path [of root]
inode:
path of me
framer:
path of framer [(me, main, name)]
frame:
path of frame [(me, main, name)]
actor:
path of actor [(me, name)]
"""
relation = '' #default relation if none given
if index < len(tokens): #are there more tokens
connective = tokens[index]
if connective == 'of': #of means relation given
index += 1 #eat token
relation = tokens[index]
index +=1
if relation not in ['root', 'me', 'framer', 'frame', 'actor']:
msg = "ParseError: Invalid relation '%s'" % (relation)
raise excepting.ParseError(msg, tokens, index)
if relation == 'root':
relation = '' #nothing gets prepended for root relative
elif relation == 'me':
pass # do nothing
if relation in ['framer']: #may be optional name for framer
name = '' #default name is empty
if index < len(tokens): #more tokens to check for optional name
name = tokens[index]
if name not in Reserved: #name given
index += 1 #eat token
if not REO_IdentPub.match(name): #check if valid name
msg = "ParseError: Invalid relation %s name '%s'" %\
(relation, name)
raise excepting.ParseError(msg, tokens, index)
else:
name = ''
if not name: #no name given so substitute default
name = framername or 'me'
relation += '.' + name #append name
if relation in ['frame']: #may be optional name of frame
name = '' #default name is empty
if index < len(tokens): #more tokens to check for optional name
name = tokens[index]
if name not in Reserved: #name given
index += 1 #eat token
if not REO_IdentPub.match(name): #check if valid name
msg = "ParseError: Invalid relation %s name '%s'" %\
(relation, name)
raise excepting.ParseError(msg, tokens, index)
else:
name = ''
if not name: #no name given so substitute default
name = 'me'
relation += '.' + name #append name
# parse optional of framer relation
framername = ''
if name == 'main': # default framer for frame main is framer main
framername = 'main'
framerRelation, index = self.parseRelation(tokens,
index,
framername=framername)
# check if spurious, of frame or, of actor
if (framerRelation and
('.frame.' in framerRelation or
'.actor.' in framerRelation )):
msg = "ParseError: Invalid relation '%s' following frame relation" %\
(framerRelation)
raise excepting.ParseError(msg, tokens, index)
if framerRelation:
relation = framerRelation + '.' + relation
else: #use default framer
framername = framername or 'me'
relation = ('framer.' + framername + '.' + relation)
if relation in ['actor']: #may be optional name of actor
name = '' #default name is empty
if index < len(tokens): #more tokens to check for optional name
name = tokens[index]
if name not in Reserved: #name given
index += 1 #eat token
if not REO_IdentPub.match(name): #check if valid name
msg = "ParseError: Invalid relation %s name '%s'" %\
(relation, name)
raise excepting.ParseError(msg, tokens, index)
else:
name = ''
if not name: #no name given so substitute default
name = 'me'
relation += '.' + name #append name
# parse optional of frame and hence framer relation
frameRelation, index = self.parseRelation(tokens, index)
# check if spurious, of framer or, of actor
if (frameRelation and
'.actor.' in frameRelation ):
msg = "ParseError: Invalid relation '%s' following actor relation" %\
(frameRelation)
raise excepting.ParseError(msg, tokens, index)
if frameRelation:
relation = frameRelation + '.' + relation
else: #use default frame and framer
relation = ('framer.' + 'me.' + 'frame.' + 'me' + '.' + relation)
return (relation, index)
def parseComparisonOpt(self, tokens, index):
"""Parse a optional comparison
method must be wrapped in appropriate try excepts
"""
comparison = None
if index < len(tokens): #at least one more token
#if at least one more token could be connective or comparision
comparison = tokens[index]
if comparison in Comparisons: #
index +=1 #so eat token
else:
comparison = None
return (comparison, index)
def parseComparisonReq(self, tokens, index):
"""Parse a required comparison
method must be wrapped in appropriate try excepts
"""
comparison = tokens[index]
index +=1 #so eat token
if comparison not in Comparisons: #
msg = "ParseError: Need has invalid comparison '%s'" % (comparison)
raise excepting.ParseError(msg, tokens, index)
return (comparison, index)
def parseFramerState(self, tokens, index):
"""Parse framer state expression
parms:
tokens = list of tokens for command
index = current index into tokens
returns:
(state, framer, index)
method must be wrapped in appropriate try excepts
Syntax:
state re [(me, framername)]
valid state only when encounter token 're' after first state
parsing end conditions that signify no state
if encounter before 're':
no more tokens
reserved token
multiple states
"""
indexSave = index # save it since we lookahead to see if "re"
states = []
found = False # tag to indicate found 're'
framer = None
while index < len(tokens):
connective = tokens[index]
if connective == 're': # state list completed
index += 1 # eat 're' token
found = True
break # do not append state == 're' to states
if connective in Reserved: #field list not present
break # do not append state == reserved to states
index += 1 # eat last state token
state = StripQuotes(connective) # candidate state since re os quotes ok
states.append(state) # save it
if not found: # no state clause 're'
index = indexSave #so restore index
states = [] #empty states list
#prevent using multiple fields
if (len(states) > 1):
msg = "ParseError: More than one state = '%s'" % (states)
raise excepting.ParseError(msg, tokens, index)
if states:
state = states[0]
if not REO_IdentPub.match(state):
msg = "ParseError: Invalid format of state '%s'" % (state)
raise excepting.ParseError(msg, tokens, index)
else:
state = None
if state is not None: # get optional framer
framer = 'me'
while index < len(tokens):
connective = tokens[index]
if connective in Reserved: # framer not present
break
framer = connective
if not REO_IdentPub.match(framer):
msg = "ParseError: Invalid format of framer name '%s'" % (framer)
raise excepting.ParseError(msg, tokens, index)
if framer != 'me' and framer != self.currentFramer.name:
msg = "ParseError: Framer name '%s' for state need not current framer" % (framer)
raise excepting.ParseError(msg, tokens, index)
index += 1
return (state, framer, index)
def parseNeedState(self, tokens, index):
"""Parse required need state
method must be wrapped in appropriate try excepts
"""
stateField, index = self.parseField(tokens, index)
statePath, index = self.parseIndirect(tokens, index)
return (statePath, stateField, index)
def parseNeedGoal(self, statePath, stateField, tokens, index):
"""Parse required goal
method must be wrapped in appropriate try excepts
"""
goalPath = None #default
goalField = None #default
direct = False
goal = tokens[index]
#parse required goal
try:
goal = Convert2StrBoolCoordNum(tokens[index]) #goal is quoted string, boolean, or number
index += 1 #eat token
direct = True
except ValueError: #means text is not (quoted string, bool, or number) so indirect
goalField, index = self.parseField(tokens, index)
goalPath, index = self.parseIndirect(tokens, index)
return (direct, goal, goalPath, goalField, index)
def parseFramerNeedGoal(self, statePath, stateField, tokens, index):
"""
Parse required goal for special framer need such as
elapsed or recurred
method must be wrapped in appropriate try excepts
"""
goalPath = None #default
goalField = None #default
direct = False
goal = tokens[index]
#parse required goal
try:
goal = Convert2StrBoolCoordNum(tokens[index]) #goal is quoted string, boolean, or number
index += 1 #eat token
direct = True
except ValueError: #means text is not (quoted string, bool, or number) so indirect
if goal == 'goal': #means goal inferred by relative statePath
index += 1 #eat token
#now create goal path as inferred from state path
#check if statePath can be interpreted as framer state relative
chunks = statePath.strip('.').split('.')
try:
if ((chunks[0] == 'framer') and
(chunks[2] == 'state')): #framer relative
chunks[2] = 'goal' # .framer.me.state becomes .framer.me.goal
else:
msg = "ParseError: Goal = 'goal' without framer state path '%s'" %\
(statePath)
raise excepting.ParseError(msg, tokens, index)
except IndexError:
msg = "ParseError: Goal = 'goal' without framer state path '%s'" %\
(statePath)
raise excepting.ParseError(msg, tokens, index)
goalPath = ".".join(chunks)
goalField = stateField #goal field is the same as the given state field
else: #not 'goal' so parse as indirect
#is 'field in' clause present
goalField, index = self.parseField(tokens, index)
goalPath, index = self.parseIndirect(tokens, index)
return (direct, goal, goalPath, goalField, index)
def parseTolerance(self, tokens, index):
"""Parse a optional tolerance
method must be wrapped in appropriate try excepts
"""
tolerance = 0
if index < len(tokens): #at least one more token
#if at least one more token could be connective
connective = tokens[index]
if connective == '+-': #valid tolerance connective
index +=1 #so eat token
tolerance = tokens[index] #get tolerance
index += 1
tolerance = Convert2Num(tolerance) #convert to value
if isinstance(tolerance, str):
msg = "ParseError: Need has invalid tolerance '%s'" % (tolerance)
raise excepting.ParseError(msg, tokens, index)
return (tolerance, index)
def prepareSrcDstFields(self, src, srcFields, dst, dstFields, tokens, index):
"""
Prepares and verifys a transfer of data
from sourceFields in source
to dstFields in dst
Handles default conditions when fields are empty
src and dst are shares
fields are lists
Ensure Actor._prepareSrcDstFields is the same
"""
if not srcFields: #no source fields so assign defaults
if src:
if 'value' in src:
srcFields = ['value'] #use value field
elif dstFields: #use destination fields for source fields
srcFields = dstFields
else: #use pre-existing source fields
srcFields = src.keys()
#else: #ambiguous multiple source fields
#msg = "ParseError: Can't determine source field"
#raise excepting.ParseError(msg, tokens, index)
else:
srcFields = ['value'] #use value field
self.verifyShareFields(src, srcFields, tokens, index)
if not dstFields: #no destination fields so assign defaults
if 'value' in dst:
dstFields = ['value'] #use value field
else: #use source fields for destination fields
dstFields = srcFields
self.verifyShareFields(dst, dstFields, tokens, index)
if len(srcFields) != len(dstFields):
msg = "ParseError: Unequal number of source %s and destination %s fields" %\
(srcFields, dstFields)
raise excepting.ParseError(msg, tokens, index)
for dstField, srcField in izip(dstFields, srcFields):
if (dstField != srcField) and (srcField != 'value'):
console.profuse(" Warning: Field names mismatch. '{0}' in {1} "
"from '{2}' in {3} ... creating anyway".format(
dstField, dst.name, srcField, src.name))
#create any non existent source or destination fields
for field in srcFields: #use source fields for source data
if field not in src:
console.profuse(" Warning: Transfer from non-existent field '{0}' "
"in share {1} ... creating anyway".format(field, src.name))
src[field] = None #create
for field in dstFields: #use destination fields for destination data
if field not in dst:
console.profuse(" Warning: Transfer into non-existent field '{0}' "
"in share {1} ... creating anyway\n".format(field, dst.name))
dst[field] = None #create
return (srcFields, dstFields)
def prepareDataDstFields(self, data, dataFields, dst, dstFields, tokens, index):
"""
Prepares and verifys a transfer of data
from dataFields in data
to dstFields in dst
Handles default conditions when fields are empty
data is dict
dst is share
fields are lists
Ensure Actor._prepareDstFields is similar
"""
if not dstFields: #no destinationField so use default rules
if 'value' in dst:
dstFields = ['value'] #use value field
else: #use dataField
dstFields = dataFields
self.verifyShareFields(dst, dstFields, tokens, index)
if len(dataFields) != len(dstFields):
msg = "ParseError: Unequal number of source %s and destination %s fields" %\
(dataFields, dstFields)
raise excepting.ParseError(msg, tokens, index)
for dstField, dataField in izip(dstFields, dataFields):
if (dstField != dataField) and (dataField != 'value'):
console.profuse(" Warning: Field names mismatch. '{0}' in {1} "
"from '{2}' ... creating anyway".format(
dstField, dst.name, dataField))
#create any non existent destination fields
for field in dstFields: #use destination fields for destination data
if field not in dst:
console.profuse(" Warning: Transfer into non-existent field '{0}' in "
"share {1} ... creating anyway\n".format(field, dst.name))
dst[field] = None #create
return (dataFields, dstFields)
def verifyShareFields(self, share, fields, tokens, index):
"""
Verify that updating fields in share won't violate the
condition that when a share has field == 'value'
it will be the only field
fields is list of field names
share is share
raises exception if condition would be violated
Ensure Actor._verifyShareFields is same
"""
if (len(fields) > 1) and ('value' in fields):
msg = "ParseError: Field = 'value' within fields = '%s'" % (fields)
raise excepting.ParseError(msg, tokens, index)
if share: #does share have fields already
for field in fields:
if field not in share: #so this field could be added to share
if ('value' in share) or (field == 'value'):
msg = "ParseError: Candidate field '%s' when fields = '%s' exist" %\
(field, share.keys())
raise excepting.ParseError(msg, tokens, index)
return
def validShareFields(self, share, fields):
"""Validates that updating fields in share won't violate the
condition that when a share has field = 'value'
it will be the only field
fields is list of field names
share is share
returns False if condition would be violated
return True otherwise
"""
if (len(fields) > 1) and ('value' in fields):
return False
if share: #does share have fields already
for field in fields:
if field not in share: #so this field could be added to share
if ('value' in share) or (field == 'value'):
return False
return True
def verifyCurrentContext(self, tokens, index):
"""Verify that parse context has
currentStore
currentFramer
currentFrame
If not raises ParseError
"""
if not self.currentStore:
msg = "ParseError: Building verb '%s'. No current store" % (tokens)
raise excepting.ParseError(msg, tokens, index)
if not self.currentFramer:
msg = "ParseError: Building verb '%s'. No current framer" % (tokens)
raise excepting.ParseError(msg, tokens, index)
if not self.currentFrame:
msg = "ParseError: Building verb '%s'. No current frame" % (tokens)
raise excepting.ParseError(msg, tokens, index)
return
def verifyName(self, name, command, tokens, index):
"""Verify that name is a valid public identifyer
Used for Tasker, Framer, and Frame names
"""
if not REO_IdentPub.match(name) or name in Reserved: #bad name
msg = "ParseError: Building verb '%s'. Invalid entity name '%s'" %\
(command, name)
raise excepting.ParseError(msg, tokens, index)
#------------------------
def DebugShareFields(store, name):
""" prints out fields of share named name from store for debugging """
share = store.fetch(name)
if share is not None:
console.terse("++++++++ Debug share fields++++++++\n{0} = {1}\n".format(
share.name, share.items))
def Test(fileName = None, verbose = False):
"""Module self test
"""
import globaling
import aiding
import excepting
import registering
import storing
import skedding
import tasking
import acting
import poking
import needing
import goaling
import traiting
import fiating
import wanting
import completing
import doing
import arbiting
import controlling
import framing
import logging
import interfacing
import housing
#import building
import monitoring
import testing
allModules = [globaling, aiding, excepting, registering, storing, skedding,
acting, poking, goaling, needing, traiting,
fiating, wanting, completing,
doing, arbiting, controlling,
tasking, framing, logging, interfacing, serving,
housing, monitoring, testing]
if not fileName:
fileName = "mission.txt"
b = Builder()
if b.build(fileName = fileName):
houses = b.houses
for house in houses:
house.store.changeStamp(0.0)
for framer in house.actives:
status = framer.runner.send(START)
for tasker in house.taskers:
status = tasker.runner.send(START) #prepares logs and reopens files
done = False
while not done:
done = True
for house in houses:
actives = []
for framer in house.actives:
#status = framer.status
desire = framer.desire
if desire is not None:
control = desire
else:
control = RUN
status = framer.runner.send(control)
console.terse("Framer {0} control {1} resulting status = {2}\n".format(
framer.name, ControlNames[control], StatusNames[status]))
if not (status == STOPPED or status == ABORTED):
actives.append(framer)
done = False
house.actives = actives
for tasker in house.taskers:
status = tasker.runner.send(RUN)
house.store.advanceStamp(0.125)
for house in houses:
for tasker in house.taskers:
status = tasker.runner.send(STOP) # closes files
return b
if __name__ == "__main__":
Test()
| [
37811,
16894,
13,
9078,
1382,
29251,
422,
4365,
3696,
198,
198,
37811,
198,
6738,
11593,
37443,
834,
1330,
7297,
198,
198,
2,
4798,
7203,
21412,
1391,
15,
92,
1911,
18982,
7,
834,
3672,
834,
4008,
198,
198,
11748,
640,
198,
11748,
302... | 2.055911 | 87,407 |
# Generated by Django 2.2.9 on 2020-02-06 09:26
from django.db import migrations, models
| [
2,
2980,
515,
416,
37770,
362,
13,
17,
13,
24,
319,
12131,
12,
2999,
12,
3312,
7769,
25,
2075,
198,
198,
6738,
42625,
14208,
13,
9945,
1330,
15720,
602,
11,
4981,
628
] | 2.84375 | 32 |
from typing import Dict
import numpy
from config import logging_configurator
from paddles.paddle_0402.config.paddle_configurator import nmist_raw_ann_config
from paddles.paddle_0402.whiteboard.from_scratch.nmist import Ann, output_training, \
initialize_gradient_weight_accumulation_matrices, initialize_bias_accumulation_vectors, input_training, \
brute_force_feed_forward, calculate_outer_layer_gradient, calculate_previous_layer_gradient, plot_cost_function
logger = logging_configurator.get_logger(__name__)
class SimpleNeuralNetwork(Ann):
"""
With 3000 iterations, this gives 86% prediction accuracy.
This is as simple as it gets. Back propogation is based upon minimizing the overall cost across all samples:
COST = (1/2) * (1/sample_count) SUM_OVER_SAMPES_Z[(abs(label - predicted)^2
"""
def _adjust_weights(self, gradient_for_weights: Dict[int, numpy.ndarray],
gradient_for_bias: Dict[int, numpy.ndarray]) -> None:
"""
This adjusts the weights according to the optimization function to minimize the quadrature of
residuals from predicted to labeled, normalized by the sample data count
:param gradient_for_weights: a dict whose key is the network layer and whose value is a weight matrix
:param gradient_for_bias: a dict whose key is the network layer and whose value is vector of bias gradients
:return:
"""
for layer_index in range(self.num_layers - 1, 0, -1):
self.weight_matrix_by_layer[layer_index] += -self.step_size * (
1.0 / len(output_training) * gradient_for_weights[layer_index])
self.bias_by_layer[layer_index] += -self.step_size * (
1.0 / len(output_training) * gradient_for_bias[layer_index])
if __name__ == "__main__":
neural_network = SimpleNeuralNetwork()
neural_network.train()
neural_network.evalulate_network()
plot_cost_function(neural_network.avg_cost_for_iterations)
| [
6738,
19720,
1330,
360,
713,
198,
198,
11748,
299,
32152,
198,
198,
6738,
4566,
1330,
18931,
62,
11250,
333,
1352,
198,
6738,
14098,
829,
13,
79,
37382,
62,
15,
32531,
13,
11250,
13,
79,
37382,
62,
11250,
333,
1352,
1330,
28642,
396,
... | 2.723577 | 738 |
from __future__ import unicode_literals
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
class Logger:
"""
This class is very simple and is of no use in the rest of the program except in main.py,
when it's initialized.
To log you must first import logging in the file.
Then you log messages with debug(), info(), warning, error(), critical() methods
The level is 10 for debug, ..., 50 for critical)
"""
def __init__(self, log_format, path, level):
"""
log_format is the wanted logging format
path is the path of the log file
level is the minimum required level for the logged messages,
if less it's nor stored nor displayed
"""
self.log_formatter = logging.Formatter(log_format)
self.root_logger = logging.getLogger()
self.mpd_logger = logging.getLogger('mpd')
self.mpd_logger.propagate = False
self.root_logger.setLevel(level)
self.mpd_logger.setLevel(level)
self.file_handler = logging.FileHandler(os.path.join(os.path.dirname(__file__), path), mode='a')
self.file_handler.setFormatter(self.log_formatter)
self.root_logger.addHandler(self.file_handler)
self.mpd_logger.addHandler(self.file_handler)
| [
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198,
2,
5145,
14,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
11748,
18931,
198,
11748,
28686,
198,
198,
4871,
59... | 2.608081 | 495 |
from __future__ import print_function
import json
import os
from urllib import request, parse
| [
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
11748,
33918,
198,
11748,
28686,
198,
6738,
2956,
297,
571,
1330,
2581,
11,
21136,
628,
628,
198
] | 3.769231 | 26 |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
import facebook
import websites
import feeds
#import beachstatus
from event import EventVault
import logging
import datetime
import time
import locale
locale.setlocale(locale.LC_TIME, '') # locale for date, time an the infamous german "Umalaute"
LOG_FILENAME = os.path.join(os.path.dirname(__file__), 'log.log')
logging.basicConfig(filename=LOG_FILENAME, level=logging.ERROR)
# Gooo !!!!11einself
main_obj = HeuteInMannheim()
| [
11748,
28686,
198,
11748,
25064,
198,
17597,
13,
6978,
13,
33295,
7,
418,
13,
6978,
13,
22179,
7,
418,
13,
6978,
13,
15908,
3672,
7,
834,
7753,
834,
828,
366,
8019,
48774,
198,
198,
11748,
23960,
198,
11748,
9293,
198,
11748,
21318,
... | 2.904494 | 178 |
#!/usr/bin/env python3
# from src.enochecker import *
import json
import secrets
from typing import Dict
from enochecker import BaseChecker, BrokenServiceException, assert_equals, run
class ExampleChecker(BaseChecker):
"""
Change the methods given here, then simply create the class and .run() it.
A few convenient methods and helpers are provided in the BaseChecker.
When using an HTTP client (requests) or a plain TCP connection (telnetlib) use the
built-in functions of the BaseChecker that include some basic error-handling.
https://enowars.github.io/enochecker/enochecker.html#enochecker.enochecker.BaseChecker.connect
https://enowars.github.io/enochecker/enochecker.html#enochecker.enochecker.BaseChecker.http
https://enowars.github.io/enochecker/enochecker.html#enochecker.enochecker.BaseChecker.http_get
https://enowars.github.io/enochecker/enochecker.html#enochecker.enochecker.BaseChecker.http_post
The full documentation is available at https://enowars.github.io/enochecker/
"""
# how many flags does this service deploy per round? each flag should be stored at a different location in the service
flag_variants = 2
# how many noises does this service deploy per round?
noise_variants = 1
# how many different havoc methods does this service use per round?
havoc_variants = 1
# The port will automatically be picked up as default by self.connect and self.http methods.
port = 80
def putflag(self) -> None:
"""
This method stores a flag in the service.
In case the service has multiple flag stores, self.variant_id gives the appropriate index.
The flag itself can be retrieved from self.flag.
On error, raise an Eno Exception.
:raises EnoException on error
"""
if self.variant_id == 0:
credentials = self.generate_credentials()
self.chain_db = credentials
self.register_and_login(credentials)
res = self.http_post("/notes", json={"note": self.flag})
assert_equals(res.status_code, 200)
elif self.variant_id == 1:
credentials = self.generate_credentials()
self.chain_db = credentials
self.register_and_login(credentials)
res = self.http_post("/profile/status", json={"status": self.flag})
assert_equals(res.status_code, 200)
else:
raise ValueError(
"variant_id {} exceeds the amount of flag variants. Not supported.".format(
self.variant_id
)
)
def getflag(self) -> None:
"""
This method retrieves a flag from the service.
Use self.flag to get the flag that needs to be recovered and self.round to get the round the flag was placed in.
On error, raise an EnoException.
:raises EnoException on error
"""
if self.variant_id == 0:
credentials = self.chain_db
self.login(credentials)
res = self.http_get("/notes")
assert_equals(res.status_code, 200)
try:
if self.flag not in res.json()["notes"]:
raise BrokenServiceException("flag is missing from /notes")
except (KeyError, json.JSONDecodeError):
raise BrokenServiceException(
"received invalid response on /notes endpoint"
)
elif self.variant_id == 1:
credentials = self.chain_db
self.login(credentials)
res = self.http_get("/profile")
assert_equals(res.status_code, 200)
try:
if self.flag != res.json()["status"]:
raise BrokenServiceException("flag is missing from /profile")
except (KeyError, json.JSONDecodeError):
raise BrokenServiceException(
"received invalid response on /profile endpoint"
)
else:
raise ValueError(
"variant_id {} not supported!".format(self.variant_id)
) # Internal error.
def putnoise(self) -> None:
"""
This method stores noise in the service. The noise should later be recoverable.
The difference between noise and flag is, tht noise does not have to remain secret for other teams.
This method can be called many times per round. Check how often using self.variant_id.
On error, raise an EnoException.
:raises EnoException on error
"""
credentials = self.generate_credentials()
self.register_and_login(credentials)
category = secrets.choice(
[
"Python",
"NodeJS",
"C",
"Rust",
"Go",
"C#",
"C++",
"Prolog",
"OCL",
"Julia",
]
)
# we are overwriting the credentials on purpose since we don't need them later in this case
self.chain_db = category
res = self.http_post(
"/posts",
json={"content": self.noise, "category": category, "public": True},
)
assert_equals(res.status_code, 200)
def getnoise(self) -> None:
"""
This method retrieves noise in the service.
The noise to be retrieved is inside self.noise
The difference between noise and flag is, that noise does not have to remain secret for other teams.
This method can be called many times per round.
The engine will also trigger different variants, indicated by variant_id.
On error, raise an EnoException.
:raises EnoException on error
"""
category = self.chain_db
res = self.http_get("/posts", json={"category": category})
assert_equals(res.status_code, 200)
try:
for post in res.json()["posts"]:
if post["content"] == self.noise:
return # returning nothing/raising no exceptions means everything is ok
except (KeyError, json.JSONDecodeError):
raise BrokenServiceException("received invalid response on /posts")
else:
raise BrokenServiceException("noise is missing from /posts")
def havoc(self) -> None:
"""
This method unleashes havoc on the app -> Do whatever you must to prove the service still works. Or not.
On error, raise an EnoException.
:raises EnoException on Error
"""
self.info("I wanted to inform you: I'm running <3")
res = self.http_get("/")
assert_equals(res.status_code, 200)
# You should probably do some more in-depth checks here.
def exploit(self) -> None:
"""
This method was added for CI purposes for exploits to be tested.
Will (hopefully) not be called during actual CTF.
:raises EnoException on Error
:return This function can return a result if it wants
If nothing is returned, the service status is considered okay.
The preferred way to report Errors in the service is by raising an appropriate EnoException
"""
pass
app = ExampleChecker.service # This can be used for gunicorn/uswgi.
if __name__ == "__main__":
run(ExampleChecker)
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
422,
12351,
13,
268,
30848,
15280,
1330,
1635,
198,
11748,
33918,
198,
11748,
13141,
198,
6738,
19720,
1330,
360,
713,
198,
198,
6738,
551,
30848,
15280,
1330,
7308,
9787,
263,
... | 2.400194 | 3,096 |
import subprocess
import sys
import time
import os
##start([], open('log.out','a'), open('error.out','a'))
##stop(open('log.out','a'), open('error.out','a'))
| [
198,
11748,
850,
14681,
198,
11748,
25064,
198,
11748,
640,
198,
11748,
28686,
198,
198,
2235,
9688,
26933,
4357,
1280,
10786,
6404,
13,
448,
41707,
64,
33809,
1280,
10786,
18224,
13,
448,
41707,
64,
6,
4008,
198,
2235,
11338,
7,
9654,
... | 2.758621 | 58 |
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
CONTEXT_ATTRIBUTE = getattr(settings, 'JSON_LD_CONTEXT_ATTRIBUTE', 'sd')
MODEL_ATTRIBUTE = getattr(settings, 'JSON_LD_MODEL_ATTRIBUTE', 'sd')
DEFAULT_CONTEXT = getattr(settings, 'JSON_LD_DEFAULT_CONTEXT', 'https://schema.org/')
DEFAULT_TYPE = getattr(settings, 'JSON_LD_DEFAULT_TYPE', 'Thing')
JSON_INDENT = getattr(settings, 'JSON_LD_INDENT', None)
GENERATE_URL = getattr(settings, 'JSON_LD_GENERATE_URL', True)
valid_empty_input_rendering_settings = [
'strict', 'silent', 'generate_thing'
]
EMPTY_INPUT_RENDERING = getattr(settings, 'JSON_LD_EMPTY_INPUT_RENDERING', 'strict')
err = ''
if EMPTY_INPUT_RENDERING not in valid_empty_input_rendering_settings:
err += 'Invalid value for JSON_LD_EMPTY_INPUT_RENDERING setting. '
err += 'Expected one of {}, but got "{}". '.format(
valid_empty_input_rendering_settings,
EMPTY_INPUT_RENDERING
)
if not (JSON_INDENT is None or isinstance(JSON_INDENT, int) and JSON_INDENT >= 0) :
err += 'Invalid value for JSON_LD_INDENT setting. '
err += 'Expected None or a non-negative integer. '
if err:
raise ImproperlyConfigured(err.strip())
| [
6738,
42625,
14208,
13,
10414,
1330,
6460,
198,
6738,
42625,
14208,
13,
7295,
13,
1069,
11755,
1330,
12205,
525,
306,
16934,
1522,
628,
198,
10943,
32541,
62,
1404,
5446,
9865,
37780,
796,
651,
35226,
7,
33692,
11,
705,
40386,
62,
11163... | 2.554167 | 480 |
#coding=utf-8
import xlrd, json, os
from lxml import etree
path = os.path.split(os.path.realpath(__file__))[0]+"/"
data = xlrd.open_workbook(path+"numbers.xls")
table = data.sheets()[0]
nrows = table.nrows
Dict = []
for i in range(nrows ):
Arr = table.row_values(i)
Dict.append(Arr)
root = etree.Element("root")
child1 = etree.SubElement(root, "numbers")
comm = etree.Comment(u"""数字信息""")
child1.append(comm)
child1.text =unicode(json.dumps(Dict).decode("utf-8"))
tree = etree.ElementTree(root)
tree.write(path+"numbers.xml ", pretty_print=True, xml_declaration=True, encoding='utf-8')
| [
2,
66,
7656,
28,
40477,
12,
23,
198,
11748,
2124,
75,
4372,
11,
33918,
11,
28686,
198,
6738,
300,
19875,
1330,
2123,
631,
198,
6978,
796,
28686,
13,
6978,
13,
35312,
7,
418,
13,
6978,
13,
5305,
6978,
7,
834,
7753,
834,
4008,
58,
... | 2.337255 | 255 |
__all__ = ["apply","fit"] | [
834,
439,
834,
796,
14631,
39014,
2430,
11147,
8973
] | 2.777778 | 9 |
from torch2cmsis.converter import CMSISConverter
| [
6738,
28034,
17,
46406,
271,
13,
1102,
332,
353,
1330,
40773,
1797,
3103,
332,
353,
198
] | 3.0625 | 16 |
from pathlib import Path
DATA_DIR = Path(__file__).parent / "data"
| [
6738,
3108,
8019,
1330,
10644,
628,
198,
26947,
62,
34720,
796,
10644,
7,
834,
7753,
834,
737,
8000,
1220,
366,
7890,
1,
198
] | 3 | 23 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from models.SEBlock import SELayer
if __name__ == '__main__':
test() | [
11748,
28034,
198,
11748,
28034,
13,
20471,
355,
299,
77,
198,
11748,
28034,
13,
20471,
13,
45124,
355,
376,
198,
11748,
28034,
13,
26791,
13,
9122,
4122,
355,
31396,
198,
198,
6738,
4981,
13,
5188,
12235,
1330,
311,
3698,
2794,
628,
... | 3 | 61 |
import numpy as np # Import important packages
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
import glob
from PIL import Image
import os
import re
def calcscale(imv): # Defines calcscale function
"""
"""
image = imv.getProcessedImage()
scale = imv.scalemax / float(image[imv.currentIndex].shape[1])
return scale
if __name__ == '__main__': # Start Qt event loop unless running in interactive mode.
import sys
app = QtGui.QApplication([]) # Launches an app
root = '/Users/holden'
win = QtGui.QMainWindow() # Create window with two ImageView widgets
win.resize(800, 800)
win.setWindowTitle('pyqtgraph example: Hiprmc ')
win.setCentralWidget(rmcView(root,0.111))
win.show()
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
| [
11748,
299,
32152,
355,
45941,
220,
1303,
17267,
1593,
10392,
198,
6738,
12972,
80,
25297,
1470,
13,
48,
83,
1330,
33734,
14055,
11,
33734,
8205,
72,
198,
11748,
12972,
80,
25297,
1470,
355,
23241,
198,
11748,
15095,
198,
6738,
350,
414... | 2.696319 | 326 |
from django.urls import re_path, path
from rest_framework.authtoken.views import obtain_auth_token
from users.views import UserOrderView, UserCreateView, UserView, UserEventView, UserCompanyView, UserAdminView, UserContactView, UserIdCompany
urlpatterns = [
re_path(r"^$", UserView.as_view(), name="user"),
path(r"<id>", UserIdCompany.as_view(), name="user_id_company"),
re_path(r"^register/", UserCreateView.as_view(), name="user_registration"),
re_path(r"^login/", obtain_auth_token, name="user_login"),
re_path(r"^admin/", UserAdminView.as_view(), name="user_admin"),
re_path(r"^events/", UserEventView.as_view(), name="user_event"),
re_path(r"^companies/", UserCompanyView.as_view(), name="user_company"),
re_path(r"^contacts/", UserContactView.as_view(), name="user_contacts"),
re_path(r"^orders/", UserOrderView.as_view(), name="user_orders")
]
| [
6738,
42625,
14208,
13,
6371,
82,
1330,
302,
62,
6978,
11,
3108,
198,
198,
6738,
1334,
62,
30604,
13,
18439,
30001,
13,
33571,
1330,
7330,
62,
18439,
62,
30001,
198,
6738,
2985,
13,
33571,
1330,
11787,
18743,
7680,
11,
11787,
16447,
7... | 2.730061 | 326 |
import time
import xgboost as xgb
from xgboost import rabit
def _fmt_metric(value, show_stdv=True):
"""format metric string"""
if len(value) == 2:
return '%s:%g' % (value[0], value[1])
elif len(value) == 3:
if show_stdv:
return '%s:%g+%g' % (value[0], value[1], value[2])
else:
return '%s:%g' % (value[0], value[1])
else:
raise ValueError("wrong metric value")
# Modification of the official early_stop callback to only trigger it from the nth round on
def early_stop(stopping_rounds, start_round=0, maximize=False, verbose=True, eval_idx=-1):
"""Create a callback that activates early stoppping.
Validation error needs to decrease at least
every **stopping_rounds** round(s) to continue training.
Requires at least one item in **evals**.
If there's more than one, will use the last.
Returns the model from the last iteration (not the best one).
If early stopping occurs, the model will have three additional fields:
``bst.best_score``, ``bst.best_iteration`` and ``bst.best_ntree_limit``.
(Use ``bst.best_ntree_limit`` to get the correct value if ``num_parallel_tree``
and/or ``num_class`` appears in the parameters)
Parameters
----------
stopp_rounds : int
The stopping rounds before the trend occur.
maximize : bool
Whether to maximize evaluation metric.
verbose : optional, bool
Whether to print message about early stopping information.
Returns
-------
callback : function
The requested callback function.
"""
state = {}
def init(env):
"""internal function"""
bst = env.model
if len(env.evaluation_result_list) == 0:
raise ValueError('For early stopping you need at least one set in evals.')
if len(env.evaluation_result_list) > 1 and verbose:
msg = ("Multiple eval metrics have been passed: "
"'{0}' will be used for early stopping.\n\n")
rabit.tracker_print(msg.format(env.evaluation_result_list[eval_idx][0]))
maximize_metrics = ('auc', 'map', 'ndcg')
maximize_at_n_metrics = ('auc@', 'map@', 'ndcg@')
maximize_score = maximize
metric_label = env.evaluation_result_list[eval_idx][0]
metric = metric_label.split('-', 1)[-1]
if any(metric.startswith(x) for x in maximize_at_n_metrics):
maximize_score = True
if any(metric.split(":")[0] == x for x in maximize_metrics):
maximize_score = True
if verbose and env.rank == 0:
msg = "Will train until {} hasn't improved in {} rounds.\n"
rabit.tracker_print(msg.format(metric_label, stopping_rounds))
state['maximize_score'] = maximize_score
state['best_iteration'] = 0
if maximize_score:
state['best_score'] = float('-inf')
else:
state['best_score'] = float('inf')
if bst is not None:
if bst.attr('best_score') is not None:
state['best_score'] = float(bst.attr('best_score'))
state['best_iteration'] = int(bst.attr('best_iteration'))
state['best_msg'] = bst.attr('best_msg')
else:
bst.set_attr(best_iteration=str(state['best_iteration']))
bst.set_attr(best_score=str(state['best_score']))
else:
assert env.cvfolds is not None
def callback(env):
"""internal function"""
if env.iteration < start_round:
return
score = env.evaluation_result_list[eval_idx][1]
if len(state) == 0:
init(env)
best_score = state['best_score']
best_iteration = state['best_iteration']
maximize_score = state['maximize_score']
if (maximize_score and score > best_score) or \
(not maximize_score and score < best_score):
msg = '[%d]\t%s' % (
env.iteration,
'\t'.join([_fmt_metric(x) for x in env.evaluation_result_list]))
state['best_msg'] = msg
state['best_score'] = score
state['best_iteration'] = env.iteration
# save the property to attributes, so they will occur in checkpoint.
if env.model is not None:
env.model.set_attr(best_score=str(state['best_score']),
best_iteration=str(state['best_iteration']),
best_msg=state['best_msg'])
elif env.iteration - best_iteration >= stopping_rounds:
best_msg = state['best_msg']
if verbose and env.rank == 0:
msg = "Stopping. Best iteration:\n{}\n\n"
rabit.tracker_print(msg.format(best_msg))
raise xgb.core.EarlyStopException(best_iteration)
return callback
| [
11748,
640,
198,
11748,
2124,
70,
39521,
355,
2124,
22296,
198,
6738,
2124,
70,
39521,
1330,
27998,
270,
198,
198,
4299,
4808,
69,
16762,
62,
4164,
1173,
7,
8367,
11,
905,
62,
19282,
85,
28,
17821,
2599,
198,
220,
220,
220,
37227,
1... | 2.239011 | 2,184 |
########################################################## README ###########################################################
# This file implements STDP curve and weight update rule
##############################################################################################################################
import numpy as np
from matplotlib import pyplot as plt
from parameters import param as par
#STDP reinforcement learning curve
#STDP weight update rule
if __name__ == '__main__':
print(rl(-20)*par.sigma)
| [
29113,
14468,
7804,
2235,
20832,
11682,
1303,
29113,
14468,
7804,
2235,
198,
198,
2,
770,
2393,
23986,
3563,
6322,
12133,
290,
3463,
4296,
3896,
198,
198,
29113,
29113,
29113,
14468,
7804,
4242,
2235,
628,
198,
198,
11748,
299,
32152,
355... | 5.207921 | 101 |
#!/usr/bin/env python
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import unittest
import voluptuous
import monasca_analytics.sink.sink_config_validator as validator
kafka = validator.validate_kafka_sink_config
if __name__ == "__main__":
unittest.main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
198,
2,
15069,
357,
66,
8,
1584,
30446,
15503,
6400,
446,
14973,
7712,
5834,
11,
406,
13,
47,
13,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
... | 3.450413 | 242 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'notepad4.ui'
#
# Created: Wed Dec 9 14:01:42 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
try:
_encoding = QtGui.QApplication.UnicodeUTF8
except AttributeError:
import pad_rc
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
5178,
7822,
7560,
422,
3555,
334,
72,
2393,
705,
1662,
47852,
19,
13,
9019,
6,
198,
2,
198,
2,
15622,
25,
3300,
4280,
220,
860,
1478,
25,
486,
25,
3682,
18... | 2.557576 | 165 |
from pydantic import BaseModel
| [
6738,
279,
5173,
5109,
1330,
7308,
17633,
201
] | 3.875 | 8 |
from typing import Optional
import numpy as np
import torch
from delve.metrics import get_explained_variance, get_layer_saturation, get_eigenval_diversity_index, batch_cov, \
batch_mean
from delve.utils import get_layer_prop, get_training_state
def add_param_eigenvals(layer,
eig_vals: Optional[torch.Tensor] = None,
top_eigvals: int = 5,
n_iter: int = None):
"""Add layer parameter eigenvalues to writer."""
if eig_vals is None:
param_eig_vals = get_layer_prop(layer, 'param_eig_vals')
raise NotImplementedError("Not yet implemented.")
if n_iter is None:
n_iter = layer.forward_iter
param_eig_vals = eig_vals.cpu().detach().numpy()
top_eigvals = min(top_eigvals, len(param_eig_vals))
layer.writer.add_scalars('{}-parameter_spectrum'.format(layer.name), {
"param_eig_val{}".format(i): param_eig_vals[i]
for i in range(top_eigvals)
}, n_iter)
def add_spectrum(layer: torch.nn.Module,
eig_vals: Optional[list] = None,
top_eigvals: int = 5,
n_iter: int = None):
"""Add layer input eigenvalues to writer."""
training_state = get_training_state(layer)
if eig_vals is None:
eig_vals = get_layer_prop(layer, f'{training_state}_eig_vals')
if n_iter is None:
n_iter = layer.forward_iter
layer.writer.add_scalars(
'{}-spectrum'.format(layer.name),
{"eig_val{}".format(i): eig_vals[i]
for i in range(top_eigvals)},
n_iter,
)
return eig_vals
def add_spectral_analysis(layer: torch.nn.Module,
eig_vals: np.ndarray,
n_iter: int,
top_eigvals: int = 5):
"""Add spectral analysis `layer` writer and display `top_eigvals`."""
training_state = get_training_state(layer)
if eig_vals is None:
eig_vals = get_layer_prop(layer, f'{training_state}_eig_vals')
if n_iter is None:
n_iter = layer.forward_iter
add_eigen_dist(layer, eig_vals, n_iter)
add_neigen_dist(layer, eig_vals, n_iter)
if top_eigvals is not None:
add_spectrum(layer, eig_vals, top_eigvals, n_iter)
return eig_vals
| [
6738,
19720,
1330,
32233,
198,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
28034,
198,
6738,
39130,
13,
4164,
10466,
1330,
651,
62,
20676,
1328,
62,
25641,
590,
11,
651,
62,
29289,
62,
82,
36921,
11,
651,
62,
68,
9324,
2100,
62,
... | 2.091827 | 1,089 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#############################################
# WARNING #
#############################################
#
# This file is auto generated by the resource
# module builder playbook.
#
# Do not edit this file manually.
#
# Changes to this file will be over written
# by the resource module builder.
#
# Changes should be made in the model used to
# generate this file or in the resource module
# builder template.
#
#############################################
"""
The module file for junos_lldp_interfaces
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'
}
DOCUMENTATION = """
---
module: junos_lldp_interfaces
version_added: 2.9
short_description: Manage link layer discovery protocol (LLDP) attributes of interfaces on Juniper JUNOS devices
description:
- This module manages link layer discovery protocol (LLDP) attributes of interfaces on Juniper JUNOS devices.
author: Ganesh Nalawade (@ganeshrn)
options:
config:
description: The list of link layer discovery protocol interface attribute configurations
type: list
elements: dict
suboptions:
name:
description:
- Name of the interface LLDP needs to be configured on.
type: str
required: True
enabled:
description:
- This is a boolean value to control disabling of LLDP on the interface C(name)
type: bool
state:
description:
- The state of the configuration after module completion.
type: str
choices:
- merged
- replaced
- overridden
- deleted
default: merged
"""
EXAMPLES = """
# Using merged
# Before state:
# -------------
# user@junos01# # show protocols lldp
# management-address 10.1.1.1;
# advertisement-interval 10000;
- name: Merge provided configuration with device configuration
junos_lldp_interfaces:
config:
- name: ge-0/0/1
- name: ge-0/0/2
enabled: False
state: merged
# After state:
# -------------
# user@junos01# show protocols lldp
# management-address 10.1.1.1;
# advertisement-interval 10000;
# interface ge-0/0/1;
# interface ge-0/0/2 {
# disable;
# }
# Using replaced
# Before state:
# -------------
# user@junos01# show protocols lldp
# management-address 10.1.1.1;
# advertisement-interval 10000;
# interface ge-0/0/1;
# interface ge-0/0/2 {
# disable;
# }
- name: Replace provided configuration with device configuration
junos_lldp_interfaces:
config:
- name: ge-0/0/2
disable: False
- name: ge-0/0/3
enabled: False
state: replaced
# After state:
# -------------
# user@junos01# show protocols lldp
# management-address 10.1.1.1;
# advertisement-interval 10000;
# interface ge-0/0/1;
# interface ge-0/0/2;
# interface ge-0/0/3 {
# disable;
# }
# Using overridden
# Before state:
# -------------
# user@junos01# show protocols lldp
# management-address 10.1.1.1;
# advertisement-interval 10000;
# interface ge-0/0/1;
# interface ge-0/0/2 {
# disable;
# }
- name: Override provided configuration with device configuration
junos_lldp_interfaces:
config:
- name: ge-0/0/2
enabled: False
state: overridden
# After state:
# -------------
# user@junos01# show protocols lldp
# management-address 10.1.1.1;
# advertisement-interval 10000;
# interface ge-0/0/2 {
# disable;
# }
# Using deleted
# Before state:
# -------------
# user@junos01# show protocols lldp
# management-address 10.1.1.1;
# advertisement-interval 10000;
# interface ge-0/0/1;
# interface ge-0/0/2;
# interface ge-0/0/3 {
# disable;
# }
- name: Delete lldp interface configuration (this will not delete other lldp configuration)
junos_lldp_interfaces:
config:
- name: ge-0/0/1
- name: ge-0/0/3
state: deleted
# After state:
# -------------
# user@junos01# show protocols lldp
# management-address 10.1.1.1;
# advertisement-interval 10000;
# interface ge-0/0/2;
# interface ge-0/0/1;
"""
RETURN = """
before:
description: The configuration as structured data prior to module invocation.
returned: always
type: list
sample: >
The configuration returned will always be in the same format
of the parameters above.
after:
description: The configuration as structured data after module completion.
returned: when changed
type: list
sample: >
The configuration returned will always be in the same format
of the parameters above.
commands:
description: The set of commands pushed to the remote device.
returned: always
type: list
sample: ['xml 1', 'xml 2', 'xml 3']
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.junos.argspec.lldp_interfaces.lldp_interfaces import Lldp_interfacesArgs
from ansible.module_utils.network.junos.config.lldp_interfaces.lldp_interfaces import Lldp_interfaces
def main():
"""
Main entry point for module execution
:returns: the result form module invocation
"""
required_if = [('state', 'merged', ('config',)),
('state', 'replaced', ('config',)),
('state', 'overridden', ('config',))]
module = AnsibleModule(argument_spec=Lldp_interfacesArgs.argument_spec,
required_if=required_if,
supports_check_mode=True)
result = Lldp_interfaces(module).execute_module()
module.exit_json(**result)
if __name__ == '__main__':
main()
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
15069,
13130,
2297,
10983,
198,
2,
22961,
3611,
5094,
13789,
410,
18,
13,
15,
10,
198,
2,
357,
3826,
27975,
45761,
393,
... | 2.799024 | 2,050 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import contextlib
import cProfile
import datetime
import io
import os
import pstats
import signal
PYSPY_OUTPUT = os.environ.get("PYSPY_OUTPUT", "/files/pyspy/")
@contextlib.contextmanager
def pyspy():
"""
This decorator provide deterministic profiling. It generate and save flame graph to file. It uses``pyspy``
internally.
Running py-spy inside of a docker container will also usually bring up a permissions denied error
even when running as root.
This error is caused by docker restricting the process_vm_readv system call we are using. This can be
overridden by setting --cap-add SYS_PTRACE when starting the docker container.
Alternatively you can edit the docker-compose yaml file
.. code-block:: yaml
your_service:
cap_add:
- SYS_PTRACE
In the case of Airflow Breeze, you should modify the ``scripts/perf/perf_kit/python.py`` file.
"""
pid = str(os.getpid())
suffix = datetime.datetime.now().isoformat()
filename = f"{PYSPY_OUTPUT}/flame-{suffix}-{pid}.html"
pyspy_pid = os.spawnlp(
os.P_NOWAIT, "sudo", "sudo", "py-spy", "record", "--idle", "-o", filename, "-p", pid
)
try:
yield
finally:
os.kill(pyspy_pid, signal.SIGINT)
print(f"Report saved to: {filename}")
@contextlib.contextmanager
def profiled(print_callers=False):
"""
This decorator provide deterministic profiling. It uses ``cProfile`` internally. It generates statistic
and print on the screen.
"""
pr = cProfile.Profile()
pr.enable()
try:
yield
finally:
pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats("cumulative")
if print_callers:
ps.print_callers()
else:
ps.print_stats()
print(s.getvalue())
if __name__ == "__main__":
# Load modules
case()
# Example:
print("PySpy:")
with pyspy():
case()
# Example:
print("cProfile")
with profiled():
case()
| [
2,
49962,
284,
262,
24843,
10442,
5693,
357,
1921,
37,
8,
739,
530,
198,
2,
393,
517,
18920,
5964,
11704,
13,
220,
4091,
262,
28536,
2393,
198,
2,
9387,
351,
428,
670,
329,
3224,
1321,
198,
2,
5115,
6634,
9238,
13,
220,
383,
7054,... | 2.777669 | 1,021 |
"""
Transformer for machine translation (Attention Is All You Need, Vaswani et al. 2018)
Thomas Mortier
March 2022
"""
import torch
import numpy as np
class Transformer(torch.nn.Module):
""" Represents the main transformer class.
"""
| [
37811,
198,
8291,
16354,
329,
4572,
11059,
357,
8086,
1463,
1148,
1439,
921,
10664,
11,
23663,
86,
3216,
2123,
435,
13,
2864,
8,
198,
198,
22405,
10788,
959,
198,
16192,
33160,
198,
37811,
198,
11748,
28034,
198,
11748,
299,
32152,
355,... | 3.342466 | 73 |
# coding=utf-8
# manfeat.py: classifier based on manually extracted features.
from __future__ import print_function
import argparse
import os
import cPickle
import itertools
from datetime import datetime
import numpy as np
from scipy.stats import mode
from keras.optimizers import Adam
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from models.shallow import ShallowNet
SPLIT_DIR = "data/perssplit"
SPLITS = ["train", "val", "test"]
PICKLED_LABEL_FILE = "data/labels.pickle"
PERS_FIELD_NAME = "Answer.q7_persuasive"
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--feats-file", type=str, required=True)
arg_parser.add_argument("--names-file", type=str, required=True)
arg_parser.add_argument("--sig-feats-file", type=str, default=None)
arg_parser.add_argument("--last-layer-file", type=str, default=None)
arg_parser.add_argument("--save-path", type=str, required=True)
arg_parser.add_argument("--train", type=str, choices=["true", "false"], required=True)
arg_parser.add_argument("--weights", type=str, default=None)
arg_parser.add_argument("--lr", type=float, nargs="+", required=True)
arg_parser.add_argument("--epochs", type=int, nargs="+", required=True)
arg_parser.add_argument("--dropout", type=float, nargs="+", required=True)
arg_parser.add_argument("--dense-layers", type=int, nargs="+", required=True)
arg_parser.add_argument("--dense-layer-units", type=int, nargs="+", required=True)
arg_parser.add_argument("--batch-size", type=int, nargs="+", required=True)
arg_parser.add_argument("--ensemble-size", type=int, required=True)
args = arg_parser.parse_args()
with open(PICKLED_LABEL_FILE, "rb") as lf:
labels_map = cPickle.load(lf)
name_splits = {}
Xs = {}
ys = {}
for split in SPLITS:
with open(os.path.join(SPLIT_DIR, "{}.txt".format(split))) as split_file:
for line in split_file:
name_splits[line.strip()] = split
Xs[split] = []
ys[split] = []
with open(args.names_file) as man_feats_names_file, open(args.feats_file) as feats_file:
for name_line, feat_line in zip(man_feats_names_file, feats_file):
name = name_line.strip()
feats = map(float, feat_line.strip().split(","))
split = name_splits[name]
Xs[split].append(feats)
score = labels_map[name][PERS_FIELD_NAME]
if score >= 5.5:
ys[split].append(1)
else:
ys[split].append(0)
for split in SPLITS:
Xs[split] = np.array(Xs[split])
ys[split] = np.array(ys[split])
if args.sig_feats_file is not None:
print("Selecting significant features")
with open(args.sig_feats_file) as sig_feats_file:
sig_feats = [int(line.strip()) - 1 for line in sig_feats_file]
for split in SPLITS:
Xs[split] = Xs[split][:, sig_feats]
if args.train == "true":
date = str(datetime.now().date())
base_save_dir = os.path.join(args.save_path, date)
os.makedirs(base_save_dir)
final_train_perfs = {}
final_val_perfs = {}
for lr, epochs, dropout, dense_layers, dense_layer_units, batch_size in itertools.product(args.lr, args.epochs, args.dropout, args.dense_layers, args.dense_layer_units, args.batch_size):
params = lr, epochs, dropout, dense_layers, dense_layer_units, batch_size
print("LR: {}, EPOCHS: {}, DROPOUT: {}, DENSE LAYERS: {}, DENSE_LAYER_UNITS: {}, BATCH_SIZE: {}".format(*params))
save_path = os.path.join(base_save_dir, "lr{};epochs{};dropout{};dense_layers{};dense_layer_units{};batch_size{}".format(*params))
os.makedirs(save_path)
train_preds = np.zeros((Xs["train"].shape[0], args.ensemble_size))
val_preds = np.zeros((Xs["val"].shape[0], args.ensemble_size))
print("Building model")
model = ShallowNet(Xs["train"].shape[1], dropout, dense_layers, dense_layer_units, args.weights)
model.compile(optimizer=Adam(lr=lr), loss="binary_crossentropy")
print("Model built")
history = model.fit(
X=Xs["train"],
y=ys["train"],
batch_size=batch_size,
nb_epoch=epochs,
verbose=1,
validation_data=(Xs["val"], ys["val"]),
shuffle=True,
show_accuracy=True,
)
model.layers.pop()
model.compile(optimizer=Adam(lr=lr), loss="binary_crossentropy")
train_pred = model.predict(X=Xs["train"], batch_size=batch_size, verbose=0)
val_pred = model.predict(X=Xs["val"], batch_size=batch_size, verbose=0)
cou = 0
with open(args.last_layer_file, "w") as layer_file:
for vec in train_pred:
layer_file.write(",".join([str(i) for i in vec]))
layer_file.write("\n")
cou += 1
for vec in val_pred:
layer_file.write(",".join([str(i) for i in vec]))
layer_file.write("\n")
cou += 1
print(cou)
with open(args.last_layer_file+".labels", "w") as label_file:
for value in ys["train"]:
label_file.write(str(value))
label_file.write("\n")
for value in ys["val"]:
label_file.write(str(value))
label_file.write("\n")
exit(1)
final_train_pred = mode(train_preds, axis=1).mode
final_val_pred = mode(val_preds, axis=1).mode
final_train_perfs[params] = eval_pred(ys["train"], final_train_pred)
final_val_perfs[params] = eval_pred(ys["val"], final_val_pred)
print("final train perf: acc {}, f1 {}; final val perf: acc {}, f1 {}".format(final_train_perfs[params]["acc"], final_train_perfs[params]["f1"], final_val_perfs[params]["acc"], final_val_perfs[params]["f1"]))
print("\n".join(map(lambda x: "{}: {}".format(x[0], x[1]), final_train_perfs.items())), file=open(os.path.join(base_save_dir, "final_train_perfs.txt"), "w"))
print("\n".join(map(lambda x: "{}: {}".format(x[0], x[1]), final_val_perfs.items())), file=open(os.path.join(base_save_dir, "final_val_perfs.txt"), "w"))
best_params = max(final_val_perfs, key=lambda x: final_val_perfs[x]["f1"])
else:
best_params = (0.0001, 100, 0.5, 5, 5, 100)
best_lr, best_epochs, best_dropout, best_dense_layers, best_dense_layer_units, best_batch_size = best_params
if args.train == "true":
print("Training ensemble on training and validation set")
save_path = os.path.join(base_save_dir, "best_params")
os.makedirs(save_path)
preds = np.zeros((Xs["test"].shape[0], args.ensemble_size))
for i in range(args.ensemble_size):
print("Building model")
model = ShallowNet(Xs["train"].shape[1], best_dropout, best_dense_layers, best_dense_layer_units, args.weights)
model.compile(optimizer=Adam(lr=best_lr), loss="binary_crossentropy")
print("Model built")
history = model.fit(
X=np.concatenate((Xs["train"], Xs["val"])),
y=np.concatenate((ys["train"], ys["val"])),
batch_size=best_batch_size,
nb_epoch=best_epochs,
verbose=1,
shuffle=True,
show_accuracy=True,
)
model.save_weights(os.path.join(save_path, "weights{}.h5".format(i)), overwrite=True)
print("\n".join(map(str, history.history["acc"])), file=open(os.path.join(save_path, "train_accs{}.txt".format(i)), "w"))
print("\n".join(map(str, history.history["loss"])), file=open(os.path.join(save_path, "train_losses{}.txt".format(i)), "w"))
pred = model.predict_classes(X=Xs["test"], batch_size=batch_size, verbose=0)
preds[:, i] = pred[:, 0]
final_pred = mode(preds, axis=1).mode
test_perf = eval_pred(ys["test"], final_pred)
else:
print("Building model")
model = ShallowNet(Xs["train"].shape[1], best_dropout, best_dense_layers, best_dense_layer_units, args.weights)
model.compile(optimizer=Adam(lr=best_lr), loss="binary_crossentropy")
print("Model built")
test_perf = eval_model(model, best_batch_size, Xs["test"], ys["test"])
print("Test perf: {}".format(test_perf))
if args.train == "true":
summary = {
"best_lr": best_lr,
"best_epochs": best_epochs,
"best_dropout": best_dropout,
"best_dense_layers": best_dense_layers,
"best_dense_layer_units": best_dense_layer_units,
"best_batch_size": best_batch_size,
"ensemble_size": args.ensemble_size,
"test_perf": test_perf
}
print("\n".join(map(lambda x: "{}: {}".format(x[0], x[1]), summary.items())), file=open(os.path.join(base_save_dir, "summary.txt"), "w"))
| [
2,
19617,
28,
40477,
12,
23,
198,
2,
582,
27594,
13,
9078,
25,
1398,
7483,
1912,
319,
14500,
21242,
3033,
13,
198,
198,
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
11748,
1822,
29572,
198,
11748,
28686,
198,
11748,
269,
31686,... | 2.254933 | 3,801 |
import pandas as pd
from datetime import date,datetime
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
class Leaderboard:
'''
To maintain the leaderboard of the models
'''
def plot(self):
'''
Plot model accuracy vs time according to the rank
in the leaderboard.
'''
df = pd.read_excel('op_lbd.xlsx', index_col=0)
df1 = df.loc[df['SOTA'] == False]
df = df.loc[df['SOTA'] == True]
# df = df.drop_duplicates('Rank')
plt.plot(df['Date'], df['Accuracy'], '.-')
plt.plot(df1['Date'], df1['Accuracy'], 'co')
plt.show()
def leaderboardPush(self, model_name, accuracy, n_params):
'''
This will push a new model to the leaderboard.
@param model_name : Name of the model
@param accuracy : Accuracy of the model
@param n_param : Nos of parameter of the model
@returns : None
'''
assert accuracy > 0.0 , "Accuracy can't be negetive"
assert accuracy < 100.0, "Accuracy can't be greater than 100.0%"
assert n_params > 0, "Number of parameters can't be zero or less"
assert type(n_params) == int, "Number of parameters can't be fraction"
items = {
"Model_name": model_name,
"Accuracy" : accuracy,
"Parameters": n_params,
"Date" : date.today(),
"SOTA" : False
}
df = pd.read_excel('lbd.xlsx', index_col=0)
sota = df.Accuracy.max()
if accuracy > sota:
items["SOTA"] = True
df = df.append(items, ignore_index=True)
df.to_excel('lbd.xlsx')
df['Rank'] = df['Accuracy'].rank(ascending=False, method='min')
df = df.sort_values('Rank', ascending=True)
#Remove this after in the PC
print(df)
df.to_excel('op_lbd.xlsx')
return | [
11748,
19798,
292,
355,
279,
67,
198,
6738,
4818,
8079,
1330,
3128,
11,
19608,
8079,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
6738,
19798,
292,
13,
29487,
889,
1330,
7881,
62,
6759,
29487,
8019,
62,
1102,
332... | 2.124733 | 938 |
import logging
from utct.common.trainer_template import TrainerTemplate
import mxnet as mx
from mxnet import gluon, autograd
class Trainer(TrainerTemplate):
"""
Class, which provides training process under Gluon/MXNet framework.
Parameters:
----------
model : object
instance of Model class with graph of CNN
optimizer : object
instance of Optimizer class with CNN optimizer
data_source : object
instance of DataSource class with training/validation iterators
saver : object
instance of Saver class with information about stored files
ctx : object
instance of MXNet context
"""
def _hyper_train_target_sub(self, **kwargs):
"""
Calling single training procedure for specific hyper parameters from hyper optimizer.
"""
if self.saver.log_filename:
fh = logging.FileHandler(self.saver.log_filename)
self.logger.addHandler(fh)
self.logger.info("Training with parameters: {}".format(kwargs))
train_loader, val_loader = self.data_source()
net = self.model()
net.initialize(
mx.init.Xavier(magnitude=2.24),
ctx=self.ctx)
trainer = self.optimizer(
params=net.collect_params(),
**kwargs)
metric = mx.metric.Accuracy()
loss = gluon.loss.SoftmaxCrossEntropyLoss()
log_interval = 1
for epoch in range(self.num_epoch):
metric.reset()
for i, (data, label) in enumerate(train_loader):
# Copy data to ctx if necessary
data = data.as_in_context(self.ctx)
label = label.as_in_context(self.ctx)
# Start recording computation graph with record() section.
# Recorded graphs can then be differentiated with backward.
with autograd.record():
output = net(data)
L = loss(output, label)
L.backward()
# take a gradient step with batch_size equal to data.shape[0]
trainer.step(data.shape[0])
# update metric at last.
metric.update([label], [output])
if i % log_interval == 0 and i > 0:
name, acc = metric.get()
print('[Epoch %d Batch %d] Training: %s=%f' % (epoch, i, name, acc))
name, acc = metric.get()
print('[Epoch %d] Training: %s=%f' % (epoch, name, acc))
name, val_acc = self._test(
model=net,
val_data=val_loader,
ctx=self.ctx)
print('[Epoch %d] Validation: %s=%f' % (epoch, name, val_acc))
if self.saver.log_filename:
self.logger.removeHandler(fh)
fh.close()
best_value = 0.0
return best_value
@staticmethod
| [
11748,
18931,
198,
198,
6738,
3384,
310,
13,
11321,
13,
2213,
10613,
62,
28243,
1330,
31924,
30800,
198,
198,
11748,
285,
87,
3262,
355,
285,
87,
198,
6738,
285,
87,
3262,
1330,
1278,
84,
261,
11,
1960,
519,
6335,
628,
198,
4871,
31... | 2.133041 | 1,368 |
import logging
import colorlog
import sys
from crawlster.config import ChoiceOption
from crawlster.helpers.base import BaseHelper
class LoggingHelper(BaseHelper):
"""Logging helper that handles all the crawling logging.
Must provide the following methods:
- initialize() (inherited from BaseHelper)
- ``debug(*args, **kwargs)`` compatible with the :py:mod:`logging`
interface
- same for ``info``, ``warning``, ``error`` and ``critical``
"""
name = 'log'
valid_log_levels = ('debug', 'info', 'warning', 'error', 'critical')
config_options = {
'log.level': ChoiceOption(valid_log_levels, default='info')
}
DEFAULT_FORMAT = "%(log_color)s%(levelname)s - %(name)s - %(message)s"
def initialize(self):
"""Creates and initializes the logger"""
level = self.parse_level(self.config.get('log.level'))
logger = logging.getLogger('crawlster')
stream_handler = self.make_stream_handler(level)
logger.addHandler(stream_handler)
logger.setLevel(level)
self.logger = logger
def make_stream_handler(self, level):
"""Creates a colored stream handler that writes to STDOUT"""
colored_formatter = colorlog.ColoredFormatter(self.DEFAULT_FORMAT)
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(colored_formatter)
stream_handler.setLevel(level)
return stream_handler
def __getattr__(self, item):
"""Delegates method calls to the wrapped logger"""
if item not in ('debug', 'info', 'warning', 'error', 'critical'):
raise AttributeError()
return getattr(self.logger, item)
def parse_level(self, level_name):
"""Converts human readable level name to logging constants"""
return getattr(logging, level_name.upper())
| [
11748,
18931,
198,
198,
11748,
3124,
6404,
198,
11748,
25064,
198,
198,
6738,
27318,
1706,
13,
11250,
1330,
18502,
19722,
198,
6738,
27318,
1706,
13,
16794,
364,
13,
8692,
1330,
7308,
47429,
628,
198,
4871,
5972,
2667,
47429,
7,
14881,
... | 2.726608 | 684 |
"""
Description:
Author: Jiaqi Gu (jqgu@utexas.edu)
Date: 2021-09-28 04:26:34
LastEditors: Jiaqi Gu (jqgu@utexas.edu)
LastEditTime: 2021-09-28 04:33:35
"""
from collections import OrderedDict
from typing import Dict, List, Union
import torch
from core.models.layers.activation import ReLUN
from core.models.layers.super_conv2d import SuperBlockConv2d
from core.models.layers.super_linear import SuperBlockLinear
from torch import Tensor, nn
from torch.types import Device, _size
from .super_model_base import SuperModel_CLASS_BASE
__all__ = ["SuperOCNN", "LinearBlock", "ConvBlock"]
if __name__ == "__main__":
pass
| [
37811,
198,
11828,
25,
198,
13838,
25,
449,
544,
40603,
1962,
357,
73,
80,
5162,
31,
315,
1069,
292,
13,
15532,
8,
198,
10430,
25,
33448,
12,
2931,
12,
2078,
8702,
25,
2075,
25,
2682,
198,
5956,
18378,
669,
25,
449,
544,
40603,
19... | 2.803571 | 224 |
import config
from auth import auth_handler
| [
11748,
4566,
198,
6738,
6284,
1330,
6284,
62,
30281,
628
] | 4.5 | 10 |
import sys
import locale
from twisted.internet import reactor, task, threads
from twisted.python import log
from kademlia.network import Server, QuorumServer
log.startLogging(sys.stdout)
port = 5485
if(len(sys.argv) > 1):
port = int(sys.argv[1])
server = QuorumServer(ksize=3)
server.listen(port)
server.bootstrap([("127.0.0.1", 8468)]).addCallback(bootstrapDone, server)
get_input()
reactor.run()
| [
11748,
25064,
198,
11748,
36693,
198,
6738,
19074,
13,
37675,
1330,
21905,
11,
4876,
11,
14390,
198,
6738,
19074,
13,
29412,
1330,
2604,
198,
6738,
479,
36920,
24660,
13,
27349,
1330,
9652,
11,
2264,
19220,
10697,
198,
198,
6404,
13,
96... | 2.77027 | 148 |
import json
"""
Train:
search, length=136208, yes_no_depends=11476
zhidao, length=135366, yes_no_depends=11273
"""
PATH = '/home/wangyongbo/2019rc/DuReader_test/data/preprocessed/trainset'
# search.train.json zhidao.train.json
def count_yesno():
"""
To count the nums of tes/no/depends in dataset
"""
with open(PATH + "/zhidao.train.json", "r", encoding="utf-8") as f:
res_list = f.readlines()
print("Total nums: ", len(res_list))
cou_t = 0
cou = 0
yes_no = []
for i in res_list:
cou_t += 1
ii = json.loads(i)
# print(ii['question_type'])
if 'yesno_answers' in ii:
if ii['yesno_answers']:
cou += 1
yes_no.append(ii['yesno_answers'])
# print(yes_no)
print(len(yes_no))
print("num of yes_no: ", cou)
print("num of train samples: ", cou_t)
| [
11748,
33918,
198,
198,
37811,
198,
44077,
25,
198,
220,
220,
220,
2989,
11,
4129,
28,
20809,
21315,
11,
3763,
62,
3919,
62,
10378,
2412,
28,
1157,
35435,
198,
220,
220,
220,
1976,
71,
3755,
78,
11,
4129,
28,
17059,
32459,
11,
3763,... | 2.045662 | 438 |
from __future__ import annotations
from io import BytesIO
from typing import IO, Any, List, NamedTuple
import numpy as np
import numpy.typing as npt
class PointCloudHeader(NamedTuple):
""" Class for Point Cloud header. """
version: str
fields: List[str]
size: List[int]
type: List[str]
count: List[int] # type: ignore
width: int
height: int
viewpoint: List[int]
points: int
data: str
class PointCloud:
"""
Class for raw .pcd file.
"""
def __init__(self, header: PointCloudHeader, points: npt.NDArray[np.float64]) -> None:
"""
PointCloud.
:param header: Pointcloud header.
:param points: <np.ndarray, X, N>. X columns, N points.
"""
self._header = header
self._points = points
@property
def header(self) -> PointCloudHeader:
"""
Returns pointcloud header.
:return: A PointCloudHeader instance.
"""
return self._header
@property
def points(self) -> npt.NDArray[np.float64]:
"""
Returns points.
:return: <np.ndarray, X, N>. X columns, N points.
"""
return self._points
def save(self, file_path: str) -> None:
"""
Saves to .pcd file.
:param file_path: The path to the .pcd file.
"""
with open(file_path, 'wb') as fp:
fp.write('# .PCD v{} - Point Cloud Data file format\n'.format(self._header.version).encode('utf8'))
for field in self._header._fields:
value = getattr(self._header, field)
if isinstance(value, list):
text = ' '.join(map(str, value))
else:
text = str(value)
fp.write('{} {}\n'.format(field.upper(), text).encode('utf8'))
fp.write(self._points.tobytes())
@classmethod
def parse(cls, pcd_content: bytes) -> PointCloud:
"""
Parses the pointcloud from byte stream.
:param pcd_content: The byte stream that holds the pcd content.
:return: A PointCloud object.
"""
with BytesIO(pcd_content) as stream:
header = cls.parse_header(stream)
points = cls.parse_points(stream, header)
return cls(header, points)
@classmethod
def parse_from_file(cls, pcd_file: str) -> PointCloud:
"""
Parses the pointcloud from .pcd file on disk.
:param pcd_file: The path to the .pcd file.
:return: A PointCloud instance.
"""
with open(pcd_file, 'rb') as stream:
header = cls.parse_header(stream)
points = cls.parse_points(stream, header)
return cls(header, points)
@staticmethod
def parse_header(stream: IO[Any]) -> PointCloudHeader:
"""
Parses the header of a pointcloud from byte IO stream.
:param stream: Binary stream.
:return: A PointCloudHeader instance.
"""
headers_list = []
while True:
line = stream.readline().decode('utf8').strip()
if line.startswith('#'):
continue
columns = line.split()
key = columns[0].lower()
val = columns[1:] if len(columns) > 2 else columns[1]
headers_list.append((key, val))
if key == 'data':
break
headers = dict(headers_list)
headers['size'] = list(map(int, headers['size']))
headers['count'] = list(map(int, headers['count']))
headers['width'] = int(headers['width'])
headers['height'] = int(headers['height'])
headers['viewpoint'] = list(map(int, headers['viewpoint']))
headers['points'] = int(headers['points'])
header = PointCloudHeader(**headers)
if any([c != 1 for c in header.count]):
raise RuntimeError('"count" has to be 1')
if not len(header.fields) == len(header.size) == len(header.type) == len(header.count):
raise RuntimeError('fields/size/type/count field number are inconsistent')
return header
@staticmethod
def parse_points(stream: IO[Any], header: PointCloudHeader) -> npt.NDArray[np.float64]:
"""
Parses points from byte IO stream.
:param stream: Byte stream that holds the points.
:param header: <np.ndarray, X, N>. A numpy array that has X columns(features), N points.
:return: Points of Point Cloud.
"""
if header.data != 'binary':
raise RuntimeError('Un-supported data foramt: {}. "binary" is expected.'.format(header.data))
# There is garbage data at the end of the stream, usually all b'\x00'.
row_type = PointCloud.np_type(header)
length = row_type.itemsize * header.points
buff = stream.read(length)
if len(buff) != length:
raise RuntimeError('Incomplete pointcloud stream: {} bytes expected, {} got'.format(length, len(buff)))
points = np.frombuffer(buff, row_type) # type: ignore
return points # type: ignore
@staticmethod
def np_type(header: PointCloudHeader) -> np.dtype: # type: ignore
"""
Helper function that translate column types in pointcloud to np types.
:param header: A PointCloudHeader object.
:return: np.dtype that holds the X features.
"""
type_mapping = {'I': 'int', 'U': 'uint', 'F': 'float'}
np_types = [type_mapping[t] + str(int(s) * 8) for t, s in zip(header.type, header.size)]
return np.dtype([(f, getattr(np, nt)) for f, nt in zip(header.fields, np_types)])
def to_pcd_bin(self) -> npt.NDArray[np.float32]:
"""
Converts pointcloud to .pcd.bin format.
:return: <np.float32, 5, N>, the point cloud in .pcd.bin format.
"""
lidar_fields = ['x', 'y', 'z', 'intensity', 'ring']
return np.array([np.array(self.points[f], dtype=np.float32) for f in lidar_fields])
def to_pcd_bin2(self) -> npt.NDArray[np.float32]:
"""
Converts pointcloud to .pcd.bin2 format.
:return: <np.float32, 6, N>, the point cloud in .pcd.bin2 format.
"""
lidar_fields = ['x', 'y', 'z', 'intensity', 'ring', 'lidar_info']
return np.array([np.array(self.points[f], dtype=np.float32) for f in lidar_fields])
| [
6738,
11593,
37443,
834,
1330,
37647,
198,
198,
6738,
33245,
1330,
2750,
4879,
9399,
198,
6738,
19720,
1330,
24418,
11,
4377,
11,
7343,
11,
34441,
51,
29291,
198,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
299,
32152,
13,
774,
1388... | 2.277083 | 2,797 |
import matplotlib.pyplot as plt
from matplotlib import rcParams
import numpy as np
a = []
data = np.loadtxt("text.txt")
plt.grid(True)
plt.hist(data, bins = 100)
plt.show()
| [
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
201,
198,
6738,
2603,
29487,
8019,
1330,
48321,
10044,
4105,
201,
198,
11748,
299,
32152,
355,
45941,
201,
198,
201,
198,
201,
198,
64,
796,
17635,
201,
198,
201,
198,
220,
220,... | 1.889831 | 118 |
# KartAI https://github.com/eritzyg/KartAI/
# Copyright (c) 2017 Eritz Yerga Gutierrez and Iker García Ferrero
# MIT License https://github.com/eritzyg/KartAI/blob/master/LICENSE
import Player as player
import Render as render
import StateManager as sm | [
2,
32872,
20185,
3740,
1378,
12567,
13,
785,
14,
263,
4224,
35641,
14,
42,
433,
20185,
14,
198,
2,
15069,
357,
66,
8,
2177,
412,
29574,
575,
263,
4908,
48283,
290,
314,
6122,
16364,
29690,
12880,
34785,
198,
2,
17168,
13789,
3740,
1... | 3.1625 | 80 |
# coding: utf-8
SUB_FORMATS = [".ass", ".srt", ".ssa", ".sub"]
ARCHIVE_TYPES = [".zip", ".rar", ".7z"]
VIDEO_FORMATS = [
".webm",
".mkv",
".flv",
".vob",
".ogv",
".ogg",
".drc",
".gif",
".gifv",
".mng",
".avi",
".mov",
".qt",
".wmv",
".yuv",
".rm",
".rmvb",
".asf",
".amv",
".mp4",
".m4p",
".m4v",
".mpg",
".mp2",
".mpeg",
".mpe",
".mpv",
".mpg",
".m2v",
".svi",
".3gp",
".3g2",
".mxf",
".roq",
".nsv",
".flv",
".f4v",
".f4p",
".f4a",
".f4b",
]
| [
2,
19617,
25,
3384,
69,
12,
23,
198,
198,
50,
10526,
62,
21389,
33586,
796,
685,
1911,
562,
1600,
27071,
82,
17034,
1600,
27071,
824,
64,
1600,
27071,
7266,
8973,
198,
31315,
9306,
62,
9936,
47,
1546,
796,
685,
1911,
13344,
1600,
27... | 1.584856 | 383 |
from __future__ import print_function, division
import os
import torch
import pandas as pd
from skimage import io, transform
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from PIL import Image, ImageOps
from random import random, randint
import pdb
# Ignore warnings
import warnings
warnings.filterwarnings("ignore")
class MedicalImageDataset(Dataset):
"""Face Landmarks dataset."""
def __init__(self, mode, root_dir, augment=False, equalize=False, load_on_gpu=False, load_all_dataset=False):
"""
Args:
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.root_dir = root_dir
self.augmentation = augment
self.equalize = equalize
self.load_on_gpu = load_on_gpu and torch.cuda.is_available()
self.load_all_dataset = load_all_dataset and self.load_on_gpu
self.img_paths = make_dataset(root_dir, mode)
self.mode = mode
if self.load_all_dataset:
self.loaded_imgs = []
for index in range(self.__len__()):
img_path, mask_path = self.img_paths[index]
img = transforms.ToTensor()(Image.open(img_path)).cuda()
mask = transforms.ToTensor()(Image.open(mask_path).convert('L')).cuda()
self.loaded_imgs.append((img, mask))
@staticmethod
| [
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
11,
7297,
198,
11748,
28686,
198,
11748,
28034,
198,
11748,
19798,
292,
355,
279,
67,
198,
6738,
1341,
9060,
1330,
33245,
11,
6121,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
28034,
13,... | 2.399682 | 628 |
from django.contrib.auth.models import User, Group
from rest_framework import serializers
# TODO: Create your serializers here.
| [
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
27530,
1330,
11787,
11,
4912,
198,
6738,
1334,
62,
30604,
1330,
11389,
11341,
198,
198,
2,
16926,
46,
25,
13610,
534,
11389,
11341,
994,
13,
198
] | 3.685714 | 35 |
import os
import pytest
from genie import create_case_lists
study_id = "test"
clinical_file_map = {'': ['FOOBAR', 'NEED']}
clinical_file_map['Testing2'] = ['test1']
clinical_file_map['Test1 Now, Please/foo'] = ['wow']
sequenced_case_list_files = create_case_lists.write_case_list_sequenced(
['test1', 'test2'], "./", study_id)
case_list_cna_path = create_case_lists.write_case_list_cna(
['test1', 'test2'], "./", study_id)
case_list_cnaseq_path = create_case_lists.write_case_list_cnaseq(
['test1', 'test2'], "./", study_id)
expected_change_text = (
'cancer_study_identifier: test\n'
'stable_id: test_Test1_Now_Please_foo\n'
'case_list_name: Tumor Type: Test1 Now, Please/foo\n'
'case_list_description: All tumors with cancer type '
'Test1 Now, Please/foo\n'
'case_list_ids: wow')
expected_same_text = (
'cancer_study_identifier: test\n'
'stable_id: test_Testing2\n'
'case_list_name: Tumor Type: Testing2\n'
'case_list_description: All tumors with cancer type Testing2\n'
'case_list_ids: test1')
expected_nocode_text = (
'cancer_study_identifier: test\n'
'stable_id: test_no_oncotree_code\n'
'case_list_name: Tumor Type: NA\n'
'case_list_description: All tumors with cancer type NA\n'
'case_list_ids: FOOBAR\tNEED')
@pytest.fixture(params=[
# tuple with (input, expectedOutput)
('', clinical_file_map[''], expected_nocode_text),
('Testing2', clinical_file_map['Testing2'], expected_same_text),
('Test1 Now, Please/foo',
clinical_file_map['Test1 Now, Please/foo'],
expected_change_text)])
| [
11748,
28686,
198,
198,
11748,
12972,
9288,
198,
198,
6738,
2429,
494,
1330,
2251,
62,
7442,
62,
20713,
198,
198,
44517,
62,
312,
796,
366,
9288,
1,
198,
198,
47367,
62,
7753,
62,
8899,
796,
1391,
7061,
25,
37250,
6080,
9864,
1503,
... | 2.41194 | 670 |
import torch.nn as nn
from torch.nn.modules.conv import _ConvNd
def basic_weight_init(slop=0, non_linearity='relu', type='kaiming_uniform'):
"""
return a weight_init method for convolution and batchnorm initialization.
convolutional layer are initialized using kaimin_uniform initialization
:param type: type of convolution normalization 'normal', 'kaiming_uniform', 'xavier_normal'
:param slop: slop of the non linearity
:param non_linearity: 'relu' or 'leaky_relu'
:return: weight initialization method
"""
return weight_init
| [
11748,
28034,
13,
20471,
355,
299,
77,
198,
6738,
28034,
13,
20471,
13,
18170,
13,
42946,
1330,
4808,
3103,
85,
45,
67,
628,
198,
4299,
4096,
62,
6551,
62,
15003,
7,
6649,
404,
28,
15,
11,
1729,
62,
29127,
414,
11639,
260,
2290,
3... | 3 | 189 |
from django.conf.urls import url
from . import views, script_views
from . import dashboard
from common.dashboard import dashboard_view_closure
urlpatterns = [
url(r'^dashboard/$', views.dashboard, name='dashboard'),
# Script pages
dashboard.Script_Dashboard.url_view_dashboard(r'script/dashboard/$'),
dashboard.Script_Dashboard.url_view_editor(r'script/editor/(?P<pk>\d+)/\w*$'),
dashboard.Script_Dashboard.url_view_public(r'script/view/(?P<pk>\d+)/\w*$'),
dashboard.Script_Dashboard.url_post_add(r'^script/add/$'),
dashboard.Script_Dashboard.url_post_edit(r'script/edit/$'),
dashboard.Script_Dashboard.url_post_delete(r'^script/delete/$'),
url(r'^script/test_run/$',
dashboard_view_closure(dashboard.Script_Dashboard, script_views.test_run),
name='test_run'
),
# Source pages
url(r'^script/source/commit/$', script_views.commit, name='commit'),
dashboard.Source_Dashboard.url_view_editor(r'^source/editor/(?P<pk>\d+)/'),
dashboard.Source_Dashboard.url_view_public(r'^source/view/(?P<pk>\d+)/'),
dashboard.Source_Dashboard.url_post_edit(r'^source/edit/$'),
dashboard.Source_Dashboard.url_post_delete(r'^source/delete/$')
] + \
dashboard.Log_Dashboard.create_standard_urls()
| [
6738,
42625,
14208,
13,
10414,
13,
6371,
82,
1330,
19016,
198,
6738,
764,
1330,
5009,
11,
4226,
62,
33571,
198,
6738,
764,
1330,
30415,
198,
6738,
2219,
13,
42460,
3526,
1330,
30415,
62,
1177,
62,
17966,
198,
198,
6371,
33279,
82,
796... | 2.573469 | 490 |
my_object = ObjectCreator()
print(my_object)
print(ObjectCreator)
echo(ObjectCreator)
print(hasattr(ObjectCreator, 'new_attr'))
ObjectCreator.new_attr = 'foo'
print(hasattr(ObjectCreator, 'new_attr'))
print(ObjectCreator.new_attr)
ObjectCreatorMirror = ObjectCreator
print(ObjectCreatorMirror.new_attr)
print(ObjectCreatorMirror())
MyClass = choose_class('foo')
print(MyClass)
print(MyClass())
| [
198,
198,
1820,
62,
15252,
796,
9515,
16719,
273,
3419,
198,
4798,
7,
1820,
62,
15252,
8,
198,
4798,
7,
10267,
16719,
273,
8,
628,
198,
198,
30328,
7,
10267,
16719,
273,
8,
198,
4798,
7,
10134,
35226,
7,
10267,
16719,
273,
11,
705... | 2.77931 | 145 |
import psycopg2
import pytz
from datetime import datetime
from bot.dao import Dao
from bot.feed import Feed
| [
11748,
17331,
22163,
70,
17,
198,
11748,
12972,
22877,
198,
6738,
4818,
8079,
1330,
4818,
8079,
198,
198,
6738,
10214,
13,
67,
5488,
1330,
360,
5488,
198,
6738,
10214,
13,
12363,
1330,
18272,
198
] | 3.205882 | 34 |
# -*- coding: utf-8 -*-
import json
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
11748,
33918,
628
] | 2.176471 | 17 |
import os
__author__ = 'bison'
| [
11748,
28686,
201,
198,
834,
9800,
834,
796,
705,
65,
1653,
6,
201,
198,
201,
198
] | 2.1875 | 16 |
from django.db import models
# Create your models here.
| [
6738,
42625,
14208,
13,
9945,
1330,
4981,
198,
198,
2,
13610,
534,
4981,
994,
13,
198
] | 3.5625 | 16 |
import json
import logging
import os
import boto3
import database
from database import Ticket, TicketTemplate, User
logger = logging.getLogger(__name__)
BUCKET_NAME = os.environ['BUCKET_NAME']
| [
11748,
33918,
198,
11748,
18931,
198,
11748,
28686,
198,
198,
11748,
275,
2069,
18,
198,
198,
11748,
6831,
198,
6738,
6831,
1330,
24014,
11,
24014,
30800,
11,
11787,
198,
198,
6404,
1362,
796,
18931,
13,
1136,
11187,
1362,
7,
834,
3672,... | 3.126984 | 63 |
"""Initial commit.
May be necessary to ghost this in production or do a manual migrate.
SQLite seems to be stupid and require an explicit name for each constraint
and it just won't take an empty name like all real databases.
Revision ID: c0732331a3c8
Revises: None
Create Date: 2016-09-28 15:34:30.135146
"""
# revision identifiers, used by Alembic.
revision = 'c0732331a3c8'
down_revision = None
from alembic import op
import sqlalchemy as sa
| [
37811,
24243,
4589,
13,
198,
198,
6747,
307,
3306,
284,
10905,
428,
287,
3227,
393,
466,
257,
10107,
32492,
13,
198,
198,
17861,
578,
2331,
284,
307,
8531,
290,
2421,
281,
7952,
1438,
329,
1123,
32315,
198,
392,
340,
655,
1839,
470,
... | 3.228571 | 140 |
import numpy as np
import tensorflow as tf
import helpers
tf.reset_default_graph()
sess = tf.InteractiveSession()
#Vocabulary size.
PAD = 0
EOS = 1
vocab_size = 10
input_embedding_size = 20 #character length
encoder_hidden_units = 20 #num neurons
decoder_hidden_units = encoder_hidden_units * 2
#in original paper, they used same number of neurons for both encoder and decoder, but we use twice
#as many so decoded output is different, the target value is the original input in this example
#input placeholders
encoder_inputs = tf.placeholder(shape=(None, None), dtype=tf.int32, name='encoder_inputs')
encoder_inputs_length = tf.placeholder(shape=(None,), dtype=tf.int32, name='encoder_inputs_length')
decoder_targets = tf.placeholder(shape=(None, None), dtype=tf.int32, name='decoder_targets')
#randomly initialized embedding matrix that can fit input sequence
#used to convert sequences to vectors (embeddings) for both encoder and decoder of the right size
#reshaping is a thing, in TF you gotta make sure you tensors are the right shape (num dimensions)
embeddings = tf.Variable(tf.random_uniform([vocab_size, input_embedding_size], -1.0, 1.0), dtype=tf.float32)
encoder_inputs_embedded = tf.nn.embedding_lookup(embeddings, encoder_inputs)
#####API LOCATION ERROR HERE
from tensorflow.python.ops.rnn_cell import LSTMCell, LSTMStateTuple
#from tensorflow.contrib.rnn.python.ops.core_rnn_cell_impl import LSTMCell, LSTMStateTuple
encoder_cell_fw = LSTMCell(encoder_hidden_units)
encoder_cell_bw = LSTMCell(encoder_hidden_units)
((encoder_fw_outputs,encoder_bw_outputs),(encoder_fw_final_state,encoder_bw_final_state)) = (
tf.nn.bidirectional_dynamic_rnn(cell_fw=encoder_cell_fw,
cell_bw=encoder_cell_bw,
inputs=encoder_inputs_embedded,
sequence_length=encoder_inputs_length,
dtype=tf.float32, time_major=True)
)
#Concatenates tensors along one dimension.
##############print("? = ",encoder_bw_outputs)
encoder_outputs = tf.concat((encoder_fw_outputs, encoder_bw_outputs), 2)
#letters h and c are commonly used to denote "output value" and "cell state".
#http://colah.github.io/posts/2015-08-Understanding-LSTMs/
#Those tensors represent combined internal state of the cell, and should be passed together.
encoder_final_state_c = tf.concat(
(encoder_fw_final_state.c, encoder_bw_final_state.c), 1)
encoder_final_state_h = tf.concat(
(encoder_fw_final_state.h, encoder_bw_final_state.h), 1)
#TF Tuple used by LSTM Cells for state_size, zero_state, and output state.
encoder_final_state = LSTMStateTuple(
c=encoder_final_state_c,
h=encoder_final_state_h
)
decoder_cell = LSTMCell(decoder_hidden_units)
encoder_max_time, batch_size = tf.unstack(tf.shape(encoder_inputs))
decoder_lengths = encoder_inputs_length + 3
# +2 additional steps, +1 leading <EOS> token for decoder inputs
#manually specifying since we are going to implement attention details for the decoder in a sec
#weights
W = tf.Variable(tf.random_uniform([decoder_hidden_units, vocab_size], -1, 1), dtype=tf.float32)
#bias
b = tf.Variable(tf.zeros([vocab_size]), dtype=tf.float32)
#create padded inputs for the decoder from the word embeddings
#were telling the program to tests a condition, and trigger an error if the condition is false.
assert EOS == 1 and PAD == 0
eos_time_slice = tf.ones([batch_size], dtype=tf.int32, name='EOS')
pad_time_slice = tf.zeros([batch_size], dtype=tf.int32, name='PAD')
#retrieves rows of the params tensor. The behavior is similar to using indexing with arrays in numpy
eos_step_embedded = tf.nn.embedding_lookup(embeddings, eos_time_slice)
pad_step_embedded = tf.nn.embedding_lookup(embeddings, pad_time_slice)
#manually specifying loop function through time - to get initial cell state and input to RNN
#normally we'd just use dynamic_rnn, but lets get detailed here with raw_rnn
#we define and return these values, no operations occur here
#attention mechanism --choose which previously generated token to pass as input in the next timestep
#Creates an RNN specified by RNNCell cell and loop function loop_fn.
#This function is a more primitive version of dynamic_rnn that provides more direct access to the
#inputs each iteration. It also provides more control over when to start and finish reading the sequence,
#and what to emit for the output.
#ta = tensor array
decoder_outputs_ta, decoder_final_state, _ = tf.nn.raw_rnn(decoder_cell, loop_fn)
decoder_outputs = decoder_outputs_ta.stack()
decoder_outputs
#to convert output to human readable prediction
#we will reshape output tensor
#Unpacks the given dimension of a rank-R tensor into rank-(R-1) tensors.
#reduces dimensionality
decoder_max_steps, decoder_batch_size, decoder_dim = tf.unstack(tf.shape(decoder_outputs))
#flettened output tensor
decoder_outputs_flat = tf.reshape(decoder_outputs, (-1, decoder_dim))
#pass flattened tensor through decoder
decoder_logits_flat = tf.add(tf.matmul(decoder_outputs_flat, W), b)
#prediction vals
decoder_logits = tf.reshape(decoder_logits_flat, (decoder_max_steps, decoder_batch_size, vocab_size))
#final prediction
decoder_prediction = tf.argmax(decoder_logits, 2)
#cross entropy loss
#one hot encode the target values so we don't rank just differentiate
stepwise_cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
labels=tf.one_hot(decoder_targets, depth=vocab_size, dtype=tf.float32),
logits=decoder_logits,
)
#loss function
loss = tf.reduce_mean(stepwise_cross_entropy)
#train it
train_op = tf.train.AdamOptimizer().minimize(loss)
sess.run(tf.global_variables_initializer())
batch_size = 2
# batches = helpers.random_sequences(length_from=3, length_to=8, vocab_lower=2, vocab_upper=10, batch_size=batch_size)
train_features_batches = helpers.loadDataFile("../MNIST_data/train_features.txt")
train_labels_batches = helpers.loadDataFile("../MNIST_data/train_labels.txt")
print("train_features_batches:", train_features_batches)
print('head of the train_features_batches:')
for seq in next(train_features_batches.__iter__())[:10]:
print(seq)
print("train_labels_batches:", train_features_batches)
print('head of the train_labels_batches:')
for seq in next(train_labels_batches.__iter__())[:10]:
print(seq)
#############
loss_track = []
max_batches = 30
batches_in_epoch = 10
import time
try:
start = time.time()
config = tf.ConfigProto()
config.gpu_options.allocator_type = 'BFC'
config.gpu_options.per_process_gpu_memory_fraction = 0.90
linesofar = 0
for batch in range(max_batches):
train_features_batches = helpers.next_batch_k("../MNIST_data/features.txt", batch_size, linesofar)
train_labels_batches = helpers.next_batch_k("../MNIST_data/labels.txt", batch_size, linesofar)
fd = next_feed(train_features_batches, train_labels_batches)
_, l = sess.run([train_op, loss], fd)
loss_track.append(l)
linesofar += batch_size
if batch == 0 or batch % batches_in_epoch == 0:
print('batch {}'.format(batch))
if(batch != 0):
print("Time used: ", time.time() - start)
print(' minibatch loss: {}'.format(sess.run(loss, fd)))
predict_ = sess.run(decoder_prediction, fd)
for i, (inp, pred) in enumerate(zip(fd[encoder_inputs].T, predict_.T)):
print(' sample {}:'.format(i + 1))
print(' input > {}'.format(inp))
print(' predicted > {}'.format(pred))
if i >= 2:
break
print()
start = time.time()
print("Optimization Finished!")
# start prediction
start = time.time()
test_features_batches = helpers.loadDataFile("../MNIST_data/test_features.txt")
test_labels_batches = helpers.loadDataFile("../MNIST_data/test_labels.txt")
test_fd = next_feed(test_features_batches, test_labels_batches)
print("Time used: ", time.time() - start)
print(' tests batch loss: {}'.format(sess.run(loss, test_fd)))
test_predict_ = sess.run(decoder_prediction, test_fd)
for i, (inp, pred) in enumerate(zip(test_fd[encoder_inputs].T, test_predict_.T)):
print(' sample {}:'.format(i + 1))
print(' input > {}'.format(inp))
print(' predicted > {}'.format(pred))
if i >= 2:
break
print()
print("Prediction Finished!")
except KeyboardInterrupt:
print('training interrupted')
| [
11748,
299,
32152,
355,
45941,
198,
11748,
11192,
273,
11125,
355,
48700,
198,
11748,
49385,
198,
198,
27110,
13,
42503,
62,
12286,
62,
34960,
3419,
220,
198,
82,
408,
796,
48700,
13,
9492,
5275,
36044,
3419,
220,
198,
198,
2,
53,
420... | 2.587206 | 3,314 |
import sys
import json
import os
import shlex
import pprint
import importlib.resources
import firebase_admin
from firebase_admin import credentials,firestore
with importlib.resources.path("src","serviceAccountKey.json") as fire_resource:
cred = credentials.Certificate(fire_resource)
firebase_admin.initialize_app(cred)
# Checks / Creates a local data.json file to store buckets.
with importlib.resources.path("src","main.py") as haar_resource:
file = os.path.abspath(haar_resource)
file = file[:-11]
file = file + "buck-data/"
if os.path.isdir(file):
i = 0
else:
os.mkdir(file)
data = file + "data.json"
f = open(data,"a+")
# Creates the Bucket class
# Interacts with local db
# Creates a New Bucket
#List out bucketsq
# Check if command is cd
# Runs commands if is_cd == True
#Run Commands From Bucket
#Add bucket from cloud
# deletes a bucket
# Main Function
| [
11748,
25064,
198,
11748,
33918,
220,
198,
11748,
28686,
198,
11748,
427,
2588,
220,
198,
11748,
279,
4798,
198,
11748,
1330,
8019,
13,
37540,
198,
198,
11748,
2046,
8692,
62,
28482,
198,
6738,
2046,
8692,
62,
28482,
1330,
18031,
11,
64... | 2.792899 | 338 |
# Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
from robot.utils import NormalizedDict
RUN_KW_REGISTER = _RunKeywordRegister()
| [
2,
220,
15069,
3648,
12,
4626,
26182,
23555,
290,
27862,
198,
2,
198,
2,
220,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
220,
345,
743,
407,
779,
428,
2393,
2845,
287,
11846,
351,
... | 3.620513 | 195 |
from django.contrib.auth.views import get_user_model
from rest_framework import serializers
User = get_user_model()
| [
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
33571,
1330,
651,
62,
7220,
62,
19849,
198,
6738,
1334,
62,
30604,
1330,
11389,
11341,
198,
198,
12982,
796,
651,
62,
7220,
62,
19849,
3419,
628
] | 3.371429 | 35 |
# !/usr/bin/env python2
import rospy
import rospkg
import yaml
from sensor_msgs.msg import CameraInfo
from std_msgs.msg import String
import roslaunch
import os
import argparse
from Config.config import load_config, DEFAULTS as DEFAULT_CONFIGS
import time
import Camera as cam
parser = argparse.ArgumentParser(description="Multi Azure Python Controller")
parser.add_argument("--mode", type=str, default="driver", help="Write logs to the given directory")
parser.add_argument("--nb", type=int, default="1", help="Enter number of cameras used")
parser.add_argument("--config", metavar="FILE", type=str, help="Path to configuration file")
parser.add_argument("--path", metavar="DIR", type=str, help="Path to save experiment mkv video")
if __name__ == '__main__':
main(parser.parse_args())
| [
2,
5145,
14,
14629,
14,
8800,
14,
24330,
21015,
17,
198,
11748,
686,
2777,
88,
198,
11748,
686,
2777,
10025,
198,
11748,
331,
43695,
198,
198,
6738,
12694,
62,
907,
14542,
13,
19662,
1330,
20432,
12360,
198,
6738,
14367,
62,
907,
1454... | 3.290984 | 244 |