metadata
dict | text
stringlengths 60
3.49M
|
---|---|
{
"source": "jonmeads/pocketMoney",
"score": 2
} |
#### File: pocketMoney/pocket/__init__.py
```python
import os
from flask import Flask, render_template, request, Response, send_from_directory
from flask_bootstrap import Bootstrap
import secrets
from .money import money
from .nav import nav
def create_app():
app = Flask(__name__)
Bootstrap(app)
secret = secrets.token_urlsafe(32)
app.secret_key = secret
app.register_blueprint(money)
from pocket import db
db.createdbIfNotExists()
nav.init_app(app)
return app
```
#### File: pocketMoney/pocket/money.py
```python
import os
from flask import Flask, render_template, request, Response, send_from_directory, Blueprint, flash, g, redirect
from functools import wraps
from flask import current_app as app
from flask_nav.elements import Navbar, View, Subgroup, Link, Text, Separator
import datetime
from crontab import CronTab
import getpass
from pocket import db as db
from .nav import nav
money = Blueprint("money", __name__)
def check_auth(username, password):
user = os.environ.get('AUTH_USER')
if user is None:
user = 'admin'
passwd = os.environ.get('AUTH_PASS')
if passwd is None:
passwd = '<PASSWORD>'
return username == user and password == <PASSWORD>
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
nav.register_element('money_top', Navbar( View('Pocket Money Tracker', '.home'), View('Schedules', '.schedules'), View('Add Child', '.addChild')))
@money.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
@money.route('/history/<child>')
def history(child):
rows = db.getHistory(child);
return render_template("history.html",rows = rows, child = child)
@money.route('/add/<child>')
@requires_auth
def add(child):
now = datetime.datetime.now()
dateString = now.strftime("%d/%m/%Y")
templateData = {
'child': child,
'dt':dateString
}
return render_template('add.html', **templateData)
@money.route('/schedules')
def schedules():
rows = db.getSchedules()
cron = CronTab(user=getpass.getuser())
return render_template('schedule.html', rows = rows, cron = cron)
@money.route('/addSchedule')
@requires_auth
def addSchedule():
rows = db.getChildren()
return render_template('addSchedule.html', rows = rows)
@money.route('/addScheduleRec', methods = ['POST', 'GET'])
def addScheduleRec():
if request.method == 'POST':
try:
print(request.form)
child = request.form['children']
amt = request.form['amt']
desc = request.form['desc']
freq = request.form['freq'] # weekly / monthly
freqWeekly = request.form['daily'] # MON - SUN
freqMonthly = request.form['monthly'] # 1 - 31
frequency = ""
if amt is None:
amt = 0
cron = CronTab(user=getpass.getuser())
job = cron.new(command="/payment.sh '" + child + "' " + amt, comment=desc)
job.minute.on(1)
job.hour.on(1)
if freq == "weekly":
job.dow.on(freqWeekly)
frequency = "Every week on " + freqWeekly
if freq == "monthly":
job.setall('1 1 ' + freqMonthly + ' * *')
frequency = "On the " + str(freqMonthly) + " day of the month"
cron.write()
db.addSchedule(child, amt, desc, frequency)
msg = "successfully added schedule"
except Exception as e:
print(e)
msg = "error adding schedule"
finally:
flash(msg)
return redirect('/')
@money.route('/deleteSchedule/<child>/<desc>/<rowid>')
@requires_auth
def deleteSchedule(child, desc, rowid):
try:
print("Deleting schedule record")
cron = CronTab(user=getpass.getuser())
cron.remove_all(comment=desc)
cron.write()
db.deleteSchedule(child, rowid)
msg = "Successfully deleted record"
except Exception as e:
print(e)
msg = "Error deleting record, please retry"
finally:
flash(msg)
return redirect('/')
@money.route('/deleteAmount/<child>/<rowid>')
@requires_auth
def deleteAmount(child, rowid):
try:
print("Deleting record")
db.deleteAmount(child, rowid)
msg = "Successfully deleted record"
except Exception as e:
print(e)
msg = "Error deleting record, please retry"
finally:
flash(msg)
return redirect('/')
@money.route('/addRec', methods = ['POST', 'GET'])
def addRec():
if request.method == 'POST':
try:
child = request.form['child']
dt = request.form['dt']
amt = request.form['amt']
desc = request.form['desc']
db.addData(child, dt, amt, desc)
msg = "Successfully added transaction"
except:
msg = "Error adding transaction, please retry"
finally:
flash(msg)
return redirect('/')
@money.route('/addChildRec', methods = ['POST', 'GET'])
def addChildRec():
if request.method == 'POST':
try:
child = request.form['child']
amt = request.form['amt']
if amt is None:
amt = 0
now = datetime.datetime.now()
dt = now.strftime("%Y-%m-%d")
db.addChild(child, amt, dt)
msg = "successfully added child"
except Exception as e:
print(e)
msg = "error adding child"
finally:
flash(msg)
return redirect('/')
@money.route('/addChild')
def addChild():
now = datetime.datetime.now()
dateString = now.strftime("%Y-%m-%d")
return render_template('addchild.html', title = 'Pocket Money Tracker', time = dateString)
@money.route("/")
def home():
now = datetime.datetime.now()
dateString = now.strftime("%Y-%m-%d")
rows = db.getBalances()
if len(rows) == 0:
return render_template('addchild.html', title = 'Pocket Money Tracker', time = dateString)
else:
return render_template('index.html', rows = rows, title = 'Pocket Money Tracker', time = dateString)
``` |
{
"source": "jonmenard/cm3",
"score": 3
} |
#### File: cm3/alg/alg_credit_checkers.py
```python
import numpy as np
import tensorflow.compat.v1 as tf
import sys
import networks
class Alg(object):
def __init__(self, experiment, dimensions, stage=1, n_agents=1,
tau=0.01, lr_V=0.001, lr_Q=0.001,
lr_actor=0.0001, gamma=0.99, use_Q_credit=1,
use_V=0, nn={}):
"""
Same as alg_credit. Checkers global state has two parts
Inputs:
experiment - string
dimensions - dictionary containing tensor dimensions
(h,w,c) for tensor
l for 1D vector
stage - 1: Q_global and actor, does not use Q_credit
2: Q_global, actor and Q_credit
tau - target variable update rate
lr_V, lr_Q, lr_actor - learning rates for optimizer
gamma - discount factor
use_Q_credit - if 1, activates Q_credit network for use in policy gradient
use_V - if 1, uses V_n(s) as the baseline in the policy gradient (this is an ablation)
nn : neural net architecture parameters
"""
self.experiment = experiment
if self.experiment == "checkers":
# Global state
self.rows_state = dimensions['rows_state']
self.columns_state = dimensions['columns_state']
self.channels_state = dimensions['channels_state']
self.l_state = n_agents * dimensions['l_state_one']
self.l_state_one_agent = dimensions['l_state_one']
self.l_state_other_agents = (n_agents-1) * dimensions['l_state_one']
# Agent observations
self.l_obs_others = dimensions['l_obs_others']
self.l_obs_self = dimensions['l_obs_self']
# Dimensions for image input
self.rows_obs = dimensions['rows_obs']
self.columns_obs = dimensions['columns_obs']
self.channels_obs = dimensions['channels_obs']
# Dimension of agent's observation of itself
self.l_action = dimensions['l_action']
self.l_goal = dimensions['l_goal']
self.n_agents = n_agents
self.tau = tau
self.lr_V = lr_V
self.lr_Q = lr_Q
self.lr_actor = lr_actor
self.gamma = gamma
self.use_V = use_V
self.use_Q_credit = use_Q_credit
self.nn = nn
self.agent_labels = np.eye(self.n_agents)
self.actions = np.eye(self.l_action)
# Initialize computational graph
self.create_networks(stage)
self.list_initialize_target_ops, self.list_update_target_ops = self.get_assign_target_ops(tf.trainable_variables())
# Use Q_global when n_agents == 1 (the choice is arbitrary,
# since both networks share the same Stage 1 architecture)
self.create_Q_global_train_op()
if self.n_agents > 1 and self.use_Q_credit:
self.list_initialize_credit_ops = self.get_assign_global_to_credit_ops()
self.create_Q_credit_train_op()
elif self.n_agents > 1 and self.use_V:
self.create_V_train_op()
self.create_policy_gradient_op()
# TF summaries
self.create_summary()
def create_networks(self, stage):
# Placeholders
self.state_env = tf.placeholder(tf.float32, [None, self.rows_state, self.columns_state, self.channels_state], 'state_env')
self.v_state_one_agent = tf.placeholder(tf.float32, [None, self.l_state_one_agent], 'v_state_one_agent')
self.v_state_m = tf.placeholder(tf.float32, [None, self.l_state_one_agent], 'v_state_m')
self.v_state_other_agents = tf.placeholder(tf.float32, [None, self.l_state_other_agents], 'v_state_other_agents')
self.v_goal = tf.placeholder(tf.float32, [None, self.l_goal], 'v_goal')
self.v_goal_others = tf.placeholder(tf.float32, [None, (self.n_agents-1)*self.l_goal], 'v_goal_others')
self.v_labels = tf.placeholder(tf.float32, [None, self.n_agents])
self.action_others = tf.placeholder(tf.float32, [None, self.n_agents-1, self.l_action], 'action_others')
self.action_one = tf.placeholder(tf.float32, [None, self.l_action], 'action_one')
if self.experiment == "checkers":
self.obs_self_t = tf.placeholder(tf.float32, [None, self.rows_obs, self.columns_obs, self.channels_obs], 'obs_self_t')
self.obs_self_v = tf.placeholder(tf.float32, [None, self.l_obs_self], 'obs_self_v')
self.obs_others = tf.placeholder(tf.float32, [None, self.l_obs_others], 'obs_others')
self.actions_prev = tf.placeholder(tf.float32, [None, self.l_action], 'action_prev')
# Actor network
self.epsilon = tf.placeholder(tf.float32, None, 'epsilon')
with tf.variable_scope("Policy_main"):
if self.experiment == 'checkers':
probs = networks.actor_checkers(self.actions_prev, self.obs_self_t, self.obs_self_v, self.obs_others, self.v_goal, f1=self.nn['A_conv_f'], k1=self.nn['A_conv_k'], n_h1=self.nn['A_n_h1'], n_h2=self.nn['A_n_h2'], n_actions=self.l_action, stage=stage)
# probs is normalized
self.probs = (1-self.epsilon) * probs + self.epsilon/float(self.l_action)
self.action_samples = tf.multinomial(tf.log(self.probs), 1)
with tf.variable_scope("Policy_target"):
if self.experiment == 'checkers':
probs_target = networks.actor_checkers(self.actions_prev, self.obs_self_t, self.obs_self_v, self.obs_others, self.v_goal, f1=self.nn['A_conv_f'], k1=self.nn['A_conv_k'], n_h1=self.nn['A_n_h1'], n_h2=self.nn['A_n_h2'], n_actions=self.l_action, stage=stage)
self.action_samples_target = tf.multinomial(tf.log( (1-self.epsilon)*probs_target + self.epsilon/float(self.l_action) ), 1)
# Q_n(s,\abf)
with tf.variable_scope("Q_global_main"):
if self.experiment == 'checkers':
self.Q_global = networks.Q_global_checkers(self.state_env, self.v_state_one_agent, self.v_goal, self.action_one, self.v_state_other_agents, self.action_others, self.obs_self_t, self.obs_self_v, f1=self.nn['Q_conv_f'], k1=self.nn['Q_conv_k'], n_h1_1=self.nn['Q_n_h1_1'], n_h1_2=self.nn['Q_n_h1_2'], n_h2=self.nn['Q_n_h2'], stage=stage)
with tf.variable_scope("Q_global_target"):
if self.experiment == 'checkers':
self.Q_global_target = networks.Q_global_checkers(self.state_env, self.v_state_one_agent, self.v_goal, self.action_one, self.v_state_other_agents, self.action_others, self.obs_self_t, self.obs_self_v, f1=self.nn['Q_conv_f'], k1=self.nn['Q_conv_k'], n_h1_1=self.nn['Q_n_h1_1'], n_h1_2=self.nn['Q_n_h1_2'], n_h2=self.nn['Q_n_h2'], stage=stage)
# Q_n(s,a^m)
if self.n_agents > 1 and self.use_Q_credit:
with tf.variable_scope("Q_credit_main"):
if self.experiment == 'checkers':
self.Q_credit = networks.Q_credit_checkers(self.state_env, self.v_state_one_agent, self.v_goal, self.action_one, self.v_state_m, self.v_state_other_agents, self.obs_self_t, self.obs_self_v, f1=self.nn['Q_conv_f'], k1=self.nn['Q_conv_k'], n_h1_1=self.nn['Q_n_h1_1'], n_h1_2=self.nn['Q_n_h1_2'], n_h2=self.nn['Q_n_h2'], stage=stage)
with tf.variable_scope("Q_credit_target"):
if self.experiment == 'checkers':
self.Q_credit_target = networks.Q_credit_checkers(self.state_env, self.v_state_one_agent, self.v_goal, self.action_one, self.v_state_m, self.v_state_other_agents, self.obs_self_t, self.obs_self_v, f1=self.nn['Q_conv_f'], k1=self.nn['Q_conv_k'], n_h1_1=self.nn['Q_n_h1_1'], n_h1_2=self.nn['Q_n_h1_2'], n_h2=self.nn['Q_n_h2'], stage=stage)
# V(s,g^n), used as ablation at stage 2
if self.n_agents > 1 and self.use_V:
with tf.variable_scope("V_main"):
self.V = networks.V_checkers_ablation(self.state_env, self.v_state_one_agent, self.v_goal, self.v_state_other_agents)
with tf.variable_scope("V_target"):
self.V_target = networks.V_checkers_ablation(self.state_env, self.v_state_one_agent, self.v_goal, self.v_state_other_agents)
def get_assign_target_ops(self, list_vars):
# ops for equating main and target
list_initial_ops = []
# ops for slow update of target toward main
list_update_ops = []
list_Q_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Q_global_main')
map_name_Q_main = {v.name.split('main')[1] : v for v in list_Q_main}
list_Q_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Q_global_target')
map_name_Q_target = {v.name.split('target')[1] : v for v in list_Q_target}
if len(list_Q_main) != len(list_Q_target):
raise ValueError("get_initialize_target_ops : lengths of Q_main and Q_target do not match")
for name, var in map_name_Q_main.items():
# create op that assigns value of main variable to target variable of the same name
list_initial_ops.append( map_name_Q_target[name].assign(var) )
for name, var in map_name_Q_main.items():
# incremental update of target towards main
list_update_ops.append( map_name_Q_target[name].assign( self.tau*var + (1-self.tau)*map_name_Q_target[name] ) )
# For policy
list_P_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Policy_main')
map_name_P_main = {v.name.split('main')[1] : v for v in list_P_main}
list_P_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Policy_target')
map_name_P_target = {v.name.split('target')[1] : v for v in list_P_target}
if len(list_P_main) != len(list_P_target):
raise ValueError("get_initialize_target_ops : lengths of P_main and P_target do not match")
for name, var in map_name_P_main.items():
# op that assigns value of main variable to target variable
list_initial_ops.append( map_name_P_target[name].assign(var) )
for name, var in map_name_P_main.items():
# incremental update of target towards main
list_update_ops.append( map_name_P_target[name].assign( self.tau*var + (1-self.tau)*map_name_P_target[name] ) )
# Repeat for Q_credit
if self.n_agents > 1 and self.use_Q_credit:
list_Qc_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Q_credit_main')
map_name_Qc_main = {v.name.split('main')[1] : v for v in list_Qc_main}
list_Qc_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Q_credit_target')
map_name_Qc_target = {v.name.split('target')[1] : v for v in list_Qc_target}
if len(list_Qc_main) != len(list_Qc_target):
raise ValueError("get_initialize_target_ops : lengths of Q_credit_main and Q_credit_target do not match")
for name, var in map_name_Qc_main.items():
# create op that assigns value of main variable to target variable of the same name
list_initial_ops.append( map_name_Qc_target[name].assign(var) )
for name, var in map_name_Qc_main.items():
# incremental update of target towards main
list_update_ops.append( map_name_Qc_target[name].assign( self.tau*var + (1-self.tau)*map_name_Qc_target[name] ) )
if self.n_agents > 1 and self.use_V:
list_V_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'V_main')
map_name_V_main = {v.name.split('main')[1] : v for v in list_V_main}
list_V_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'V_target')
map_name_V_target = {v.name.split('target')[1] : v for v in list_V_target}
if len(list_V_main) != len(list_V_target):
raise ValueError("get_initialize_target_ops : lengths of V_main and V_target do not match")
for name, var in map_name_V_main.items():
# create op that assigns value of main variable to target variable of the same name
list_initial_ops.append( map_name_V_target[name].assign(var) )
for name, var in map_name_V_main.items():
# incremental update of target towards main
list_update_ops.append( map_name_V_target[name].assign( self.tau*var + (1-self.tau)*map_name_V_target[name] ) )
return list_initial_ops, list_update_ops
def get_assign_global_to_credit_ops(self):
"""Get ops that assign value of Q_global network to Q_credit network.
To be used at the start of Stage 2, after Q_global network has been initialized
with the Stage 1 weights
"""
list_update_ops = []
list_Q_global = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Q_global_main')
map_name_Q_global = {v.name.split('main')[1] : v for v in list_Q_global}
list_Q_credit = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Q_credit_main')
map_name_Q_credit = {v.name.split('main')[1] : v for v in list_Q_credit}
if len(list_Q_global) != len(list_Q_credit):
raise ValueError("get_assign_global_to_credit_ops : lengths of Q_global and Q_credit do not match")
for name, var in map_name_Q_global.items():
list_split = name.split('/')
if ('stage-2' not in list_split):
# op that assigns value of Q_global variable to Q_credit variable of the same name
list_update_ops.append( map_name_Q_credit[name].assign(var) )
return list_update_ops
def run_actor(self, actions_prev, obs_others, obs_self_t, obs_self_v, goals, epsilon, sess):
"""Get actions for all agents as a batch
Args:
actions_prev: list of integers
obs_others: list of vector or tensor describing other agents
obs_self_t: list of observation grid centered on self
obs_self_v: list of 1D observation vectors
goals: [n_agents, n_lanes]
epsilon: float
sess: TF session
"""
# convert to batch
obs_others = np.array(obs_others)
obs_self_t = np.array(obs_self_t)
obs_self_v = np.array(obs_self_v)
actions_prev_1hot = np.zeros([self.n_agents, self.l_action])
actions_prev_1hot[np.arange(self.n_agents), actions_prev] = 1
feed = {self.obs_others:obs_others, self.obs_self_t:obs_self_t,
self.obs_self_v:obs_self_v, self.v_goal:goals,
self.actions_prev: actions_prev_1hot, self.epsilon:epsilon}
action_samples_res = sess.run(self.action_samples, feed_dict=feed)
return np.reshape(action_samples_res, action_samples_res.shape[0])
def run_actor_target(self, actions_prev, obs_others, obs_self_t, obs_self_v, goals, epsilon, sess):
"""Gets actions from the slowly-updating policy."""
feed = {self.obs_others:obs_others, self.obs_self_t:obs_self_t,
self.obs_self_v:obs_self_v, self.v_goal:goals,
self.actions_prev: actions_prev, self.epsilon:epsilon}
action_samples_res = sess.run(self.action_samples_target, feed_dict=feed)
return np.reshape(action_samples_res, action_samples_res.shape[0])
def create_Q_credit_train_op(self):
# TD target calculated in train_step() using V_target
self.Q_credit_td_target= tf.placeholder(tf.float32, [None], 'Q_credit_td_target')
# Q_credit network has only one output
self.loss_Q_credit = tf.reduce_mean(tf.square(self.Q_credit_td_target - tf.squeeze(self.Q_credit)))
self.Q_credit_opt = tf.train.AdamOptimizer(self.lr_Q)
self.Q_credit_op = self.Q_credit_opt.minimize(self.loss_Q_credit)
def create_Q_global_train_op(self):
# TD target calculated in train_step() using Q_target
self.Q_global_td_target = tf.placeholder(tf.float32, [None], 'Q_global_td_target')
# Q_global network has only one output
self.loss_Q_global = tf.reduce_mean(tf.square(self.Q_global_td_target - tf.squeeze(self.Q_global)))
self.Q_global_opt = tf.train.AdamOptimizer(self.lr_Q)
self.Q_global_op = self.Q_global_opt.minimize(self.loss_Q_global)
def create_V_train_op(self):
self.V_td_target = tf.placeholder(tf.float32, [None], 'V_td_target')
self.loss_V = tf.reduce_mean(tf.square(self.V_td_target - tf.squeeze(self.V)))
self.V_opt = tf.train.AdamOptimizer(self.lr_V)
self.V_op = self.V_opt.minimize(self.loss_V)
def create_policy_gradient_op(self):
# batch of 1-hot action vectors
self.action_taken = tf.placeholder(tf.float32, [None, self.l_action], 'action_taken')
# self.probs has shape [batch, l_action]
log_probs = tf.log(tf.reduce_sum(tf.multiply(self.probs, self.action_taken), axis=1)+1e-15)
# if stage==2, must be [batch*n_agents, n_agents], consecutive <n_agents> rows are same
self.Q_actual = tf.placeholder(tf.float32, [None, self.n_agents], 'Q_actual')
# First dim is n_agents^2 * batch;
# If n_agents=1, first dim is batch; second dim is l_action
# For <n_agents> > 1, the rows are Q_1(s,a^1),...,Q_N(s,a^1),Q_1(s,a^2),...,Q_N(s,a^2), ... , Q_1(s,a^N),...,Q_N(s,a^N)
# where each row contains <l_action> Q-values, one for each possible action
# Note that all Q networks have only one output, and the <l_action> dimension is due to evaluating all possible actions before feeding in feed_dict
self.Q_cf = tf.placeholder(tf.float32, [None, self.l_action], 'Q_cf')
# First dim is n_agents^2 * batch;
# If n_agents=1, first dim is batch; second dim is l_action
self.probs_evaluated = tf.placeholder(tf.float32, [None, self.l_action])
if self.n_agents == 1:
advantage2 = tf.reduce_sum(tf.multiply(self.Q_cf, self.probs_evaluated), axis=1)
advantage = tf.subtract(tf.squeeze(self.Q_actual), advantage2)
self.policy_loss = -tf.reduce_mean( tf.multiply(log_probs, advantage) )
else:
if self.use_Q_credit:
# For the general case of any number of agents (covers n_agents==1)
pi_mult_Q = tf.multiply( self.probs_evaluated, self.Q_cf )
# [batch*n_agents, n_agents]
counterfactuals = tf.reshape( tf.reduce_sum(pi_mult_Q, axis=1), [-1,self.n_agents] )
# [batch*n_agents, n_agents], each block of nxn is matrix A_{mn} at one time step
advantages = tf.subtract(self.Q_actual, counterfactuals)
# [batch, n_agents]
sum_n_A = tf.reshape( tf.reduce_sum(advantages, axis=1), [-1, self.n_agents] )
elif self.use_V:
self.V_evaluated = tf.placeholder(tf.float32, [None, self.n_agents], 'V_evaluated')
advantages = tf.subtract(self.Q_actual, self.V_evaluated)
sum_n_A = tf.reshape( tf.reduce_sum(advantages, axis=1), [-1, self.n_agents] )
else:
sum_n_A = tf.reshape( tf.reduce_sum(self.Q_actual, axis=1), [-1, self.n_agents] )
log_probs_shaped = tf.reshape(log_probs, [-1, self.n_agents]) # [batch, n_agents]
m_terms = tf.multiply( log_probs_shaped, sum_n_A ) # [batch, n_agents]
self.policy_loss = -tf.reduce_mean( tf.reduce_sum(m_terms, axis=1) )
self.policy_opt = tf.train.AdamOptimizer(self.lr_actor)
self.policy_op = self.policy_opt.minimize(self.policy_loss)
def create_summary(self):
summaries_Q_global = [tf.summary.scalar('loss_Q_global', self.loss_Q_global)]
Q_global_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Q_global_main')
for v in Q_global_variables:
summaries_Q_global.append( tf.summary.histogram(v.op.name, v) )
grads = self.Q_global_opt.compute_gradients(self.loss_Q_global, Q_global_variables)
for grad, var in grads:
if grad is not None:
summaries_Q_global.append( tf.summary.histogram(var.op.name+'/gradient', grad) )
self.summary_op_Q_global = tf.summary.merge(summaries_Q_global)
if self.n_agents > 1 and self.use_Q_credit:
summaries_Q_credit = [tf.summary.scalar('loss_Q_credit', self.loss_Q_credit)]
Q_credit_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Q_credit_main')
for v in Q_credit_variables:
summaries_Q_credit.append( tf.summary.histogram(v.op.name, v) )
grads = self.Q_credit_opt.compute_gradients(self.loss_Q_credit, Q_credit_variables)
for grad, var in grads:
if grad is not None:
summaries_Q_credit.append( tf.summary.histogram(var.op.name+'/gradient', grad) )
self.summary_op_Q_credit = tf.summary.merge(summaries_Q_credit)
elif self.n_agents > 1 and self.use_V:
summaries_V = [tf.summary.scalar('loss_V', self.loss_V)]
V_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'V_main')
for v in V_variables:
summaries_V.append( tf.summary.histogram(v.op.name, v) )
grads = self.V_opt.compute_gradients(self.loss_V, V_variables)
for grad, var in grads:
if grad is not None:
summaries_V.append( tf.summary.histogram(var.op.name+'/gradient', grad) )
self.summary_op_V = tf.summary.merge(summaries_V)
summaries_policy = [tf.summary.scalar('policy_loss', self.policy_loss)]
policy_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Policy_main')
for v in policy_variables:
summaries_policy.append(tf.summary.histogram(v.op.name, v))
grads = self.policy_opt.compute_gradients(self.policy_loss, policy_variables)
for grad, var in grads:
if grad is not None:
summaries_policy.append( tf.summary.histogram(var.op.name+'/gradient', grad) )
self.summary_op_policy = tf.summary.merge(summaries_policy)
def process_actions(self, n_steps, actions):
"""Reformats actions for better matrix computation.
Args:
n_steps: int
actions: np.array shape [time, agents], values are action indices
Returns
1. actions_1hot [n_agents * n_steps, l_action] : each row is
action taken by one agent at one time step
2. actions_others_1hot [n_agents * n_steps, n_agents-1, l_action] :
each row is for one agent at one time step, containing all
(n-1) other agents' actions
"""
# Each row of actions is one time step,
# row contains action indices for all agents
# Convert to [time, agents, l_action]
# so each agent gets its own 1-hot row vector
actions_1hot = np.zeros([n_steps, self.n_agents, self.l_action], dtype=int)
grid = np.indices((n_steps, self.n_agents))
actions_1hot[grid[0], grid[1], actions] = 1
# Convert to format [time*agents, agents-1, l_action]
# so that the set of <n_agent> actions at each time step
# is duplicated <n_agent> times, and each duplicate
# now contains all <n_agent>-1 actions representing
# the OTHER agents actions
list_to_interleave = []
for n in range(self.n_agents):
# extract all actions except agent n's action
list_to_interleave.append( actions_1hot[:, np.arange(self.n_agents)!=n, :] )
# interleave
actions_others_1hot = np.zeros([self.n_agents*n_steps, self.n_agents-1, self.l_action])
for n in range(self.n_agents):
actions_others_1hot[n::self.n_agents, :, :] = list_to_interleave[n]
# In-place reshape of actions to [time*n_agents, l_action]
actions_1hot.shape = (n_steps*self.n_agents, self.l_action)
return actions_1hot, actions_others_1hot
def process_batch(self, batch):
"""Extract quantities of the same type from batch.
Formats batch so that each agent at each time step is one batch entry.
Duplicate global quantities <n_agents> times to be
compatible with this scheme.
Args:
batch: a large np.array containing a batch of transitions.
Returns many np.arrays
"""
# shapes are [time, ...original dims...]
state_env = np.stack(batch[:,0]) # [time, grid]
state_agents = np.stack(batch[:,1]) # [time, agents, l_state_one_agent]
# note that *_local objects have shape
# [time, agents, ...original dim...]
obs_others = np.stack(batch[:,2]) # [time,agents,h,w,c] or [time, agents, obs_others]
obs_self_t = np.stack(batch[:,3]) # [time,agents,row,column,channel]
obs_self_v = np.stack(batch[:,4]) # [time,agents,l_obs_self]
actions_prev = np.stack(batch[:,5])
actions = np.stack(batch[:,6]) # [time,agents]
reward = np.stack(batch[:,7]) # [time]
reward_local = np.stack(batch[:,8]) # [time,agents]
state_env_next = np.stack(batch[:,9]) # [time, grid]
state_agents_next = np.stack(batch[:,10]) # [time, agents, l_state_one_agent]
obs_others_next = np.stack(batch[:,11]) # [time,agents,h,w,c]
obs_self_t_next = np.stack(batch[:,12]) # [time,agents,row,column,channel]
obs_self_v_next = np.stack(batch[:,13]) # [time,agents,l_obs_self]
done = np.stack(batch[:,14]) # [time]
goals = np.stack(batch[:,15]) # [time, agents, l_goal]
# Try to free memory
batch = None
n_steps = state_agents.shape[0]
# For all global quantities, for each time step,
# duplicate values <n_agents> times for
# batch processing of all agents
state_env = np.repeat(state_env, self.n_agents, axis=0)
state_env_next = np.repeat(state_env_next, self.n_agents, axis=0)
done = np.repeat(done, self.n_agents, axis=0)
# In-place reshape for *_local quantities,
# so that one time step for one agent is considered
# one batch entry
if self.experiment == 'checkers':
obs_others.shape = (n_steps*self.n_agents, self.l_obs_others)
obs_others_next.shape = (n_steps*self.n_agents, self.l_obs_others)
obs_self_t.shape = (n_steps*self.n_agents, self.rows_obs, self.columns_obs, self.channels_obs)
obs_self_t_next.shape = (n_steps*self.n_agents, self.rows_obs, self.columns_obs, self.channels_obs)
obs_self_v.shape = (n_steps*self.n_agents, self.l_obs_self)
obs_self_v_next.shape = (n_steps*self.n_agents, self.l_obs_self)
reward_local.shape = (n_steps*self.n_agents)
actions_1hot, actions_others_1hot = self.process_actions(n_steps, actions)
actions_prev_1hot = np.zeros([n_steps, self.n_agents, self.l_action], dtype=int)
grid = np.indices((n_steps, self.n_agents))
actions_prev_1hot[grid[0], grid[1], actions_prev] = 1
actions_prev_1hot.shape = (n_steps*self.n_agents, self.l_action)
return n_steps, state_env, state_agents, obs_others, obs_self_t, obs_self_v, actions_prev_1hot, actions_1hot, actions_others_1hot, reward, reward_local, state_env_next, state_agents_next, obs_others_next, obs_self_t_next, obs_self_v_next, done, goals
def process_goals(self, goals, n_steps):
"""Reformats goals for better matrix computation.
Args:
goals: np.array with shape [batch, n_agents, l_goal]
Returns: two np.arrays
1. [n_agents * n_steps, l_goal] : each row is goal for one
agent, block of <n_agents> rows belong to one sampled transition from batch
2. [n_agents * n_steps, (n_agents-1)*l_goal] : each row is
the goals of all OTHER agents, as a single row vector. Block of
<n_agents> rows belong to one sampled transition from batch
"""
# Reshape so that one time step for one agent is one batch entry
goals_self = np.reshape(goals, (n_steps*self.n_agents, self.l_goal))
goals_others = np.zeros((n_steps*self.n_agents, self.n_agents-1, self.l_goal))
for n in range(self.n_agents):
goals_others[n::self.n_agents, :, :] = goals[:, np.arange(self.n_agents)!=n, :]
# Reshape to be [n_agents * n_steps, (n_agents-1)*l_goal]
goals_others.shape = (n_steps*self.n_agents, (self.n_agents-1)*self.l_goal)
return goals_self, goals_others
def process_global_state(self, v_global, n_steps):
"""Reformats global state for more efficient computation of the gradient.
Args:
v_global: has shape [n_steps, n_agents, l_state_one_agent]
n_steps: int
Returns: three streams
1. [n_agents * n_steps, l_state_one_agent] : each row is state of one agent,
and a block of <n_agents> rows belong to one sampled transition from batch
2. [n_agents * n_steps, l_state_other_agents] : each row is the state of all
OTHER agents, as a single row vector. A block of <n_agents> rows belong to one
sampled transition from batch
3. [n_steps*n_agents, n_agents*l_state] : each row is concatenation of state of all agents
For each time step, the row is duplicated <n_agents> times, since the same state s is used
in <n_agents> different evaluations of Q(s,a^{-n},a^n)
"""
# Reshape into 2D, each block of <n_agents> rows correspond to one time step
v_global_one_agent = np.reshape(v_global, (n_steps*self.n_agents, self.l_state_one_agent))
v_global_others = np.zeros((n_steps*self.n_agents, self.n_agents-1, self.l_state_one_agent))
for n in range(self.n_agents):
v_global_others[n::self.n_agents, :, :] = v_global[:, np.arange(self.n_agents)!=n, :]
# Reshape into 2D, each row is state of all other agents, each block of
# <n_agents> rows correspond to one time step
v_global_others.shape = (n_steps*self.n_agents, (self.n_agents-1)*self.l_state_one_agent)
v_global_concated = np.reshape(v_global, (n_steps, self.l_state))
state = np.repeat(v_global_concated, self.n_agents, axis=0)
return v_global_one_agent, v_global_others, state
def train_step(self, sess, batch, epsilon, idx_train,
summarize=False, writer=None):
"""Main training step."""
# Each agent for each time step is now a batch entry
n_steps, state_env, state_agents, obs_others, obs_self_t, obs_self_v, actions_prev_1hot, actions_1hot, actions_others_1hot, reward, reward_local, state_env_next, state_agents_next, obs_others_next, obs_self_t_next, obs_self_v_next, done, goals = self.process_batch(batch)
goals_self, goals_others = self.process_goals(goals, n_steps)
v_global_one_agent, v_global_others, state = self.process_global_state(state_agents, n_steps)
v_global_one_agent_next, v_global_others_next, state_next = self.process_global_state(state_agents_next, n_steps)
# ------------ Train Q^{\pibf}_n(s,\abf) --------------- #
# ------------------------------------------------------ #
# Need a_{t+1} for all agents to evaluate TD target for Q
# actions is single dimension [n_steps*n_agents]
actions = self.run_actor_target(actions_1hot, obs_others_next, obs_self_t_next, obs_self_v_next, goals_self, epsilon, sess)
# Now each row is one time step, containing action
# indices for all agents
actions_r = np.reshape(actions, [n_steps, self.n_agents])
actions_self_next, actions_others_next = self.process_actions(n_steps, actions_r)
# Get target Q_n(s',\abf')
feed = {self.state_env : state_env_next,
self.v_state_one_agent : v_global_one_agent_next,
self.v_goal : goals_self,
self.action_one : actions_self_next,
self.v_state_other_agents : v_global_others_next,
self.action_others : actions_others_next,
self.obs_self_t : obs_self_t_next,
self.obs_self_v : obs_self_v_next}
Q_global_target_res = np.squeeze(sess.run(self.Q_global_target, feed_dict=feed))
# if true, then 0, else 1
done_multiplier = -(done - 1)
Q_global_td_target = reward_local + self.gamma * Q_global_target_res * done_multiplier
# Run optimizer
feed = {self.Q_global_td_target : Q_global_td_target,
self.state_env : state_env,
self.v_state_one_agent : v_global_one_agent,
self.v_goal : goals_self,
self.action_one : actions_1hot,
self.v_state_other_agents : v_global_others,
self.action_others : actions_others_1hot,
self.obs_self_t : obs_self_t,
self.obs_self_v : obs_self_v}
if summarize:
# Get Q_global_res = Q_n(s,\abf) for use later in policy gradient
summary, _, Q_global_res = sess.run([self.summary_op_Q_global, self.Q_global_op, self.Q_global], feed_dict=feed)
writer.add_summary(summary, idx_train)
else:
_, Q_global_res = sess.run([self.Q_global_op, self.Q_global], feed_dict=feed)
# For feeding into Q_actual
Q_global_res_rep = np.repeat(np.reshape(Q_global_res, [n_steps, self.n_agents]), self.n_agents, axis=0)
# ----------- Train Q^{\pibf}_n(s,a^m) -------------- #
# --------------------------------------------------- #
if self.n_agents > 1 and self.use_Q_credit:
# When going down rows, n is the inner index and m is the outer index
# Repeat the things indexed by n, so that the group of n_agents rows
# at each time step is repeated n_agent times
s_n_next_rep = np.reshape(np.repeat(np.reshape(v_global_one_agent_next, [-1, self.n_agents*self.l_state_one_agent]), self.n_agents, axis=0), [-1, self.l_state_one_agent])
s_others_next_rep = np.reshape(np.repeat(np.reshape(v_global_others_next, [-1, self.n_agents*self.l_state_other_agents]), self.n_agents, axis=0), [-1, self.l_state_other_agents])
goals_self_rep = np.reshape(np.repeat(np.reshape(goals_self, [-1, self.n_agents*self.l_goal]), self.n_agents, axis=0), [-1, self.l_goal])
# Duplicate the things indexed by m so that consecutive n_agents rows are the same (so that when summing over n, they are the same)
actions_self_next_rep = np.repeat(actions_self_next, self.n_agents, axis=0)
s_m_next_rep = np.repeat(v_global_one_agent_next, self.n_agents, axis=0)
obs_self_t_next_rep = np.repeat(obs_self_t_next, self.n_agents, axis=0)
obs_self_v_next_rep = np.repeat(obs_self_v_next, self.n_agents, axis=0)
# Duplicate shared state
s_env_next_rep = np.repeat(state_env_next, self.n_agents, axis=0)
# Get target Q_n(s',a'^m)
feed = {self.state_env : s_env_next_rep,
self.v_state_one_agent : s_n_next_rep,
self.v_goal : goals_self_rep,
self.action_one : actions_self_next_rep,
self.v_state_m : s_m_next_rep,
self.v_state_other_agents : s_others_next_rep,
self.obs_self_t : obs_self_t_next_rep,
self.obs_self_v : obs_self_v_next_rep}
Q_credit_target_res = np.squeeze(sess.run(self.Q_credit_target, feed_dict=feed))
# reward_local is n_steps*n_agents
# Duplicate into n_steps*n_agents*n_agents so that each time step is
# [r^1,r^2,r^3,r^4,...,r^1,r^2,r^3,r^4] (assume N=4)
# Now n_steps*n_agents*n_agents
reward_local_rep = np.reshape(np.repeat(np.reshape(reward_local, [-1, self.n_agents*1]), self.n_agents, axis=0), [-1])
done_rep = np.reshape(np.repeat(np.reshape(done, [-1, self.n_agents*1]), self.n_agents, axis=0), [-1])
# if true, then 0, else 1
done_multiplier = -(done_rep - 1)
Q_credit_td_target = reward_local_rep + self.gamma * Q_credit_target_res*done_multiplier
# Duplicate the things indexed by n
s_n_rep = np.reshape(np.repeat(np.reshape(v_global_one_agent, [-1, self.n_agents*self.l_state_one_agent]), self.n_agents, axis=0), [-1, self.l_state_one_agent])
s_others_rep = np.reshape(np.repeat(np.reshape(v_global_others, [-1, self.n_agents*self.l_state_other_agents]), self.n_agents, axis=0), [-1, self.l_state_other_agents])
# Duplicate the things indexed by m
actions_self_rep = np.repeat(actions_1hot, self.n_agents, axis=0)
s_m_rep = np.repeat(v_global_one_agent, self.n_agents, axis=0)
obs_self_t_rep = np.repeat(obs_self_t, self.n_agents, axis=0)
obs_self_v_rep = np.repeat(obs_self_v, self.n_agents, axis=0)
# Duplicate shared state
s_env_rep = np.repeat(state_env, self.n_agents, axis=0)
feed = {self.Q_credit_td_target : Q_credit_td_target,
self.state_env : s_env_rep,
self.v_state_one_agent : s_n_rep,
self.v_goal : goals_self_rep,
self.action_one : actions_self_rep,
self.v_state_m : s_m_rep,
self.v_state_other_agents : s_others_rep,
self.obs_self_t : obs_self_t_rep,
self.obs_self_v : obs_self_v_rep}
# Run optimizer for global critic
if summarize:
summary, _ = sess.run([self.summary_op_Q_credit, self.Q_credit_op], feed_dict=feed)
writer.add_summary(summary, idx_train)
else:
_ = sess.run(self.Q_credit_op, feed_dict=feed)
if self.n_agents > 1 and self.use_V:
# Get target V_n(s')
feed = {self.state_env : state_env_next,
self.v_state_one_agent : v_global_one_agent_next,
self.v_goal : goals_self,
self.v_state_other_agents : v_global_others_next}
V_target_res = np.squeeze(sess.run(self.V_target, feed_dict=feed))
# if true, then 0, else 1
done_multiplier = -(done - 1)
V_td_target = reward_local + self.gamma * V_target_res * done_multiplier
# Run optimizer
feed = {self.V_td_target : V_td_target,
self.state_env : state_env,
self.v_state_one_agent : v_global_one_agent,
self.v_goal : goals_self,
self.v_state_other_agents : v_global_others}
if summarize:
# Get V_res = V_n(s) for use later in policy gradient
summary, _, V_res = sess.run([self.summary_op_V, self.V_op, self.V], feed_dict=feed)
writer.add_summary(summary, idx_train)
else:
_, V_res = sess.run([self.V_op, self.V], feed_dict=feed)
# For feeding into advantage function
V_res_rep = np.repeat(np.reshape(V_res, [n_steps, self.n_agents]), self.n_agents, axis=0)
# --------------- Train policy ------------- #
# ------------------------------------------ #
if self.n_agents == 1:
# Stage 1
feed = {self.obs_others : obs_others,
self.obs_self_t : obs_self_t,
self.obs_self_v : obs_self_v,
self.actions_prev : actions_prev_1hot,
self.v_goal : goals_self,
self.epsilon : epsilon}
probs_res = sess.run(self.probs, feed_dict=feed)
# compute Q(s,a=all possible,g)
s_env_rep = np.repeat(state_env, self.l_action, axis=0)
s_rep = np.repeat(v_global_one_agent, self.l_action, axis=0)
goals_self_rep = np.repeat(goals_self, self.l_action, axis=0)
obs_self_t_rep = np.repeat(obs_self_t, self.l_action, axis=0)
obs_self_v_rep = np.repeat(obs_self_v, self.l_action, axis=0)
actions_cf = np.tile(self.actions, (n_steps, 1))
feed = {self.state_env : s_env_rep,
self.v_state_one_agent : s_rep,
self.v_goal : goals_self_rep,
self.action_one : actions_cf,
self.v_state_other_agents : v_global_others, # not used
self.action_others : actions_others_1hot,
self.obs_self_t : obs_self_t_rep,
self.obs_self_v : obs_self_v_rep}
Q_cf = sess.run(self.Q_global, feed_dict=feed)
Q_cf.shape = (n_steps, self.l_action)
else:
if self.use_Q_credit:
# Compute values for probs_evaluated
feed = {self.obs_others : obs_others,
self.obs_self_t : obs_self_t,
self.obs_self_v : obs_self_v,
self.actions_prev : actions_prev_1hot,
self.v_goal : goals_self,
self.epsilon : epsilon}
probs_res = sess.run(self.probs, feed_dict=feed)
probs_res = np.repeat(probs_res, self.n_agents, axis=0)
# Duplicate everything by number of possible actions, to prepare for batch
# computation of counterfactuals
s_n_rep = np.repeat(s_n_rep, self.l_action, axis=0)
goals_self_rep = np.repeat(goals_self_rep, self.l_action, axis=0)
s_m_rep = np.repeat(s_m_rep, self.l_action, axis=0)
s_others_rep = np.repeat(s_others_rep, self.l_action, axis=0)
s_env_rep = np.repeat(s_env_rep, self.l_action, axis=0)
obs_self_t_rep = np.repeat(obs_self_t_rep, self.l_action, axis=0)
obs_self_v_rep = np.repeat(obs_self_v_rep, self.l_action, axis=0)
# Counterfactual actions
actions_cf = np.tile(self.actions, (self.n_agents*self.n_agents*n_steps,1))
# Compute Q_n(s,a^m) for all n and m and all actions a^m=i, for all steps
feed = {self.state_env : s_env_rep,
self.v_state_one_agent : s_n_rep,
self.v_goal : goals_self_rep,
self.action_one : actions_cf,
self.v_state_m : s_m_rep,
self.v_state_other_agents : s_others_rep,
self.obs_self_t : obs_self_t_rep,
self.obs_self_v : obs_self_v_rep}
Q_cf = sess.run(self.Q_credit, feed_dict=feed) # n_steps * n_agents^2 * l_action
Q_cf.shape = (n_steps*self.n_agents*self.n_agents, self.l_action)
else:
# probs_res and Q_cf just need to have dimension [anything, l_action]
# They are not used in this case
probs_res = np.zeros([1,self.l_action])
Q_cf = np.zeros([1,self.l_action])
feed = {self.obs_others : obs_others,
self.obs_self_t : obs_self_t,
self.obs_self_v : obs_self_v,
self.actions_prev : actions_prev_1hot,
self.v_goal : goals_self,
self.epsilon : epsilon,
self.action_taken : actions_1hot,
self.Q_actual : Q_global_res_rep,
self.probs_evaluated : probs_res,
self.Q_cf : Q_cf}
if self.n_agents > 1 and self.use_V:
feed[self.V_evaluated] = V_res_rep
if summarize:
summary, _ = sess.run([self.summary_op_policy, self.policy_op], feed_dict=feed)
writer.add_summary(summary, idx_train)
else:
_ = sess.run(self.policy_op, feed_dict=feed)
sess.run(self.list_update_target_ops)
```
#### File: cm3/alg/train_onpolicyJon.py
```python
import tensorflow.compat.v1 as tf
import numpy as np
import sys, os
sys.path.append('../')
import json
import time
import random
import alg_creditJon as alg_credit
import alg_credit_checkers
import alg_baseline
import alg_baseline_checkers
import evaluate
import replay_buffer
import replay_buffer_dual
# Particle
from env.multiagentParticleEnvs.multiagent.environment import MultiAgentEnv
import env.multiagentParticleEnvs.multiagent.scenarios as scenarios
#UE
from env.multiagentParticleEnvs.multiagent.environment_sub import MultiSubUEEnv
def train_function(config):
# ----------- Alg parameters ----------------- #
experiment = config['experiment']
if experiment == "particle":
scenario_name = config['scenario']
seed = config['seed']
np.random.seed(seed)
random.seed(seed)
# Curriculum stage
stage = config['stage']
port = config['port']
dir_name = config['dir_name']
dir_restore = config['dir_restore']
use_alg_credit = config['use_alg_credit']
use_Q_credit = config['use_Q_credit']
# If 1, then uses Q-net and global reward
use_Q = config['use_Q']
use_V = config['use_V']
dimensions = config['dimensions_particle']
# If 1, then restores variables from same stage
restore_same_stage = config['restore_same_stage']
# If 1, then does not restore variables, even if stage > 1
train_from_nothing = config['train_from_nothing']
# Name of model to restore
model_name = config['model_name']
# Total number of training episodes
N_train = config['N_train']
period = config['period']
# Number of evaluation episodes to run every <period>
N_eval = config['N_eval']
summarize = config['summarize']
alpha = config['alpha']
lr_Q = config['lr_Q']
lr_V = config['lr_V']
lr_actor = config['lr_actor']
dual_buffer = config['dual_buffer']
buffer_size = config['buffer_size']
threshold = config['threshold']
batch_size = config['batch_size']
pretrain_episodes = config['pretrain_episodes']
steps_per_train = config['steps_per_train']
max_steps = config['max_steps']
episodes_per_train = config['episodes_per_train']
epochs = config['epochs']
# Probability of using random configuration
prob_random = config['prob_random']
epsilon_start = config['epsilon_start']
epsilon_end = config['epsilon_end']
epsilon_div = config['epsilon_div'] / episodes_per_train
epsilon_step = 2.0/ (N_train)
epsilon_step = (epsilon_start - epsilon_end)/float(epsilon_div)
with open(config["particle_config"]) as f:
config_particle = json.load(f)
#n_agents = config_particle['n_agents']
#scenario = scenarios.load(scenario_name + ".py").Scenario()
#world = scenario.make_world(n_agents, config_particle, prob_random)
n_subChans = int(4)
if(stage) == 1:
n_agents = int(1)
env = MultiSubUEEnv(n_agents,n_subChans,3)
else:
n_agents = int(4)
env = MultiSubUEEnv(n_agents,n_subChans)
#env = MultiSubUEEnv(n_agents,n_subChans,5)
## this is where the enviroment is made
#env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation, None, scenario.done, max_steps=max_steps)
#env = MultiSubUEEnv(n_agents,n_subChans,4)
l_action = env.call_action_dim()
l_state = env.call_state_dim()
l_global = env.call_global_dim()
l_goal = 1
# Create entire computational graph
# Creation of new trainable variables for new curriculum
# stage is handled by networks.py, given the stage number
if use_alg_credit:
alg = alg_credit.Alg(experiment, l_action, l_global, l_goal, l_state, stage, n_agents, lr_V=lr_V, lr_Q=lr_Q, lr_actor=lr_actor, use_Q_credit=use_Q_credit, use_V=use_V, nn=config['nn'])
else:
alg = alg_baseline.Alg(experiment, l_action,l_state, stage, n_agents, lr_V=lr_V, lr_Q=lr_Q, lr_actor=lr_actor, use_Q=use_Q, use_V=use_V, alpha=alpha, nn=config['nn'], IAC=config['IAC'])
print("Initialized computational graph")
list_variables = tf.trainable_variables()
if stage == 1 or restore_same_stage or train_from_nothing:
saver = tf.train.Saver()
elif stage == 2:
to_restore = []
for v in list_variables:
list_split = v.name.split('/')
if ('stage-%d'%stage not in list_split) and ('Policy_target' not in list_split) and ('Q_credit_main' not in list_split) and ('Q_credit_target' not in list_split):
to_restore.append(v)
saver = tf.train.Saver(to_restore)
else:
# restore only those variables that were not
# just created at this curriculum stage
to_restore = [v for v in list_variables if 'stage-%d'%stage not in v.name.split('/')]
saver = tf.train.Saver(to_restore)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.set_random_seed(seed)
sess = tf.Session(config=config)
writer = tf.summary.FileWriter('../saved/%s' % dir_name, sess.graph)
sess.run(tf.global_variables_initializer())
print("Initialized variables")
if train_from_nothing == 0:
print("Restoring variables from %s" % dir_restore)
#C:\Users\gasma\Documents\GitHub\cm3\completedModels\6x6_6global
#saver.restore(sess, '../saved/%s/%s' % (dir_restore, model_name))
saver.restore(sess, 'C:/Users/gasma/Documents/GitHub/cm3/completedModels/4x4-stage1/%s' % (model_name))
if stage == 2 and use_alg_credit and use_Q_credit:
# Copy weights of Q_global to Q_credit at the start of Stage 2
sess.run(alg.list_initialize_credit_ops)
for var in list_variables:
if var.name == 'Q_global_main/Q_branch1/kernel:0':
print("Q_global")
print(sess.run(var))
print("")
if var.name == 'Q_credit_main/Q_branch1/kernel:0':
print("Q_credit")
print(sess.run(var))
print("")
# initialize target networks to equal main networks
sess.run(alg.list_initialize_target_ops)
# save everything without exclusion
saver = tf.train.Saver(max_to_keep=None)
epsilon = epsilon_start
# For computing average over 100 episodes
reward_local_century = np.zeros(n_agents)
reward_global_century = 0
# Write log headers
header = "Step,Episode,r_global"
header_c = "Step,Century,r_global_avg"
for idx in range(n_agents):
header += ',r_%d' % idx
header_c += ',r_avg_%d' % idx
header_c += ",r_global_eval"
for idx in range(n_agents):
header_c += ',r_eval_%d' % idx
header_c += ',r_eval_local,t_env (s),t_train(s)'
header += '\n'
header_c += '\n'
if not os.path.exists('../log/%s' % dir_name):
os.makedirs('../log/%s' % dir_name)
with open('../log/%s/log.csv' % dir_name, 'w') as f:
f.write(header)
with open('../log/%s/log_century.csv' % dir_name, 'w') as f:
f.write(header_c)
if dual_buffer:
buf = replay_buffer_dual.Replay_Buffer(size=buffer_size)
num_good = 0
num_bad = 0
else:
buf = replay_buffer.Replay_Buffer(size=buffer_size)
t_env = 0
t_train = 0
dist_action = np.zeros(l_action)
step = 0
successes = 0
# Each iteration is a training episode
step = 0
episode = 0
episodeSince = 0
total_reward = 0
totalTime = 0
evaluateStep = 0
updated = 0
start_time = time.time()
for idx_episode in range(1, N_train+1):
episode += 1
ep_step = 0
actions = np.random.randint(0, l_action, n_agents)
global_state, local_others, local_self,goals,done = env.reset()
oneStep = True
#goals = np.eye([n_agents])
reward_global = 0
reward_local = np.zeros(n_agents)
if dual_buffer:
buf_episode = []
# this is the traning loop
while oneStep:
step += 1
ep_step += 1
episodeSince += 1
updated += 1
sys.stderr.write('\r%d / %d ' % (episodeSince, period))
sys.stderr.flush()
oneStep = False
t_env_start = time.time()
if idx_episode < pretrain_episodes and (stage == 1 or train_from_nothing == 1):
# Random actions when filling replay buffer
actions = np.random.randint(0, l_action, n_agents)
else:
# Run actor network for all agents as batch
actions = []
randomNumbers = np.random.uniform(0,1,n_agents)
a = alg.run_actor(local_others, local_self, goals, 0, sess)
for i in range(n_agents):
if(randomNumbers[i] <= epsilon):
action = np.random.choice(l_action)
actions.append(action)
else:
actions.append(a[i])
dist_action[actions[0]] += 1
# step environment
next_global_state, next_local_others, next_local_self, reward, local_rewards, done = env.step(actions)
if(done):
successes += 1
t_env += time.time() - t_env_start
# store transition into memory
if dual_buffer:
buf_episode.append( np.array([ global_state, np.array(local_others), np.array(local_self), actions, reward, local_rewards, next_global_state, np.array(next_local_others), np.array(next_local_self), done, goals]) )
else:
buf.add(np.array([ global_state, np.array(local_others), np.array(local_self), actions, reward, local_rewards, next_global_state, np.array(next_local_others), np.array(next_local_self), done, goals]) )
global_state = next_global_state
local_others = next_local_others
local_self = next_local_self
reward_local += local_rewards
reward_global += reward
#if dual_buffer:
#if experiment == 'particle':
#buf.add(buf_episode, scenario.collisions != 0)
t_train_start = time.time()
if (idx_episode >= pretrain_episodes) and (updated >= episodes_per_train):
updated = 0
for idx_epoch in range(epochs):
# Sample batch of transitions from replay buffer
batch = buf.sample_batch(batch_size)
if summarize and idx_episode == 0 and idx_epoch == 0:
# Write TF summary every <period> episodes, for the first minibatch
alg.train_step(sess, batch, epsilon, idx_episode, summarize=True, writer=writer)
else:
alg.train_step(sess, batch, epsilon, idx_episode, summarize=False, writer=None)
# Decrease exploration only after training
if epsilon > epsilon_end:
epsilon -= epsilon_step
# Clear buffer
if dual_buffer:
num_good += len(buf.memory_2)
num_bad += len(buf.memory_1)
buf = replay_buffer_dual.Replay_Buffer(size=buffer_size)
#else:
#buf = replay_buffer.Replay_Buffer(size=buffer_size)
t_train += time.time() - t_train_start
reward_local_century += reward_local
reward_global_century += reward_global
# ----------- Log performance --------------- #
if episodeSince >= period:
episodeSince = 0
dist_action = dist_action / np.sum(dist_action)
t_end = time.time()
print("\nEvaluating - Successes",successes )
successes = 0
if experiment == 'particle':
success = evaluate.test_UE_Sub(N_eval, env, sess, n_agents, l_goal, alg, render=False)
print(step)
#print(success)
#print(actions_chosen)
if(success > 0):
if(epsilon - .1 > 0):
epsilon -= .01
# s += ','.join(['{:.2f}'.format(val/float(period)) for val in reward_local_century])
# s += ',%.2f,' % (r_global_eval)
# s += ','.join(['{:.2f}'.format(val) for val in r_local_eval])
# s += ',%.2f,%d,%d' % (np.sum(r_local_eval), int(t_env), int(t_train))
# s += '\n'
#with open('../log/%s/log_century.csv' % dir_name, 'a') as f:
#f.write(s)
reward_local_century = np.zeros(n_agents)
reward_global_century = 0
#print("Fav Action ", dist_action)
if dual_buffer:
print("length buffer good %d, length buffer others %d, epsilon %.3f" % (num_good, num_bad, epsilon))
num_good = 0
num_bad = 0
else:
print("epsilon %.3f" % epsilon)
dist_action = np.zeros(l_action)
t_env = 0
t_train = 0
if(success == 1):
print("Traning done, target reached")
break
s = '%d,%d,%.2f,' % (step, idx_episode, reward_global)
s += ','.join(['{:.2f}'.format(val) for val in reward_local])
s += '\n'
with open('../log/%s/log.csv' % dir_name, 'a') as f:
f.write(s)
finish_time = time.time()
print ("TRAINING TIME (sec)", finish_time - start_time)
print("Saving stage %d variables" % stage)
if not os.path.exists('../saved/%s' % dir_name):
os.makedirs('../saved/%s' % dir_name)
saver.save(sess, '../saved/%s/model_final.ckpt' % dir_name)
if __name__ == "__main__":
with open('config.json', 'r') as f:
config = json.load(f)
train_function(config)
``` |
{
"source": "jonmeow/pre-commit-tool-hooks",
"score": 3
} |
#### File: pre-commit-tool-hooks/pre_commit_hooks/markdown_toc.py
```python
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
https://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 argparse
import re
import sys
from typing import List, Optional
from pre_commit_hooks import markdown_links
def _parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
"""Parses command-line arguments and flags."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"paths",
metavar="PATH",
nargs="+",
help="One or more paths of files to check.",
)
return parser.parse_args(args=argv)
def _update_toc(path: str) -> Optional[str]:
"""Updates the table of contents for a file."""
with open(path) as f:
contents = f.read()
if "<!-- toc -->" not in contents:
return None
if "<!-- tocstop -->" not in contents:
return "Missing tocstop"
try:
headers, _ = markdown_links.get_links(contents)
except ValueError as e:
return str(e)
toc = ["<!-- toc -->\n\n## Table of contents\n"]
for header in headers:
if header.label.lower() == "table of contents":
continue
if header.level == 1:
# This is the doc title; exclude it.
continue
indent = " " * 4 * (header.level - 2)
toc.append(f"{indent}- [{header.label}](#{header.anchor})")
# Add a blank line after entries, if any.
if len(toc) > 1:
toc.append("")
toc.append("<!-- tocstop -->")
new_contents = re.sub(
"<!-- toc -->.*?<!-- tocstop -->",
"\n".join(toc),
contents,
count=1,
flags=re.DOTALL,
)
if new_contents != contents:
with open(path, "w") as f:
f.write(new_contents)
return None
def main(argv: Optional[List[str]] = None) -> int:
if not argv:
argv = sys.argv
parsed_args = _parse_args(argv[1:])
paths = parsed_args.paths
exit_code = 0
for path in paths:
if not path.endswith(".md"):
continue
msg = _update_toc(path)
if msg:
print(f"Error in {path}: {msg}")
exit_code = 1
return exit_code
if __name__ == "__main__":
sys.exit(main())
``` |
{
"source": "jon/missile-command",
"score": 3
} |
#### File: jon/missile-command/calibrate.py
```python
from rocket_backend import *
from time import time
from time import sleep
points = []
manager = RocketManager()
manager.acquire_devices()
try:
rocket = manager.launchers[0]
except IndexError:
print "No rocket launchers"
exit(1)
DOWN = 0
UP = 1
LEFT = 2
RIGHT = 3
def wait_for(direction):
"""docstring for wait_for"""
limits = (False,)*4
while not limits[direction]:
limits = rocket.check_limits()
def mean(collection):
"""docstring for mean"""
return float(sum(collection)) / len(collection)
for x in range(1):
rocket.start_movement(DOWN)
wait_for(DOWN)
start_vert = time()
rocket.start_movement(UP)
wait_for(UP)
stop_vert = time()
rocket.start_movement(LEFT)
wait_for(LEFT)
start_horiz = time()
rocket.start_movement(RIGHT)
wait_for(RIGHT)
stop_horiz = time()
points.append((stop_vert - start_vert, stop_horiz - start_horiz))
mean_vert = mean([vert for vert, horiz in points])
mean_horiz = mean([horiz for vert, horiz in points])
print (mean_vert, mean_horiz)
rocket.start_movement(UP)
wait_for(UP)
rocket.start_movement(DOWN)
sleep(mean_vert / 2.0)
rocket.stop_movement()
rocket.start_movement(LEFT)
wait_for(LEFT)
rocket.start_movement(RIGHT)
sleep(mean_horiz / 2.0)
rocket.stop_movement()
for p in points:
print p
```
#### File: jon/missile-command/server.py
```python
import sys
import launchers
from getopt import getopt
from socket import *
opts, args = getopt(sys.argv[1:], 'i:p:', ['interface=', 'port=' ])
interface = ''
port = 7421
for o, a in opts:
if o in ('-i', '--interface'):
interface = a
elif o in ('-p', '--port'):
port = int(a)
sock = socket()
sock.bind((interface, port))
sock.listen(1)
l = launchers.find_launchers()
def handle_command(client, command):
"""Handles a single command from the client"""
global quit
parts = command.split(' ')
name = parts[0]
if name == 'quit':
quit = True
raise Exception("Quit")
if len(parts) < 2:
return
launcher = l[int(parts[1])] # Pull out the nth launcher
args = parts[2:]
if hasattr(launcher, name):
method = getattr(launcher, name)
intargs = [ float(a) for a in args ] # Try all integers, most args are!
method(*intargs)
input_buffer = ""
def receive_command(client):
"""Receives and handles a command from the client"""
global input_buffer
input_buffer += client.recv(1024)
commands = input_buffer.split("\n")
input_buffer = commands[-1] # Yank off last element which is an incomplete command
commands = commands[:-1] # Strip down to complete commands
for command in commands:
handle_command(client, command)
quit = False
while not quit:
client, client_address = sock.accept()
print "Client connected", client_address
while client:
try:
receive_command(client)
except Exception, e:
print e
client.shutdown(SHUT_RDWR)
client.close()
client = None
sock.close()
``` |
{
"source": "jonmmease/geoviews",
"score": 2
} |
#### File: geoviews/data/geopandas.py
```python
from __future__ import absolute_import
import sys
import warnings
from collections import defaultdict
import numpy as np
from holoviews.core.util import isscalar, unique_iterator, unique_array, pd
from holoviews.core.data import Dataset, Interface, MultiInterface
from holoviews.core.data.interface import DataError
from holoviews.core.data import PandasInterface
from holoviews.core.data.spatialpandas import get_value_array
from holoviews.core.dimension import dimension_name
from holoviews.element import Path
from ..util import geom_to_array, geom_types, geom_length
from .geom_dict import geom_from_dict
class GeoPandasInterface(MultiInterface):
types = ()
datatype = 'geodataframe'
multi = True
@classmethod
def loaded(cls):
return 'geopandas' in sys.modules
@classmethod
def applies(cls, obj):
if not cls.loaded():
return False
from geopandas import GeoDataFrame, GeoSeries
return isinstance(obj, (GeoDataFrame, GeoSeries))
@classmethod
def geo_column(cls, data):
from geopandas import GeoSeries
col = 'geometry'
if col in data and isinstance(data[col], GeoSeries):
return col
cols = [c for c in data.columns if isinstance(data[c], GeoSeries)]
if not cols and len(data):
raise ValueError('No geometry column found in geopandas.DataFrame, '
'use the PandasInterface instead.')
return cols[0] if cols else None
@classmethod
def init(cls, eltype, data, kdims, vdims):
import pandas as pd
from geopandas import GeoDataFrame, GeoSeries
if kdims is None:
kdims = eltype.kdims
if vdims is None:
vdims = eltype.vdims
if isinstance(data, GeoSeries):
data = data.to_frame()
if isinstance(data, list):
if all(isinstance(d, geom_types) for d in data):
data = [{'geometry': d} for d in data]
if all(isinstance(d, dict) and 'geometry' in d and isinstance(d['geometry'], geom_types)
for d in data):
data = GeoDataFrame(data)
if not isinstance(data, GeoDataFrame):
data = from_multi(eltype, data, kdims, vdims)
elif not isinstance(data, GeoDataFrame):
raise ValueError("GeoPandasInterface only support geopandas "
"DataFrames not %s." % type(data))
elif 'geometry' not in data:
cls.geo_column(data)
index_names = data.index.names if isinstance(data, pd.DataFrame) else [data.index.name]
if index_names == [None]:
index_names = ['index']
for kd in kdims+vdims:
kd = dimension_name(kd)
if kd in data.columns:
continue
if any(kd == ('index' if name is None else name)
for name in index_names):
data = data.reset_index()
break
try:
shp_types = {gt[5:] if 'Multi' in gt else gt for gt in data.geom_type}
except:
shp_types = []
if len(shp_types) > 1:
raise DataError('The GeopandasInterface can only read dataframes which '
'share a common geometry type, found %s types.' % shp_types,
cls)
return data, {'kdims': kdims, 'vdims': vdims}, {}
@classmethod
def validate(cls, dataset, vdims=True):
dim_types = 'key' if vdims else 'all'
geom_dims = cls.geom_dims(dataset)
if len(geom_dims) != 2:
raise DataError('Expected %s instance to declare two key '
'dimensions corresponding to the geometry '
'coordinates but %d dimensions were found '
'which did not refer to any columns.'
% (type(dataset).__name__, len(geom_dims)), cls)
not_found = [d.name for d in dataset.dimensions(dim_types)
if d not in geom_dims and d.name not in dataset.data]
if not_found:
raise DataError("Supplied data does not contain specified "
"dimensions, the following dimensions were "
"not found: %s" % repr(not_found), cls)
@classmethod
def dtype(cls, dataset, dimension):
name = dataset.get_dimension(dimension, strict=True).name
if name not in dataset.data:
return np.dtype('float') # Geometry dimension
return dataset.data[name].dtype
@classmethod
def has_holes(cls, dataset):
from shapely.geometry import Polygon, MultiPolygon
col = cls.geo_column(dataset.data)
for geom in dataset.data[col]:
if isinstance(geom, Polygon) and geom.interiors:
return True
elif isinstance(geom, MultiPolygon):
for g in geom:
if isinstance(g, Polygon) and g.interiors:
return True
return False
@classmethod
def holes(cls, dataset):
from shapely.geometry import Polygon, MultiPolygon
holes = []
col = cls.geo_column(dataset.data)
for geom in dataset.data[col]:
if isinstance(geom, Polygon) and geom.interiors:
holes.append([[geom_to_array(h) for h in geom.interiors]])
elif isinstance(geom, MultiPolygon):
holes += [[[geom_to_array(h) for h in g.interiors] for g in geom]]
else:
holes.append([[]])
return holes
@classmethod
def select(cls, dataset, selection_mask=None, **selection):
if cls.geom_dims(dataset):
df = cls.shape_mask(dataset, selection)
else:
df = dataset.data
if not selection:
return df
elif selection_mask is None:
selection_mask = cls.select_mask(dataset, selection)
indexed = cls.indexed(dataset, selection)
df = df.iloc[selection_mask]
if indexed and len(df) == 1 and len(dataset.vdims) == 1:
return df[dataset.vdims[0].name].iloc[0]
return df
@classmethod
def shape_mask(cls, dataset, selection):
xdim, ydim = cls.geom_dims(dataset)
xsel = selection.pop(xdim.name, None)
ysel = selection.pop(ydim.name, None)
if xsel is None and ysel is None:
return dataset.data
from shapely.geometry import box
if xsel is None:
x0, x1 = cls.range(dataset, xdim)
elif isinstance(xsel, slice):
x0, x1 = xsel.start, xsel.stop
elif isinstance(xsel, tuple):
x0, x1 = xsel
else:
raise ValueError("Only slicing is supported on geometries, %s "
"selection is of type %s."
% (xdim, type(xsel).__name__))
if ysel is None:
y0, y1 = cls.range(dataset, ydim)
elif isinstance(ysel, slice):
y0, y1 = ysel.start, ysel.stop
elif isinstance(ysel, tuple):
y0, y1 = ysel
else:
raise ValueError("Only slicing is supported on geometries, %s "
"selection is of type %s."
% (ydim, type(ysel).__name__))
bounds = box(x0, y0, x1, y1)
col = cls.geo_column(dataset.data)
df = dataset.data.copy()
df[col] = df[col].intersection(bounds)
return df[df[col].area > 0]
@classmethod
def select_mask(cls, dataset, selection):
mask = np.ones(len(dataset.data), dtype=np.bool)
for dim, k in selection.items():
if isinstance(k, tuple):
k = slice(*k)
arr = dataset.data[dim].values
if isinstance(k, slice):
with warnings.catch_warnings():
warnings.filterwarnings('ignore', r'invalid value encountered')
if k.start is not None:
mask &= k.start <= arr
if k.stop is not None:
mask &= arr < k.stop
elif isinstance(k, (set, list)):
iter_slcs = []
for ik in k:
with warnings.catch_warnings():
warnings.filterwarnings('ignore', r'invalid value encountered')
iter_slcs.append(arr == ik)
mask &= np.logical_or.reduce(iter_slcs)
elif callable(k):
mask &= k(arr)
else:
index_mask = arr == k
if dataset.ndims == 1 and np.sum(index_mask) == 0:
data_index = np.argmin(np.abs(arr - k))
mask = np.zeros(len(dataset), dtype=np.bool)
mask[data_index] = True
else:
mask &= index_mask
return mask
@classmethod
def geom_dims(cls, dataset):
return [d for d in dataset.kdims + dataset.vdims
if d.name not in dataset.data]
@classmethod
def dimension_type(cls, dataset, dim):
col = cls.geo_column(dataset.data)
arr = geom_to_array(dataset.data[col].iloc[0])
ds = dataset.clone(arr, datatype=cls.subtypes, vdims=[])
return ds.interface.dimension_type(ds, dim)
@classmethod
def isscalar(cls, dataset, dim, per_geom=False):
"""
Tests if dimension is scalar in each subpath.
"""
dim = dataset.get_dimension(dim)
geom_dims = cls.geom_dims(dataset)
if dim in geom_dims:
return False
elif per_geom:
return all(isscalar(v) or len(list(unique_array(v))) == 1
for v in dataset.data[dim.name])
dim = dataset.get_dimension(dim)
return len(dataset.data[dim.name].unique()) == 1
@classmethod
def range(cls, dataset, dim):
dim = dataset.get_dimension(dim)
geom_dims = cls.geom_dims(dataset)
if dim in geom_dims:
col = cls.geo_column(dataset.data)
idx = geom_dims.index(dim)
bounds = dataset.data[col].bounds
if idx == 0:
return bounds.minx.min(), bounds.maxx.max()
else:
return bounds.miny.min(), bounds.maxy.max()
else:
vals = dataset.data[dim.name]
return vals.min(), vals.max()
@classmethod
def aggregate(cls, columns, dimensions, function, **kwargs):
raise NotImplementedError
@classmethod
def add_dimension(cls, dataset, dimension, dim_pos, values, vdim):
data = dataset.data.copy()
geom_col = cls.geo_column(dataset.data)
if dim_pos >= list(data.columns).index(geom_col):
dim_pos -= 1
if dimension.name not in data:
data.insert(dim_pos, dimension.name, values)
return data
@classmethod
def groupby(cls, dataset, dimensions, container_type, group_type, **kwargs):
geo_dims = cls.geom_dims(dataset)
if any(d in geo_dims for d in dimensions):
raise DataError("GeoPandasInterface does not allow grouping "
"by geometry dimension.", cls)
return PandasInterface.groupby(dataset, dimensions, container_type, group_type, **kwargs)
@classmethod
def reindex(cls, dataset, kdims=None, vdims=None):
return dataset.data
@classmethod
def sample(cls, columns, samples=[]):
raise NotImplementedError
@classmethod
def sort(cls, dataset, by=[], reverse=False):
geo_dims = cls.geom_dims(dataset)
if any(d in geo_dims for d in by):
raise DataError("SpatialPandasInterface does not allow sorting "
"by geometry dimension.", cls)
return PandasInterface.sort(dataset, by, reverse)
@classmethod
def shape(cls, dataset):
return (cls.length(dataset), len(dataset.dimensions()))
@classmethod
def length(cls, dataset):
geom_type = cls.geom_type(dataset)
if geom_type != 'Point':
return len(dataset.data)
return sum([geom_length(g) for g in dataset.data.geometry])
@classmethod
def nonzero(cls, dataset):
return bool(cls.length(dataset))
@classmethod
def redim(cls, dataset, dimensions):
return PandasInterface.redim(dataset, dimensions)
@classmethod
def values(cls, dataset, dimension, expanded=True, flat=True, compute=True, keep_index=False):
dimension = dataset.get_dimension(dimension)
geom_dims = dataset.interface.geom_dims(dataset)
data = dataset.data
isgeom = (dimension in geom_dims)
geom_col = cls.geo_column(dataset.data)
is_points = cls.geom_type(dataset) == 'Point'
if not len(data):
dtype = float if isgeom else dataset.data[dimension.name].dtype
return np.array([], dtype=dtype)
col = cls.geo_column(dataset.data)
if isgeom and keep_index:
return data[col]
elif not isgeom:
return get_value_array(data, dimension, expanded, keep_index,
geom_col, is_points, geom_length)
column = data[dimension.name]
if not expanded or keep_index or not len(data):
return column if keep_index else column.values
else:
arrays = []
for i, geom in enumerate(data[col]):
length = geom_length(geom)
arrays.append(np.full(length, column.iloc[i]))
return np.concatenate(arrays) if len(arrays) > 1 else arrays[0]
values = []
geom_type = data.geom_type.iloc[0]
ds = dataset.clone(data.iloc[0].to_dict(), datatype=['geom_dictionary'])
for i, row in data.iterrows():
ds.data = row.to_dict()
values.append(ds.interface.values(ds, dimension))
if 'Point' not in geom_type and expanded:
values.append([np.NaN])
values = values if 'Point' in geom_type or not expanded else values[:-1]
if len(values) == 1:
return values[0]
elif not values:
return np.array([])
elif not expanded:
array = np.empty(len(values), dtype=object)
array[:] = values
return array
else:
return np.concatenate(values)
@classmethod
def iloc(cls, dataset, index):
from geopandas import GeoSeries
from shapely.geometry import MultiPoint
rows, cols = index
geom_dims = cls.geom_dims(dataset)
geom_col = cls.geo_column(dataset.data)
scalar = False
columns = list(dataset.data.columns)
if isinstance(cols, slice):
cols = [d.name for d in dataset.dimensions()][cols]
elif np.isscalar(cols):
scalar = np.isscalar(rows)
cols = [dataset.get_dimension(cols).name]
else:
cols = [dataset.get_dimension(d).name for d in index[1]]
if not all(d in cols for d in geom_dims):
raise DataError("Cannot index a dimension which is part of the "
"geometry column of a spatialpandas DataFrame.", cls)
cols = list(unique_iterator([
columns.index(geom_col) if c in geom_dims else columns.index(c) for c in cols
]))
geom_type = dataset.data[geom_col].geom_type.iloc[0]
if geom_type != 'MultiPoint':
if scalar:
return dataset.data.iloc[rows[0], cols[0]]
elif isscalar(rows):
rows = [rows]
return dataset.data.iloc[rows, cols]
geoms = dataset.data[geom_col]
count = 0
new_geoms, indexes = [], []
for i, geom in enumerate(geoms):
length = len(geom)
if np.isscalar(rows):
if count <= rows < (count+length):
new_geoms.append(geom[rows-count])
indexes.append(i)
break
elif isinstance(rows, slice):
if rows.start is not None and rows.start > (count+length):
continue
elif rows.stop is not None and rows.stop < count:
break
start = None if rows.start is None else max(rows.start - count, 0)
stop = None if rows.stop is None else min(rows.stop - count, length)
if rows.step is not None:
dataset.param.warning(".iloc step slicing currently not supported for"
"the multi-tabular data format.")
indexes.append(i)
new_geoms.append(geom[start:stop])
elif isinstance(rows, (list, set)):
sub_rows = [(r-count) for r in rows if count <= r < (count+length)]
if not sub_rows:
continue
indexes.append(i)
new_geoms.append(MultiPoint([geom[r] for r in sub_rows]))
count += length
new = dataset.data.iloc[indexes].copy()
new[geom_col] = GeoSeries(new_geoms)
return new
@classmethod
def split(cls, dataset, start, end, datatype, **kwargs):
objs = []
xdim, ydim = dataset.kdims[:2]
if not len(dataset.data):
return []
row = dataset.data.iloc[0]
col = cls.geo_column(dataset.data)
arr = geom_to_array(row[col])
d = {(xdim.name, ydim.name): arr}
d.update({vd.name: row[vd.name] for vd in dataset.vdims})
geom_type = cls.geom_type(dataset)
ds = dataset.clone([d], datatype=['multitabular'])
for i, row in dataset.data.iterrows():
if datatype == 'geom':
objs.append(row[col])
continue
geom = row[col]
gt = geom_type or get_geom_type(geom)
arr = geom_to_array(geom)
d = {xdim.name: arr[:, 0], ydim.name: arr[:, 1]}
d.update({vd.name: row[vd.name] for vd in dataset.vdims})
ds.data = [d]
if datatype == 'array':
obj = ds.array(**kwargs)
elif datatype == 'dataframe':
obj = ds.dframe(**kwargs)
elif datatype in ('columns', 'dictionary'):
d['geom_type'] = gt
obj = d
elif datatype is None:
obj = ds.clone()
else:
raise ValueError("%s datatype not support" % datatype)
objs.append(obj)
return objs
def get_geom_type(geom):
"""Returns the HoloViews geometry type.
Args:
geom: A shapely geometry
Returns:
A string representing type of the geometry.
"""
from shapely.geometry import (
Point, LineString, Polygon, Ring, MultiPoint, MultiPolygon, MultiLineString
)
if isinstance(geom, (Point, MultiPoint)):
return 'Point'
elif isinstance(geom, (LineString, MultiLineString)):
return 'Line'
elif isinstance(geom, Ring):
return 'Ring'
elif isinstance(geom, (Polygon, MultiPolygon)):
return 'Polygon'
def to_geopandas(data, xdim, ydim, columns=[], geom='point'):
"""Converts list of dictionary format geometries to spatialpandas line geometries.
Args:
data: List of dictionaries representing individual geometries
xdim: Name of x-coordinates column
ydim: Name of y-coordinates column
ring: Whether the data represents a closed ring
Returns:
A spatialpandas.GeoDataFrame version of the data
"""
from geopandas import GeoDataFrame
from shapely.geometry import (
Point, LineString, Polygon, MultiPoint, MultiPolygon, MultiLineString
)
poly = any('holes' in d for d in data) or geom == 'Polygon'
if poly:
single_type, multi_type = Polygon, MultiPolygon
elif geom == 'Line':
single_type, multi_type = LineString, MultiLineString
else:
single_type, multi_type = Point, MultiPoint
converted = defaultdict(list)
for geom_dict in data:
geom_dict = dict(geom_dict)
geom = geom_from_dict(geom_dict, xdim, ydim, single_type, multi_type)
for c, v in geom_dict.items():
converted[c].append(v)
converted['geometry'].append(geom)
return GeoDataFrame(converted, columns=['geometry']+columns)
def from_multi(eltype, data, kdims, vdims):
"""Converts list formats into geopandas.GeoDataFrame.
Args:
eltype: Element type to convert
data: The original data
kdims: The declared key dimensions
vdims: The declared value dimensions
Returns:
A GeoDataFrame containing the data in the list based format.
"""
from geopandas import GeoDataFrame
new_data = []
types = []
xname, yname = (kd.name for kd in kdims[:2])
for d in data:
types.append(type(d))
if isinstance(d, dict):
d = {k: v if isscalar(v) else np.asarray(v) for k, v in d.items()}
new_data.append(d)
continue
new_el = eltype(d, kdims, vdims)
if new_el.interface is GeoPandasInterface:
types[-1] = GeoDataFrame
new_data.append(new_el.data)
continue
new_dict = {}
for d in new_el.dimensions():
if d in (xname, yname):
scalar = False
else:
scalar = new_el.interface.isscalar(new_el, d)
vals = new_el.dimension_values(d, not scalar)
new_dict[d.name] = vals[0] if scalar else vals
new_data.append(new_dict)
if len(set(types)) > 1:
raise DataError('Mixed types not supported')
if new_data and types[0] is GeoDataFrame:
data = pd.concat(new_data)
else:
columns = [d.name for d in kdims+vdims if d not in (xname, yname)]
geom = GeoPandasInterface.geom_type(eltype)
if not len(data):
return GeoDataFrame([], columns=['geometry']+columns)
data = to_geopandas(new_data, xname, yname, columns, geom)
return data
Interface.register(GeoPandasInterface)
Dataset.datatype = Dataset.datatype+['geodataframe']
Path.datatype = Path.datatype+['geodataframe']
``` |
{
"source": "jonmmease/hilbert_frame",
"score": 3
} |
#### File: hilbert_frame/hilbert_frame/hilbert_curve.py
```python
from numba import jit, vectorize, int64
import numpy as np
"""
Inspired by https://github.com/galtay/hilbert_curve
"""
@jit(nopython=True)
def _int_2_binary(n, width):
"""Return a binary string representation of `num` zero padded to `width`
bits."""
res = np.zeros(width, dtype=np.uint8)
i = 0
for i in range(width):
res[width - i - 1] = n % 2
n = n >> 1
return res
@jit(nopython=True)
def _binary_2_int(bin_vec):
res = 0
next_val = 1
width = len(bin_vec)
for i in range(width):
res += next_val*bin_vec[width - i - 1]
next_val <<= 1
return res
@jit(nopython=True)
def _hilbert_integer_to_transpose(p, h):
"""Store a hilbert integer (`h`) as its transpose (`x`).
Args:
p (int): iterations to use in the hilbert curve
h (int): integer distance along hilbert curve
Returns:
x (list): transpose of h
(n components with values between 0 and 2**p-1)
"""
n = 2
h_bits = _int_2_binary(h, p * n)
x = [_binary_2_int(h_bits[i::n]) for i in range(n)]
return x
@jit([int64(int64, int64, int64)], nopython=True)
def _transpose_to_hilbert_integer(p, x, y):
"""Restore a hilbert integer (`h`) from its transpose (`x`).
Args:
p (int): iterations to use in the hilbert curve
x (list): transpose of h
(n components with values between 0 and 2**p-1)
Returns:
h (int): integer distance along hilbert curve
"""
bin1 = _int_2_binary(x, p)
bin2 = _int_2_binary(y, p)
concat = np.zeros(2*p, dtype=np.uint8)
for i in range(p):
concat[2*i] = bin1[i]
concat[2*i+1] = bin2[i]
h = _binary_2_int(concat)
return h
@jit(nopython=True)
def coordinates_from_distance(p, h):
"""Return the coordinates for a given hilbert distance.
Args:
p (int): iterations to use in the hilbert curve
h (int): integer distance along hilbert curve
Returns:
x (list): transpose of h
(n components with values between 0 and 2**p-1)
"""
n = 2
x = _hilbert_integer_to_transpose(p, h)
Z = 2 << (p-1)
# Gray decode by H ^ (H/2)
t = x[n-1] >> 1
for i in range(n-1, 0, -1):
x[i] ^= x[i-1]
x[0] ^= t
# Undo excess work
Q = 2
while Q != Z:
P = Q - 1
for i in range(n-1, -1, -1):
if x[i] & Q:
# invert
x[0] ^= P
else:
# exchange
t = (x[0] ^ x[i]) & P
x[0] ^= t
x[i] ^= t
Q <<= 1
# done
return x
@vectorize([int64(int64, int64, int64)], nopython=True)
def distance_from_coordinates(p, x, y):
"""Return the hilbert distance for a given set of coordinates.
Args:
p (int): iterations to use in the hilbert curve
x_in (list): transpose of h
(n components with values between 0 and 2**p-1)
Returns:
h (int): integer distance along hilbert curve
"""
n = 2
x = np.array([x, y], dtype=np.int64)
M = 1 << (p - 1)
# Inverse undo excess work
Q = M
while Q > 1:
P = Q - 1
for i in range(n):
if x[i] & Q:
x[0] ^= P
else:
t = (x[0] ^ x[i]) & P
x[0] ^= t
x[i] ^= t
Q >>= 1
# Gray encode
for i in range(1, n):
x[i] ^= x[i-1]
t = 0
Q = M
while Q > 1:
if x[n-1] & Q:
t ^= Q - 1
Q >>= 1
for i in range(n):
x[i] ^= t
h = _transpose_to_hilbert_integer(p, x[0], x[1])
return h
```
#### File: hilbert_frame/hilbert_frame/__init__.py
```python
import copy
from fastparquet import ParquetFile, parquet_thrift
from fastparquet.writer import write_common_metadata
from six import string_types
import hilbert_frame.hilbert_curve as hc
import numpy as np
import pandas as pd
import dask.dataframe as dd
import os
import shutil
import json
def data2coord(vals, val_range, side_length):
if isinstance(vals, (list, tuple)):
vals = np.array(vals)
x_width = val_range[1] - val_range[0]
return ((vals - val_range[0]) * (side_length / x_width)
).astype(np.int64).clip(0, side_length - 1)
def compute_distance(df, x, y, p, x_range, y_range):
side_length = 2 ** p
x_coords = data2coord(df[x], x_range, side_length)
y_coords = data2coord(df[y], y_range, side_length)
return hc.distance_from_coordinates(p, x_coords, y_coords)
def compute_extents(df, x, y):
x_min = df[x].min()
x_max = df[x].max()
y_min = df[y].min()
y_max = df[y].max()
return pd.DataFrame({'x_min': x_min,
'x_max': x_max,
'y_min': y_min,
'y_max': y_max},
index=[0])
class HilbertFrame2D(object):
@staticmethod
def from_dataframe(df,
filename,
x='x',
y='y',
p=10,
npartitions=None,
shuffle=None,
persist=False,
engine='auto',
compression='default'):
# Validate dirname
if (not isinstance(filename, string_types) or
not filename.endswith('.parquet')):
raise ValueError(
'filename must be a string ending with a .parquet extension')
# Remove any existing directory
if os.path.exists(filename):
shutil.rmtree(filename)
# Normalize to dask dataframe
if isinstance(df, pd.DataFrame):
ddf = dd.from_pandas(df, npartitions=4)
elif isinstance(df, dd.DataFrame):
ddf = df
else:
raise ValueError("""
df must be a pandas or dask DataFrame instance.
Received value of type {typ}""".format(typ=type(df)))
# Compute npartitions if needed
if npartitions is None:
# Make partitions of ~8 million rows with a minimum of 8
# partitions
max(int(np.ceil(len(df) / 2**23)), 8)
# Compute data extents
extents = ddf.map_partitions(
compute_extents, x, y).compute()
x_range = (float(extents['x_min'].min()),
float(extents['x_max'].max()))
y_range = (float(extents['y_min'].min()),
float(extents['y_max'].max()))
# Compute distance of points in integer hilbert space
ddf = ddf.assign(distance=ddf.map_partitions(
compute_distance, x=x, y=y, p=p,
x_range=x_range, y_range=y_range))
# Set index to distance
ddf = ddf.set_index('distance',
npartitions=npartitions,
shuffle=shuffle)
# Build partitions grid
# Uses distance divisions computed above, but does not revisit data
distance_divisions = [int(d) for d in ddf.divisions]
# Save other properties as custom metadata in the parquet file
props = dict(
version='1.0',
x=x,
y=y,
p=p,
distance_divisions=distance_divisions,
x_range=x_range,
y_range=y_range,
)
# Drop distance index
ddf = ddf.reset_index(drop=True)
# Save ddf to parquet
dd.to_parquet(ddf, filename, engine=engine, compression=compression)
# Open file
pf = ParquetFile(filename)
# Add a new property to the file metadata
new_fmd = copy.copy(pf.fmd)
new_kv = parquet_thrift.KeyValue()
new_kv.key = 'hilbert_frame'
new_kv.value = json.dumps(props)
new_fmd.key_value_metadata.append(new_kv)
# Overwrite file metadata
fn = os.path.join(filename, '_metadata')
write_common_metadata(fn, new_fmd, no_row_groups=False)
fn = os.path.join(filename, '_common_metadata')
write_common_metadata(fn, new_fmd)
# Construct HilbertFrame2D from file
return HilbertFrame2D(filename, persist=persist)
@staticmethod
def build_partition_grid(distance_grid, dask_divisions, p):
search_divisions = np.array(
list(dask_divisions[1:-1]))
side_length = 2 ** p
partition_grid = np.zeros([side_length] * 2, dtype='int')
for i in range(side_length):
for j in range(side_length):
partition_grid[i, j] = np.searchsorted(
search_divisions,
distance_grid[i, j],
sorter=None,
side='right')
return partition_grid
@staticmethod
def build_distance_grid(p):
side_length = 2 ** p
distance_grid = np.zeros([side_length] * 2, dtype='int')
for i in range(side_length):
for j in range(side_length):
distance_grid[i, j] = (
hc.distance_from_coordinates(p, i, j))
return distance_grid
def __init__(self, filename, persist=False):
# Open hilbert properties
# Reopen file
pf = ParquetFile(filename)
# Access custom metadata
props = json.loads(pf.key_value_metadata['hilbert_frame'])
# Set all props as attributes
self.x = props['x']
self.y = props['y']
self.p = props['p']
self.x_range = props['x_range']
self.y_range = props['y_range']
self.distance_divisions = props['distance_divisions']
# Compute grids
self.distance_grid = HilbertFrame2D.build_distance_grid(self.p)
self.partition_grid = HilbertFrame2D.build_partition_grid(
self.distance_grid, self.distance_divisions, self.p)
# Compute simple derived properties
n = 2
self.side_length = 2 ** self.p
self.max_distance = 2 ** (n * self.p) - 1
self.x_width = self.x_range[1] - self.x_range[0]
self.y_width = self.y_range[1] - self.y_range[0]
self.x_bin_width = self.x_width / self.side_length
self.y_bin_width = self.y_width / self.side_length
# Read parquet file
self.ddf = dd.read_parquet(filename)
# Persist if requested
if persist:
self.ddf = self.ddf.persist()
def range_query(self, query_x_range, query_y_range):
# Compute bounds in hilbert coords
expanded_x_range = [query_x_range[0],
query_x_range[1] + self.x_bin_width]
expanded_y_range = [query_y_range[0],
query_y_range[1] + self.y_bin_width]
query_x_range_coord = data2coord(expanded_x_range,
self.x_range,
self.side_length)
query_y_range_coord = data2coord(expanded_y_range,
self.y_range,
self.side_length)
partition_query = self.partition_grid[
slice(*query_x_range_coord), slice(*query_y_range_coord)]
query_partitions = sorted(np.unique(partition_query))
if query_partitions:
partition_dfs = [self.ddf.get_partition(p) for p in
query_partitions]
query_frame = dd.concat(partition_dfs)
return query_frame
else:
return self.ddf.loc[1:0]
@property
def hilbert_distance(self):
x = self.x
y = self.y
p = self.p
x_range = self.x_range
y_range = self.y_range
return self.ddf.map_partitions(
compute_distance, x=x, y=y, p=p, x_range=x_range, y_range=y_range)
``` |
{
"source": "jonmmease/holoviews",
"score": 3
} |
#### File: plotting/plotly/element.py
```python
import numpy as np
import plotly.graph_objs as go
import param
from ...core.util import basestring
from .plot import PlotlyPlot
from ..plot import GenericElementPlot, GenericOverlayPlot
from .. import util
class ElementPlot(PlotlyPlot, GenericElementPlot):
aspect = param.Parameter(default='cube', doc="""
The aspect ratio mode of the plot. By default, a plot may
select its own appropriate aspect ratio but sometimes it may
be necessary to force a square aspect ratio (e.g. to display
the plot as an element of a grid). The modes 'auto' and
'equal' correspond to the axis modes of the same name in
matplotlib, a numeric value may also be passed.""")
bgcolor = param.ClassSelector(class_=(str, tuple), default=None, doc="""
If set bgcolor overrides the background color of the axis.""")
invert_axes = param.ObjectSelector(default=False, doc="""
Inverts the axes of the plot. Note that this parameter may not
always be respected by all plots but should be respected by
adjoined plots when appropriate.""")
invert_xaxis = param.Boolean(default=False, doc="""
Whether to invert the plot x-axis.""")
invert_yaxis = param.Boolean(default=False, doc="""
Whether to invert the plot y-axis.""")
invert_zaxis = param.Boolean(default=False, doc="""
Whether to invert the plot z-axis.""")
labelled = param.List(default=['x', 'y'], doc="""
Whether to plot the 'x' and 'y' labels.""")
logx = param.Boolean(default=False, doc="""
Whether to apply log scaling to the x-axis of the Chart.""")
logy = param.Boolean(default=False, doc="""
Whether to apply log scaling to the y-axis of the Chart.""")
logz = param.Boolean(default=False, doc="""
Whether to apply log scaling to the y-axis of the Chart.""")
margins = param.NumericTuple(default=(50, 50, 50, 50), doc="""
Margins in pixel values specified as a tuple of the form
(left, bottom, right, top).""")
show_legend = param.Boolean(default=False, doc="""
Whether to show legend for the plot.""")
xaxis = param.ObjectSelector(default='bottom',
objects=['top', 'bottom', 'bare', 'top-bare',
'bottom-bare', None], doc="""
Whether and where to display the xaxis, bare options allow suppressing
all axis labels including ticks and xlabel. Valid options are 'top',
'bottom', 'bare', 'top-bare' and 'bottom-bare'.""")
xticks = param.Parameter(default=None, doc="""
Ticks along x-axis specified as an integer, explicit list of
tick locations, list of tuples containing the locations and
labels or a matplotlib tick locator object. If set to None
default matplotlib ticking behavior is applied.""")
yaxis = param.ObjectSelector(default='left',
objects=['left', 'right', 'bare', 'left-bare',
'right-bare', None], doc="""
Whether and where to display the yaxis, bare options allow suppressing
all axis labels including ticks and ylabel. Valid options are 'left',
'right', 'bare' 'left-bare' and 'right-bare'.""")
yticks = param.Parameter(default=None, doc="""
Ticks along y-axis specified as an integer, explicit list of
tick locations, list of tuples containing the locations and
labels or a matplotlib tick locator object. If set to None
default matplotlib ticking behavior is applied.""")
zlabel = param.String(default=None, doc="""
An explicit override of the z-axis label, if set takes precedence
over the dimension label.""")
graph_obj = None
def initialize_plot(self, ranges=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
fig = self.generate_plot(self.keys[-1], ranges)
self.drawn = True
return fig
def generate_plot(self, key, ranges):
element = self._get_frame(key)
if element is None:
return self.handles['fig']
plot_opts = self.lookup_options(element, 'plot').options
self.set_param(**{k: v for k, v in plot_opts.items()
if k in self.params()})
self.style = self.lookup_options(element, 'style')
ranges = self.compute_ranges(self.hmap, key, ranges)
ranges = util.match_spec(element, ranges)
data_args, data_kwargs = self.get_data(element, ranges)
opts = self.graph_options(element, ranges)
graph = self.init_graph(data_args, dict(opts, **data_kwargs))
self.handles['graph'] = graph
layout = self.init_layout(key, element, ranges)
self.handles['layout'] = layout
if isinstance(graph, go.Figure):
graph.update({'layout': layout})
self.handles['fig'] = graph
else:
if not isinstance(graph, list):
graph = [graph]
fig = go.Figure(data=graph, layout=layout)
self.handles['fig'] = fig
return fig
def graph_options(self, element, ranges):
if self.overlay_dims:
legend = ', '.join([d.pprint_value_string(v) for d, v in
self.overlay_dims.items()])
else:
legend = element.label
opts = dict(showlegend=self.show_legend,
legendgroup=element.group,
name=legend)
if self.layout_num:
opts['xaxis'] = 'x' + str(self.layout_num)
opts['yaxis'] = 'y' + str(self.layout_num)
return opts
def init_graph(self, plot_args, plot_kwargs):
return self.graph_obj(*plot_args, **plot_kwargs)
def get_data(self, element, ranges):
return {}
def get_aspect(self, xspan, yspan):
"""
Computes the aspect ratio of the plot
"""
return self.width/self.height
def init_layout(self, key, element, ranges, xdim=None, ydim=None):
l, b, r, t = self.get_extents(element, ranges)
options = {}
xdim = element.get_dimension(0) if xdim is None else xdim
ydim = element.get_dimension(1) if ydim is None else ydim
xlabel, ylabel, zlabel = self._get_axis_labels([xdim, ydim])
if self.invert_axes:
xlabel, ylabel = ylabel, xlabel
l, b, r, t = b, l, t, r
if 'x' not in self.labelled:
xlabel = ''
if 'y' not in self.labelled:
ylabel = ''
if xdim:
xaxis = dict(range=[l, r], title=xlabel)
if self.logx:
xaxis['type'] = 'log'
options['xaxis'] = xaxis
if ydim:
yaxis = dict(range=[b, t], title=ylabel)
if self.logy:
yaxis['type'] = 'log'
options['yaxis'] = yaxis
l, b, r, t = self.margins
margin = go.layout.Margin(l=l, r=r, b=b, t=t, pad=4)
return go.Layout(width=self.width, height=self.height,
title=self._format_title(key, separator=' '),
plot_bgcolor=self.bgcolor, margin=margin,
**options)
def update_frame(self, key, ranges=None):
"""
Updates an existing plot with data corresponding
to the key.
"""
self.generate_plot(key, ranges)
class ColorbarPlot(ElementPlot):
colorbar = param.Boolean(default=False, doc="""
Whether to display a colorbar.""")
colorbar_opts = param.Dict(default={}, doc="""
Allows setting including borderwidth, showexponent, nticks,
outlinecolor, thickness, bgcolor, outlinewidth, bordercolor,
ticklen, xpad, ypad, tickangle...""")
def get_color_opts(self, dim, element, ranges, style):
opts = {}
if self.colorbar:
opts['colorbar'] = dict(title=dim.pprint_label,
**self.colorbar_opts)
else:
opts['showscale'] = False
cmap = style.pop('cmap', 'viridis')
if cmap == 'fire':
values = np.linspace(0, 1, len(util.fire_colors))
cmap = [(v, 'rgb(%d, %d, %d)' % tuple(c))
for v, c in zip(values, np.array(util.fire_colors)*255)]
elif isinstance(cmap, basestring):
if cmap[0] == cmap[0].lower():
cmap = cmap[0].upper() + cmap[1:]
if cmap.endswith('_r'):
cmap = cmap[:-2]
opts['reversescale'] = True
opts['colorscale'] = cmap
if dim:
if dim.name in ranges:
cmin, cmax = ranges[dim.name]['combined']
else:
cmin, cmax = element.range(dim.name)
opts['cmin'] = cmin
opts['cmax'] = cmax
opts['cauto'] = False
return dict(style, **opts)
class OverlayPlot(GenericOverlayPlot, ElementPlot):
def initialize_plot(self, ranges=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
return self.generate_plot(list(self.hmap.data.keys())[0], ranges)
def generate_plot(self, key, ranges):
element = self._get_frame(key)
ranges = self.compute_ranges(self.hmap, key, ranges)
figure = None
for okey, subplot in self.subplots.items():
fig = subplot.generate_plot(key, ranges)
if figure is None:
figure = fig
else:
figure.add_traces(fig.data)
layout = self.init_layout(key, element, ranges)
figure['layout'].update(layout)
self.handles['fig'] = figure
return figure
``` |
{
"source": "jonmon6691/arduino_lora_boilerplate",
"score": 3
} |
#### File: jonmon6691/arduino_lora_boilerplate/lora_ping.py
```python
import serial
import time
import random
import itertools
def send_cmd(self, cmd_string, timeit=False):
cmd = f"{cmd_string}\r\n".encode()
print(cmd)
self.write(cmd)
if timeit:
t = time.time()
print(self.readline(), end=' ') # Block until OK response
print(time.time() - t)
else:
print(self.readline()) # Block until OK response
serial.Serial.cmd = send_cmd
s = serial.Serial('/dev/ttyUSB0', 115200, timeout=2)
# f must be greater than 711100000
# f must be less than 1024000000
f = 915000000 # 915MHz is default
s.cmd(f"AT+BAND={f}", timeit=True)
# Default: b'+PARAMETER=12,7,1,4\r\n'
sf, bw, cr, pp = 12, 7, 1, 4
# sf spreading factor (7-12)
# bw bandwidth 0-9 -> (7.8kHz - 500kHz)
# cr coding rate 1-4
# pp Programmed preamble 4-7
s.cmd(f"AT+PARAMETER={sf},{bw},{cr},{pp}")
while True:
# uncomment one of the lines below to perform a parameter sweep
#if True:
#for f in range(711100000, 1024000000, 1000):
#for sf in range(7, 13, 1):
for bw in range(0, 9, 1):
#for cr in range(1, 5, 1):
#for pp in range(3, 25, 1):
s.cmd(f"AT+PARAMETER={sf},{bw},{cr},{pp}")
s.cmd('AT+SEND=0,4,PING+Afterplus', timeit=True)
print(s.readline()) # Check for receive
``` |
{
"source": "jonmoon76/aoc2020",
"score": 3
} |
#### File: aoc2020/src/day15.py
```python
seed = [14,1,17,0,3,20]
example_seed = [ 0, 3, 6]
ARRAY_SIZE = 1000000
class State:
time = 0
previousGo = 0
previousRoundsList = []
previousRoundsDict = {}
def __init__ (self):
for i in range(1, ARRAY_SIZE):
self.previousRoundsList.append(NumberState())
def update(self, n):
if n < ARRAY_SIZE:
numberState = self.previousRoundsList[n]
else:
try:
numberState = self.previousRoundsDict[n]
except KeyError:
numberState = NumberState()
self.previousRoundsDict[n] = numberState
numberState.update(self.time)
self.time = self.time + 1
self.previousGo = numberState
self.previousN = n
class NumberState:
def __init__ (self):
self.lastTime = None
self.previousTime = None
def update(self, n):
self.previousTime = self.lastTime
self.lastTime = n
# makeMove : State -> State
# makeMove state =
# case Dict.get state.previousGo state.previousRounds of
# Just ( a, Nothing ) ->
# updateState 0 state
# Just ( a, Just b ) ->
# updateState (a - b) state
# Nothing ->
# Debug.todo "Assert: Must have made previous move"
def makeMove (state):
previousGo = state.previousGo
if previousGo.previousTime == None:
state.update(0)
else:
state.update(previousGo.lastTime - previousGo.previousTime)
def seedMoves (seed):
state = State()
for move in seed:
state.update(move)
return state
def playGame( maxTime, state : State):
while state.time < maxTime:
if state.time % 100000 == 0:
print ("{} : {}".format(state.time, len(state.previousRoundsDict)))
makeMove(state)
state = seedMoves(seed)
playGame(30000000, state)
print(state.previousN)
``` |
{
"source": "JonMoore75/PyQt_MVC",
"score": 3
} |
#### File: JonMoore75/PyQt_MVC/Test.py
```python
import sys
from dataclasses import dataclass
from copy import deepcopy
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QPushButton
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from enum import Enum, auto
Signal, Slot = pyqtSignal, pyqtSlot
class Cmds(Enum):
INC = auto()
DEC = auto()
NUM = auto()
# This implementation decouples the UI view, model and control classes fairly well. Downsides to this approach are
# not yet able to have commands that pass data - could use Command pattern or PyQt signals?
# Also need to keep track of three sets of data when adding commands, the list of enums, the map of enum commands to
# functions in the controller and the key mapping. Might suggest strings and ASCII codes are better than enums and
# PyQt ket codes?
class MainWindow(QMainWindow):
intSignal = Signal(int)
def __init__(self, button_map):
super(QMainWindow, self).__init__()
# Maps to map commands, keys and functions
self.key_table = {QtCore.Qt.Key_Plus: Cmds.INC, QtCore.Qt.Key_Minus: Cmds.DEC}
self.key_table.update({k: Cmds.NUM for k in range(QtCore.Qt.Key_0, QtCore.Qt.Key_9+1)})
print(self.key_table)
self.func_map = {}
# Set UI layout
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
ui_layout = QGridLayout()
central_widget.setLayout(ui_layout)
# Create UI elements
self.display = QLabel()
ui_layout.addWidget(self.display)
self.buttons = {}
for cmd in button_map:
title = button_map[cmd]
self.buttons[cmd] = QPushButton(title)
ui_layout.addWidget(self.buttons[cmd])
# Need to use this form of lambda to get local copy of button variable
# otherwise button will be last value in the list for ALL buttons
# lambda's (or local functions) use value at call time NOT creation!
# See https://stackoverflow.com/questions/10452770/python-lambdas-binding-to-local-values
self.buttons[cmd].clicked.connect(lambda state, x=cmd: self.ExecuteCmd(x))
def ExecuteCmd(self, cmd, data=None):
""" Takes a command enum code and calls the corresponding function """
if cmd in self.func_map:
if data is not None:
self.func_map[cmd](data)
else:
print('No data call')
self.func_map[cmd]()
def UpdateDisplay(self, value):
""" If a change has been made then update the display """
str_value = str(value)
self.display.setText(str_value)
def Connect(self, func_map):
""" Allows other class (eg model or controller etc) to specify what function to call for each command """
self.func_map = func_map
def keyPressEvent(self, event):
""" Handles key presses."""
key = event.key()
if key in self.key_table:
cmd = self.key_table[key]
if QtCore.Qt.Key_0 <= key <= QtCore.Qt.Key_9:
num = int(key) - int(QtCore.Qt.Key_0)
print(key, num, cmd)
self.ExecuteCmd(cmd, num)
else:
self.ExecuteCmd(cmd)
class Controller:
def __init__(self, _model, _view):
self.model = _model
self.view = _view
self.view.Connect({Cmds.INC: self.Increment, Cmds.DEC: self.Decrement, Cmds.NUM: self.NumberCommand})
self.view.UpdateDisplay(self.model.value)
def Increment(self):
print('Increment called')
self.model.Increment()
self.view.UpdateDisplay(self.model.value)
def Decrement(self):
print('Decrement called')
self.model.Decrement()
self.view.UpdateDisplay(self.model.value)
def NumberCommand(self, value):
print(value)
@dataclass
class Model:
value: int = 0
def Increment(self):
self.value += 1
def Decrement(self):
self.value -= 1
###############################################################################
def run_app():
app = QtWidgets.QApplication(sys.argv)
button_map = {Cmds.INC: '+1', Cmds.DEC: '-1'}
model = Model()
main_win = MainWindow(button_map)
main_win.show()
control = Controller(model, main_win)
return app.exec_()
if __name__ == "__main__":
sys.exit(run_app())
``` |
{
"source": "jonmorehouse/vimhub",
"score": 3
} |
#### File: vimhub/lib/git.py
```python
import os
import subprocess
import re
import utils
import config
try:
import vim
except:
vim = False
remote_hash = {}
path_hash = {}
def remotes(path):
if remote_hash.get(path):
return remote_hash.get(path)
# grab only the remotes - this is safer than using python due to global character differences amongst shells (line endings etc)
command = "cd %s && git remote -v | awk '{ print $1 \"=\" $2 }'" % path
output = os.popen(command).read()
# redraw vim screen if there was stderr
if vim:
vim.command("redraw!")
remotes = {}
# loop through each line and generate creator/project name
for line in output.splitlines():
pieces = tuple(line.split("="))
if remotes.has_key(pieces[0]):
continue
# split into pieces so we can abstract the relevant parts of ui
uri_pieces = re.split(r"[\:,\/]+", pieces[1])
# remove any trailing .gits
project_name = re.sub(r"\.git$", "", uri_pieces[-1])
# grab the github username
creator = uri_pieces[-2]
remotes[pieces[0]] = (creator, project_name)
# hash
remote_hash[path] = remotes
return remote_hash.get(path)
def repo_path(path = None):
if not path:
path = os.getcwd()
if not path_hash.has_key(path):
command = "cd %s && git rev-parse --show-toplevel" % path
try:
path_hash[path] = os.popen(command).read().strip()
except:
sys.exit(1)
return
return path_hash[path]
``` |
{
"source": "jon-mqn/genealogical_record_linkage",
"score": 3
} |
#### File: genealogical_record_linkage/scripts/fs_xml_cen.py
```python
from __future__ import division
import re
import os
import time
import fnmatch
import gzip
def ungzip(gz):
inF = gzip.open(gz, 'rb')
outF = open(gz[:-3], 'wb')
try:
outF.write( inF.read() )
except:
print 'failed'
pass
inF.close()
outF.close()
def write_file(path, dir):
#initialize summary variables
lines_written=failed=ark_found=gender_found=given_name_found=surname_found=census_place_found=census_next_line=birth_info_soon=0
birth_year_found=birth_place_found=fs_record_id_soon=fs_record_id_found=race_soon=race_found=relationship_soon=relationship_found=0
output = dir + '/done/' + path + '_processed.txt'
loop_start = time.time()
with open(path, 'r+') as infile, open(output, 'w') as output_file:
#initialize the variables
arkid=unique_identifier=fs_record_id=given_name=surname=birth_year=birth_place=gender=race=relationship=census_place=" "
#write the first line of the output file
first_line = 'file|arkid|fs_record_id|given_name|surname|birth_year|birth_place|gender|race|relationship|census_place\n'
output_file.write(first_line)
for line in infile:
#remove leading spaces
line = line.lstrip()
#finds the arkid
if line[0:4] == '<ide' and ark_found == 0:
arkid = re.search(r"([2-9A-Z]{4}-[0-9A-Z]{3})",line)
if arkid:
arkid = arkid.group(1)
ark_found = 1
else:
continue
#now find gender, make it binary
if line[1:7] == 'gender' and gender_found == 0:
gender = re.search(r"/(Female|Male)",line)
if gender:
gender = 1 if gender.group(1) == "Male" else 0
gender_found = 1
#now find birth name
if re.search(r"/(Given)\" value",line) and given_name_found == 0:
given_name = re.search(r"value\=\"(.*)\">",line)
given_name = given_name.group(1)
given_name_found == 1
if re.search(r"/(Surname)\" value",line) and surname_found == 0:
surname = re.search(r"value\=\"(.*)\">",line)
surname = surname.group(1)
surname_found == 1
#now find census location
if line[0:7] == '<place>' and census_place_found == 0:
census_next_line = 1
continue
if census_next_line == 1:
census_next_line = 0
census_place = re.search(r"<original>(.*)</original>",line)
census_place = census_place.group(1)
census_place_found = 1
#now find bith year
if re.search(r"/(Birth)\"",line) and birth_year_found == 0:
birth_info_soon = 1
if birth_info_soon == 1 and birth_year_found == 0:
birth_year = re.search(r"<original>([A-Za-z0-9 ,]+)</original>",line)
if birth_year:
birth_year = birth_year.group(1)
birth_year_found = 1
continue
else:
birthyear = '0000'
if birth_info_soon == 1 and birth_year_found == 1 and birth_place_found == 0:
birth_place = re.search(r"<original>([A-Za-z0-9 ,]+)</original>",line)
if birth_place:
birth_place = birth_place.group(1)
birth_place_found = 1
birth_info_soon == 0
#now get record id that we could manipulate to group families
if re.search(r"\"(FS_RECORD_ID)\"",line) and fs_record_id_found == 0:
fs_record_id_soon = 1
continue
if fs_record_id_soon == 1 and fs_record_id_found == 0:
fs_record_id = re.search(r"<text>([0-9_]+)</text>",line)
if fs_record_id:
fs_record_id = fs_record_id.group(1)
fs_record_id_found = 1
fs_record_id_soon = 0
#now get race
if re.search(r"\"(PR_RACE_OR_COLOR)\"",line) and race_found == 0:
race_soon = 1
continue
if race_soon == 1:
race = re.search(r"<text>(.*)</text>",line).group(1)
race_found = 1
race_soon = 0
#now get relationship to head
if re.search(r"\"(PR_RELATIONSHIP_TO_HEAD)\"",line) and relationship_found == 0:
relationship_soon = 1
continue
if relationship_soon == 1:
relationship = re.search(r"<text>(.*)</text>",line).group(1)
relationship_found = 1
relationship_soon = 0
#now to find the end of a persons record, write to csv, reinitialize starting vars
if re.search(r"(</person>)",line):
lines_written = lines_written + 1
try:
out_line = path + '|' + str(arkid) + '|' + str(fs_record_id) + '|' + str(given_name) + '|' + str(surname) + '|' + str(birth_year) + '|' + str(birth_place) + '|' + str(gender) + '|' + str(race) + '|' + str(relationship) + '|' + str(census_place) + '\n'
output_file.write(out_line)
except:
failed += 1
lines_written=failed=ark_found=gender_found=given_name_found=surname_found=census_place_found=census_next_line=birth_info_soon=0
birth_year_found=birth_place_found=fs_record_id_soon=fs_record_id_found=race_soon=race_found=relationship_soon=relationship_found=0
loop_end = time.time()
loop_elapsed = loop_end - loop_start
#summary
print '\nsummary:\n'
print 'file: ' + path
print 'time elapsed: %.2f'%(loop_elapsed)
print 'lines written: %d'%(lines_written)
print 'failed: %d\n'%(failed)
def main():
dir = 'R:/JoePriceResearch/record_linking/data/census_1910/'
os.chdir(dir)
#find zip files
files = fnmatch.filter(dir,'.gz')
begin = time.time()
i = 0
for file in files:
print 'working on ' + file
ungzip(file)
txt = file[:-3]
write_file(txt, dir)
i += 1
os.remove(txt)
remaining = len(files) - i
average_time = (time.time() - begin)/(60*i)
time_remaining = average_time*remaining
print 'done: %d'%(done)
print 'remaining: %d'%(remaining)
print 'average time: %.2f'%(average_time)
print 'time remaining: %.2f\n'%(time_remaining)
time_elapsed = (time.time() - begin)/60
print 'time elapsed: %.2f'%(time_elapsed)
if __name__ == "__main__":
main()
``` |
{
"source": "JonMrowczynski/MusicTransformer-Pytorch",
"score": 2
} |
#### File: JonMrowczynski/MusicTransformer-Pytorch/evaluate.py
```python
import torch.nn as nn
from torch.utils.data import DataLoader
from dataset.e_piano import create_epiano_datasets
from model.music_transformer import MusicTransformer
from utilities.argument_funcs import parse_eval_args, print_eval_args
from utilities.constants import *
from utilities.device import get_device, use_cuda
from utilities.run_model import eval_model
# main
def main():
"""
----------
Author: <NAME>
----------
Entry point. Evaluates a model specified by command line arguments
----------
"""
args = parse_eval_args()
print_eval_args(args)
if args.force_cpu:
use_cuda(False)
print("WARNING: Forced CPU usage, expect model to perform slower")
print("")
# Test dataset
_, _, test_dataset = create_epiano_datasets(args.dataset_dir, args.max_sequence)
test_loader = DataLoader(test_dataset, batch_size=args.batch_size, num_workers=args.n_workers)
model = MusicTransformer(n_layers=args.n_layers, num_heads=args.num_heads,
d_model=args.d_model, dim_feedforward=args.dim_feedforward,
max_sequence=args.max_sequence, rpr=args.rpr).to(get_device())
model.load_state_dict(torch.load(args.model_weights, map_location=get_device()))
# No smoothed loss
loss = nn.CrossEntropyLoss(ignore_index=TOKEN_PAD)
print("Evaluating:")
model.eval()
avg_loss, avg_acc = eval_model(model, test_loader, loss)
print("Avg loss:", avg_loss)
print("Avg acc:", avg_acc)
print(SEPERATOR)
print("")
if __name__ == "__main__":
main()
```
#### File: MusicTransformer-Pytorch/model/loss.py
```python
import torch
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
# Borrowed from https://github.com/jason9693/MusicTransformer-pytorch/blob/5f183374833ff6b7e17f3a24e3594dedd93a5fe5/custom/criterion.py#L28
class SmoothCrossEntropyLoss(_Loss):
"""
https://arxiv.org/abs/1512.00567
"""
__constants__ = ['label_smoothing', 'vocab_size', 'ignore_index', 'reduction']
def __init__(self, label_smoothing, vocab_size, ignore_index=-100, reduction='mean', is_logits=True):
assert 0.0 <= label_smoothing <= 1.0
super().__init__(reduction=reduction)
self.label_smoothing = label_smoothing
self.vocab_size = vocab_size
self.ignore_index = ignore_index
self.input_is_logits = is_logits
def forward(self, input, target):
"""
Args:
input: [B * T, V]
target: [B * T]
Returns:
cross entropy: [1]
"""
mask = (target == self.ignore_index).unsqueeze(-1)
q = F.one_hot(target.long(), self.vocab_size).type(torch.float32)
u = 1.0 / self.vocab_size
q_prime = (1.0 - self.label_smoothing) * q + self.label_smoothing * u
q_prime = q_prime.masked_fill(mask, 0)
ce = self.cross_entropy_with_logits(q_prime, input)
if self.reduction == 'mean':
lengths = torch.sum(target != self.ignore_index)
return ce.sum() / lengths
elif self.reduction == 'sum':
return ce.sum()
else:
raise NotImplementedError
@staticmethod
def cross_entropy_with_logits(p, q):
return -torch.sum(p * (q - q.logsumexp(dim=-1, keepdim=True)), dim=-1)
``` |
{
"source": "jonmsawyer/django-exception-mailer",
"score": 2
} |
#### File: jonmsawyer/django-exception-mailer/mailer.py
```python
import traceback
import json
import collections
import inspect
from datetime import datetime
from django.conf import settings
from django.core.mail import send_mail, mail_admins
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
__version__ = "0.1"
lexer = get_lexer_by_name("python", stripall=True)
formatter = HtmlFormatter(cssclass="source")
def pretty_print(d, indent=0):
if not isinstance(d, dict):
return d
# Sometimes our dictionary will have non-string keys. Stringify the keys so they can be
# ordered without raising a TypeError exception.
new_dict = {}
for key in d.keys():
new_dict[str(key)] = d.get(key)
try:
od = collections.OrderedDict(sorted(new_dict.items()))
except TypeError as e:
od = collections.OrderedDict(new_dict)
del new_dict
txt = ''
t = ' ' * (indent+1)
for key, value in od.items():
txt = txt + t + str(key) + ": "
if isinstance(value, dict):
txt = txt + '{\n' + pretty_print(value, indent+1) + t + '}\n'
elif value == None:
txt = txt + '<None>' + ',\n'
elif isinstance(value, bool):
if value:
txt = txt + 'True,\n'
else:
txt = txt + 'False,\n'
else:
txt = txt + repr(value) + ',\n'
return txt
class AdminMailer(object):
# mail_admins(subject, message, fail_silently=False,
# connection=None, html_message=None)
@staticmethod
def mail(subject='', message='',
fail_silently=True, connection=None, html_message=None):
mail_admins(subject, message, fail_silently, connection, html_message)
class ExceptionMailer(AdminMailer):
subject = 'Exception!'
@staticmethod
def get_name(name):
if name is None:
return ''
if isinstance(name, str):
return repr(name.strip())
return repr(name)
@staticmethod
def get_subject(name):
if name != '' and name is not None:
return "%s [%s]" % (ExceptionMailer.subject, name)
return ExceptionMailer.subject
@staticmethod
def get_mailer_traceback(stack, exception):
frame, from_file, line_no, where_in, code, something_else = stack
if isinstance(exception, Exception):
e = "\nException is %r" % (exception,)
else:
e = ''
code = (''.join(code)).strip()
return (
'File "%s", line %s, in %s\n %s%s' % (from_file, line_no, where_in, code, e)
).strip()
@staticmethod
def get_session(request):
try:
return pretty_print(request.session.__dict__)
except Exception as e:
return "(No session available. Reason: %s)" % (e,)
@staticmethod
def get_meta(request):
try:
return pretty_print(request.META)
except Exception as e:
return "(No META available. Reason: %s)" % (e,)
@staticmethod
def get_ip(request):
try:
ip = request.META.get('HTTP_X_FORWARDED_FOR', '').split(',')[0]
if ip == '':
return "%s (not proxied)" % (request.META.get('REMOTE_ADDR', ''),)
else:
return "%s (proxied)" % (ip,)
except Exception as e:
return "(No IP available. Reason: %s)" % (e,)
@staticmethod
def get_method(request):
try:
return request.META.get('REQUEST_METHOD', '???')
except Exception as e:
return "(No request method available. Reason: %s)" % (e,)
@staticmethod
def get_base_path(request):
try:
return request.META.get('REQUEST_URI', '').split('?')[0]
except Exception as e:
return "(No base path available. Reason: %s)" % (e,)
@staticmethod
def get_user_agent(request):
try:
return request.META.get('HTTP_USER_AGENT')
except Exception as e:
return "(No user agent available. Reason: %s)" % (e,)
@staticmethod
def get_request_url(request):
try:
proto = request.META.get('HTTP_X_FORWARDED_PROTO', 'proto')
host = request.META.get('HTTP_X_FORWARDED_HOST', 'unknown.host')
uri = request.META.get('REQUEST_URI', '/#unknown_request_uri')
if proto == 'proto' or host == 'unknown.host' or uri == '/#unknown_request_uri':
proto = request.META.get('REQUEST_SCHEME', 'proto')
host = request.META.get('HTTP_HOST', 'unknown.host')
uri = request.META.get('SCRIPT_URL', '/#unknown_script_url')
return "%s://%s%s" % (proto, host, uri)
except Exception as e:
return "(No request URL available. Reason: %s)" % (e,)
@staticmethod
def get_referer(request):
try:
return request.META.get('HTTP_REFERER', '')
except Exception as e:
return "(No referer available. Reason: %s)" % (e,)
@staticmethod
def get_query_string(request):
try:
return request.META.get('QUERY_STRING', '')
except Exception as e:
return "(No query string available. Reason: %s)" % (e,)
@staticmethod
def get_get_params(request):
try:
return pretty_print(request.GET)
except Exception as e:
return "(No GET available. Reason: %s)" % (e,)
@staticmethod
def get_post_params(request):
try:
return pretty_print(request.POST)
except Exception as e:
return "(No POST available. Reason: %s)" % (e,)
@staticmethod
def get_path_info(request):
try:
return request.META.get('mod_wsgi.path_info', '/#unknown_path_info')
except Exception as e:
return "(No path info available. Reason: %s)" % (e,)
@staticmethod
def get_proxied_url(request):
try:
return request.META.get('SCRIPT_URI', '???')
except Exception as e:
return "(No proxied url available. Reason: %s)" % (e,)
@staticmethod
def get_globals(_globals):
if _globals is None:
return ''
return pretty_print(_globals)
@staticmethod
def get_locals(_locals):
if _locals is None:
return ''
return pretty_print(_locals)
@staticmethod
def mail(request, name='', ignore=False, exception=None, _globals=None, _locals=None):
if ignore is True:
return
dttm = datetime.now().isoformat(' ')
name = ExceptionMailer.get_name(name)
subject = ExceptionMailer.get_subject(name)
stack_frame = inspect.stack()[1]
text_msg_params = {
'timestamp': dttm,
'mailer_traceback': ExceptionMailer.get_mailer_traceback(stack_frame, exception),
'exception_traceback': traceback.format_exc().strip(),
'session': ExceptionMailer.get_session(request),
'meta': ExceptionMailer.get_meta(request),
'ip': ExceptionMailer.get_ip(request),
'method': ExceptionMailer.get_method(request),
'base_path': ExceptionMailer.get_base_path(request),
'user_agent': ExceptionMailer.get_user_agent(request),
'request_url': ExceptionMailer.get_request_url(request),
'referer': ExceptionMailer.get_referer(request),
'query_string': ExceptionMailer.get_query_string(request),
'get': ExceptionMailer.get_get_params(request),
'post': ExceptionMailer.get_post_params(request),
'path_info': ExceptionMailer.get_path_info(request),
'proxied_url': ExceptionMailer.get_proxied_url(request),
'globals': ExceptionMailer.get_globals(_globals),
'locals': ExceptionMailer.get_locals(_locals),
'subject': subject,
}
text_message = '''
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# == {subject} ==
Remote IP: {ip}
Method: {method}
Request URI: {request_url}
Base Path: {base_path}
Query String: ?{query_string}
WSGI Path Info: {path_info}
User Agent: {user_agent}
Proxied URI: {proxied_url}
Referer: {referer}
Timestamp: {timestamp}
# == Parameters ==
GET: {{
{get}}}
POST: {{
{post}}}
# == Exception Traceback ==
{exception_traceback}
# == ExceptionMailer Traceback ==
{mailer_traceback}
# == Client Session ==
{{
{session}}}
# == Request META (HTTP Headers and Env Variables) ==
{{
{meta}}}
# == Locals ==
{{
{locals}}}
# == Globals ==
{{
{globals}}}
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# --OQ Mailer
'''.format(**text_msg_params)
html_params = {
'style': formatter.get_style_defs(),
'body': highlight(text_message, lexer, formatter)
}
html_message = '''<!DOCTYPE html>
<html>
<head><style>{style}</style></head>
<body>{body}</body>
</html>
'''.format(**html_params)
# Mail it off
mail_admins(
subject=subject,
message=text_message,
fail_silently=True,
connection=None,
html_message=html_message
)
``` |
{
"source": "jonmsawyer/jscraper",
"score": 3
} |
#### File: jscraper/scrapers/TwitterScraper.py
```python
import os
import sys
import argparse
try:
from scrapers.TemplateScraper import TemplateScraper
from scrapers.ScraperDriver import ScraperDriver
except ImportError:
from TemplateScraper import TemplateScraper
from ScraperDriver import ScraperDriver
class TwitterScraper(TemplateScraper):
"""Twitter scraper class."""
name = 'twitter'
filename = os.path.basename(__file__)
def __init__(self, driver, *args, **kwargs):
super().__init__(driver, self.name, *args, **kwargs)
self.log('name from TwitterScraper():', self.name)
def parse_arguments(self):
'''Get the arguments parser and add arguments to it. Then parse `args` with the parser
definition defined in the base class to obtain an `options` dict.
'''
self.parser = argparse.ArgumentParser(prog=self.prog,
description='Scrape a URI resource for images.')
self.parser.add_argument('-VOODOO', metavar='Z', type=str, dest='VOODOO',
default='TwitterScraper-VOODOO',
help='TwitterScraper-extended base option.')
self.parser.add_argument('--begin-date', metavar='BEGIN_DATE', type=str, dest='begin_date',
default='1970-01-01 00:00:00.00',
help=('TwitterScraper-only option. Download images that have '
'their modification date to be greater than BEGIN_DATE'))
self.parser.add_argument('--end-date', metavar='END_DATE', type=str, dest='end_date',
default='2099-12-12 23:59:59.999',
help=('TwitterScraper-only option. Download images that have '
'their modification date to be less than END_DATE'))
super().parse_arguments()
@staticmethod
def sub_parser(subparsers):
'''A subparser is passed in as `subparsers`. Add a new subparser to the `subparsers` object
then return that subparser. See `argparse.ArgumentsParser` for details.
'''
parser = subparsers.add_parser('twitter', help=('Invoke the twitter scraper to scrape '
'images off of twitter.com'))
return parser
def handle(self):
'''Main class method that drives the work on scraping the images for this GenericScraper.
'''
self.write('Args:', self.args)
self.write('Parser:', self.parser)
self.write('Parsed options:', self.options)
self.write('')
self.write('This is the TwitterScraper.')
if __name__ == '__main__':
# If TwitterScraper was invoked via the command line, initialize a driver and obtain the
# TwitterScraper, then execute the main handle() method.
driver = ScraperDriver(*sys.argv)
driver.log('Args:', sys.argv)
scraper = TwitterScraper(driver)
driver.log('scraper =', scraper)
scraper.handle()
``` |
{
"source": "jonmsawyer/jsonbench",
"score": 2
} |
#### File: apps/benchmark/models.py
```python
import platform, re
import django
from django.utils import timezone
from django.db import models
import psutil
app_re = re.compile('func=(.*?),')
class BenchmarkSuite(models.Model):
suite_name = models.CharField(max_length=255, blank=True, null=True)
suite_docstring = models.CharField(max_length=1000, blank=True, null=True)
command_line_arguments = models.CharField(max_length=255, blank=True, null=True)
app_to_benchmark = models.CharField(max_length=255, blank=True, null=True)
db_type = models.CharField(max_length=255, blank=True, null=True)
db_info = models.CharField(max_length=255, blank=True, null=True)
db_stat_before_suite = models.CharField(max_length=255, blank=True, null=True)
db_stat_after_suite = models.CharField(max_length=255, blank=True, null=True)
cpu_info = models.CharField(max_length=255, blank=True, null=True)
python_info = models.CharField(max_length=255, blank=True, null=True)
django_info = models.CharField(max_length=255, blank=True, null=True)
django_user = models.CharField(max_length=255, blank=True, null=True)
last_handled_exception = models.CharField(max_length=255, blank=True, null=True)
last_unhandled_exception = models.CharField(max_length=255, blank=True, null=True)
records_in = models.PositiveIntegerField(blank=True, null=True)
records_out = models.PositiveIntegerField(blank=True, null=True)
begin_time = models.DateTimeField(blank=True, null=True)
end_time = models.DateTimeField(blank=True, null=True)
duration = models.DurationField(blank=True, null=True)
is_complete = models.NullBooleanField()
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
def __str__(self):
return '{id} | {created_at} | {app} | {suite} | {duration}'.format(
id=self.id, created_at=self.created_at, app=self.app_to_benchmark,
suite=self.suite_name, duration=self.duration
)
@staticmethod
def NewWebBenchmarkSuite(request, name):
try:
matches = app_re.search(str(request.resolver_match))
app = matches.groups()[0]
except Exception as e:
app = str(request.resolver_match)
bs = BenchmarkSuite(
suite_name='web.{}.request.{} {}'.format(name, request.method, request.get_full_path()),
app_to_benchmark=app,
cpu_info=str(platform.uname()),
python_info=str(platform.python_build()),
django_info=django.get_version(),
django_user=str(request.user)
)
bs.save()
return bs
def start(self):
self.is_complete = None
self.end_time = None
self.begin_time = timezone.now()
self.is_complete = None
self.save()
def stop(self):
try:
self.current_step.stop()
except:
pass
self.is_complete = True
self.end_time = timezone.now()
self.duration = self.end_time - self.begin_time
self.is_complete = True
self.save()
def next_step(self, request, name):
try:
current_step = self.current_step
current_step.stop()
next_step = current_step.step_number + 1
except:
current_step = None
next_step = 1
try:
matches = app_re.search(str(request.resolver_match))
app = matches.groups()[0]
except Exception as e:
app = str(request.resolver_match)
bs = BenchmarkStep(
benchmark=self,
step_number=next_step,
description='{} | {}'.format(name, app)
)
bs.save()
bs.start()
self.current_step = bs
def log(self, log):
BenchmarkLog(benchmark=self, log=log).save()
class BenchmarkStep(models.Model):
benchmark = models.ForeignKey(BenchmarkSuite)
step_number = models.PositiveIntegerField()
description = models.CharField(max_length=255, blank=True, null=True)
ram_info_before_step = models.CharField(max_length=255, blank=True, null=True)
ram_info_after_step = models.CharField(max_length=255, blank=True, null=True)
last_handled_exception = models.CharField(max_length=255, blank=True, null=True)
last_unhandled_exception = models.CharField(max_length=255, blank=True, null=True)
records_in = models.PositiveIntegerField(blank=True, null=True)
records_out = models.PositiveIntegerField(blank=True, null=True)
begin_time = models.DateTimeField(blank=True, null=True)
end_time = models.DateTimeField(blank=True, null=True)
duration = models.DurationField(blank=True, null=True)
is_complete = models.NullBooleanField()
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
def __str__(self):
# TODO: Fix references
return '{id} | Benchmark ID {bid} | Step {number} | {description}'.format(
id=self.id, bid=self.benchmark.id,
number=self.step_number, description=self.description
)
def start(self):
self.begin_time = timezone.now()
self.end_time = None
self.duration = None
self.is_complete = None
self.ram_info_before_step = str(psutil.virtual_memory())
self.save()
def stop(self):
self.end_time = timezone.now()
self.duration = self.end_time - self.begin_time
self.is_complete = True
self.ram_info_after_step = str(psutil.virtual_memory())
self.save()
class BenchmarkLog(models.Model):
benchmark = models.ForeignKey(BenchmarkSuite)
log = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
def __str__(self):
return '{id} | Benchmark ID {bid} | Created at {created_at} | Updated at {updated_at}'.format(
id=self.id, bid=self.benchmark.id,
created_at=self.created_at, updated_at=self.updated_at
)
```
#### File: benchmark/templatetags/benchmark_extras.py
```python
import collections # For an OrderedDict[ionary]
from django import template
from django import forms
from django.utils.safestring import mark_safe
from django.db import models
register = template.Library()
def to_dict(ob):
attrs = dir(ob)
dict_list = []
for attr in attrs:
if attr.startswith('__') and attr.endswith('__'):
continue
try:
dict_list.append((attr, getattr(ob, attr)))
except Exception as e:
dict_list.append((attr, 'Exception: {}'.format(e)))
return dict(dict_list)
@register.filter
def pretty(ob, indent=0):
if isinstance(ob, dict):
d = ob
else:
d = to_dict(ob)
od = collections.OrderedDict(sorted(d.items()))
txt = ''
t = ' ' * (indent+1)
for key, value in od.items():
txt = txt + t + str(key) + ": "
if isinstance(value, dict):
txt = txt + '{\n' + pretty(value, indent+1) + t + '}\n'
elif value == None:
txt = txt + '<None>' + ',\n'
elif isinstance(value, bool):
if value:
txt = txt + 'True,\n'
else:
txt = txt + 'False,\n'
else:
txt = txt + repr(value).replace('<', '<').replace('>', '>') + ',\n'
return mark_safe(txt)
@register.filter
def dir_list(obj):
return str(obj.__class__) + "\n" + str(dir(obj))
@register.filter
def value(string, value):
return string.format(value)
```
#### File: apps/jsondictbench/views.py
```python
import json
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from django.conf import settings
from apps.jsondictbench.models import Board, Thread, Post, ForumUser
boards_per_page = settings.JSONBENCH_BOARDS_PER_PAGE
threads_per_page = settings.JSONBENCH_THREADS_PER_PAGE
posts_per_page = settings.JSONBENCH_POSTS_PER_PAGE
@login_required
def index(request):
cd = {'boards': None, 'prof': None}
p = Paginator(Board.objects.all(), boards_per_page)
try:
boards = p.page(request.GET.get('ipage'))
except PageNotAnInteger:
boards = p.page(1)
except EmptyPage:
boards = p.page(p.num_pages)
cd['boards'] = boards
cd['prof'] = 'prof' if 'prof' in request.GET else ''
return render(request, 'jsondictbench/index.html', cd)
@login_required
def view_board(request, board_id=None):
cd = {'board_id': board_id, 'threads': None, 'prof': None}
board = Board.objects.get(pk=board_id)
p = Paginator(board.thread_set.all(), threads_per_page)
try:
threads = p.page(request.GET.get('bpage'))
except PageNotAnInteger:
threads = p.page(1)
except EmptyPage:
threads = p.page(p.num_pages)
cd['board'] = board
cd['threads'] = threads
cd['prof'] = 'prof' if 'prof' in request.GET else ''
cd['ipage'] = request.GET.get('ipage', '')
return render(request, 'jsondictbench/view_board.html', cd)
@login_required
def view_thread(request, board_id=None, thread_id=None):
cd = {'board_id': board_id, 'thread_id': thread_id, 'posts': None, 'prof': None}
board = Board.objects.get(pk=board_id)
thread = Thread.objects.get(pk=thread_id)
p = Paginator(thread.post_set.all(), posts_per_page)
try:
posts = p.page(request.GET.get('tpage'))
except PageNotAnInteger:
posts = p.page(1)
except EmptyPage:
posts = p.page(p.num_pages)
cd['board'] = board
cd['thread'] = thread
cd['posts'] = posts
cd['prof'] = 'prof' if 'prof' in request.GET else ''
cd['ipage'] = request.GET.get('ipage', '')
cd['bpage'] = request.GET.get('bpage', '')
cd['posts_per_page'] = posts_per_page
return render(request, 'jsondictbench/view_thread.html', cd)
@login_required
def view_post(request, board_id=None, thread_id=None, post_id=None):
cd = {'board_id': board_id, 'thread_id': thread_id, 'post_id': post_id, 'posts': None, 'prof': None}
bs = request.benchmarksuite
board = Board.objects.get(pk=board_id)
thread = Thread.objects.get(pk=thread_id)
post = Post.objects.get(pk=post_id)
p = Paginator(thread.post_set.all(), 1)
try:
posts = p.page(request.GET.get('ppage'))
except PageNotAnInteger:
posts = p.page(1)
except EmptyPage:
posts = p.page(p.num_pages)
cd['board'] = board
cd['thread'] = thread
cd['posts'] = posts
cd['post'] = post
cd['prof'] = 'prof' if 'prof' in request.GET else ''
cd['ipage'] = request.GET.get('ipage', '')
cd['bpage'] = request.GET.get('bpage', '')
cd['tpage'] = request.GET.get('tpage', '')
cd['ppage'] = request.GET.get('ppage', '')
if posts.has_previous():
prev_posts = p.page(posts.previous_page_number())
for prev_post in prev_posts:
cd['prev_post'] = prev_post # shoud only loop once
cd['prev_post_tpage'] = int((prev_posts.number - 1)/posts_per_page) + 1
else:
cd['prev_post'] = None
cd['prev_post_tpage'] = posts.number
if posts.has_next():
next_posts = p.page(posts.next_page_number())
for next_post in next_posts:
cd['next_post'] = next_post # should only loop once
cd['next_post_tpage'] = int((next_posts.number - 1)/posts_per_page) + 1
else:
cd['next_post'] = None
cd['next_post_tpage'] = posts.number
if request.GET.get('mark_read'):
bs.next_step(request, 'jsondictbench: before read_post') if bs else None
cd['post_has_been_read'] = read_post(thread, post, request.user)
bs.next_step(request, 'jsondictbench: after read_post') if bs else None
if request.GET.get('mark_unread'):
bs.next_step(request, 'jsondictbench: before unread_post') if bs else None
cd['post_has_been_unread'] = unread_post(thread, post, request.user)
bs.next_step(request, 'jsondictbench: after unread_post') if bs else None
bs.next_step(request, 'jsondictbench: before is_post_read') if bs else None
cd['post_is_read'] = is_post_read(thread, post, request.user)
bs.next_step(request, 'jsondictbench: after read_post') if bs else None
return render(request, 'jsondictbench/view_post.html', cd)
def is_post_read(thread, post, user):
read_posts = json.loads(ForumUser.objects.get(user=user).posts_read)
try:
if post.id in read_posts.get(str(thread.id)):
return True
else:
return False
except TypeError: # thread.id is not in read_posts dict, which results in NoneType
return False
def read_post(thread, post, user):
try:
forum_user = ForumUser.objects.get(user=user)
read_posts = json.loads(forum_user.posts_read)
if str(thread.id) not in read_posts:
read_posts[str(thread.id)] = []
read_posts.get(str(thread.id)).append(post.id)
forum_user.posts_read = json.dumps(read_posts, indent=4)
forum_user.save()
return True
except:
return False
def unread_post(thread, post, user):
try:
forum_user = ForumUser.objects.get(user=user)
read_posts = json.loads(forum_user.posts_read)
if post.id in read_posts.get(str(thread.id)):
read_posts.get(str(thread.id)).remove(post.id)
forum_user.posts_read = json.dumps(read_posts, indent=4)
forum_user.save()
return True
else:
return False
except:
return False
```
#### File: management/commands/_base_command.py
```python
import json
from io import TextIOWrapper
from django.core.management.base import BaseCommand, CommandError
class _BaseCommand(BaseCommand):
##################################################################
# Style objects reference from django.core.management.color.Style:
#
# self.style.ERROR
# self.style.ERROR_OUTPUT
# self.style.HTTP_BAD_REQUEST
# self.style.HTTP_INFO
# self.style.HTTP_NOT_FOUND
# self.style.HTTP_NOT_MODIFIED
# self.style.HTTP_REDIRECT
# self.style.HTTP_SERVER_ERROR
# self.style.HTTP_SUCCESS
# self.style.MIGRATE_HEADING
# self.style.MIGRATE_LABEL
# self.style.NOTICE
# self.style.SQL_COLTYPE
# self.style.SQL_FIELD
# self.style.SQL_KEYWORD
# self.style.SQL_TABLE
# self.style.SUCCESS
# self.style.WARNING
#
##################################################################
def write(self, *args, **kwargs):
try:
flush = kwargs.pop('flush')
except KeyError:
flush = False
self.stdout.write(*args, **kwargs)
if flush:
self.stdout.flush()
def write_success(self, *args, **kwargs):
self.write(self.style.SUCCESS(*args), **kwargs)
def write_notice(self, *args, **kwargs):
self.write(self.style.NOTICE(*args), **kwargs)
def write_warning(self, *args, **kwargs):
self.write(self.style.WARNING(*args), **kwargs)
def write_error(self, *args, **kwargs):
self.write(self.style.ERROR(*args), **kwargs)
def write_to_json_file(self, filename, content, json_indent=4):
self.write_to_file(filename, content, to_json=True, json_indent=json_indent)
def write_to_file(self, filename, content, to_json=False, json_indent=4):
if isinstance(filename, str):
fname = filename
ftype = 'string'
elif isinstance(filename, TextIOWrapper):
fname = filename.name
ftype = 'file'
else:
raise CommandError('{} is not of type str or of type io.TextIOWrapper'.format(filename))
self.write_notice('writing to file "{}" ... '.format(fname), ending='', flush=True)
if ftype == 'string':
with open(filename, 'a') as fh:
if to_json:
fh.write(json.dumps(content, indent=json_indent))
else:
fh.write(str(content))
elif ftype == 'file':
if to_json:
filename.write(json.dumps(content, indent=json_indent))
else:
filename.write(str(content))
self.write_success('success!')
def positive_int(self, string):
value = int(string)
if value <= 0:
raise CommandError('{} is not a positive integer'.format(string))
return value
``` |
{
"source": "jonmsawyer/maio",
"score": 2
} |
#### File: management/commands/maio_gen_secret_key.py
```python
from random import choice
from string import printable
from django.core.management.base import CommandError
from ._base import MaioBaseCommand
class Command(MaioBaseCommand):
args = '<None>'
help = 'Generates a pseudorandom SECRET_KEY for use in conf/site_settings.py'
def add_arguments(self, parser):
# Positional arguments
parser.add_argument('num_chars', nargs='?', type=int, default=50, metavar='NUM_CHARS',
help=('Generate a secret key with %(metavar)s characters. Default '
'is %(default)s characters.'))
def handle(self, *args, **options):
num_chars = options.get('num_chars', 50)
self.out("SECRET_KEY = '%s'" % (
''.join([choice(printable[:-6]) for x in range(0, int(num_chars))]) \
.replace("'", "\\'"),))
```
#### File: maio/scripts/get_images.py
```python
import os
import sys
import hashlib
os.environ['DJANGO_SETTINGS_MODULE'] = 'maio.settings'
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
sys.path.insert(0, BASE_DIR)
import magic
from PIL import Image
from django.conf import settings
import django
django.setup()
from maio_core.models import File
MAIO_SETTINGS = settings.MAIO_SETTINGS
mimetype_extension = {
'image': {
'image/gif': '.gif',
'image/jpeg': '.jpg',
'image/pjpeg': '.jpg',
'image/png': '.png',
'image/svg+xml': '.svg',
'image/tiff': '.tiff',
'image/bmp': '.bmp',
'image/x-windows-bmp': '.bmp',
'image/x-tiff': '.tiff',
}
}
def usage():
print("Usage:")
print("")
print("%s DIR" % (sys.argv[0],))
print("")
print(" DIR")
print(" The directory to recursively walk for images to store in the database.")
print("")
def mk_md5_dir(md5, root):
if len(md5) == 32:
part1 = md5[0:2]
part2 = md5[2:4]
part3 = md5[4:6]
dirtomake = os.path.join(root, part1, part2, part3)
if os.path.isdir(dirtomake):
return dirtomake
if os.path.isdir(root):
os.makedirs(dirtomake)
return dirtomake
def is_image(mimetype):
for key, value in mimetype_extension['image'].items():
if mimetype == key:
return True
return False
if len(sys.argv) == 1:
print("Please provide a directory to recursively walk for pictures.")
print("")
usage()
exit(1)
directory = sys.argv[1]
if not os.path.isdir(directory):
print("\"%s\" is not a valid directory." % (directory,))
print("")
usage()
exit(1)
mime = magic.Magic(mime=True)
for root, subdirs, files in os.walk(directory):
for filename in files:
try:
file_path = os.path.join(root, filename)#.decode('utf-8')
except UnicodeDecodeError as e:
if "'utf8' codec can't decode bytes" in str(e):
print("Error processing %s, unreadable file name ..." % (os.path.join(root, filename),))
continue
else:
raise
except:
raise
# get mime type
try:
mimetype = mime.from_file(file_path)
except IOError as e:
if 'File does not exist' in str(e):
print('file %s does not exist' % (file_path,))
continue
else:
raise
except UnicodeDecodeError as e:
print("File: ", file_path)
raise
except:
raise
if not is_image(mimetype):
print('%s is not a valid image type... (it might be a symlink?)' % (file_path,))
continue
# stat file
sfile = os.stat(file_path)
# open image
truncated = False
try:
im = Image.open(file_path)
if MAIO_SETTINGS.get('images_min_inclusive', '').lower() == 'and':
if im.size[0] < MAIO_SETTINGS.get('images_min_width', 0) or \
im.size[1] < MAIO_SETTINGS.get('images_min_height', 0):
continue
elif MAIO_SETTINGS.get('images_min_inclusive', '').lower() == 'or':
if im.size[0] < MAIO_SETTINGS.get('images_min_width', 0) and \
im.size[1] < MAIO_SETTINGS.get('images_min_height', 0):
continue
else:
pass
im.load()
if im.mode != "RGB":
im = im.convert("RGB")
except IOError as e:
print('Error in processing %s ...' % (file_path,), end='')
if 'truncated' in str(e):
print('truncated')
truncated = True
pass
elif 'cannot identify image file' in str(e):
print('invalid image file')
continue
elif 'No such file or directory' in str(e):
print('no such file or directory')
continue
else:
raise
# get md5sum
md5sum = hashlib.md5()
with open(file_path, 'rb') as fh:
md5sum.update(fh.read())
md5 = md5sum.hexdigest()
# process thumbnail
thumb_dir = mk_md5_dir(md5, settings.MAIO_SETTINGS['thumbnail_directory'])
thumb = os.path.join(thumb_dir,
md5 + '.jpg')
if not os.path.isfile(thumb):
im.thumbnail((128, 128), Image.ANTIALIAS)
im.save(thumb)
print(md5sum.hexdigest(), mimetype, file_path)
# save file information to the database
try:
file_path_hash = hashlib.md5()
file_path_hash.update(file_path.encode('utf-8'))
fph = file_path_hash.hexdigest()
f = File(mime_type=mimetype, size=sfile.st_size, mtime=sfile.st_mtime,
md5sum=md5, tn_path=thumb, file_path=file_path, file_path_hash=fph)
f.save()
except django.db.utils.IntegrityError:
f = File.objects.get(file_path_hash=fph)
if sfile.st_mtime == f.mtime:
print("Already in database and up-to-date, skipping %s ..." % (file_path,))
continue
f.mime_type = mimetype
f.size = sfile.st_size
f.mtime = sfile.st_mtime
f.md5sum = md5
f.tn_path = thumb
f.save()
except:
raise
``` |
{
"source": "jonmun/contextualSpellCheck",
"score": 3
} |
#### File: contextualSpellCheck/tests/test_contextualSpellCheck.py
```python
import pytest
import spacy
from pytest import approx
import warnings
import os
from ..contextualSpellCheck import ContextualSpellCheck
# print(contextualSpellCheck.__name__,contextualSpellCheck.__package__,contextualSpellCheck.__file__,sep="\n")
# This is the class we want to test. So, we need to import it
nlp = spacy.load("en_core_web_sm")
checker = ContextualSpellCheck() # instantiate the Person Class
@pytest.mark.parametrize(
"inputSentence, misspell",
[
(
"Income was $9.4 million \
compared to the prior year of $2.7 million.",
[],
),
("who is <NAME>?", []),
("He released this package in year 2020!", []),
],
)
def test_no_misspellIdentify(inputSentence, misspell):
print("Start no spelling mistake test\n")
doc = nlp(inputSentence)
assert checker.misspell_identify(doc) == (misspell, doc)
@pytest.mark.parametrize(
"inputSentence, misspell",
[
(
"Income was $9.4 milion compared to the prior year of $2.7 milion.",
[4, 13],
)
],
)
def test_type_misspellIdentify(inputSentence, misspell):
print("Start type correction test for spelling mistake identification\n")
doc = nlp(inputSentence)
assert isinstance(checker.misspell_identify(doc)[0], type(misspell))
assert isinstance(checker.misspell_identify(doc)[1], type(doc))
assert checker.misspell_identify(doc)[1] == doc
@pytest.mark.parametrize(
"inputSentence, misspell",
[
(
"Income was $9.4 milion compared to the prior year of $2.7 milion.",
[4, 13],
),
("This packge was cretaed in 2020", [1, 3]),
],
)
def test_identify_misspellIdentify(inputSentence, misspell):
print("Start misspell word identifation test\n")
doc = nlp(inputSentence)
checkerReturn = checker.misspell_identify(doc)[0]
assert isinstance(checkerReturn, list)
# Changed the approach after v0.1.0
assert [tok.text_with_ws for tok in checkerReturn] == [
doc[i].text_with_ws for i in misspell
]
assert [tok.i for tok in checkerReturn] == [doc[i].i for i in misspell]
@pytest.mark.parametrize(
"inputSentence, misspell",
[
(
"Income was $9.4 milion compared to the prior year of $2.7 milion.",
3,
),
(
"Income was $9.4 milion compared to the prior year of $2.7 milion.",
12,
),
("This packge was cretaed in 2020", 5),
],
)
def test_skipNumber_misspellIdentify(inputSentence, misspell):
print("Start number not in misspell word test\n")
doc = nlp(inputSentence)
# Number should not be skipped for misspell
assert doc[misspell] not in checker.misspell_identify(doc)[0]
@pytest.mark.parametrize(
"inputSentence, misspell",
[
("<NAME> should be skipped", 1),
("<NAME> should not be in mis spell", 0),
("<NAME> shuld not be in mis spell", 1),
],
)
def test_skipName_misspellIdentify(inputSentence, misspell):
print("Start name not in misspell word test\n")
doc = nlp(inputSentence)
# Number should not be skipped for misspell
assert doc[misspell] not in checker.misspell_identify(doc)[0]
@pytest.mark.parametrize(
"inputSentence, misspell",
[
("<EMAIL> should be skipped", 0),
("<EMAIL> should not be in mis spell", 0),
],
)
def test_skipEmail_misspellIdentify(inputSentence, misspell):
print("Start Email not in misspell word test\n")
doc = nlp(inputSentence)
assert doc[misspell] not in checker.misspell_identify(doc)[0]
@pytest.mark.parametrize(
"inputSentence, misspell",
[
("eng-movies.com should be skipped", 0),
("bollywood.in should not be in mis spell", 0),
],
)
def test_skipURL_misspellIdentify(inputSentence, misspell):
print("Start URL not in misspell word test\n")
doc = nlp(inputSentence)
assert doc[misspell] not in checker.misspell_identify(doc)[0]
@pytest.mark.parametrize(
"inputSentence, misspell",
[
("eng-movies.com shuld be skipped", 0),
("bollywood.in shuld not be in mis spell", 0),
],
)
def test_type_candidateGenerator(inputSentence, misspell):
doc = nlp(inputSentence)
misspell, doc = checker.misspell_identify(doc)
assert isinstance(checker.candidate_generator(doc, misspell), tuple)
assert isinstance(checker.candidate_generator(doc, misspell)[0], type(doc))
assert isinstance(checker.candidate_generator(doc, misspell)[1], dict)
@pytest.mark.parametrize(
"inputSentence, misspell",
[
(
"Income was $9.4 milion compared to the prior year of $2.7 milion.",
{
4: [
"million",
"billion",
",",
"trillion",
"Million",
"%",
"##M",
"annually",
"##B",
"USD",
],
13: [
"billion",
"million",
"trillion",
"##M",
"Million",
"##B",
"USD",
"##b",
"millions",
"%",
],
},
),
(
"This packge was introduced in 2020",
{
1: [
"system",
"model",
"version",
"technology",
"program",
"standard",
"class",
"feature",
"plan",
"service",
]
},
),
],
)
def test_identify_candidateGenerator(inputSentence, misspell):
print("Start misspell word identifation test\n")
doc = nlp(inputSentence)
(misspellings, doc) = checker.misspell_identify(doc)
doc, suggestions = checker.candidate_generator(doc, misspellings)
# changed after v1.0 because of deepCopy creatng issue with ==
# gold_suggestions = {doc[key]: value for key, value in misspell.items()}
assert [tok.i for tok in suggestions] == [key for key in misspell.keys()]
assert [suggString for suggString in suggestions.values()] == [
suggString for suggString in misspell.values()
]
# assert suggestions == gold_suggestions
@pytest.mark.parametrize(
"inputSentence, misspell",
[
(
"Income was $9.4 milion compared to the prior year of $2.7 milion.",
True,
),
("This package was introduced in 2020", False),
],
)
def test_extension_candidateGenerator(inputSentence, misspell):
doc = nlp(inputSentence)
(misspellings, doc) = checker.misspell_identify(doc)
checker.candidate_generator(doc, misspellings)
assert doc._.performed_spellCheck == misspell
@pytest.mark.parametrize(
"inputSentence, misspell",
[
(
"Income was $9.4 milion compared to the prior year of $2.7 milion.",
{
4: [
("million", 0.59422),
("billion", 0.24349),
(",", 0.08809),
("trillion", 0.01835),
("Million", 0.00826),
("%", 0.00672),
("##M", 0.00591),
("annually", 0.0038),
("##B", 0.00205),
("USD", 0.00113),
],
13: [
("billion", 0.65934),
("million", 0.26185),
("trillion", 0.05391),
("##M", 0.0051),
("Million", 0.00425),
("##B", 0.00268),
("USD", 0.00153),
("##b", 0.00077),
("millions", 0.00059),
("%", 0.00041),
],
},
),
(
"This packge was introduced in 2020",
{
1: [
("system", 0.0876),
("model", 0.04924),
("version", 0.04367),
("technology", 0.03086),
("program", 0.01936),
("standard", 0.01607),
("class", 0.01557),
("feature", 0.01527),
("plan", 0.01435),
("service", 0.01351),
]
},
),
],
)
def test_extension2_candidateGenerator(inputSentence, misspell):
doc = nlp(inputSentence)
(misspellings, doc) = checker.misspell_identify(doc)
doc, suggestions = checker.candidate_generator(doc, misspellings)
# changes after v0.1.0
assert [tokIndex.i for tokIndex in doc._.score_spellCheck.keys()] == [
tokIndex for tokIndex in misspell.keys()
]
assert [
word_score[0]
for value in doc._.score_spellCheck.values()
for word_score in value
] == [word_score[0] for value in misspell.values() for word_score in value]
assert [
word_score[1]
for value in doc._.score_spellCheck.values()
for word_score in value
] == approx(
[word_score[1] for value in misspell.values() for word_score in value],
rel=1e-4,
abs=1e-4,
)
@pytest.mark.parametrize(
"inputSentence, misspell",
[
(
"Income was $9.4 milion compared to the prior year of $2.7 milion.",
{4: "million", 13: "million"},
),
("This package was introduced in 2020", {}),
],
)
def test_ranking_candidateRanking(inputSentence, misspell):
doc = nlp(inputSentence)
(misspellings, doc) = checker.misspell_identify(doc)
doc, suggestions = checker.candidate_generator(doc, misspellings)
selectedWord = checker.candidate_ranking(doc, suggestions)
# changes made after v0.1
# assert selectedWord ==
# {doc[key]: value for key, value in misspell.items()}
assert [tok.i for tok in selectedWord.keys()] == [
tok for tok in misspell.keys()
]
assert [tokString for tokString in selectedWord.values()] == [
tok for tok in misspell.values()
]
def test_compatible_spacyPipeline():
nlp.add_pipe(checker)
assert "contextual spellchecker" in nlp.pipe_names
nlp.remove_pipe("contextual spellchecker")
assert "contextual spellchecker" not in nlp.pipe_names
def test_doc_extensions():
nlp.add_pipe(checker)
doc = nlp(
"Income was $9.4 milion compared to the prior year of $2.7 milion."
)
gold_suggestion = {
doc[4]: "million",
doc[13]: "million",
}
gold_outcome = (
"Income was $9.4 million compared to the prior year of $2.7 million."
)
gold_score = {
doc[4]: [
("million", 0.59422),
("billion", 0.24349),
(",", 0.08809),
("trillion", 0.01835),
("Million", 0.00826),
("%", 0.00672),
("##M", 0.00591),
("annually", 0.0038),
("##B", 0.00205),
("USD", 0.00113),
],
doc[13]: [
("billion", 0.65934),
("million", 0.26185),
("trillion", 0.05391),
("##M", 0.0051),
("Million", 0.00425),
("##B", 0.00268),
("USD", 0.00153),
("##b", 0.00077),
("millions", 0.00059),
("%", 0.00041),
],
}
assert doc._.contextual_spellCheck
assert doc._.performed_spellCheck
# updated after v0.1
assert [tok.i for tok in doc._.suggestions_spellCheck.keys()] == [
tok.i for tok in gold_suggestion.keys()
]
assert [
tokString for tokString in doc._.suggestions_spellCheck.values()
] == [tokString for tokString in gold_suggestion.values()]
assert doc._.outcome_spellCheck == gold_outcome
# splitting components to make use of approx function
assert [tok.i for tok in doc._.score_spellCheck.keys()] == [
tok.i for tok in gold_score.keys()
]
assert [tok.text_with_ws for tok in doc._.score_spellCheck.keys()] == [
tok.text_with_ws for tok in gold_score.keys()
]
assert [
word_score[0]
for value in doc._.score_spellCheck.values()
for word_score in value
] == [
word_score[0] for value in gold_score.values() for word_score in value
]
assert [
word_score[1]
for value in doc._.score_spellCheck.values()
for word_score in value
] == approx(
[
word_score[1]
for value in gold_score.values()
for word_score in value
],
rel=1e-4,
abs=1e-4,
)
nlp.remove_pipe("contextual spellchecker")
def test_span_extensions():
try:
nlp.add_pipe(checker)
except BaseException:
print("contextual SpellCheck already in pipeline")
doc = nlp(
"Income was $9.4 milion compared to the prior year of $2.7 milion."
)
gold_score = {
doc[2]: [],
doc[3]: [],
doc[4]: [
("million", 0.59422),
("billion", 0.24349),
(",", 0.08809),
("trillion", 0.01835),
("Million", 0.00826),
("%", 0.00672),
("##M", 0.00591),
("annually", 0.0038),
("##B", 0.00205),
("USD", 0.00113),
],
doc[5]: [],
}
assert doc[2:6]._.get_has_spellCheck
# splitting components to make use of approx function
print(doc[2:6]._.score_spellCheck)
print(gold_score)
assert doc[2:6]._.score_spellCheck.keys() == gold_score.keys()
assert [
word_score[0]
for value in doc[2:6]._.score_spellCheck.values()
for word_score in value
] == [
word_score[0] for value in gold_score.values() for word_score in value
]
assert [
word_score[1]
for value in doc[2:6]._.score_spellCheck.values()
for word_score in value
] == approx(
[
word_score[1]
for value in gold_score.values()
for word_score in value
],
rel=1e-4,
abs=1e-4,
)
# assert doc[2:6]._.score_spellCheck ==
# approx(gold_score,rel=1e-4, abs=1e-4)
nlp.remove_pipe("contextual spellchecker")
def test_token_extension():
if "contextual spellchecker" not in nlp.pipe_names:
nlp.add_pipe(checker)
doc = nlp(
"Income was $9.4 milion compared to the prior year of $2.7 milion."
)
gold_suggestions = "million"
gold_score = [
("million", 0.59422),
("billion", 0.24349),
(",", 0.08809),
("trillion", 0.01835),
("Million", 0.00826),
("%", 0.00672),
("##M", 0.00591),
("annually", 0.0038),
("##B", 0.00205),
("USD", 0.00113),
]
assert doc[4]._.get_require_spellCheck
assert doc[4]._.get_suggestion_spellCheck == gold_suggestions
# Match words and score separately to incorporate approx fn in pytest
assert [word_score[0] for word_score in doc[4]._.score_spellCheck] == [
word_score[0] for word_score in gold_score
]
assert [
word_score[1] for word_score in doc[4]._.score_spellCheck
] == approx(
[word_score[1] for word_score in gold_score], rel=1e-4, abs=1e-4
)
nlp.remove_pipe("contextual spellchecker")
def test_warning():
if "contextual spellchecker" not in nlp.pipe_names:
nlp.add_pipe(checker)
merge_ents = nlp.create_pipe("merge_entities")
nlp.add_pipe(merge_ents)
doc = nlp(
"Income was $9.4 milion compared to the prior year of $2.7 milion."
)
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
# warnings.simplefilter("always")
# Trigger a warning.
assert not doc[4]._.get_require_spellCheck
assert doc[4]._.get_suggestion_spellCheck == ""
assert doc[4]._.score_spellCheck == []
# Verify Warning
assert issubclass(w[-1].category, UserWarning)
assert (
"Position of tokens modified by downstream \
element in pipeline eg. merge_entities"
in str(w[-1].message)
)
nlp.remove_pipe("contextual spellchecker")
print(nlp.pipe_names)
nlp.remove_pipe("merge_entities")
print(nlp.pipe_names)
# warnings.simplefilter("default")
with pytest.raises(TypeError) as e:
ContextualSpellCheck(vocab_path=True)
assert (
e
== "Please check datatype provided. \
vocab_path should be str, debug and performance should be bool"
)
max_edit_distance = "non_int_or_float"
with pytest.raises(ValueError) as e:
ContextualSpellCheck(max_edit_dist=max_edit_distance)
assert (
e
== f"cannot convert {max_edit_distance} to int. \
Please provide a valid integer"
)
try:
ContextualSpellCheck(max_edit_dist="3.1")
except Exception as uncatched_error:
pytest.fail(str(uncatched_error))
def test_vocab_file():
with warnings.catch_warnings(record=True) as w:
ContextualSpellCheck(vocab_path="testing.txt")
assert any([issubclass(i.category, UserWarning) for i in w])
assert any(["Using default vocab" in str(i.message) for i in w])
currentPath = os.path.dirname(__file__)
debugPathFile = os.path.join(currentPath, "debugFile.txt")
orgDebugFilePath = os.path.join(currentPath, "originaldebugFile.txt")
testVocab = os.path.join(currentPath, "testVocab.txt")
print(testVocab, currentPath, debugPathFile)
ContextualSpellCheck(vocab_path=testVocab, debug=True)
with open(orgDebugFilePath) as f1:
with open(debugPathFile) as f2:
assert f1.read() == f2.read()
def test_bert_model_name():
model_name = "a_random_model"
error_message = (
f"Can't load config for '{model_name}'. Make sure that:\n\n"
f"- '{model_name}' is a correct model identifier listed on \
'https://huggingface.co/models'\n\n"
f"- or '{model_name}' is the correct path to a directory \
containing a config.json file\n\n"
)
with pytest.raises(OSError) as e:
ContextualSpellCheck(model_name=model_name)
assert e == error_message
def test_correct_model_name():
model_name = "TurkuNLP/bert-base-finnish-cased-v1"
try:
ContextualSpellCheck(model_name=model_name)
except OSError:
pytest.fail("Specificed model is not present in transformers")
except Exception as uncatched_error:
pytest.fail(str(uncatched_error))
@pytest.mark.parametrize(
"max_edit_distance,expected_spell_check_flag",
[(0, False), (1, False), (2, True), (3, True)],
)
def test_max_edit_dist(max_edit_distance, expected_spell_check_flag):
if "contextual spellchecker" in nlp.pipe_names:
nlp.remove_pipe("contextual spellchecker")
checker_edit_dist = ContextualSpellCheck(max_edit_dist=max_edit_distance)
nlp.add_pipe(checker_edit_dist)
doc = nlp(
"Income was $9.4 milion compared to the prior year of $2.7 milion."
)
# To check the status of `performed_spell_check` flag
assert doc[4]._.get_require_spellCheck == expected_spell_check_flag
assert doc[3:5]._.get_has_spellCheck == expected_spell_check_flag
assert doc._.performed_spellCheck == expected_spell_check_flag
# To check the response of "suggestions_spellCheck"
gold_outcome = (
"Income was $9.4 million compared to the prior year of $2.7 million."
)
gold_token = "million"
gold_outcome = gold_outcome if expected_spell_check_flag else ""
gold_token = gold_token if expected_spell_check_flag else ""
print("gold_outcome:", gold_outcome, "gold_token:", gold_token)
assert doc[4]._.get_suggestion_spellCheck == gold_token
assert doc._.outcome_spellCheck == gold_outcome
nlp.remove_pipe("contextual spellchecker")
@pytest.mark.parametrize(
"input_sentence,expected_outcome,\
expected_suggestion_doc,possible_misspel_index,misspell_suggestion",
[
(
"This is not a pure Python Spell Checking based on <NAME>’s \
blog post on setting up a simple spell checking algorithm.",
"",
{},
8,
"",
),
(
"Everyone has to help to fix the problems of society. \
There has to be more training, more opportunity to bridge the gap \
between the haves and the have nots.",
"Everyone has to help to fix the problems of society. \
There has to be more training, more opportunity to bridge the gap \
between the have and the havets.",
{"haves": "have", "nots": "##ts"},
31,
"",
),
],
)
def test_doc_extensions_bug(
input_sentence,
expected_outcome,
expected_suggestion_doc,
possible_misspel_index,
misspell_suggestion,
):
nlp_lg = spacy.load("en_core_web_lg")
checker_deep_tokenize = ContextualSpellCheck(max_edit_dist=3)
nlp_lg.add_pipe(checker_deep_tokenize)
doc = nlp_lg(input_sentence)
# To check the status of `performed_spell_check` flag
assert doc._.outcome_spellCheck == expected_outcome
assert [tok.text for tok in doc._.suggestions_spellCheck.keys()] == [
tok for tok in expected_suggestion_doc.keys()
]
assert [
tokString for tokString in doc._.suggestions_spellCheck.values()
] == [tokString for tokString in expected_suggestion_doc.values()]
assert (
doc[possible_misspel_index]._.get_suggestion_spellCheck
== misspell_suggestion
)
``` |
{
"source": "jonmurphy1618/artisan-keycap",
"score": 3
} |
#### File: jonmurphy1618/artisan-keycap/colorscan.py
```python
from PIL import Image
import colorsys
import os
import jsonlines
import json
def color_tag_image (image_file):
red, orange, yellow, green, turquoise, blue, lilac, pink, white, gray, black, brown = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
image = []
# print ('\n')
try:
if os.path.getsize(image_file) > 1000000: #image filesize limit required for servers with limited RAM resources
raise ValueError('Error: File size is too large.')
with Image.open(image_file) as image: #debug
image = image.convert('RGBA').resize((64, 64), Image.ANTIALIAS) #debug
# image = Image.open(image_file).convert('RGBA').resize((64, 64), Image.ANTIALIAS)
for px in image.getdata():
h, s, l = colorsys.rgb_to_hsv(px[0]/255., px[1]/255., px[2]/255.)
h = h * 360
s = s * 100
l = l * 100
if l > 95:
white += 1
elif l < 8:
black += 1
elif s < 8:
gray += 1
elif h < 12 or h > 349:
red += 1
elif h > 11 and h < 35:
if s > 70:
orange += 1
else:
brown += 1
elif h > 34 and h < 65:
yellow += 1
elif h > 64 and h < 150:
green += 1
elif h > 149 and h < 200:
turquoise += 1
elif h > 195 and h < 240:
blue += 1
elif h > 235 and h < 275:
lilac += 1
elif h > 274 and h < 350:
pink += 1
except ValueError as err:
print(err)
except:
print('Error: Cannot open image')
finally:
return {
'white': white,
'black': black,
'gray': gray,
'red': red,
'orange': orange,
'brown': brown,
'yellow': yellow,
'green': green,
'turquoise': turquoise,
'blue': blue,
'lilac': lilac,
'pink': pink
}
#with open('./output/test.jl', 'r') as jsonfile:
# data = json.load(jsonfile)
data = []
with jsonlines.open('./output/test.jl') as jsonfile:
for obj in jsonfile:
data.append(obj)
for itemset in data:
for fileinfo in itemset.get('files'):
print (color_tag_image('./output/' + fileinfo.get('path')))
fileinfo['color_values'] = color_tag_image('./output/' + fileinfo.get('path'))
with open('./webhost/www/test.json', 'w') as jsonfile:
json.dump(data, jsonfile)
``` |
{
"source": "jonmv/sample-apps",
"score": 2
} |
#### File: semantic-qa-retrieval/bin/convert-to-vespa-squad.py
```python
from retrievalqaeval.sb_sed import infer_sentence_breaks
import json
import sys
import tensorflow as tf
import tensorflow_hub as hub
import tf_sentencepiece
def get_questions_to_answers(qas,sentence_breaks,context):
questions_to_answers = []
for qa in qas:
question = qa["question"]
answer_sentences = set()
for answer in qa["answers"]:
answer_start = answer["answer_start"]
sentence = None
for start, end in sentence_breaks:
if start <= answer_start < end:
sentence = context[start:end] #The sentence which the answer was found in
break
if sentence not in answer_sentences:
answer_sentences.add(str(sentence))
questions_to_answers.append((question,answer_sentences))
return questions_to_answers
def make_vespa_feed_paragraph(questions,text,context_id):
vespa_doc = {
"put": "id:squad:context::%i" % context_id,
"fields": {
"text": text,
"dataset": "squad",
"questions": questions,
"context_id": context_id,
}
}
return vespa_doc
def make_vespa_feed(sentence_id,questions,sentence,sentence_embedding,context_id):
answer_tensor = session.run(response_embeddings,feed_dict={answer:[sentence],answer_context:[context]})['outputs'][0]
vespa_doc = {
"put": "id:squad:sentence::%i" % sentence_id,
"fields": {
"text": sentence,
"dataset": "squad",
"questions": questions,
"context_id": context_id,
"sentence_embedding": {
"values": sentence_embedding.tolist()
}
}
}
return vespa_doc
print("Downloading QA universal sentence encoder - about 1GB which needs to be downloaded")
g = tf.Graph()
with g.as_default():
module = hub.Module("https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/1")
answer = tf.compat.v1.placeholder(tf.string)
answer_context = tf.compat.v1.placeholder(tf.string)
response_embeddings = module(
dict(input=answer,
context=answer_context),
signature="response_encoder", as_dict=True)
question_input = tf.compat.v1.placeholder(tf.string)
question_embeddings = module(
dict(input=question_input),
signature="question_encoder", as_dict=True)
init_op = tf.group([tf.compat.v1.global_variables_initializer(), tf.compat.v1.tables_initializer()])
g.finalize()
# Initialize session.
session = tf.compat.v1.Session(graph=g)
session.run(init_op)
print("Done creating TF session")
query_file = open("squad_queries.txt","w")
feed_file = open("squad_vespa_feed.json","w")
queries = []
with open(sys.argv[1]) as fp:
question_id = 0
sentence_id = 0
data = json.load(fp)
context_id = 0
for passage in data["data"]:
for paragraph in passage["paragraphs"]:
context = paragraph["context"]
paragraph_questions = []#set of questions answered by sentences in paragraph
sentence_breaks = list(infer_sentence_breaks(context))
sentences = set([context[start:end] for (start,end) in sentence_breaks])
questions_to_answers = get_questions_to_answers(paragraph['qas'],sentence_breaks,context)
answer_sentences = {}
for question,answers in questions_to_answers:
queries.append((question_id,question,len(answers)))
for a in answers:
if a in answer_sentences:
answer_sentences[a].append(question_id)
else:
answer_sentences[a] = [question_id]
paragraph_questions.append(question_id)
question_id +=1
answer_context_array = [context for s in sentences]
sentences = list(sentences)
sentence_embeddings = session.run(response_embeddings,feed_dict={answer:sentences,answer_context:answer_context_array})['outputs']
for i in range(0,len(sentences)):
s = sentences[i]
if s in answer_sentences:
feed_file.write(json.dumps(make_vespa_feed(sentence_id,answer_sentences[s],s,sentence_embeddings[i],context_id)))
feed_file.write("\n")
else:
feed_file.write(json.dumps(make_vespa_feed(sentence_id,[],s,sentence_embeddings[i],context_id)))
feed_file.write("\n")
sentence_id +=1
feed_file.write(json.dumps(make_vespa_feed_paragraph(paragraph_questions,context,context_id)))
feed_file.write("\n")
context_id +=1
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
#Create embedding for queries
chunks = chunks(queries,200)
for chunk in chunks:
chunk_queries = [str(q[1]) for q in chunk]
embeddings = session.run(question_embeddings,feed_dict={question_input:chunk_queries})['outputs']
for i in range(0,len(chunk)):
question_id,question,number_answers = chunk[i]
query_file.write("%i\t%s\t%i\t%s\n" % (int(question_id),str(question),int(number_answers),str(embeddings[i].tolist())))
query_file.close()
feed_file.close()
```
#### File: sample-apps/use-case-shopping/convert_meta.py
```python
import sys
import time
import random
import json
def process(data):
fields = {}
fields["asin"] = data["asin"]
fields["timestamp"] = int(time.time()) - random.randint(0, 60*60*24*365) # no date in data, set to a random value up to one year back
fields["title"] = data["title"]
fields["description"] = data["description"]
fields["price"] = data["price"]
fields["rating_stars"] = 0
fields["rating_count"] = 0
fields["images"] = [data["imUrl"]]
if "brand" in data:
fields["brand"] = data["brand"]
# In the data set, categories are of the form
# [ ["Sports & Outdoors", "Accessories", "Sport Watches"] ]
# For filtering on categories, these should be matched exactly, so we transform to
# [ "Sports & Outdoors", "Sports & Outdoors|Accessories", "Sports & Outdoors|Accessories|Sport Watches"]
# because there are multiple subcategories with the same name, and
# we want to maintain the category hierarchy for grouping.
# For free text search however, we want to match on stemmed terms.
# We have another field for this, and reverse the categories for better relevance:
# "Sport Watches Accessories Sports & Outdoors"
if "categories" in data:
fields["categories"] = []
fields["categories_text"] = ""
for category in data["categories"]:
for level in range(len(category)):
fields["categories"].append("|".join(category[0:level+1]))
fields["categories_text"] += " ".join(category[::-1])
if "related" in data:
related = []
for key in data["related"]:
related.extend(data["related"][key])
fields["related"] = related
document = {}
document["put"] = "id:item:item::" + fields["asin"]
document["fields"] = fields
return document
def main():
output_data = []
lines = 0
skipped = 0
for line in sys.stdin.readlines():
try:
lines += 1
if lines % 1000 == 0:
sys.stderr.write("Processed %d lines so far...\n" % lines)
processed = process(eval(line))
if processed is not None:
output_data.append(processed)
except Exception as e:
skipped += 1 # silently skip errors for now
print(json.dumps(output_data, indent=2))
sys.stderr.write("Done. Processed %d lines. Skipped %d lines, probably due to missing data.\n" % (lines, skipped))
if __name__ == "__main__":
main()
``` |
{
"source": "jonnaglieri/aws-fargate-outbound-connector-transfer-family",
"score": 2
} |
#### File: jonnaglieri/aws-fargate-outbound-connector-transfer-family/app.py
```python
import os
import boto3
import paramiko
import json
import zipfile
from boto3.s3.transfer import TransferConfig
from datetime import datetime
#SET VARIABLE NAMES
secret_name = os.environ['SECRET_NAME']
region_name = os.environ['REGION']
sftp_dir = os.environ['SFTP_DIRECTORY_PATH']
my_bucket = os.environ['BUCKET']
ftp_port = int(os.environ['PORT'])
#RETRIVE SECRETS FROM SECRETS MANAGER
session = boto3.session.Session()
secrets_manager = session.client(
service_name = 'secretsmanager',
region_name = region_name
)
secrets_response = secrets_manager.get_secret_value(
SecretId = secret_name
)
secrets_dict = json.loads(secrets_response['SecretString'])
hostname = secrets_dict['SFTP_TEST_SERVER_HOST']
username = secrets_dict['SFTP_TEST_SERVER_USERNAME']
password = secrets_dict['<PASSWORD>SERVER_PASSWORD']
#SET UP SFTP CONNECTION USING PARAMIKO
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(
hostname = secrets_dict['SFTP_TEST_SERVER_HOST'],
username = secrets_dict['SFTP_TEST_SERVER_USERNAME'],
password = secrets_dict['<PASSWORD>']
)
#DEFINE SFTP CONNECTION USING SECRETS MANAGER SECRETS
def open_ftp_connection(ftp_host, ftp_port, ftp_username, ftp_password):
client = paramiko.SSHClient()
client.load_system_host_keys()
try:
transport = paramiko.Transport(ftp_host, ftp_port)
except Exception:
return 'conn_error'
try:
transport.connect(username = ftp_username, password = ftp_password)
except Exception:
return 'auth_error'
ftp_connection = paramiko.SFTPClient.from_transport(transport)
return ftp_connection
#SET THE SFTP CONNECTION
ftp_connection = open_ftp_connection(hostname, ftp_port, username, password)
#SET THE SFTP DIRECTORY PATH
ftp_file = ftp_connection.chdir(sftp_dir)
#SELECT ALL FILES TO UPLOAD INTO LIST
files_to_upload = ftp_connection.listdir()
#DEFINE MULTIPART UPLOAD SPECS FOR FILES LARGERS THAN 100MB
MB = 1024 ** 2
GB = 1024 ** 3
MULTIPART_THRESHOLD = 100 * MB
MULTIPART_CHUNKSIZE = 20 * MB
MAX_CONCURRENCY = 10
USER_THREADS = True
config = TransferConfig(
multipart_threshold = MULTIPART_THRESHOLD,
multipart_chunksize = MULTIPART_CHUNKSIZE,
max_concurrency = MAX_CONCURRENCY,
use_threads = True)
#UPLOAD TO S3 ALL FILES IN SFTP DIRECTORY PATH
for ftp_file in files_to_upload:
sftp_file_obj = ftp_connection.file(ftp_file, mode='r')
s3_connection = boto3.client('s3')
s3_connection.upload_fileobj(sftp_file_obj, my_bucket, ftp_file, Config = config)
#OPTIONAL -- ZIP FILES INTO A SEPARATE FOLDER CALLED 'ZIPPEDFILES'
os.path.abspath(os.getcwd())
directory = "zippedfiles"
path = os.path.join(os.path.abspath(os.getcwd()), directory)
os.mkdir(path)
s3 = boto3.resource('s3')
#SELECT ONLY ZIP FILES IN S3
my_bucket = s3.Bucket(my_bucket)
zip_files = my_bucket.objects.filter()
#DOWNLOAD FILES INTO FARGATE CURRENT PWD
for s3_object in my_bucket.objects.all():
filename = s3_object.key
my_bucket.download_file(s3_object.key, filename)
#UNZIP AN FILES THAT ARE ZIPPED IN MEMORY
dir = os.listdir()
for object in dir:
try:
with zipfile.ZipFile(object,"r") as zip_ref:
zip_ref.extractall(path)
except Exception:
pass
#UPLOAD ALL ZIPPED FILES TO S3
for subdir, dirs, files in os.walk(path):
for file in files:
full_path = os.path.join(subdir, file)
with open(full_path, 'rb') as data:
my_bucket.put_object(Key = full_path[len(path)+1:], Body = data)
``` |
{
"source": "jonnangle/moto-1",
"score": 2
} |
#### File: moto/athena/exceptions.py
```python
from __future__ import unicode_literals
import json
from werkzeug.exceptions import BadRequest
class AthenaClientError(BadRequest):
def __init__(self, code, message):
super(AthenaClientError, self).__init__()
self.description = json.dumps(
{
"Error": {
"Code": code,
"Message": message,
"Type": "InvalidRequestException",
},
"RequestId": "6876f774-7273-11e4-85dc-39e55ca848d1",
}
)
```
#### File: moto/awslambda/utils.py
```python
from collections import namedtuple
ARN = namedtuple("ARN", ["region", "account", "function_name", "version"])
def make_function_arn(region, account, name):
return "arn:aws:lambda:{0}:{1}:function:{2}".format(region, account, name)
def make_function_ver_arn(region, account, name, version="1"):
arn = make_function_arn(region, account, name)
return "{0}:{1}".format(arn, version)
def split_function_arn(arn):
arn = arn.replace("arn:aws:lambda:")
region, account, _, name, version = arn.split(":")
return ARN(region, account, name, version)
```
#### File: moto/codecommit/models.py
```python
from boto3 import Session
from moto.core import BaseBackend, BaseModel
from moto.core.utils import iso_8601_datetime_with_milliseconds
from datetime import datetime
from moto.iam.models import ACCOUNT_ID
from .exceptions import RepositoryDoesNotExistException, RepositoryNameExistsException
import uuid
class CodeCommit(BaseModel):
def __init__(self, region, repository_description, repository_name):
current_date = iso_8601_datetime_with_milliseconds(datetime.utcnow())
self.repository_metadata = dict()
self.repository_metadata["repositoryName"] = repository_name
self.repository_metadata[
"cloneUrlSsh"
] = "ssh://git-codecommit.{0}.amazonaws.com/v1/repos/{1}".format(
region, repository_name
)
self.repository_metadata[
"cloneUrlHttp"
] = "https://git-codecommit.{0}.amazonaws.com/v1/repos/{1}".format(
region, repository_name
)
self.repository_metadata["creationDate"] = current_date
self.repository_metadata["lastModifiedDate"] = current_date
self.repository_metadata["repositoryDescription"] = repository_description
self.repository_metadata["repositoryId"] = str(uuid.uuid4())
self.repository_metadata["Arn"] = "arn:aws:codecommit:{0}:{1}:{2}".format(
region, ACCOUNT_ID, repository_name
)
self.repository_metadata["accountId"] = ACCOUNT_ID
class CodeCommitBackend(BaseBackend):
def __init__(self):
self.repositories = {}
def create_repository(self, region, repository_name, repository_description):
repository = self.repositories.get(repository_name)
if repository:
raise RepositoryNameExistsException(repository_name)
self.repositories[repository_name] = CodeCommit(
region, repository_description, repository_name
)
return self.repositories[repository_name].repository_metadata
def get_repository(self, repository_name):
repository = self.repositories.get(repository_name)
if not repository:
raise RepositoryDoesNotExistException(repository_name)
return repository.repository_metadata
def delete_repository(self, repository_name):
repository = self.repositories.get(repository_name)
if repository:
self.repositories.pop(repository_name)
return repository.repository_metadata.get("repositoryId")
return None
codecommit_backends = {}
for region in Session().get_available_regions("codecommit"):
codecommit_backends[region] = CodeCommitBackend()
```
#### File: moto/cognitoidentity/exceptions.py
```python
from __future__ import unicode_literals
import json
from werkzeug.exceptions import BadRequest
class ResourceNotFoundError(BadRequest):
def __init__(self, message):
super(ResourceNotFoundError, self).__init__()
self.description = json.dumps(
{"message": message, "__type": "ResourceNotFoundException"}
)
```
#### File: moto/datasync/responses.py
```python
import json
from moto.core.responses import BaseResponse
from .models import datasync_backends
class DataSyncResponse(BaseResponse):
@property
def datasync_backend(self):
return datasync_backends[self.region]
def list_locations(self):
locations = list()
for arn, location in self.datasync_backend.locations.items():
locations.append({"LocationArn": location.arn, "LocationUri": location.uri})
return json.dumps({"Locations": locations})
def _get_location(self, location_arn, typ):
return self.datasync_backend._get_location(location_arn, typ)
def create_location_s3(self):
# s3://bucket_name/folder/
s3_bucket_arn = self._get_param("S3BucketArn")
subdirectory = self._get_param("Subdirectory")
metadata = {"S3Config": self._get_param("S3Config")}
location_uri_elts = ["s3:/", s3_bucket_arn.split(":")[-1]]
if subdirectory:
location_uri_elts.append(subdirectory)
location_uri = "/".join(location_uri_elts)
arn = self.datasync_backend.create_location(
location_uri, metadata=metadata, typ="S3"
)
return json.dumps({"LocationArn": arn})
def describe_location_s3(self):
location_arn = self._get_param("LocationArn")
location = self._get_location(location_arn, typ="S3")
return json.dumps(
{
"LocationArn": location.arn,
"LocationUri": location.uri,
"S3Config": location.metadata["S3Config"],
}
)
def create_location_smb(self):
# smb://smb.share.fqdn/AWS_Test/
subdirectory = self._get_param("Subdirectory")
server_hostname = self._get_param("ServerHostname")
metadata = {
"AgentArns": self._get_param("AgentArns"),
"User": self._get_param("User"),
"Domain": self._get_param("Domain"),
"MountOptions": self._get_param("MountOptions"),
}
location_uri = "/".join(["smb:/", server_hostname, subdirectory])
arn = self.datasync_backend.create_location(
location_uri, metadata=metadata, typ="SMB"
)
return json.dumps({"LocationArn": arn})
def describe_location_smb(self):
location_arn = self._get_param("LocationArn")
location = self._get_location(location_arn, typ="SMB")
return json.dumps(
{
"LocationArn": location.arn,
"LocationUri": location.uri,
"AgentArns": location.metadata["AgentArns"],
"User": location.metadata["User"],
"Domain": location.metadata["Domain"],
"MountOptions": location.metadata["MountOptions"],
}
)
def delete_location(self):
location_arn = self._get_param("LocationArn")
self.datasync_backend.delete_location(location_arn)
return json.dumps({})
def create_task(self):
destination_location_arn = self._get_param("DestinationLocationArn")
source_location_arn = self._get_param("SourceLocationArn")
name = self._get_param("Name")
metadata = {
"CloudWatchLogGroupArn": self._get_param("CloudWatchLogGroupArn"),
"Options": self._get_param("Options"),
"Excludes": self._get_param("Excludes"),
"Tags": self._get_param("Tags"),
}
arn = self.datasync_backend.create_task(
source_location_arn, destination_location_arn, name, metadata=metadata
)
return json.dumps({"TaskArn": arn})
def update_task(self):
task_arn = self._get_param("TaskArn")
self.datasync_backend.update_task(
task_arn,
name=self._get_param("Name"),
metadata={
"CloudWatchLogGroupArn": self._get_param("CloudWatchLogGroupArn"),
"Options": self._get_param("Options"),
"Excludes": self._get_param("Excludes"),
"Tags": self._get_param("Tags"),
},
)
return json.dumps({})
def list_tasks(self):
tasks = list()
for arn, task in self.datasync_backend.tasks.items():
tasks.append(
{"Name": task.name, "Status": task.status, "TaskArn": task.arn}
)
return json.dumps({"Tasks": tasks})
def delete_task(self):
task_arn = self._get_param("TaskArn")
self.datasync_backend.delete_task(task_arn)
return json.dumps({})
def describe_task(self):
task_arn = self._get_param("TaskArn")
task = self.datasync_backend._get_task(task_arn)
return json.dumps(
{
"TaskArn": task.arn,
"Status": task.status,
"Name": task.name,
"CurrentTaskExecutionArn": task.current_task_execution_arn,
"SourceLocationArn": task.source_location_arn,
"DestinationLocationArn": task.destination_location_arn,
"CloudWatchLogGroupArn": task.metadata["CloudWatchLogGroupArn"],
"Options": task.metadata["Options"],
"Excludes": task.metadata["Excludes"],
}
)
def start_task_execution(self):
task_arn = self._get_param("TaskArn")
arn = self.datasync_backend.start_task_execution(task_arn)
return json.dumps({"TaskExecutionArn": arn})
def cancel_task_execution(self):
task_execution_arn = self._get_param("TaskExecutionArn")
self.datasync_backend.cancel_task_execution(task_execution_arn)
return json.dumps({})
def describe_task_execution(self):
task_execution_arn = self._get_param("TaskExecutionArn")
task_execution = self.datasync_backend._get_task_execution(task_execution_arn)
result = json.dumps(
{"TaskExecutionArn": task_execution.arn, "Status": task_execution.status}
)
if task_execution.status == "SUCCESS":
self.datasync_backend.tasks[task_execution.task_arn].status = "AVAILABLE"
# Simulate task being executed
task_execution.iterate_status()
return result
```
#### File: moto/dynamodbstreams/responses.py
```python
from __future__ import unicode_literals
from moto.core.responses import BaseResponse
from .models import dynamodbstreams_backends
from six import string_types
class DynamoDBStreamsHandler(BaseResponse):
@property
def backend(self):
return dynamodbstreams_backends[self.region]
def describe_stream(self):
arn = self._get_param("StreamArn")
return self.backend.describe_stream(arn)
def list_streams(self):
table_name = self._get_param("TableName")
return self.backend.list_streams(table_name)
def get_shard_iterator(self):
arn = self._get_param("StreamArn")
shard_id = self._get_param("ShardId")
shard_iterator_type = self._get_param("ShardIteratorType")
sequence_number = self._get_param("SequenceNumber")
# according to documentation sequence_number param should be string
if isinstance(sequence_number, string_types):
sequence_number = int(sequence_number)
return self.backend.get_shard_iterator(
arn, shard_id, shard_iterator_type, sequence_number
)
def get_records(self):
arn = self._get_param("ShardIterator")
limit = self._get_param("Limit")
if limit is None:
limit = 1000
return self.backend.get_records(arn, limit)
```
#### File: ec2/responses/general.py
```python
from __future__ import unicode_literals
from moto.core.responses import BaseResponse
class General(BaseResponse):
def get_console_output(self):
instance_id = self._get_param("InstanceId")
if not instance_id:
# For compatibility with boto.
# See: https://github.com/spulec/moto/pull/1152#issuecomment-332487599
instance_id = self._get_multi_param("InstanceId")[0]
instance = self.ec2_backend.get_instance(instance_id)
template = self.response_template(GET_CONSOLE_OUTPUT_RESULT)
return template.render(instance=instance)
GET_CONSOLE_OUTPUT_RESULT = """
<GetConsoleOutputResponse xmlns="http://ec2.amazonaws.com/doc/2013-10-15/">
<requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
<instanceId>{{ instance.id }}</instanceId>
<timestamp>2010-10-14T01:12:41.000Z</timestamp>
<output>TGludXggdmVyc2lvbiAyLjYuMTYteGVuVSAoYnVpbGRlckBwYXRjaGJhdC5hbWF6b25zYSkgKGdj
YyB2ZXJzaW9uIDQuMC4xIDIwMDUwNzI3IChSZWQgSGF0ID<KEY>
</GetConsoleOutputResponse>"""
```
#### File: moto/redshift/exceptions.py
```python
from __future__ import unicode_literals
import json
from werkzeug.exceptions import BadRequest
class RedshiftClientError(BadRequest):
def __init__(self, code, message):
super(RedshiftClientError, self).__init__()
self.description = json.dumps(
{
"Error": {"Code": code, "Message": message, "Type": "Sender"},
"RequestId": "6876f774-7273-11e4-85dc-39e55ca848d1",
}
)
class ClusterNotFoundError(RedshiftClientError):
def __init__(self, cluster_identifier):
super(ClusterNotFoundError, self).__init__(
"ClusterNotFound", "Cluster {0} not found.".format(cluster_identifier)
)
class ClusterSubnetGroupNotFoundError(RedshiftClientError):
def __init__(self, subnet_identifier):
super(ClusterSubnetGroupNotFoundError, self).__init__(
"ClusterSubnetGroupNotFound",
"Subnet group {0} not found.".format(subnet_identifier),
)
class ClusterSecurityGroupNotFoundError(RedshiftClientError):
def __init__(self, group_identifier):
super(ClusterSecurityGroupNotFoundError, self).__init__(
"ClusterSecurityGroupNotFound",
"Security group {0} not found.".format(group_identifier),
)
class ClusterParameterGroupNotFoundError(RedshiftClientError):
def __init__(self, group_identifier):
super(ClusterParameterGroupNotFoundError, self).__init__(
"ClusterParameterGroupNotFound",
"Parameter group {0} not found.".format(group_identifier),
)
class InvalidSubnetError(RedshiftClientError):
def __init__(self, subnet_identifier):
super(InvalidSubnetError, self).__init__(
"InvalidSubnet", "Subnet {0} not found.".format(subnet_identifier)
)
class SnapshotCopyGrantAlreadyExistsFaultError(RedshiftClientError):
def __init__(self, snapshot_copy_grant_name):
super(SnapshotCopyGrantAlreadyExistsFaultError, self).__init__(
"SnapshotCopyGrantAlreadyExistsFault",
"Cannot create the snapshot copy grant because a grant "
"with the identifier '{0}' already exists".format(snapshot_copy_grant_name),
)
class SnapshotCopyGrantNotFoundFaultError(RedshiftClientError):
def __init__(self, snapshot_copy_grant_name):
super(SnapshotCopyGrantNotFoundFaultError, self).__init__(
"SnapshotCopyGrantNotFoundFault",
"Snapshot copy grant not found: {0}".format(snapshot_copy_grant_name),
)
class ClusterSnapshotNotFoundError(RedshiftClientError):
def __init__(self, snapshot_identifier):
super(ClusterSnapshotNotFoundError, self).__init__(
"ClusterSnapshotNotFound",
"Snapshot {0} not found.".format(snapshot_identifier),
)
class ClusterSnapshotAlreadyExistsError(RedshiftClientError):
def __init__(self, snapshot_identifier):
super(ClusterSnapshotAlreadyExistsError, self).__init__(
"ClusterSnapshotAlreadyExists",
"Cannot create the snapshot because a snapshot with the "
"identifier {0} already exists".format(snapshot_identifier),
)
class InvalidParameterValueError(RedshiftClientError):
def __init__(self, message):
super(InvalidParameterValueError, self).__init__(
"InvalidParameterValue", message
)
class ResourceNotFoundFaultError(RedshiftClientError):
code = 404
def __init__(self, resource_type=None, resource_name=None, message=None):
if resource_type and not resource_name:
msg = "resource of type '{0}' not found.".format(resource_type)
else:
msg = "{0} ({1}) not found.".format(resource_type, resource_name)
if message:
msg = message
super(ResourceNotFoundFaultError, self).__init__("ResourceNotFoundFault", msg)
class SnapshotCopyDisabledFaultError(RedshiftClientError):
def __init__(self, cluster_identifier):
super(SnapshotCopyDisabledFaultError, self).__init__(
"SnapshotCopyDisabledFault",
"Cannot modify retention period because snapshot copy is disabled on Cluster {0}.".format(
cluster_identifier
),
)
class SnapshotCopyAlreadyDisabledFaultError(RedshiftClientError):
def __init__(self, cluster_identifier):
super(SnapshotCopyAlreadyDisabledFaultError, self).__init__(
"SnapshotCopyAlreadyDisabledFault",
"Snapshot Copy is already disabled on Cluster {0}.".format(
cluster_identifier
),
)
class SnapshotCopyAlreadyEnabledFaultError(RedshiftClientError):
def __init__(self, cluster_identifier):
super(SnapshotCopyAlreadyEnabledFaultError, self).__init__(
"SnapshotCopyAlreadyEnabledFault",
"Snapshot Copy is already enabled on Cluster {0}.".format(
cluster_identifier
),
)
```
#### File: moto/ssm/utils.py
```python
ACCOUNT_ID = "1234567890"
def parameter_arn(region, parameter_name):
if parameter_name[0] == "/":
parameter_name = parameter_name[1:]
return "arn:aws:ssm:{0}:{1}:parameter/{2}".format(
region, ACCOUNT_ID, parameter_name
)
```
#### File: swf/models/activity_type.py
```python
from .generic_type import GenericType
class ActivityType(GenericType):
@property
def _configuration_keys(self):
return [
"defaultTaskHeartbeatTimeout",
"defaultTaskScheduleToCloseTimeout",
"defaultTaskScheduleToStartTimeout",
"defaultTaskStartToCloseTimeout",
]
@property
def kind(self):
return "activity"
```
#### File: moto/swf/utils.py
```python
def decapitalize(key):
return key[0].lower() + key[1:]
```
#### File: moto-1/tests/backport_assert_raises.py
```python
from __future__ import unicode_literals
"""
Patch courtesy of:
https://marmida.com/blog/index.php/2012/08/08/monkey-patching-assert_raises/
"""
# code for monkey-patching
import nose.tools
# let's fix nose.tools.assert_raises (which is really unittest.assertRaises)
# so that it always supports context management
# in order for these changes to be available to other modules, you'll need
# to guarantee this module is imported by your fixture before either nose or
# unittest are imported
try:
nose.tools.assert_raises(Exception)
except TypeError:
# this version of assert_raises doesn't support the 1-arg version
class AssertRaisesContext(object):
def __init__(self, expected):
self.expected = expected
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, tb):
self.exception = exc_val
if issubclass(exc_type, self.expected):
return True
nose.tools.assert_equal(exc_type, self.expected)
# if you get to this line, the last assertion must have passed
# suppress the propagation of this exception
return True
def assert_raises_context(exc_type):
return AssertRaisesContext(exc_type)
nose.tools.assert_raises = assert_raises_context
```
#### File: tests/test_core/test_request_mocking.py
```python
import requests
import sure # noqa
import boto3
from moto import mock_sqs, settings
@mock_sqs
def test_passthrough_requests():
conn = boto3.client("sqs", region_name="us-west-1")
conn.create_queue(QueueName="queue1")
res = requests.get("https://httpbin.org/ip")
assert res.status_code == 200
if not settings.TEST_SERVER_MODE:
@mock_sqs
def test_requests_to_amazon_subdomains_dont_work():
res = requests.get("https://fakeservice.amazonaws.com/foo/bar")
assert res.content == b"The method is not implemented"
assert res.status_code == 400
```
#### File: tests/test_core/test_url_mapping.py
```python
from __future__ import unicode_literals
import sure # noqa
from moto.core.utils import convert_regex_to_flask_path
def test_flask_path_converting_simple():
convert_regex_to_flask_path("/").should.equal("/")
convert_regex_to_flask_path("/$").should.equal("/")
convert_regex_to_flask_path("/foo").should.equal("/foo")
convert_regex_to_flask_path("/foo/bar/").should.equal("/foo/bar/")
def test_flask_path_converting_regex():
convert_regex_to_flask_path("/(?P<key_name>[a-zA-Z0-9\-_]+)").should.equal(
'/<regex("[a-zA-Z0-9\-_]+"):key_name>'
)
convert_regex_to_flask_path("(?P<account_id>\d+)/(?P<queue_name>.*)$").should.equal(
'<regex("\d+"):account_id>/<regex(".*"):queue_name>'
)
```
#### File: tests/test_ec2/test_vpc_peering.py
```python
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
from moto.ec2.exceptions import EC2ClientError
from botocore.exceptions import ClientError
import boto3
import boto
from boto.exception import EC2ResponseError
import sure # noqa
from moto import mock_ec2, mock_ec2_deprecated
from tests.helpers import requires_boto_gte
@requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_vpc_peering_connections():
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
peer_vpc = conn.create_vpc("172.16.58.3/16")
vpc_pcx = conn.create_vpc_peering_connection(vpc.id, peer_vpc.id)
vpc_pcx._status.code.should.equal("initiating-request")
return vpc_pcx
@requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_vpc_peering_connections_get_all():
conn = boto.connect_vpc("the_key", "the_secret")
vpc_pcx = test_vpc_peering_connections()
vpc_pcx._status.code.should.equal("initiating-request")
all_vpc_pcxs = conn.get_all_vpc_peering_connections()
all_vpc_pcxs.should.have.length_of(1)
all_vpc_pcxs[0]._status.code.should.equal("pending-acceptance")
@requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_vpc_peering_connections_accept():
conn = boto.connect_vpc("the_key", "the_secret")
vpc_pcx = test_vpc_peering_connections()
vpc_pcx = conn.accept_vpc_peering_connection(vpc_pcx.id)
vpc_pcx._status.code.should.equal("active")
with assert_raises(EC2ResponseError) as cm:
conn.reject_vpc_peering_connection(vpc_pcx.id)
cm.exception.code.should.equal("InvalidStateTransition")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
all_vpc_pcxs = conn.get_all_vpc_peering_connections()
all_vpc_pcxs.should.have.length_of(1)
all_vpc_pcxs[0]._status.code.should.equal("active")
@requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_vpc_peering_connections_reject():
conn = boto.connect_vpc("the_key", "the_secret")
vpc_pcx = test_vpc_peering_connections()
verdict = conn.reject_vpc_peering_connection(vpc_pcx.id)
verdict.should.equal(True)
with assert_raises(EC2ResponseError) as cm:
conn.accept_vpc_peering_connection(vpc_pcx.id)
cm.exception.code.should.equal("InvalidStateTransition")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
all_vpc_pcxs = conn.get_all_vpc_peering_connections()
all_vpc_pcxs.should.have.length_of(1)
all_vpc_pcxs[0]._status.code.should.equal("rejected")
@requires_boto_gte("2.32.1")
@mock_ec2_deprecated
def test_vpc_peering_connections_delete():
conn = boto.connect_vpc("the_key", "the_secret")
vpc_pcx = test_vpc_peering_connections()
verdict = vpc_pcx.delete()
verdict.should.equal(True)
all_vpc_pcxs = conn.get_all_vpc_peering_connections()
all_vpc_pcxs.should.have.length_of(1)
all_vpc_pcxs[0]._status.code.should.equal("deleted")
with assert_raises(EC2ResponseError) as cm:
conn.delete_vpc_peering_connection("pcx-1234abcd")
cm.exception.code.should.equal("InvalidVpcPeeringConnectionId.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2
def test_vpc_peering_connections_cross_region():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
vpc_pcx_usw1.status["Code"].should.equal("initiating-request")
vpc_pcx_usw1.requester_vpc.id.should.equal(vpc_usw1.id)
vpc_pcx_usw1.accepter_vpc.id.should.equal(vpc_apn1.id)
# test cross region vpc peering connection exist
vpc_pcx_apn1 = ec2_apn1.VpcPeeringConnection(vpc_pcx_usw1.id)
vpc_pcx_apn1.id.should.equal(vpc_pcx_usw1.id)
vpc_pcx_apn1.requester_vpc.id.should.equal(vpc_usw1.id)
vpc_pcx_apn1.accepter_vpc.id.should.equal(vpc_apn1.id)
@mock_ec2
def test_vpc_peering_connections_cross_region_fail():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering wrong region with no vpc
with assert_raises(ClientError) as cm:
ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-2"
)
cm.exception.response["Error"]["Code"].should.equal("InvalidVpcID.NotFound")
@mock_ec2
def test_vpc_peering_connections_cross_region_accept():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
# accept peering from ap-northeast-1
ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1")
ec2_usw1 = boto3.client("ec2", region_name="us-west-1")
acp_pcx_apn1 = ec2_apn1.accept_vpc_peering_connection(
VpcPeeringConnectionId=vpc_pcx_usw1.id
)
des_pcx_apn1 = ec2_usw1.describe_vpc_peering_connections(
VpcPeeringConnectionIds=[vpc_pcx_usw1.id]
)
des_pcx_usw1 = ec2_usw1.describe_vpc_peering_connections(
VpcPeeringConnectionIds=[vpc_pcx_usw1.id]
)
acp_pcx_apn1["VpcPeeringConnection"]["Status"]["Code"].should.equal("active")
des_pcx_apn1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("active")
des_pcx_usw1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("active")
@mock_ec2
def test_vpc_peering_connections_cross_region_reject():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
# reject peering from ap-northeast-1
ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1")
ec2_usw1 = boto3.client("ec2", region_name="us-west-1")
rej_pcx_apn1 = ec2_apn1.reject_vpc_peering_connection(
VpcPeeringConnectionId=vpc_pcx_usw1.id
)
des_pcx_apn1 = ec2_usw1.describe_vpc_peering_connections(
VpcPeeringConnectionIds=[vpc_pcx_usw1.id]
)
des_pcx_usw1 = ec2_usw1.describe_vpc_peering_connections(
VpcPeeringConnectionIds=[vpc_pcx_usw1.id]
)
rej_pcx_apn1["Return"].should.equal(True)
des_pcx_apn1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("rejected")
des_pcx_usw1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("rejected")
@mock_ec2
def test_vpc_peering_connections_cross_region_delete():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
# reject peering from ap-northeast-1
ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1")
ec2_usw1 = boto3.client("ec2", region_name="us-west-1")
del_pcx_apn1 = ec2_apn1.delete_vpc_peering_connection(
VpcPeeringConnectionId=vpc_pcx_usw1.id
)
des_pcx_apn1 = ec2_usw1.describe_vpc_peering_connections(
VpcPeeringConnectionIds=[vpc_pcx_usw1.id]
)
des_pcx_usw1 = ec2_usw1.describe_vpc_peering_connections(
VpcPeeringConnectionIds=[vpc_pcx_usw1.id]
)
del_pcx_apn1["Return"].should.equal(True)
des_pcx_apn1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("deleted")
des_pcx_usw1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("deleted")
@mock_ec2
def test_vpc_peering_connections_cross_region_accept_wrong_region():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
# accept wrong peering from us-west-1 which will raise error
ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1")
ec2_usw1 = boto3.client("ec2", region_name="us-west-1")
with assert_raises(ClientError) as cm:
ec2_usw1.accept_vpc_peering_connection(VpcPeeringConnectionId=vpc_pcx_usw1.id)
cm.exception.response["Error"]["Code"].should.equal("OperationNotPermitted")
exp_msg = (
"Incorrect region ({0}) specified for this request.VPC "
"peering connection {1} must be "
"accepted in region {2}".format("us-west-1", vpc_pcx_usw1.id, "ap-northeast-1")
)
cm.exception.response["Error"]["Message"].should.equal(exp_msg)
@mock_ec2
def test_vpc_peering_connections_cross_region_reject_wrong_region():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
# reject wrong peering from us-west-1 which will raise error
ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1")
ec2_usw1 = boto3.client("ec2", region_name="us-west-1")
with assert_raises(ClientError) as cm:
ec2_usw1.reject_vpc_peering_connection(VpcPeeringConnectionId=vpc_pcx_usw1.id)
cm.exception.response["Error"]["Code"].should.equal("OperationNotPermitted")
exp_msg = (
"Incorrect region ({0}) specified for this request.VPC "
"peering connection {1} must be accepted or "
"rejected in region {2}".format("us-west-1", vpc_pcx_usw1.id, "ap-northeast-1")
)
cm.exception.response["Error"]["Message"].should.equal(exp_msg)
```
#### File: tests/test_secretsmanager/test_server.py
```python
from __future__ import unicode_literals
import json
import sure # noqa
import moto.server as server
from moto import mock_secretsmanager
"""
Test the different server responses for secretsmanager
"""
DEFAULT_SECRET_NAME = "test-secret"
@mock_secretsmanager
def test_get_secret_value():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": DEFAULT_SECRET_NAME, "SecretString": "foo-secret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
get_secret = test_client.post(
"/",
data={"SecretId": DEFAULT_SECRET_NAME, "VersionStage": "AWSCURRENT"},
headers={"X-Amz-Target": "secretsmanager.GetSecretValue"},
)
json_data = json.loads(get_secret.data.decode("utf-8"))
assert json_data["SecretString"] == "foo-secret"
@mock_secretsmanager
def test_get_secret_that_does_not_exist():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
get_secret = test_client.post(
"/",
data={"SecretId": "i-dont-exist", "VersionStage": "AWSCURRENT"},
headers={"X-Amz-Target": "secretsmanager.GetSecretValue"},
)
json_data = json.loads(get_secret.data.decode("utf-8"))
assert json_data["message"] == "Secrets Manager can't find the specified secret."
assert json_data["__type"] == "ResourceNotFoundException"
@mock_secretsmanager
def test_get_secret_that_does_not_match():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": DEFAULT_SECRET_NAME, "SecretString": "foo-secret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
get_secret = test_client.post(
"/",
data={"SecretId": "i-dont-match", "VersionStage": "AWSCURRENT"},
headers={"X-Amz-Target": "secretsmanager.GetSecretValue"},
)
json_data = json.loads(get_secret.data.decode("utf-8"))
assert json_data["message"] == "Secrets Manager can't find the specified secret."
assert json_data["__type"] == "ResourceNotFoundException"
@mock_secretsmanager
def test_get_secret_that_has_no_value():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": DEFAULT_SECRET_NAME},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
get_secret = test_client.post(
"/",
data={"SecretId": DEFAULT_SECRET_NAME},
headers={"X-Amz-Target": "secretsmanager.GetSecretValue"},
)
json_data = json.loads(get_secret.data.decode("utf-8"))
assert (
json_data["message"]
== "Secrets Manager can't find the specified secret value for staging label: AWSCURRENT"
)
assert json_data["__type"] == "ResourceNotFoundException"
@mock_secretsmanager
def test_create_secret():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
res = test_client.post(
"/",
data={"Name": "test-secret", "SecretString": "foo-secret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
res_2 = test_client.post(
"/",
data={"Name": "test-secret-2", "SecretString": "bar-secret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
json_data = json.loads(res.data.decode("utf-8"))
assert json_data["ARN"] != ""
assert json_data["Name"] == "test-secret"
json_data_2 = json.loads(res_2.data.decode("utf-8"))
assert json_data_2["ARN"] != ""
assert json_data_2["Name"] == "test-secret-2"
@mock_secretsmanager
def test_describe_secret():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": "test-secret", "SecretString": "foosecret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
describe_secret = test_client.post(
"/",
data={"SecretId": "test-secret"},
headers={"X-Amz-Target": "secretsmanager.DescribeSecret"},
)
create_secret_2 = test_client.post(
"/",
data={"Name": "test-secret-2", "SecretString": "barsecret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
describe_secret_2 = test_client.post(
"/",
data={"SecretId": "test-secret-2"},
headers={"X-Amz-Target": "secretsmanager.DescribeSecret"},
)
json_data = json.loads(describe_secret.data.decode("utf-8"))
assert json_data # Returned dict is not empty
assert json_data["ARN"] != ""
assert json_data["Name"] == "test-secret"
json_data_2 = json.loads(describe_secret_2.data.decode("utf-8"))
assert json_data_2 # Returned dict is not empty
assert json_data_2["ARN"] != ""
assert json_data_2["Name"] == "test-secret-2"
@mock_secretsmanager
def test_describe_secret_that_does_not_exist():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
describe_secret = test_client.post(
"/",
data={"SecretId": "i-dont-exist"},
headers={"X-Amz-Target": "secretsmanager.DescribeSecret"},
)
json_data = json.loads(describe_secret.data.decode("utf-8"))
assert json_data["message"] == "Secrets Manager can't find the specified secret."
assert json_data["__type"] == "ResourceNotFoundException"
@mock_secretsmanager
def test_describe_secret_that_does_not_match():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": DEFAULT_SECRET_NAME, "SecretString": "foosecret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
describe_secret = test_client.post(
"/",
data={"SecretId": "i-dont-match"},
headers={"X-Amz-Target": "secretsmanager.DescribeSecret"},
)
json_data = json.loads(describe_secret.data.decode("utf-8"))
assert json_data["message"] == "Secrets Manager can't find the specified secret."
assert json_data["__type"] == "ResourceNotFoundException"
@mock_secretsmanager
def test_rotate_secret():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": DEFAULT_SECRET_NAME, "SecretString": "foosecret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
client_request_token = "<PASSWORD>"
rotate_secret = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"ClientRequestToken": client_request_token,
},
headers={"X-Amz-Target": "secretsmanager.RotateSecret"},
)
json_data = json.loads(rotate_secret.data.decode("utf-8"))
assert json_data # Returned dict is not empty
assert json_data["ARN"] != ""
assert json_data["Name"] == DEFAULT_SECRET_NAME
assert json_data["VersionId"] == client_request_token
# @mock_secretsmanager
# def test_rotate_secret_enable_rotation():
# backend = server.create_backend_app('secretsmanager')
# test_client = backend.test_client()
# create_secret = test_client.post(
# '/',
# data={
# "Name": "test-secret",
# "SecretString": "foosecret"
# },
# headers={
# "X-Amz-Target": "secretsmanager.CreateSecret"
# },
# )
# initial_description = test_client.post(
# '/',
# data={
# "SecretId": "test-secret"
# },
# headers={
# "X-Amz-Target": "secretsmanager.DescribeSecret"
# },
# )
# json_data = json.loads(initial_description.data.decode("utf-8"))
# assert json_data # Returned dict is not empty
# assert json_data['RotationEnabled'] is False
# assert json_data['RotationRules']['AutomaticallyAfterDays'] == 0
# rotate_secret = test_client.post(
# '/',
# data={
# "SecretId": "test-secret",
# "RotationRules": {"AutomaticallyAfterDays": 42}
# },
# headers={
# "X-Amz-Target": "secretsmanager.RotateSecret"
# },
# )
# rotated_description = test_client.post(
# '/',
# data={
# "SecretId": "test-secret"
# },
# headers={
# "X-Amz-Target": "secretsmanager.DescribeSecret"
# },
# )
# json_data = json.loads(rotated_description.data.decode("utf-8"))
# assert json_data # Returned dict is not empty
# assert json_data['RotationEnabled'] is True
# assert json_data['RotationRules']['AutomaticallyAfterDays'] == 42
@mock_secretsmanager
def test_rotate_secret_that_does_not_exist():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
rotate_secret = test_client.post(
"/",
data={"SecretId": "i-dont-exist"},
headers={"X-Amz-Target": "secretsmanager.RotateSecret"},
)
json_data = json.loads(rotate_secret.data.decode("utf-8"))
assert json_data["message"] == "Secrets Manager can't find the specified secret."
assert json_data["__type"] == "ResourceNotFoundException"
@mock_secretsmanager
def test_rotate_secret_that_does_not_match():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": DEFAULT_SECRET_NAME, "SecretString": "foosecret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
rotate_secret = test_client.post(
"/",
data={"SecretId": "i-dont-match"},
headers={"X-Amz-Target": "secretsmanager.RotateSecret"},
)
json_data = json.loads(rotate_secret.data.decode("utf-8"))
assert json_data["message"] == "Secrets Manager can't find the specified secret."
assert json_data["__type"] == "ResourceNotFoundException"
@mock_secretsmanager
def test_rotate_secret_client_request_token_too_short():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": DEFAULT_SECRET_NAME, "SecretString": "foosecret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
client_request_token = "<PASSWORD>"
rotate_secret = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"ClientRequestToken": client_request_token,
},
headers={"X-Amz-Target": "secretsmanager.RotateSecret"},
)
json_data = json.loads(rotate_secret.data.decode("utf-8"))
assert json_data["message"] == "ClientRequestToken must be 32-64 characters long."
assert json_data["__type"] == "InvalidParameterException"
@mock_secretsmanager
def test_rotate_secret_client_request_token_too_long():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": DEFAULT_SECRET_NAME, "SecretString": "foosecret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
client_request_token = (
"<PASSWORD>-" "<PASSWORD>"
)
rotate_secret = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"ClientRequestToken": client_request_token,
},
headers={"X-Amz-Target": "secretsmanager.RotateSecret"},
)
json_data = json.loads(rotate_secret.data.decode("utf-8"))
assert json_data["message"] == "ClientRequestToken must be 32-64 characters long."
assert json_data["__type"] == "InvalidParameterException"
@mock_secretsmanager
def test_rotate_secret_rotation_lambda_arn_too_long():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": DEFAULT_SECRET_NAME, "SecretString": "foosecret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
rotation_lambda_arn = "85B7-446A-B7E4" * 147 # == 2058 characters
rotate_secret = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"RotationLambdaARN": rotation_lambda_arn,
},
headers={"X-Amz-Target": "secretsmanager.RotateSecret"},
)
json_data = json.loads(rotate_secret.data.decode("utf-8"))
assert json_data["message"] == "RotationLambdaARN must <= 2048 characters long."
assert json_data["__type"] == "InvalidParameterException"
@mock_secretsmanager
def test_put_secret_value_puts_new_secret():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"SecretString": "foosecret",
"VersionStages": ["AWSCURRENT"],
},
headers={"X-Amz-Target": "secretsmanager.PutSecretValue"},
)
put_second_secret_value_json = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"SecretString": "foosecret",
"VersionStages": ["AWSCURRENT"],
},
headers={"X-Amz-Target": "secretsmanager.PutSecretValue"},
)
second_secret_json_data = json.loads(
put_second_secret_value_json.data.decode("utf-8")
)
version_id = second_secret_json_data["VersionId"]
secret_value_json = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"VersionId": version_id,
"VersionStage": "AWSCURRENT",
},
headers={"X-Amz-Target": "secretsmanager.GetSecretValue"},
)
second_secret_json_data = json.loads(secret_value_json.data.decode("utf-8"))
assert second_secret_json_data
assert second_secret_json_data["SecretString"] == "foosecret"
@mock_secretsmanager
def test_put_secret_value_can_get_first_version_if_put_twice():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
first_secret_string = "first_secret"
second_secret_string = "second_secret"
put_first_secret_value_json = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"SecretString": first_secret_string,
"VersionStages": ["AWSCURRENT"],
},
headers={"X-Amz-Target": "secretsmanager.PutSecretValue"},
)
first_secret_json_data = json.loads(
put_first_secret_value_json.data.decode("utf-8")
)
first_secret_version_id = first_secret_json_data["VersionId"]
test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"SecretString": second_secret_string,
"VersionStages": ["AWSCURRENT"],
},
headers={"X-Amz-Target": "secretsmanager.PutSecretValue"},
)
get_first_secret_value_json = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"VersionId": first_secret_version_id,
"VersionStage": "AWSCURRENT",
},
headers={"X-Amz-Target": "secretsmanager.GetSecretValue"},
)
get_first_secret_json_data = json.loads(
get_first_secret_value_json.data.decode("utf-8")
)
assert get_first_secret_json_data
assert get_first_secret_json_data["SecretString"] == first_secret_string
@mock_secretsmanager
def test_put_secret_value_versions_differ_if_same_secret_put_twice():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
put_first_secret_value_json = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"SecretString": "secret",
"VersionStages": ["AWSCURRENT"],
},
headers={"X-Amz-Target": "secretsmanager.PutSecretValue"},
)
first_secret_json_data = json.loads(
put_first_secret_value_json.data.decode("utf-8")
)
first_secret_version_id = first_secret_json_data["VersionId"]
put_second_secret_value_json = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"SecretString": "secret",
"VersionStages": ["AWSCURRENT"],
},
headers={"X-Amz-Target": "secretsmanager.PutSecretValue"},
)
second_secret_json_data = json.loads(
put_second_secret_value_json.data.decode("utf-8")
)
second_secret_version_id = second_secret_json_data["VersionId"]
assert first_secret_version_id != second_secret_version_id
@mock_secretsmanager
def test_can_list_secret_version_ids():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
put_first_secret_value_json = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"SecretString": "secret",
"VersionStages": ["AWSCURRENT"],
},
headers={"X-Amz-Target": "secretsmanager.PutSecretValue"},
)
first_secret_json_data = json.loads(
put_first_secret_value_json.data.decode("utf-8")
)
first_secret_version_id = first_secret_json_data["VersionId"]
put_second_secret_value_json = test_client.post(
"/",
data={
"SecretId": DEFAULT_SECRET_NAME,
"SecretString": "secret",
"VersionStages": ["AWSCURRENT"],
},
headers={"X-Amz-Target": "secretsmanager.PutSecretValue"},
)
second_secret_json_data = json.loads(
put_second_secret_value_json.data.decode("utf-8")
)
second_secret_version_id = second_secret_json_data["VersionId"]
list_secret_versions_json = test_client.post(
"/",
data={"SecretId": DEFAULT_SECRET_NAME},
headers={"X-Amz-Target": "secretsmanager.ListSecretVersionIds"},
)
versions_list = json.loads(list_secret_versions_json.data.decode("utf-8"))
returned_version_ids = [v["VersionId"] for v in versions_list["Versions"]]
assert [
first_secret_version_id,
second_secret_version_id,
].sort() == returned_version_ids.sort()
@mock_secretsmanager
def test_get_resource_policy_secret():
backend = server.create_backend_app("secretsmanager")
test_client = backend.test_client()
create_secret = test_client.post(
"/",
data={"Name": "test-secret", "SecretString": "foosecret"},
headers={"X-Amz-Target": "secretsmanager.CreateSecret"},
)
describe_secret = test_client.post(
"/",
data={"SecretId": "test-secret"},
headers={"X-Amz-Target": "secretsmanager.GetResourcePolicy"},
)
json_data = json.loads(describe_secret.data.decode("utf-8"))
assert json_data # Returned dict is not empty
assert json_data["ARN"] != ""
assert json_data["Name"] == "test-secret"
#
# The following tests should work, but fail on the embedded dict in
# RotationRules. The error message suggests a problem deeper in the code, which
# needs further investigation.
#
# @mock_secretsmanager
# def test_rotate_secret_rotation_period_zero():
# backend = server.create_backend_app('secretsmanager')
# test_client = backend.test_client()
# create_secret = test_client.post('/',
# data={"Name": "test-secret",
# "SecretString": "foosecret"},
# headers={
# "X-Amz-Target": "secretsmanager.CreateSecret"
# },
# )
# rotate_secret = test_client.post('/',
# data={"SecretId": "test-secret",
# "RotationRules": {"AutomaticallyAfterDays": 0}},
# headers={
# "X-Amz-Target": "secretsmanager.RotateSecret"
# },
# )
# json_data = json.loads(rotate_secret.data.decode("utf-8"))
# assert json_data['message'] == "RotationRules.AutomaticallyAfterDays must be within 1-1000."
# assert json_data['__type'] == 'InvalidParameterException'
# @mock_secretsmanager
# def test_rotate_secret_rotation_period_too_long():
# backend = server.create_backend_app('secretsmanager')
# test_client = backend.test_client()
# create_secret = test_client.post('/',
# data={"Name": "test-secret",
# "SecretString": "foosecret"},
# headers={
# "X-Amz-Target": "secretsmanager.CreateSecret"
# },
# )
# rotate_secret = test_client.post('/',
# data={"SecretId": "test-secret",
# "RotationRules": {"AutomaticallyAfterDays": 1001}},
# headers={
# "X-Amz-Target": "secretsmanager.RotateSecret"
# },
# )
# json_data = json.loads(rotate_secret.data.decode("utf-8"))
# assert json_data['message'] == "RotationRules.AutomaticallyAfterDays must be within 1-1000."
# assert json_data['__type'] == 'InvalidParameterException'
```
#### File: test_swf/models/test_timeout.py
```python
from freezegun import freeze_time
import sure # noqa
from moto.swf.models import Timeout
from ..utils import make_workflow_execution
def test_timeout_creation():
wfe = make_workflow_execution()
# epoch 1420113600 == "2015-01-01 13:00:00"
timeout = Timeout(wfe, 1420117200, "START_TO_CLOSE")
with freeze_time("2015-01-01 12:00:00"):
timeout.reached.should.be.falsy
with freeze_time("2015-01-01 13:00:00"):
timeout.reached.should.be.truthy
```
#### File: test_swf/responses/test_workflow_executions.py
```python
import boto
from boto.swf.exceptions import SWFResponseError
from datetime import datetime, timedelta
import sure # noqa
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises # noqa
from moto import mock_swf_deprecated
from moto.core.utils import unix_time
# Utils
@mock_swf_deprecated
def setup_swf_environment():
conn = boto.connect_swf("the_key", "the_secret")
conn.register_domain("test-domain", "60", description="A test domain")
conn.register_workflow_type(
"test-domain",
"test-workflow",
"v1.0",
task_list="queue",
default_child_policy="TERMINATE",
default_execution_start_to_close_timeout="300",
default_task_start_to_close_timeout="300",
)
conn.register_activity_type("test-domain", "test-activity", "v1.1")
return conn
# StartWorkflowExecution endpoint
@mock_swf_deprecated
def test_start_workflow_execution():
conn = setup_swf_environment()
wf = conn.start_workflow_execution(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
)
wf.should.contain("runId")
@mock_swf_deprecated
def test_signal_workflow_execution():
conn = setup_swf_environment()
hsh = conn.start_workflow_execution(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
)
run_id = hsh["runId"]
wfe = conn.signal_workflow_execution(
"test-domain", "my_signal", "uid-abcd1234", "my_input", run_id
)
wfe = conn.describe_workflow_execution("test-domain", run_id, "uid-abcd1234")
wfe["openCounts"]["openDecisionTasks"].should.equal(2)
@mock_swf_deprecated
def test_start_already_started_workflow_execution():
conn = setup_swf_environment()
conn.start_workflow_execution(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
)
conn.start_workflow_execution.when.called_with(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
).should.throw(SWFResponseError)
@mock_swf_deprecated
def test_start_workflow_execution_on_deprecated_type():
conn = setup_swf_environment()
conn.deprecate_workflow_type("test-domain", "test-workflow", "v1.0")
conn.start_workflow_execution.when.called_with(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
).should.throw(SWFResponseError)
# DescribeWorkflowExecution endpoint
@mock_swf_deprecated
def test_describe_workflow_execution():
conn = setup_swf_environment()
hsh = conn.start_workflow_execution(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
)
run_id = hsh["runId"]
wfe = conn.describe_workflow_execution("test-domain", run_id, "uid-abcd1234")
wfe["executionInfo"]["execution"]["workflowId"].should.equal("uid-abcd1234")
wfe["executionInfo"]["executionStatus"].should.equal("OPEN")
@mock_swf_deprecated
def test_describe_non_existent_workflow_execution():
conn = setup_swf_environment()
conn.describe_workflow_execution.when.called_with(
"test-domain", "wrong-run-id", "wrong-workflow-id"
).should.throw(SWFResponseError)
# GetWorkflowExecutionHistory endpoint
@mock_swf_deprecated
def test_get_workflow_execution_history():
conn = setup_swf_environment()
hsh = conn.start_workflow_execution(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
)
run_id = hsh["runId"]
resp = conn.get_workflow_execution_history("test-domain", run_id, "uid-abcd1234")
types = [evt["eventType"] for evt in resp["events"]]
types.should.equal(["WorkflowExecutionStarted", "DecisionTaskScheduled"])
@mock_swf_deprecated
def test_get_workflow_execution_history_with_reverse_order():
conn = setup_swf_environment()
hsh = conn.start_workflow_execution(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
)
run_id = hsh["runId"]
resp = conn.get_workflow_execution_history(
"test-domain", run_id, "uid-abcd1234", reverse_order=True
)
types = [evt["eventType"] for evt in resp["events"]]
types.should.equal(["DecisionTaskScheduled", "WorkflowExecutionStarted"])
@mock_swf_deprecated
def test_get_workflow_execution_history_on_non_existent_workflow_execution():
conn = setup_swf_environment()
conn.get_workflow_execution_history.when.called_with(
"test-domain", "wrong-run-id", "wrong-workflow-id"
).should.throw(SWFResponseError)
# ListOpenWorkflowExecutions endpoint
@mock_swf_deprecated
def test_list_open_workflow_executions():
conn = setup_swf_environment()
# One open workflow execution
conn.start_workflow_execution(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
)
# One closed workflow execution to make sure it isn't displayed
run_id = conn.start_workflow_execution(
"test-domain", "uid-abcd12345", "test-workflow", "v1.0"
)["runId"]
conn.terminate_workflow_execution(
"test-domain",
"uid-abcd12345",
details="some details",
reason="a more complete reason",
run_id=run_id,
)
yesterday = datetime.utcnow() - timedelta(days=1)
oldest_date = unix_time(yesterday)
response = conn.list_open_workflow_executions(
"test-domain", oldest_date, workflow_id="test-workflow"
)
execution_infos = response["executionInfos"]
len(execution_infos).should.equal(1)
open_workflow = execution_infos[0]
open_workflow["workflowType"].should.equal(
{"version": "v1.0", "name": "test-workflow"}
)
open_workflow.should.contain("startTimestamp")
open_workflow["execution"]["workflowId"].should.equal("uid-abcd1234")
open_workflow["execution"].should.contain("runId")
open_workflow["cancelRequested"].should.be(False)
open_workflow["executionStatus"].should.equal("OPEN")
# ListClosedWorkflowExecutions endpoint
@mock_swf_deprecated
def test_list_closed_workflow_executions():
conn = setup_swf_environment()
# Leave one workflow execution open to make sure it isn't displayed
conn.start_workflow_execution(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
)
# One closed workflow execution
run_id = conn.start_workflow_execution(
"test-domain", "uid-abcd12345", "test-workflow", "v1.0"
)["runId"]
conn.terminate_workflow_execution(
"test-domain",
"uid-abcd12345",
details="some details",
reason="a more complete reason",
run_id=run_id,
)
yesterday = datetime.utcnow() - timedelta(days=1)
oldest_date = unix_time(yesterday)
response = conn.list_closed_workflow_executions(
"test-domain", start_oldest_date=oldest_date, workflow_id="test-workflow"
)
execution_infos = response["executionInfos"]
len(execution_infos).should.equal(1)
open_workflow = execution_infos[0]
open_workflow["workflowType"].should.equal(
{"version": "v1.0", "name": "test-workflow"}
)
open_workflow.should.contain("startTimestamp")
open_workflow["execution"]["workflowId"].should.equal("uid-abcd12345")
open_workflow["execution"].should.contain("runId")
open_workflow["cancelRequested"].should.be(False)
open_workflow["executionStatus"].should.equal("CLOSED")
# TerminateWorkflowExecution endpoint
@mock_swf_deprecated
def test_terminate_workflow_execution():
conn = setup_swf_environment()
run_id = conn.start_workflow_execution(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
)["runId"]
resp = conn.terminate_workflow_execution(
"test-domain",
"uid-abcd1234",
details="some details",
reason="a more complete reason",
run_id=run_id,
)
resp.should.be.none
resp = conn.get_workflow_execution_history("test-domain", run_id, "uid-abcd1234")
evt = resp["events"][-1]
evt["eventType"].should.equal("WorkflowExecutionTerminated")
attrs = evt["workflowExecutionTerminatedEventAttributes"]
attrs["details"].should.equal("some details")
attrs["reason"].should.equal("a more complete reason")
attrs["cause"].should.equal("OPERATOR_INITIATED")
@mock_swf_deprecated
def test_terminate_workflow_execution_with_wrong_workflow_or_run_id():
conn = setup_swf_environment()
run_id = conn.start_workflow_execution(
"test-domain", "uid-abcd1234", "test-workflow", "v1.0"
)["runId"]
# terminate workflow execution
conn.terminate_workflow_execution("test-domain", "uid-abcd1234")
# already closed, with run_id
conn.terminate_workflow_execution.when.called_with(
"test-domain", "uid-abcd1234", run_id=run_id
).should.throw(
SWFResponseError, "WorkflowExecution=[workflowId=uid-abcd1234, runId="
)
# already closed, without run_id
conn.terminate_workflow_execution.when.called_with(
"test-domain", "uid-abcd1234"
).should.throw(SWFResponseError, "Unknown execution, workflowId = uid-abcd1234")
# wrong workflow id
conn.terminate_workflow_execution.when.called_with(
"test-domain", "uid-non-existent"
).should.throw(SWFResponseError, "Unknown execution, workflowId = uid-non-existent")
# wrong run_id
conn.terminate_workflow_execution.when.called_with(
"test-domain", "uid-abcd1234", run_id="foo"
).should.throw(
SWFResponseError, "WorkflowExecution=[workflowId=uid-abcd1234, runId="
)
``` |
{
"source": "jonnasnovaes/scrambler",
"score": 2
} |
#### File: scrambler/ui/mainUi.py
```python
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(619, 320)
Dialog.setStyleSheet("color: rgb(0, 0, 0);")
self.textEdit = QtWidgets.QTextEdit(Dialog)
self.textEdit.setGeometry(QtCore.QRect(30, 40, 401, 101))
self.textEdit.setObjectName("textEdit")
self.textEdit_2 = QtWidgets.QTextEdit(Dialog)
self.textEdit_2.setGeometry(QtCore.QRect(30, 190, 401, 101))
self.textEdit_2.setObjectName("textEdit_2")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(30, 20, 47, 13))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(30, 170, 47, 13))
self.label_2.setObjectName("label_2")
self.line = QtWidgets.QFrame(Dialog)
self.line.setGeometry(QtCore.QRect(450, 0, 20, 321))
self.line.setFrameShape(QtWidgets.QFrame.VLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(500, 40, 91, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(Dialog)
self.pushButton_2.setGeometry(QtCore.QRect(500, 80, 91, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "Entrada"))
self.label_2.setText(_translate("Dialog", "Saída"))
self.pushButton.setText(_translate("Dialog", "Embaralhar"))
self.pushButton_2.setText(_translate("Dialog", "Desembaralhar"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
``` |
{
"source": "JonnatasCabral/todolist",
"score": 2
} |
#### File: todolist/todos/serializers.py
```python
from rest_framework import serializers
from todos import models
from users.serializers import UserSerializer
from users.models import User
class TaskSerializer(serializers.ModelSerializer):
title = serializers.CharField(
max_length=100, allow_blank=False, required=True
)
deadline = serializers.DateTimeField(
format="%Y-%m-%d %H:%M:%S",
required=False)
assigned_to = UserSerializer(required=False)
assigned_to_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), write_only=True, required=False)
def validate(self, data):
data['assigned_to'] = data.pop('assigned_to_id', None)
return data
class Meta:
model = models.Task
fields = (
'id', 'title','text', 'todolist', 'deadline',
'is_done', 'assigned_to_id', 'assigned_to'
)
class ToDoListSerializer(serializers.ModelSerializer):
created_by = UserSerializer(
read_only=True,
default=serializers.CurrentUserDefault())
tasks = serializers.SerializerMethodField()
def get_tasks(self, obj):
tasks = models.Task.objects.filter(todolist_id=obj.id)
serializer = TaskSerializer(tasks, many=True)
return serializer.data
class Meta:
model = models.ToDoList
fields = ('id', 'title', 'created_by', 'tasks')
class UpdateDoneSerializer(serializers.ModelSerializer):
class Meta:
model = models.Task
fields = (
'id', 'is_done'
)
```
#### File: todos/views/viewset.py
```python
from rest_framework import viewsets
from rest_framework import mixins
from todos import serializers
from todos import models
class ToDoListViewSet(viewsets.ModelViewSet):
queryset = models.ToDoList.objects.all()
serializer_class = serializers.ToDoListSerializer
def perform_create(self, serializer):
serializer.validated_data['created_by'] = self.request.user
return super(ToDoListViewSet, self).perform_create(serializer)
class TaskViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin,
mixins.UpdateModelMixin, mixins.DestroyModelMixin,
viewsets.GenericViewSet):
queryset = models.Task.objects.all()
serializer_class = serializers.TaskSerializer
class UpdateDoneViewSet(mixins.UpdateModelMixin,
viewsets.GenericViewSet):
queryset = models.Task.objects.all()
serializer_class = serializers.UpdateDoneSerializer
```
#### File: users/tests/test_views.py
```python
from unittest.mock import MagicMock
from django.http import Http404
from django.test import TestCase
from model_mommy import mommy
from users.views import UserListViewSet
from users.models import User
class TestUserViewSet(TestCase):
def setUp(self):
self.users = mommy.make('users.User', _quantity=10)
self.view = UserListViewSet()
def test_get_queryset(self):
self.assertEqual(
list(self.view.get_queryset()),
list(User.objects.filter())
)
``` |
{
"source": "jonnathan-romero/jonn_lib",
"score": 2
} |
#### File: jonnathan-romero/jonn_lib/jonn_lib.py
```python
import os
import gc
import dcor
import smtplib
import mysql.connector
import numpy as np
import pandas as pd
import os.path as op
import cvxopt as cvx
import networkx as nx
import seaborn as sns
import scipy.stats as ss
import yahoofinancials as yf
import statsmodels.api as sm
import matplotlib.pyplot as plt
import statsmodels.tsa.api as smt
import matplotlib.gridspec as gridspec
from pypfopt import *
from email import encoders
from arch import arch_model
from functools import partial
from scipy.stats import norm
from scipy.integrate import quad
from scipy.optimize import newton
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from mysql.connector import errorcode
from email.mime.multipart import MIMEMultipart
from email.utils import COMMASPACE, formatdate
from datetime import datetime, timedelta, date
from yahoo_fin import stock_info as si
%matplotlib inline
blue, gold, green, red, purple, brown = sns.color_palette('colorblind', 6)
def daterange(start_date, end_date):
'''
daterange(date(2005, 12, 31), date(2020, 3, 25))
creates range between 2 dates given
'''
for n in range(int ((end_date - start_date).days)):
yield start_date + timedelta(n)
def reduce_mem_usage(df):
""" iterate through all the columns of a dataframe and modify the data type
to reduce memory usage.
"""
start_mem = df.memory_usage().sum() / 1024**2
#print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
for col in df.columns:
col_type = df[col].dtype
gc.collect()
if col_type != object:
c_min = df[col].min()
c_max = df[col].max()
if str(col_type)[:3] == 'int':
if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
df[col] = df[col].astype(np.int8)
elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
df[col] = df[col].astype(np.int16)
elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
df[col] = df[col].astype(np.int32)
elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
df[col] = df[col].astype(np.int64)
else:
if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
df[col] = df[col].astype(np.float16)
elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
df[col] = df[col].astype(np.float32)
else:
df[col] = df[col].astype(np.float64)
else:
df[col] = df[col].astype('category')
end_mem = df.memory_usage().sum() / 1024**2
#print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
#print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))
return df
def df_distance_correlation(df):
'''
creates distance correlation matrix
'''
#initializes an empty DataFrame
df_dcor = pd.DataFrame(index=df.columns, columns=df.columns)
#initialzes a counter at zero
k=0
#iterates over the time series of each stock
for i in stocks:
#stores the ith time series as a vector
v_i = df.loc[:, i].values
#iterates over the time series of each stock subect to the counter k
for j in stocks[k:]:
#stores the jth time series as a vector
v_j = df.loc[:, j].values
#computes the dcor coefficient between the ith and jth vectors
dcor_val = dcor.distance_correlation(v_i, v_j)
#appends the dcor value at every ij entry of the empty DataFrame
df_dcor.at[i,j] = dcor_val
#appends the dcor value at every ji entry of the empty DataFrame
df_dcor.at[j,i] = dcor_val
#increments counter by 1
k+=1
#returns a DataFrame of dcor values for every pair of stocks
return df_dcor
def build_corr_nx(df):
'''
builds correlation network given a distance correlation
aka run on output from df_distance_correlation
'''
# converts the distance correlation dataframe to a numpy matrix with dtype float
cor_matrix = df.values.astype('float')
# Since dcor ranges between 0 and 1, (0 corresponding to independence and 1
# corresponding to dependence), 1 - cor_matrix results in values closer to 0
# indicating a higher degree of dependence where values close to 1 indicate a lower degree of
# dependence. This will result in a network with nodes in close proximity reflecting the similarity
# of their respective time-series and vice versa.
sim_matrix = 1 - cor_matrix
# transforms the similarity matrix into a graph
G = nx.from_numpy_matrix(sim_matrix)
# extracts the indices (i.e., the stock names from the dataframe)
stock_names = df.index.values
# relabels the nodes of the network with the stock names
G = nx.relabel_nodes(G, lambda x: stock_names[x])
# assigns the edges of the network weights (i.e., the dcor values)
G.edges(data=True)
# copies G
## we need this to delete edges or othwerwise modify G
H = G.copy()
# iterates over the edges of H (the u-v pairs) and the weights (wt)
for (u, v, wt) in G.edges.data('weight'):
# selects edges with dcor values less than or equal to 0.33
if wt >= 1 - 0.325:
# removes the edges
H.remove_edge(u, v)
# selects self-edges
if u == v:
# removes the self-edges
H.remove_edge(u, v)
# returns the final stock correlation network
return H
# function to display the network from the distance correlation matrix
def plt_corr_nx(H, title):
'''
plots correlation network
run on output from build_corr_nx
'''
# creates a set of tuples: the edges of G and their corresponding weights
edges, weights = zip(*nx.get_edge_attributes(H, "weight").items())
# This draws the network with the Kamada-Kawai path-length cost-function.
# Nodes are positioned by treating the network as a physical ball-and-spring system. The locations
# of the nodes are such that the total energy of the system is minimized.
pos = nx.kamada_kawai_layout(H)
with sns.axes_style('whitegrid'):
# figure size and style
plt.figure(figsize=(12, 9))
plt.title(title, size=16)
# computes the degree (number of connections) of each node
deg = H.degree
# list of node names
nodelist = []
# list of node sizes
node_sizes = []
# iterates over deg and appends the node names and degrees
for n, d in deg:
nodelist.append(n)
node_sizes.append(d)
# draw nodes
nx.draw_networkx_nodes(
H,
pos,
node_color="#DA70D6",
nodelist=nodelist,
node_size=np.power(node_sizes, 2.33),
alpha=0.8,
font_weight="bold",
)
# node label styles
nx.draw_networkx_labels(H, pos, font_size=13, font_family="sans-serif", font_weight='bold')
# color map
cmap = sns.cubehelix_palette(3, as_cmap=True, reverse=True)
# draw edges
nx.draw_networkx_edges(
H,
pos,
edge_list=edges,
style="solid",
edge_color=weights,
edge_cmap=cmap,
edge_vmin=min(weights),
edge_vmax=max(weights),
)
# builds a colorbar
sm = plt.cm.ScalarMappable(
cmap=cmap,
norm=plt.Normalize(vmin=min(weights),
vmax=max(weights))
)
sm._A = []
plt.colorbar(sm)
# displays network without axes
plt.axis("off")
def send_mail(send_from, send_to, subject, message, files=[] ,server="smtp.gmail.com", port=587, username='', password='', use_tls=True):
"""Compose and send email with provided info and attachments.
send_mail('<EMAIL>', ['<EMAIL>','<EMAIL>'],'HI', 'THIS', files=['TP_python_prev.pdf'], server="smtp.gmail.com",port=587, username='<EMAIL>', password='<PASSWORD>',use_tls=True)
Args:
send_from (str): from name
send_to (str): to name
subject (str): message title
message (str): message body
files (list[str]): list of file paths to be attached to email
server (str): mail server host name
port (int): port number
username (str): server auth username
password (str): server auth password
use_tls (bool): use TLS mode
"""
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(message))
for path in files:
part = MIMEBase('application', "octet-stream")
with open(path, 'rb') as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="{}"'.format(op.basename(path)))
msg.attach(part)
smtp = smtplib.SMTP(server, port)
if use_tls:
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
def create_database(database, password):
'''
creates a database
'''
cnx = mysql.connector.connect(user='root', password=password, host='localhost', auth_plugin='mysql_native_password')
cursor = cnx.cursor()
try:
cursor.execute("CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(database))
except mysql.connector.Error as err:
print("Failed creating database: {}".format(err))
cursor.close()
cnx.close()
exit(1)
cursor.close()
cnx.close()
def create_table(database, password, table_name, table):
'''
creates table in database
create_table_jonn_db('jonn_db', 'temp_example', "CREATE TABLE `temp_example` ("
" `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
" `birth_date` date NOT NULL,"
" `first_name` varchar(14) NOT NULL,"
" `last_name` varchar(16) NOT NULL,"
" `gender` enum('M','F') NOT NULL,"
" `hire_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`)"
") ENGINE=InnoDB" )
'''
cnx = mysql.connector.connect(user='root', password=password, host='localhost', database=database, auth_plugin='mysql_native_password')
cursor = cnx.cursor()
try:
print("Creating table {}: ".format(table_name), end='')
cursor.execute(table)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)
else:
print("OK")
cursor.close()
cnx.close()
def insert_data_db():
print ('https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html')
def query_data_db():
print('https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html')
def drop_corr(df, keep_cols, thresh=0.99):
'''
removes column if overly correlated
'''
df_corr = df.corr().abs()
upper = df_corr.where(np.triu(np.ones(df_corr.shape), k=1).astype(np.bool))
to_remove = [column for column in upper.columns if any(upper[column] > thresh)]
to_remove = [x for x in to_remove if x not in keep_cols]
df_corr = df_corr.drop(columns = to_remove)
return df_corr, to_remove
def return_live_price(ticker):
'''
returns current price of stock
'''
return si.get_live_price(ticker)
def get_historical_prices(symbol, start_date, end_date, time_interval):
'''
get_historical_prices('TLT', '1989-12-31', datetime.now().strftime("%Y-%m-%d"), 'daily')
uses yahoo financials to download stock prices monthly, weekly or daily
'''
obj = yf.YahooFinancials(symbol)
data = obj.get_historical_price_data(start_date=start_date, end_date=end_date, time_interval=time_interval)
df = pd.DataFrame(data[symbol]['prices'])
df = df.rename(columns={'formatted_date':'Date'})
df = df.set_index(df['Date'], drop=True)
try:
divs = pd.DataFrame(data[symbol]['eventsData']['dividends']).T
divs = divs.rename(columns={'formatted_date':'Date','amount':'dividend'})
divs = divs.set_index(divs['Date'],drop=True)
df = df.merge(divs['dividend'],left_index=True,right_index=True,how='outer')
df['dividend'] = df['dividend'].fillna(0)
except:
pass
try:
df['log_total_return']=np.log(df['adjclose']/df['adjclose'].shift(1))
df['log_div_return']=np.log(df['adjclose']/(df['adjclose']-df['dividend']))
df['log_price_return']=np.log(df['close']/df['close'].shift(1))
df['total_return'] = (df['adjclose']-df['adjclose'].shift(1))/df['adjclose'].shift(1)
df['div_return'] = (df['dividend'])/df['adjclose'].shift(1)
df['price_return']= (df['close']-df['close'].shift(1))/df['close'].shift(1)
df = df.add_suffix('_'+symbol)
except:
pass
return df
def garch(data, p=1, o=0, q=1, update_freq=5, **kwds):
'''
garch model
'''
model = arch_model(data, 'Garch', p=p, o=o, q=q, **kwds)
res = model.fit(update_freq=update_freq, disp=False)
return res
def garch_forecast_sim(data, p=1, o=0, q=1, update_freq=5,horizon=30, n_simulations=1000, **kwds):
'''
garch forecast
'''
np.random.seed(0)
garch_model = garch(data,p=p,o=o,q=q,update_freq=update_freq)
forecasts = garch_model.forecast(horizon=horizon, method='simulation',simulations=n_simulations)
sim_ser = pd.Series(forecasts.simulations.values[-1,:,-1])
sim_ser.name = 'garch'
return sim_ser
def calc_garch_var(data, p=1, o=0, q=1, update_freq=5, horizon=30, n_simulations=1000, alpha=0.05, **kwds):
'''
calculate garch variance
'''
sim_ser = garch_forecast_sim(data, p=p, o=o, q=q, update_freq=update_freq,horizon=horizon, n_simulations=n_simulations//horizon, **kwds)
var = calc_quantile_var(sim_ser, alpha=alpha)
return var
def tsplot(y, lags=None, figsize=(12, 12), style='bmh'):
'''
creates ACF PACF and QQ plots for time series analysis
'''
if not isinstance(y, pd.Series):
y = pd.Series(y)
with plt.style.context(style):
fig = plt.figure(figsize=figsize)
layout = (3, 2)
ts_ax = plt.subplot2grid(layout, (0, 0), colspan=2)
acf_ax = plt.subplot2grid(layout, (1, 0))
pacf_ax = plt.subplot2grid(layout, (1, 1))
qq_ax = plt.subplot2grid(layout, (2, 0), colspan=2)
#y.plot(ax=ts_ax)
y.plot(ax=ts_ax, marker='o', c='gray', ms=5.,
markerfacecolor=blue, markeredgecolor='white', markeredgewidth=.25)
ts_ax.set_title(f'{y.name}')
smt.graphics.plot_acf(y, lags=lags, ax=acf_ax, alpha=0.5)
smt.graphics.plot_pacf(y, lags=lags, ax=pacf_ax, alpha=0.5)
sm.qqplot(y, line='s', ax=qq_ax, marker='X', markerfacecolor=blue,
markeredgecolor='k', markeredgewidth=0.25)
qq_ax.set_title('QQ Plot')
plt.tight_layout()
return
def BlackScholes(S,K,r,T,sigma, voltype='Normal', option = 'call'):
"""Return price of swaption in BlackScholes model
Inputs:
S = spot (current value of forward swap rate)
K = strike
sigma = volatility (in normal or lognormal units)
T = expiry
r = interest rates
voltype = one of 'Normal' or 'Lognormal' """
if voltype=='Normal':
moneyness = S-K
atMaturityStdev = sigma*np.sqrt(T)
scaledMoneyness = moneyness/atMaturityStdev
return (moneyness * norm.cdf(scaledMoneyness)+atMaturityStdev * norm.pdf(scaledMoneyness))
elif voltype=='Lognormal':
d1 = (np.log(1.0*S/K)+(r+sigma**2/2.0)*T)/(sigma*np.sqrt(T))
d2 = d1 - sigma*np.sqrt(T)
if option == 'call':
return S*norm.cdf(d1)-K*np.exp(-r*T)*norm.cdf(d2)
else:
return (K * np.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1))
else:
raise Exception("Unsupported option volatility type, should be 'Normal' or 'Lognormal', '" + voltype + "' entered." )
def impliedVol(Opt_price, S0,K,r,T, vol_guess , voltype = 'Lognormal'):
'''
calculates implied volatility given
'''
return newton(func = lambda sigma:BlackScholes(S0,K,r,T, sigma, voltype='Lognormal')-Opt_price,x0 = vol_guess,tol = 1e-8)
def BSMC(S0, K, r, T, sig , N , payoff):
'''
BS Monte Carlo
'''
np.random.seed(seed=3)
W = ss.norm.rvs( loc=(r - 0.5 * sig**2)*T, scale=np.sqrt(T)*sig, size=N )
S_T = S0 * np.exp(W)
if payoff =="call":
V = np.average(np.maximum(S_T-K, 0.0)*np.exp(-r*T))
else:
V = np.average(np.maximum(K-S_T, 0.0)*np.exp(-r*T))
return V
def BSMCAnti(S0, K, r, T, sig , N , payoff):
'''
calculates BS using antithetic
'''
np.random.seed(seed=3)
W = ss.norm.rvs( loc=0, scale=np.sqrt(T)*sig, size=int(N/2) )
volBias = np.sqrt(T)*sig/np.std(W)
S_T = np.concatenate([S0 * np.exp((r - 0.5 * sig**2)*T+W*volBias),S0 * np.exp((r - 0.5 * sig**2)*T-W*volBias)])
if payoff =="call":
V = np.average(np.maximum(S_T-K, 0.0)*np.exp(-r*T))
else:
V = np.average(np.maximum(K-S_T, 0.0)*np.exp(-r*T))
return V
def tree_call(S0, K, r, T, sig , N , payoff):
'''
calucalcutes binomial pricing
'''
dT = float(T) / N # Delta t
u = np.exp(sig * np.sqrt(dT)) # up factor
d = 1.0 / u # down factor
N=int(N)
V = np.zeros(N+1) # initialize the price vector
S_T = np.array( [(S0 * u**j * d**(N - j)) for j in range(N + 1)] ) # price S_T at time T
a = np.exp(r * dT) # risk free compounded return
p = (a - d)/ (u - d) # risk neutral up probability
q = 1.0 - p # risk neutral down probability
if payoff =="call":
V[:] = np.maximum(S_T-K, 0.0)
else:
V[:] = np.maximum(K-S_T, 0.0)
for i in range(N-1, -1, -1):
V[:-1] = np.exp(-r*dT) * (p * V[1:] + q * V[:-1]) # the price vector is overwritten at each step
return V[0]
def markowitz_opt(ret_vec, covar_mat, max_risk):
'''
markowitz_opt([0.07, 0.06, 0.0], [[0.2,0,0],[0,0.3,0],[0,0,0]], 0.07)
Finds the best return for a given level of risks usesing cvxopt
'''
U,V = np.linalg.eig(covar_mat)
U[U<0] = 0
Usqrt = np.sqrt(U)
A = np.dot(np.diag(Usqrt), V.T)
G1temp = np.zeros((A.shape[0]+1, A.shape[1]))
G1temp[1:, :] = -A
h1temp = np.zeros((A.shape[0]+1, 1))
h1temp[0] = max_risk
ret_c = len(ret_vec)
for i in np.arange(ret_c):
ei = np.zeros((1, ret_c))
ei[0, i] = 1
if i == 0:
G2temp = [cvx.matrix(-ei)]
h2temp = [cvx.matrix(np.zeros((1,1)))]
else:
G2temp += [cvx.matrix(-ei)]
h2temp += [cvx.matrix(np.zeros((1,1)))]
Ftemp = np.ones((1, ret_c))
F = cvx.matrix(Ftemp)
g = cvx.matrix(np.ones((1,1)))
G = [cvx.matrix(G1temp)] + G2temp
H = [cvx.matrix(h1temp)] + h2temp
cvx.solvers.options['show_progress'] = False
sol = cvx.solvers.socp(
-cvx.matrix(ret_vec),
Gq=G, hq=H, A=F, b=g)
xsol = np.array(sol['x'])
return xsol
``` |
{
"source": "JonNData/lambdata",
"score": 3
} |
#### File: lambdata/test/my_mod_test.py
```python
import unittest
from my_lambdata.my_mod import enlarge
class TestMyMod(unittest.TestCase):
def test_enlarge(self):
"""
Unit test that the enlarge function in the my_mod file is working properly
"""
self.assertEqual(enlarge(5), 500)
if __name__ == '__main__':
unittest.main()
``` |
{
"source": "JonNData/used-car-predictor",
"score": 3
} |
#### File: used-car-predictor/pages/predictions.py
```python
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from joblib import load
import dash_daq as daq
import pandas as pd
# Imports from this application
from app import app
# 2 column layout. 1st column width = 4/12
# https://dash-bootstrap-components.opensource.faculty.ai/l/components/layout
# Load pipeline
pipeline = load('assets/pipeline_drive.joblib')
column1 = dbc.Col(
[
dcc.Markdown(
"""
## Inputs
Fill out the car specifications
"""
),
# Year
html.Div(children='Year', style={
'textAlign': 'left'}),
dcc.Input(
id='input_year',
placeholder='Enter a year...',
type='number',
value='1999',
className = 'mb-4',
),
# Manufacturer
html.Div(children='Manufacturer', style={
'textAlign': 'left'}),
dcc.Dropdown(
id='input_manufacturer',
options= [
{'label': 'Acura', 'value': 'acura'},
{'label': 'Alfa-Romeo', 'value': 'alfa-romeo'},
{'label': 'Aston-Martin ', 'value': 'aston-martin'},
{'label': 'Audi', 'value': 'audi'},
{'label': 'Bmw', 'value': 'bmw'},
{'label': 'Buick ', 'value': 'buick'},
{'label': 'Cadillac ', 'value': 'cadillac'},
{'label': 'Chevrolet ', 'value': 'chevrolet'},
{'label': 'Chrysler', 'value': 'chrysler'},
{'label': 'Datsun ', 'value': 'datsun'},
{'label': 'Dodge ', 'value': 'dodge'},
{'label': 'Ferrari ', 'value': 'ferrari'},
{'label': 'Fiat', 'value': 'fiat'},
{'label': 'Ford ', 'value': 'ford'},
{'label': 'Gmc ', 'value': 'gmc'},
{'label': 'Harley-Davidson ', 'value': 'harley-davidson'},
{'label': 'Hennessey', 'value': 'hennessey'},
{'label': 'Honda ', 'value': 'honda'},
{'label': 'Hyundai ', 'value': 'hyundai'},
{'label': 'Infiniti ', 'value': 'infiniti'},
{'label': 'Jaguar ', 'value': 'jaguar'},
{'label': 'Jeep ', 'value': 'jeep'},
{'label': 'Kia', 'value': 'kia'},
{'label': 'Land Rover ', 'value': 'land rover'},
{'label': 'Lexus ', 'value': 'lexus'},
{'label': 'Lincoln ', 'value': 'lincoln'},
{'label': 'Mazda', 'value': 'mazda'},
{'label': 'Mercedes-Benz', 'value': 'mercedes-benz'},
{'label': 'Mercury', 'value': 'mercury'},
{'label': 'Mini ', 'value': 'mini'},
{'label': 'Mitsubishi', 'value': 'mitsubishi'},
{'label': 'Morgan ', 'value': 'morgan'},
{'label': 'Nissan ', 'value': 'nissan'},
{'label': 'Pontiac ', 'value': 'pontiac'},
{'label': 'Porsche', 'value': 'porche'},
{'label': 'Ram ', 'value': 'ram'},
{'label': 'Rover ', 'value': 'rover'},
{'label': 'Saturn ', 'value': 'saturn'},
{'label': 'Subaru', 'value': 'subaru'},
{'label': 'Tesla ', 'value': 'tesla'},
{'label': 'Toyota ', 'value': 'toyota'},
{'label': 'Volkswagen ', 'value': 'volkswagen'},
{'label': 'Volvo', 'value': 'volvo'},
{'label': 'Other', 'value': 'nan'}
],
className = 'mb-3',
value=1
),
# Cylinders
html.Div(children='Cylinders', style={
'textAlign': 'left'}),
dcc.Slider(
id = 'input_cylinders',
min=2,
max=12,
marks={
# {'2 cylinders': '2 clndr'},
# {'4 cylinders': '4 clndr'},
# {'6 cylinders': '6 clndr'},
# {'8 cylinders': '8 clndr'},
# {'10 cylinders': '10 clndr'},
# {'12 cylinders': '12 clndr'}
2: {'label': '2cyln', 'style': {'color': '#77b0b1'}},
4: {'label': '4cyln'},
6: {'label': '6cyln'},
8: {'label': '8cyln'},
10: {'label': '10cyln'},
12: {'label': '12cyln', 'style': {'color': '#f50'}}
},
className = 'mb-3',
value=2,
),
# Fuel
html.Div(children='Fuel Type', style={
'textAlign': 'left'}),
dcc.Dropdown(
id='input_fuel',
options= [
{'label': 'Gas', 'value': 'gas'},
{'label': 'Hybrid', 'value': 'hybrid'},
{'label': 'Electric', 'value': 'electric'},
{'label': 'Diesel', 'value': 'diesel'},
{'label': 'Other', 'value': 'nan'}
],
className = 'mb-3',
value=3
),
# Odometer
html.Div(children='Odometer', style={
'textAlign': 'left'
}),
dcc.Input(
id='input_odometer',
placeholder='Enter a value in miles...',
type='number',
className = 'mb-3',
value='20000'
),
# Drive
html.Div(children='Drive Type', className = 'mb-1',style={
'textAlign': 'left'
}),
dcc.RadioItems(
id='input_drive',
options=[
{'label': 'Front-Wheel Drive ', 'value': 'fwd'},
{'label': 'Rear-Wheel Drive ', 'value': 'rwd'},
{'label': 'All-Wheel Drive ', 'value': 'nan'}
],
value='fwd',
labelStyle={'margin-right': '20px'}
)
],
md=4,
)
column2 = dbc.Col(
[
html.H2("Output"),
# Manufacturer emblem
html.Div(html.Img(id='manufacturer-image', className= 'img-fluid')),
# Miles led display
html.H3(children='Miles', style={'textAlign': 'left'}, className= 'mt-5'),
daq.LEDDisplay(
id='my-daq-leddisplay',
value="10000",
className = 'mb-5'
),
# Prediction output
html.H2("Prediction"),
html.Div(id='prediction-content', className='lead'),
]
)
layout = dbc.Row([column1, column2])
# Manufacturer emblem
@app.callback(
Output('manufacturer-image', 'src'),
[Input('input_manufacturer', 'value')]
)
def manufacturer_emblem(input_manufacturer):
print(f'\n\n{input_manufacturer}\n\n')
if input_manufacturer == 'acura':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/acura-150x150.png'
elif input_manufacturer == 'aston-martin':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/aston_martin-150x150.png'
elif input_manufacturer == 'alfa-romeo':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/alfa_romeo-150x150.png'
elif input_manufacturer == 'audi':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/audi-150x150.png'
elif input_manufacturer == 'bmw':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/bmw-150x150.png'
elif input_manufacturer == 'buick':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/buick-150x150.png'
elif input_manufacturer == 'cadillac':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/cadillac-150x150.png'
elif input_manufacturer == 'chevrolet':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/chevrolet-150x150.png'
elif input_manufacturer == 'chrysler':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/chrysler-150x150.png'
elif input_manufacturer == 'dodge':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/dodge-150x150.png'
elif input_manufacturer == 'ferrari':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/ferrari-150x150.png'
elif input_manufacturer == 'fiat':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/fiat-150x150.png'
elif input_manufacturer == 'ford':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/ford-150x150.png'
elif input_manufacturer == 'gmc':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/gmc-150x150.png'
elif input_manufacturer == 'harley-davidson':
return 'https://simg.nicepng.com/png/small/70-701995_all-harley-davidson-logos-png-harley-davidson-logo.png'
elif input_manufacturer == 'hennessey':
return 'https://www.car-logos.org/wp-content/uploads/2011/10/hennessey-150x150.png'
elif input_manufacturer == 'honda':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/honda-150x150.png'
elif input_manufacturer == 'hyundai':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/hyundai-150x150.png'
elif input_manufacturer == 'infiniti':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/inf-150x150.png'
elif input_manufacturer == 'jaguar':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/jagu-150x150.png'
elif input_manufacturer == 'jeep':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/jeep-150x150.png'
elif input_manufacturer == 'kia':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/kia-150x150.png'
elif input_manufacturer == 'land rover':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/land-rover-150x150.png'
elif input_manufacturer == 'lexus':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/lexus-150x150.png'
elif input_manufacturer == 'lincoln':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/linc-150x150.png'
elif input_manufacturer == 'mazda':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/mazda-150x150.png'
elif input_manufacturer == 'mercedes-benz':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/marchedrs-150x150.png'
elif input_manufacturer == 'mercury':
return 'https://www.martystransmission.com/wp-content/uploads/2018/01/mercury-logo.jpg'
elif input_manufacturer == 'mini':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/mini-150x150.png'
elif input_manufacturer == 'mitsubishi':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/mitub-150x150.png'
elif input_manufacturer == 'morgan':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/morgan-150x150.png'
elif input_manufacturer == 'nissan':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/nissan-150x150.png'
elif input_manufacturer == 'pontiac':
return 'https://p7.hiclipart.com/preview/756/277/149/pontiac-firebird-general-motors-car-pontiac-fiero-explicit-content-logo-thumbnail.jpg'
elif input_manufacturer == 'porche':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/porsche-150x150.png'
elif input_manufacturer == 'volvo':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/volvo-150x150.png'
elif input_manufacturer == 'ram':
return 'https://lh3.googleusercontent.com/proxy/osC3IbnnPa7376NVw2L3lGSJWhY2mhQbykpT722s15PxMBhwAAE64GJdRDmtJbAWpWgU5s8WZZUhk-qQw-cWeD08ib5TmWt-xFh2e1RB26WPrKk'
elif input_manufacturer == 'rover':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/land-rover-150x150.png'
elif input_manufacturer == 'saturn':
return 'https://i.ya-webdesign.com/images/saturn-car-logo-png-14.png'
elif input_manufacturer == 'subaru':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/subaru-150x150.png'
elif input_manufacturer == 'tesla':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/tesla-150x150.png'
elif input_manufacturer == 'toyota':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/toyota-150x150.png'
elif input_manufacturer == 'volkswagen':
return 'https://www.car-logos.org/wp-content/uploads/2011/09/volkswagen-150x150.png'
else:
return 'assets/silhouette-carros-icons-vector.jpg'
# Odometer reading
@app.callback(
Output(component_id='my-daq-leddisplay', component_property='value'),
[Input(component_id='input_odometer', component_property='value')]
)
def update_output_div(input_value):
return input_value
# Prediction reading
@app.callback(
Output('prediction-content', 'children'),
[Input('input_year', 'value'),
Input('input_manufacturer', 'value'),
Input('input_cylinders', 'value'),
Input('input_fuel', 'value'),
Input('input_odometer', 'value'),
Input('input_drive', 'value')],
)
def predict(input_year, input_manufacturer, input_cylinders, input_fuel, input_odometer, input_drive):
if input_cylinders == 2:
input_cylinders = '2 cylinders'
elif input_cylinders == 4:
input_cylinders = '4 cylinders'
elif input_cylinders == 6:
input_cylinders = '6 cylinders'
elif input_cylinders == 8:
input_cylinders = '8 cylinders'
elif input_cylinders == 10:
input_cylinders = '10 cylinders'
else:
input_cylinders = '12 cylinders'
# Convert input to dataframe
df = pd.DataFrame(
data=[[input_year, input_manufacturer, input_cylinders, input_fuel, input_odometer, input_drive]],
columns=['year', 'manufacturer', 'cylinders', 'fuel', 'odometer', 'drive']
)
# Make predictions
y_pred = pipeline.predict(df)[0]
# Show prediction
return (f'The model predicts this car has a price of ${y_pred:,.0f}')
``` |
{
"source": "jonndoe/Character-Level-Language-Modeling-with-Deeper-Self-Attention-pytorch",
"score": 2
} |
#### File: jonndoe/Character-Level-Language-Modeling-with-Deeper-Self-Attention-pytorch/testfile.py
```python
import data
import torch
default_path='./data/wikitext-2'
import os
import hashlib
fn = 'corpus.{}.data'.format(hashlib.md5(default_path.encode()).hexdigest())
print('fn is:', fn)
if os.path.exists(fn):
print('Loading cached dataset...')
corpus = torch.load(fn)
print(corpus.dictionary)
else:
print('Producing dataset...')
corpus = data.Corpus(default_path)
torch.save(corpus, fn)
print(default_path.encode().hex())
print(len(default_path.encode()))
print('dictionary :', corpus.dictionary)
print('train :', corpus.train)
print('valid :', corpus.valid)
print('test :', corpus.test)
for i in corpus.test:
print(i)
print(i.__str__())
if i.__str__() != 'tensor(0)':
for k in i:
print(k)
'''
mydict = data.Dictionary()
mydict.add_word('goodgoodnet')
print(mydict)
print(mydict.idx2word)
print(mydict.word2idx)
print(mydict.counter)
print(mydict.total)
mydict.add_word('goodgoodnet')
print(mydict)
print(mydict.idx2word)
print(mydict.word2idx)
print(mydict.counter)
print(mydict.total)
word_list = ['hello', 'bazar', 'deddit', 'neggit', 'nonobabaro', 'hello', 'bazar', 'bazarit', 'netto', 'netto', 'netto',]
for word in word_list:
mydict.add_word(word)
print('idx2word :', mydict.idx2word)
print('word2idx :', mydict.word2idx)
print('counter :', mydict.counter)
print('total :', mydict.total)
'''
'''
class Car():
def __init__(self, maker="Ford", model="Mustang", color="blue", max_speed=100, eng_volume=1.5,):
self.maker = 'Ford'
self.model = 'Mustang'
self.color = 'red'
self.max_speed = 200
self.eng_volume = 2
self.engine_working_now = False
def start_driving(self):
self.engine_working_now = True
def __str__(self):
return self.maker +' '+ self.model +' '+ self.color
mycar = Car()
print(mycar)
print(mycar.engine_working_now)
mycar.start_driving()
print(mycar.engine_working_now)
print(mycar.__sizeof__())
print(mycar.__init__())
print(mycar.__sizeof__())
print(mycar.__class__)
'''
``` |
{
"source": "jonnedtc/Eye-Center-Locator",
"score": 3
} |
#### File: jonnedtc/Eye-Center-Locator/PupilDetector.py
```python
import numpy as np
from scipy.ndimage.filters import gaussian_filter
class GradientIntersect:
def createGrid(self, Y, X):
# create grid vectors
grid = np.array([[y,x] for y in range(1-Y,Y) for x in range (1-X,X)], dtype='float')
# normalize grid vectors
grid2 = np.sqrt(np.einsum('ij,ij->i',grid,grid))
grid2[grid2==0] = 1
grid /= grid2[:,np.newaxis]
# reshape grid for easier displacement selection
grid = grid.reshape(Y*2-1,X*2-1,2)
return grid
def createGradient(self, image):
# get image size
Y, X = image.shape
# calculate gradients
gy, gx = np.gradient(image)
gx = np.reshape(gx, (X*Y,1))
gy = np.reshape(gy, (X*Y,1))
gradient = np.hstack((gy,gx))
# normalize gradients
gradient2 = np.sqrt(np.einsum('ij,ij->i',gradient,gradient))
gradient2[gradient2==0] = 1
gradient /= gradient2[:,np.newaxis]
return gradient
def locate(self, image, sigma = 2, accuracy = 1):
# get image size
Y, X = image.shape
# get grid
grid = self.createGrid(Y, X)
# create empty score matrix
scores = np.zeros((Y,X))
# normalize image
image = (image.astype('float') - np.min(image)) / np.max(image)
# blur image
blurred = gaussian_filter(image, sigma=sigma)
# get gradient
gradient = self.createGradient(image)
# loop through all pixels
for cy in range(0,Y,accuracy):
for cx in range(0,X,accuracy):
# select displacement
displacement = grid[Y-cy-1:Y*2-cy-1,X-cx-1:X*2-cx-1,:]
displacement = np.reshape(displacement,(X*Y,2))
# calculate score
score = np.einsum('ij,ij->i', displacement, gradient)
score = np.einsum('i,i->', score, score)
scores[cy,cx] = score
# multiply with the blurred darkness
scores = scores * (1-blurred)
# if we skipped pixels, get more accurate around the best pixel
if accuracy>1:
# get maximum value index
(yval,xval) = np.unravel_index(np.argmax(scores),scores.shape)
# prevent maximum value index from being close to 0 or max
yval = min(max(yval,accuracy), Y-accuracy-1)
xval = min(max(xval,accuracy), X-accuracy-1)
# loop through new pixels
for cy in range(yval-accuracy,yval+accuracy+1):
for cx in range(xval-accuracy,xval+accuracy+1):
# select displacement
displacement = grid[Y-cy-1:Y*2-cy-1,X-cx-1:X*2-cx-1,:]
displacement = np.reshape(displacement,(X*Y,2))
# calculate score
score = np.einsum('ij,ij->i', displacement, gradient)
score = np.einsum('i,i->', score, score)
scores[cy,cx] = score * (1-blurred[cy,cx])
# get maximum value index
(yval,xval) = np.unravel_index(np.argmax(scores),scores.shape)
# return values
return (yval, xval)
def track(self, image, prev, sigma = 2, radius=50, distance = 10):
py, px = prev
# select image
image = image[py-radius:py+radius+1, px-radius:px+radius+1]
# get image size
Y, X = image.shape
# get grid
grid = self.createGrid(Y, X)
# create empty score matrix
scores = np.zeros((Y,X))
# normalize image
image = (image.astype('float') - np.min(image)) / np.max(image)
# blur image
blurred = gaussian_filter(image, sigma=sigma)
# get gradient
gradient = self.createGradient(image)
# loop through all pixels
for cy in range(radius-distance, radius+distance+1):
for cx in range(radius-distance, radius+distance+1):
# select displacement
displacement = grid[Y-cy-1:Y*2-cy-1,X-cx-1:X*2-cx-1,:]
displacement = np.reshape(displacement,(X*Y,2))
# calculate score
score = np.einsum('ij,ij->i', displacement, gradient)
score = np.einsum('i,i->', score, score)
scores[cy,cx] = score
# multiply with the blurred darkness
scores = scores * (1-blurred)
# get maximum value index
(yval,xval) = np.unravel_index(np.argmax(scores),scores.shape)
# return values
return (py+yval-radius, px+xval-radius)
class IsophoteCurvature:
def __init__(self, blur = 3, minrad = 2, maxrad = 20):
self.blur = blur
self.minrad = minrad
self.maxrad = maxrad
def locate(self, image):
# normalize image
image = gaussian_filter(image, sigma=self.blur)
image = (image.astype('float') - np.min(image))
image = image / np.max(image)
# calculate gradients
Ly, Lx = np.gradient(image)
Lyy, Lyx = np.gradient(Ly)
Lxy, Lxx = np.gradient(Lx)
Lvv = Ly**2 * Lxx - 2*Lx * Lxy * Ly + Lx**2 * Lyy
Lw = Lx**2 + Ly**2
Lw[Lw==0] = 0.001
Lvv[Lvv==0] = 0.001
k = - Lvv / (Lw**1.5)
# calculate displacement
Dx = -Lx * (Lw / Lvv)
Dy = -Ly * (Lw / Lvv)
displacement = np.sqrt(Dx**2 + Dy**2)
# calculate curvedness
curvedness = np.absolute(np.sqrt(Lxx**2 + 2 * Lxy**2 + Lyy**2))
center_map = np.zeros(image.shape, image.dtype)
(height, width)=center_map.shape
for y in range(height):
for x in range(width):
if Dx[y][x] == 0 and Dy[y][x] == 0:
continue
if (x + Dx[y][x])>0 and (y + Dy[y][x])>0:
if (x + Dx[y][x]) < center_map.shape[1] and (y + Dy[y][x]) < center_map.shape[0] and k[y][x]<0:
if displacement[y][x] >= self.minrad and displacement[y][x] <= self.maxrad:
center_map[int(y+Dy[y][x])][int(x+Dx[y][x])] += curvedness[y][x]
center_map = gaussian_filter(center_map, sigma=self.blur)
blurred = gaussian_filter(image, sigma=self.blur)
center_map = center_map * (1-blurred)
# return maximum location in center_map
position = np.unravel_index(np.argmax(center_map), center_map.shape)
return position
``` |
{
"source": "Jonneitapuro/isoskaba2",
"score": 2
} |
#### File: isoskaba2/skaba/tests.py
```python
from django.test import TestCase, Client
import unittest
from skaba.models import User, Event, Guild
TEST_EVENT_NAME = 'Test event'
TEST_EVENT_DESC = 'This is an event for testing'
TEST_EVENT_SLUG = 'test-event'
TEST_EVENT_POINTS = 10
TEST_EVENT_GUILD = 1
TEST_ADMIN_PASSWORD = 'password'
TEST_ADMIN_USERNAME = 'test_admin1'
try:
test_admin = User.objects.create_superuser(TEST_ADMIN_USERNAME, '<EMAIL>', TEST_ADMIN_PASSWORD)
except:
pass
class EventTest(unittest.TestCase):
def setUp(self):
self.client = Client()
def create_mock_event(self):
self.event = Event.objects.create(name=TEST_EVENT_NAME,
description=TEST_EVENT_DESC,
slug=TEST_EVENT_SLUG,
points=TEST_EVENT_POINTS,
guild=TEST_EVENT_GUILD)
def test_create(self):
self.client.login(username=TEST_ADMIN_USERNAME, password=<PASSWORD>)
response = self.client.post('/admin/events/add/',
{
'name': TEST_EVENT_NAME,
'description': TEST_EVENT_DESC,
'slug': TEST_EVENT_SLUG,
'points': TEST_EVENT_POINTS,
'guild': TEST_EVENT_GUILD
})
self.assertEqual(response.status_code, 302)
self.assertIsNotNone(Event.objects.filter(slug=TEST_EVENT_SLUG))
``` |
{
"source": "jonnelafin/CodeNameProjection",
"score": 2
} |
#### File: CodeNameProjection/tools/blender_modelExporter.py
```python
import os
bl_info = {
"name": "PB3D Exporter",
"description": "Exports the selected object into an .pb3d",
"author": "<NAME> aka Jonnelafin",
"version": (1, 1),
"blender": (2, 80, 0),
"location": "Object Properties > Export to .PB3D",
"warning": "", # used for warning icon and text in addons panel
"wiki_url": "https://github.com/jonnelafin/PB3D",
"tracker_url": "https://developer.blender.org",
"support": "COMMUNITY",
"category": "Import-Export",
}
import bpy, bmesh
#obj = bpy.context.active_object
obj = ""
#scn = bpy.context.scene
scn = ""
#frame = bpy.context.scene.frame_current
frame = 0
#end = scn.frame_end
end = 1
frames = range(end)
from bpy.props import (StringProperty,
BoolProperty,
IntProperty,
FloatProperty,
FloatVectorProperty,
EnumProperty,
PointerProperty,
)
from bpy.types import (Panel,
Menu,
Operator,
PropertyGroup,
)
#Flags
keyframes = True
filename = "default"
filetype = ".pb3d"
useExternalOut = False
onlyAnim = False
#AXIS
#up_z = [0, 0, 0]
#up_y = [-90, 0, 0]
#up_y = [0, -90, 0]
up_z = [0, 2, 1]
up_y = [0, 1, 2]
up_x = [2, 1, 0]
axis = [0, 2, 1]
if not keyframes:
frames = [frame]
verts = []
lines = []
faces = []
colors = []
pr = ""
t = 0
def oops(self, context):
global pr
self.layout.label(text="Processing animation frames" + pr + "...")
def make_path_absolute(path = ""):
""" Prevent Blender's relative paths of doom """
sane_path = lambda p: os.path.abspath(bpy.path.abspath(p))
if path.startswith("//"):
return sane_path(path)
return path
def func_object_duplicate_flatten_modifiers(context, ob):
depth = bpy.context.evaluated_depsgraph_get()
eobj = ob.evaluated_get(depth)
mesh = bpy.data.meshes.new_from_object(eobj)
name = ob.name + "_clean"
new_object = bpy.data.objects.new(name, mesh)
new_object.data = mesh
bpy.context.collection.objects.link(new_object)
return new_object
def updateMesh():
global verts
global lines
global faces
global filename
global colors
global axis
#filename = obj.name
#new_obj = obj.copy()
#new_obj.data = obj.data.copy()
#new_obj.animation_data_clear()
#bpy.data.scenes[0].objects.link(new_obj)
new_obj = func_object_duplicate_flatten_modifiers(bpy.context, obj)
mesh = new_obj.data
if not mesh.vertex_colors:
new_obj.vertex_colors.new()
mesh = new_obj.data
if obj.mode == 'EDIT':
# this works only in edit mode,
bm = bmesh.from_edit_mesh(new_obj.data)
verts = [vert.co for vert in bm.verts]
lines = [edge.vertices for edge in bm.edges]
faces = [face.vertices for edge in bm.polygons]
else:
# this works only in object mode,
verts = [vert.co for vert in new_obj.data.vertices]
lines = [edge.vertices for edge in new_obj.data.edges]
faces = [edge.vertices for edge in new_obj.data.polygons]
#GET COLORS
doneC = []
for polygon in mesh.polygons:
for i, index in enumerate(polygon.vertices):
if(not index in doneC):
loop_index = polygon.loop_indices[i]
colors.append(mesh.vertex_colors.active.data[loop_index].color)
print("color: " + str(i) + str(mesh.vertex_colors.active.data[loop_index].color) + " | " + str(index))
doneC.append(index)
# coordinates as tuples
plain_verts = [vert.to_tuple() for vert in verts]
#Delete the new_obj
bpy.ops.object.select_all(action='DESELECT')
new_obj.select_set(True) # Blender 2.8x
bpy.ops.object.delete()
#Do orientation
for i in range(len(verts)):
ori = verts[i]
verts[i] = [ori[axis[0]], ori[axis[1]], ori[axis[2]]]
#deselectA()
def exp(self):
global verts
global lines
global faces
global filename
global obj, scn, frame, end, frames
obj = bpy.context.active_object
scn = bpy.context.scene
frame = bpy.context.scene.frame_current
end = scn.frame_end
frames = range(end)
updateMesh()
#print(plain_verts)
st = ""
st2 = ""
st3 = ""
print("Reading vertices...",end="")
for t in frames:
pr = "" + str((len(frames)/100*t)) + "%"
print("Processing frame " + str(t) + "/" + str(len(frames)) + "[" + pr + "]...")
self.report({'INFO'}, "Processing frame " + str(t) + "/" + str(len(frames)) + "[" + pr + "]...")
#bpy.context.window_manager.popup_menu(oops, title="Exporting model...", icon='FILE_TEXT')
bpy.context.scene.frame_set(t)
updateMesh()
st = st + "\n#" + str(t) + "\n"
for i in verts:
for c in i:
#print(int(c*100),end=" ")
st = st + str(int(c*100)) + " "
#print()
st = st + "\n"
st = st + "\n"
print("DONE")
self.report({'INFO'}, "DONE")
print("Reading edges...",end="")
self.report({'INFO'}, "Reading edges...")
for i in lines:
#print("LINE: " + str(i))
p1 = i[0]
p2 = i[1]
st2 = st2 + str(p1) + " " + str(p2) + " "
st2 = st2 + "\n"
st2 = st2 + "\n"
print("DONE")
self.report({'INFO'}, "DONE")
print("Reading faces...",end="")
self.report({'INFO'}, "Reading faces...")
for i in faces:
#print("LINE: " + str(i))
p1 = i[0]
p2 = i[1]
p3 = i[2]
st3 = st3 + str(p1) + " " + str(p2) + " " + str(p3) + " "
quad = (len(i) == 4)
if quad:
p4 = i[3]
st3 = st3 + str(p4) + " "
st3 = st3 + "\n"
st3 = st3 + "\n"
print("DONE")
self.report({'INFO'}, "DONE")
print("Saving...")
self.report({'INFO'}, "Saving...")
f = bpy.data.texts.new(filename + filetype)
f.from_string(st)
f = bpy.data.texts.new(filename + "_lines" + filetype)
f.from_string(st2)
f = bpy.data.texts.new(filename + "_faces" + filetype)
f.from_string(st3)
print("Everything done, have a good day.")
self.report({'INFO'}, "Done, Have A Good Day!")
def init():
updateMesh()
#print(plain_verts)
print("Reading vertices...",end="")
st = ""
st2 = ""
st3 = ""
def step(self):
global verts
global lines
global faces
global filename
global t
global st, st2, st3
global done
pr = "" + str((len(frames)/100*t)) + "%"
print("Processing frame " + str(t) + "/" + str(len(frames)) + "[" + pr + "]...")
self.report({'INFO'}, "Processing frame " + str(t) + "/" + str(len(frames)) + "[" + pr + "]...")
#bpy.context.window_manager.popup_menu(oops, title="Exporting model...", icon='FILE_TEXT')
bpy.context.scene.frame_set(t)
updateMesh()
st = st + "\n#" + str(t) + "\n"
for i in verts:
for c in i:
#print(int(c*100),end=" ")
st = st + str(int(c*100)) + " "
#print()
st = st + "\n"
st = st + "\n"
if t + 1 < len(frames):
t = t + 1
else:
done = True
def end_func(self):
global verts
global lines
global faces
global filename
global t
global st, st2, st3
global useExternalOut
global onlyAnim
print("Reading edges...",end="")
self.report({'INFO'}, "Reading edges...")
for i in lines:
#print("LINE: " + str(i))
p1 = i[0]
p2 = i[1]
st2 = st2 + str(p1) + " " + str(p2) + " "
st2 = st2 + "\n"
st2 = st2 + "\n"
print("DONE")
print("Reading faces...",end="")
self.report({'INFO'}, "Reading faces...")
for i in faces:
#print("LINE: " + str(i))
p1 = i[0]
p2 = i[1]
p3 = i[2]
st3 = st3 + str(p1) + " " + str(p2) + " " + str(p3) + " "
quad = (len(i) == 4)
if quad:
p4 = i[3]
st3 = st3 + str(p4) + " "
st3 = st3 + "\n"
st3 = st3 + "\n"
print("DONE")
print("Saving...")
self.report({'INFO'}, "Saving......")
print("Reading vertex color info...",end="")
self.report({'INFO'}, "Reading vertex color info...")
st4 = ""
for i in colors:
#print("Color: " + str(i))
r = i[0]
g = i[1]
b = i[2]
st4 = st4 + str(r) + " " + str(g) + " " + str(b) + " "
st4 = st4 + "\n"
st4 = st4 + "\n"
print("DONE")
if useExternalOut:
fn = filename.replace(".pb3d", "")
f = open(fn + filetype,"w")
f.write(st)
f.close()
if(not onlyAnim):
f = open(fn + "_lines" + filetype, "w")
f.write(st2)
f.close()
f = open(fn + "_faces" + filetype, "w")
f.write(st3)
f.close()
f = open(fn + "_color" + filetype, "w")
f.write(st4)
f.close()
if not useExternalOut:
f = bpy.data.texts.new(filename + filetype)
f.from_string(st)
if(not onlyAnim):
f = bpy.data.texts.new(filename + "_lines" + filetype)
f.from_string(st2)
f = bpy.data.texts.new(filename + "_faces" + filetype)
f.from_string(st3)
f = bpy.data.texts.new(filename + "_color" + filetype)
f.from_string(st4)
print("Everything done, have a good day.")
self.report({'INFO'}, "Everything done, have a good day.")
done = False
class exporter(bpy.types.Operator):
"""Click to export selected object in to .pb3d"""
bl_idname = "object.pb_3d_exporter"
bl_label = "Export PB3D"
global done
def modal(self, context, event):
if done:
end_func(self)
return {"FINISHED"}
if event.type in {'RIGHTMOUSE', 'ESC'}:
self.cancel(context)
return {'CANCELLED'}
if event.type == 'TIMER':
step(self)
return {'PASS_THROUGH'}
@classmethod
def poll(cls, context):
return context.active_object is not None
def execute(self, context):
#RESET
#---
global obj, scn, frame, end, frames, keyframes, verts, lines, faces, pr, t, done
done = False
obj = bpy.context.active_object
scn = bpy.context.scene
frame = bpy.context.scene.frame_current
end = scn.frame_end
frames = range(end)
if not keyframes:
frames = [frame]
verts = []
lines = []
faces = []
pr = ""
t = 0
#---
wm = context.window_manager
self._timer = wm.event_timer_add(1, window=context.window)
wm.modal_handler_add(self)
#exp(self)
return {'RUNNING_MODAL'}
class MyProperties(PropertyGroup):
global up_z, up_y, up_x
my_bool: BoolProperty(
name="Use external location",
description="If unchecked, the files will be found in the scripts tab in blender",
default = True
)
my_bool2: BoolProperty(
name="Only export animation (if you have the lines/faces already)",
description="Only export animation (if you have the lines/faces already)",
default = False
)
my_int: IntProperty(
name = "Int Value",
description="A integer property",
default = 23,
min = 10,
max = 100
)
my_float: FloatProperty(
name = "Float Value",
description = "A float property",
default = 23.7,
min = 0.01,
max = 30.0
)
my_float_vector: FloatVectorProperty(
name = "Float Vector Value",
description="Something",
default=(0.0, 0.0, 0.0),
min= 0.0, # float
max = 0.1
)
my_string: StringProperty(
name="File Name",
description=":",
default="",
maxlen=1024,
)
my_path: StringProperty(
name = "Export Dir",
description="Choose a directory:",
default="",
maxlen=1024,
subtype='DIR_PATH'
)
my_enum: EnumProperty(
name="Up axis",
description="Apply Data to attribute.",
items=[ ("z", "Z", ""),
("y", "Y", ""),
("x", "X", ""),
]
)
class pbPanel(bpy.types.Panel):
bl_idname = "pbui"
bl_label = "Export to .PB3D"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "object"
def draw(self, context):
global filename, useExternalOut, up_z, up_y, up_x, onlyAnim
scene = context.scene
my_tool = scene.my_tool
#self.layout.label(text="You can export to .pb3d here:")
self.layout.prop(my_tool, "my_path")
self.layout.prop(my_tool, "my_string")
self.layout.prop(my_tool, "my_enum")
self.layout.prop(my_tool, "my_bool")
self.layout.prop(my_tool, "my_bool2")
self.layout.operator("object.pb_3d_exporter")
self.layout.label(text="You can always cancel exporting by pressing esc or mouse 2")
self.layout.label(text="Animation range will be set to scene frame range")
useExternalOut = bpy.context.scene.my_tool.my_bool
filename = bpy.context.scene.my_tool.my_path + "/" + bpy.context.scene.my_tool.my_string
filename = make_path_absolute(filename)
ax = bpy.context.scene.my_tool.my_enum
onlyAnim = bpy.context.scene.my_tool.my_bool2
if(ax == 'z'):
axis = up_z
if(ax == 'y'):
axis = up_y
if(ax == 'x'):
axis = up_x
def register():
bpy.utils.register_class(exporter)
bpy.utils.register_class(pbPanel)
bpy.utils.register_class(MyProperties)
bpy.types.Scene.my_tool = PointerProperty(type=MyProperties)
print("PB3D Exporter registered.")
def unregister():
# bpy.utils.unregister_class(exporter)
bpy.utils.unregister_class(exporter)
bpy.utils.unregister_class(pbPanel)
bpy.utils.unregister_class(MyProperties)
print("PB3D Exporter unregistered.")
if __name__ == "__main__":
register()
``` |
{
"source": "jonnelafin/contemplate",
"score": 3
} |
#### File: jonnelafin/contemplate/app.py
```python
import xxhash
import os
from flask import Flask, redirect
from flask import request
from flask import jsonify
#print(xxhash.xxh64('xxhash').hexdigest())
#print(xxhash.xxh64('xxhash', seed=20141025).hexdigest())
app = Flask(__name__)
key = "default"
split = 4
numMaxT = 10000000
version = "1.0"
def intKey():
global key
return int(xxhash.xxh64('xxhash').intdigest() / 40000000)
#print(intKey())
def final(comp):
return int( (int(comp) - int(intKey())) )
def finalReverse(comp):
return int(comp) + int(intKey())
def sep(pro):
global key
pro2 = pro + len(key)
return str(pro2*3) + str(pro*24) + str(pro*4)
def numfind(targ):
global key
i = 0#30386530
done = False
while done == False:
has = xxhash.xxh64(key, seed=i).intdigest()
# print(has)
if(str(has)[:].startswith(str(targ))):
# print(str(has))
has2 = str(has).replace("\\","").replace("'","")[:]
# print(has2)
# print(i)
done = True
return i
elif i > numMaxT:
done = True
return 0
i = i + 1
def find(targ):
global key
i = 0#30386530
done = False
while done == False:
has = xxhash.xxh64(key, seed=i).digest()
# print(has)
if(str(has)[2:].startswith(str(targ))):
# print(str(has))
has2 = str(has).replace("\\","").replace("","")[2:]
# print(has2)
# print(i)
done = True
return i
elif i > numMaxT:
done = True
return i
i = i + 1
def decode(seedA, place):
global key
return str(xxhash.xxh64(key, seed= int(seedA/place) ).digest()).replace("\\","").replace("","")[2:]
def percentage(part, whole):
return 100 * float(part)/float(whole)
def progress(a, p, cust=" "):
per = int(percentage(p, a) / 10)
nf = "_"*(10-per)
f = "|"*per
d = " " + str(p) + " / " + str(a) + ", " + str(percentage(p, a)) + "%"
print(f + nf + d + cust,end="\r")
def numprocess(inp):
global split
line = inp.replace(" ", "<").replace("'",">").replace("?","_").replace("…","...").replace("'","|")
n = split
ns = int(n/2)
code = ""#sep(1)
i = 1
parts = [line[i:i+n] for i in range(0, len(line), n)]
for part in parts:
# if len(part) < 2
# print(part)
sepa = sep(i)
f = str(numfind(part))
if len(f) < n:
code = code + f + "-"
elif f[-1] != "0":
f1 = str(numfind(f[ns:]))
f2 = str(numfind(f[:ns]))
print(f1)
print(f2)
code = code + f1 + "_" + f2 + "-"
else:
code = code + f + "-"
progress(len(parts), i)
i = i + 1
print()
# print(code)
print("Raw: " + str(code) )
return str(code)
def process(inp):
line = inp.replace(" ", "<").replace("'",">").replace("?","_").replace("…","...").replace("'","|")
n = 2
code = ""#sep(1)
i = 1
parts = [line[i:i+n] for i in range(0, len(line), n)]
for part in parts:
# if len(part) < 2
# print(part)
sepa = sep(i)
code = code + str(find(part)*i) + sepa
progress(len(parts), i)
i = i + 1
print()
# print(code)
print("Raw: " + str(code) )
# print("Compressed: " + str(numprocess(code)) )
return str(final(code))
def deProcess(inp):
whole = ""
i = 1
done = False
p = str(int(finalReverse(inp)))
while done == False:
sepa = sep(i)
# print("Left: " + p)
# print(sepa + ": ",end="")
v = p.replace(sepa,"")
if v != p:
orig = p.split(sepa)[0]
v = orig.replace(sepa, "")
# print(v)
if v != "":
whole = whole + (decode(int(v),i)[:2] ).replace("<"," ").replace(">","'").replace("_","?").replace("|","'")
# p.replace(orig,"")
p = p.split(orig + sepa)[1].replace(sepa,"")
i = i + 1
else:
i = i + 1
p = p.split(orig + sepa)[1].replace(sepa,"")
else:
done = False
break
# print(whole)
print()
return whole
#msg = "hi!"
#eProcess(process("Hello world!"))
#ida = find(msg)
#print(decode(ida)[:2])
def ask():
global key
k = input("Key (Press enter to skip): ")
if k != "":
key = k
i = input("Decrypt or Encrypt? d/e: ")
if i == "e":
msg = input("Message: ")
to = process(msg)
print("Encoded: " + to)
print("Will produce: " + deProcess(to))
elif i == "d":
msg = input("Encoded Message: ")
print("Trying to un-encode...")
print(deProcess(msg))
elif i == "k":
for i in range(10):
print(sep(i))
elif i == "n":
numprocess(input("To find: "))
elif i == "nt":
sz = int(input("Max: "))
ran = int(input("Iterations: "))
avgl = 0
s = 0
from random import randint
for i in range(ran):
n = randint(1, int("9"*sz))
r = 1000000000000
r = numfind(n)
if len(str(r)) > sz:
m = int( len(str(r)) / 2)
r2 = str(numfind(n))[1:]
r1 = str(numfind(n))[:1]
s = s + len(str(r1))
avgl = avgl + 1
s = s + len(str(r2))
avgl = avgl + 1
else:
# print(r)
s = s + len(str(r))
avgl = avgl + 1
progress(ran, i, " | avg: " + str(s/avgl) + " ")
print("Average with size of " + str(sz) + ": " + str(s/avgl) + " | avg. compression of " + str(sz-(s/avgl)) + " letters ")
else:
print("That's not a valid answer, let's try again.")
ask()
# ask()
#Flask code
@app.route('/')
def hello():
view = "<title>Contemplation</title>"
view = view + "<h3> Hash-Reversal encoder-decoder \"Contemplation\"</h3>"
view = view + "<br \\>-----------------------------------------------------------------------<br \\>"
view = view + "<h4>Encode</h4>"
view = view + "<form action=\" " + "/enc" + "\" method=\"post\">"
view = view + "<input type=\"text\" name=\"msg\">"
view = view + "<input type=\"submit\">"
view = view + "</form>"
view = view + "<h4>Decode</h4>"
view = view + "<form action=\" " + "/dec" + "\" method=\"post\">"
view = view + "<input type=\"text\" name=\"msg\">"
view = view + "<input type=\"submit\">"
view = view + "</form>"
view = view + "<br \\>-----------------------------------------------------------------------<br \\>"
view = view + "<br \\><hr \\>"
view = view + "Contemplation v. " + str(version) + " | <a href=\"https://raw.githubusercontent.com/jonnelafin/A-/master/LICENSE\">LICENSE</a>"
return view
@app.route('/enc', methods=['POST'])
def handle_data():
msg = request.form['msg']
view = ""
to = process(msg)
print("Encoded: " + to)
view = view + "<br \\>"
view = view + "Encoded: " + "<br \\>" + to
view = view + "<br \\>"
by = deProcess(to)
print("Will produce: " + by)
view = view + "Will produce: " + "<br \\>" + by
view = view + "<br \\>"
return view
# return redirect("/", code=302)
@app.route('/dec', methods=['POST'])
def handle_data2():
msg = request.form['msg']
view = ""
by = deProcess(msg)
print("Decoded: " + by)
view = view + "Decoded: " + "<br \\>" + by
view = view + "<br \\>"
return view
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
``` |
{
"source": "JonneSaloranta/Sales",
"score": 3
} |
#### File: Sales/main/CustomExceptions.py
```python
class ProductTitleException(Exception):
def __init__(self):
print("Product title is not valid!")
class ProductPriceException(Exception):
def __init__(self):
print("Product price is not valid!")
``` |
{
"source": "JonnesLin/ex_reminder",
"score": 2
} |
#### File: ex_reminder/ex_reminder/ex_reminder.py
```python
import yagmail
class reminder:
def __init__(self, sender_email, authorized_code, host, receiver_email, subject='An experiment from ex_reminder!'):
self.subject = subject
self.receiver_email = receiver_email
self.host = host
self.authorized_code = authorized_code
self.sender_email = sender_email
self.yag = yagmail.SMTP(user=self.sender_email, password=self.authorized_code, host=self.host)
def send(self, content):
self.yag.send(self.receiver_email, self.subject, content)
``` |
{
"source": "jonnieey/scribepy",
"score": 3
} |
#### File: src/scribepy/main.py
```python
import sys
import argparse
from pathlib import Path
from loguru import logger
from pynput import keyboard
from scribepy import custom_logger
from scribepy.cli import play_file as cli
def get_parser():
"""
Create custom parser
Returns: parser -> ArgumentParser
"""
usage = "scribepy [OPTIONS] [COMMAND] [COMMAND_OPTIONS]"
description = "Command line audio player for transcription"
parser = argparse.ArgumentParser(
prog="scribepy",
usage=usage,
description=description,
add_help=False,
)
main_help = "Show this help message and exit."
subcommand_help = "Show this help message and exit."
global_options = parser.add_argument_group(title="Global options")
global_options.add_argument("-h", "--help", action="help", help=main_help)
global_options.add_argument(
"-L",
"--log-level",
type=str.upper,
help="Log level to use",
choices=(
"TRACE",
"DEBUG",
"INFO",
"SUCCESS",
"WARNING",
"ERROR",
"CRITICAL",
),
)
global_options.add_argument(
"-P",
"--log-path",
metavar="",
help="Log file to use",
)
global_options.add_argument("file", help="File to play")
return parser
def main(args=None):
parser = get_parser()
opts = parser.parse_args(args=args)
kwargs = opts.__dict__
log_level = kwargs.pop("log_level")
log_path = kwargs.pop("log_path")
if log_path:
log_path = Path(log_path)
if log_path.is_dir():
log_path = log_path / "scribepy-{time}.log"
custom_logger(sink=log_path, level=log_level or "WARNING")
elif log_level:
custom_logger(sink=sys.stderr, level="WARNING")
try:
return cli(**kwargs)
except Exception as error:
logger.exception(error)
print(error)
sys.exit(0)
if __name__ == "__main__":
main()
```
#### File: src/scribepy/top.py
```python
from asciimatics.exceptions import ResizeScreenError
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from scribepy.player import Player
from scribepy.connector import Connector
from scribepy.tui.browser import BrowserFrame
from scribepy.tui.mainwindow import MainWindowFrame
from scribepy.tui.progressbar import ProgressBar
import sys
def init(screen, old_scene):
"""
Initialize scenes to play
Arguments:
screen: Screen instance.
old_scene: Initial scene.
Return:
None
"""
player = Player()
connector = Connector()
connector.set_player(player)
mainwindow = MainWindowFrame(screen)
browser = BrowserFrame(screen)
browser.set_connector(connector)
connector.set_browser(browser)
progressbar = ProgressBar(screen)
progressbar.set_connector(connector)
scenes = []
scenes.append(Scene([mainwindow], -1, name="Main Window"))
scenes.append(Scene([browser], -1, name="Scribepy File Browser"))
scenes.append(Scene([progressbar], -1, clear=False, name="Progress Bar"))
screen.play(scenes, start_scene=old_scene)
def launch_tui(**kwargs):
last_scene = None
while True:
try:
Screen.wrapper(init, catch_interrupt=False, arguments=[last_scene])
sys.exit(0)
except ResizeScreenError as e:
last_scene = e.scene
if __name__ == "__main__":
main()
```
#### File: scribepy/tui/progressbar.py
```python
from asciimatics.screen import Screen
from asciimatics.event import KeyboardEvent
from asciimatics.renderers import BarChart
from asciimatics.effects import Print
from asciimatics.exceptions import NextScene
class ProgressBar(Print):
def __init__(self, screen):
Print.__init__(
self,
screen,
BarChart(
7,
60,
[self.get_progress],
char=">",
scale=100.0,
# Create custom labels
labels=True,
axes=BarChart.X_AXIS,
),
x=(screen.width - 60) // 2,
y=(screen.height - 7) // 2,
transparent=False,
speed=2,
),
def _update(self, frame_no):
if (
self.connector.player.position / self.connector.player.length
) == 1:
raise NextScene("Scribepy File Browser")
else:
Print._update(self, frame_no)
def process_event(self, event):
if isinstance(event, KeyboardEvent):
if event.key_code in [ord("q"), ord("Q"), ord("s")]:
self.connector.player.destruct()
raise NextScene("Scribepy File Browser")
elif event.key_code in [ord(" "), ord("p")]:
self.connector.player.pause_play_toggle
elif event.key_code in [ord("l"), Screen.KEY_RIGHT]:
self.connector.player.move_to_position_seconds(
self.connector.player.position + 3
)
elif event.key_code in [ord("h"), Screen.KEY_LEFT]:
self.connector.player.move_to_position_seconds(
self.connector.player.position - 3
)
elif event.key_code in [ord("k"), Screen.KEY_UP]:
self.connector.increase_volume()
elif event.key_code in [ord("j"), Screen.KEY_DOWN]:
self.connector.decrease_volume()
def get_progress(self):
return (
self.connector.player.position / self.connector.player.length
) * 100
def set_connector(self, c):
self.connector = c
```
#### File: tui/utils/widgets.py
```python
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from builtins import chr
from datetime import datetime, timedelta
from abc import ABCMeta, abstractmethod, abstractproperty
from future.utils import with_metaclass
from asciimatics.event import KeyboardEvent, MouseEvent
from asciimatics.screen import Screen
from asciimatics.widgets.widget import Widget
from asciimatics.widgets.scrollbar import _ScrollBar
from re import match as re_match
from re import compile as re_compile
import os
import unicodedata
from asciimatics.widgets.utilities import _enforce_width
from future.moves.itertools import zip_longest
from asciimatics.utilities import readable_timestamp, readable_mem
class _CustomBaseListBox(with_metaclass(ABCMeta, Widget)):
"""
An Internal class to contain common function between list box types.
"""
__slots__ = [
"_options",
"_titles",
"_label",
"_line",
"_start_line",
"_required_height",
"_on_change",
"_on_select",
"_validator",
"_search",
"_last_search",
"_scroll_bar",
"_parser",
]
def __init__(
self,
height,
options,
titles=None,
label=None,
name=None,
parser=None,
on_change=None,
on_select=None,
validator=None,
):
"""
:param height: The required number of input lines for this widget.
:param options: The options for each row in the widget.
:param label: An optional label for the widget.
:param name: The name for the widget.
:param parser: Optional parser to colour text.
:param on_change: Optional function to call when selection changes.
:param on_select: Optional function to call when the user actually selects an entry from
this list - e.g. by double-clicking or pressing Enter.
:param validator: Optional function to validate selection for this widget.
"""
super(_CustomBaseListBox, self).__init__(name)
self._titles = titles
self._label = label
self._parser = parser
self._options = self._parse_options(options)
self._line = 0
self._value = None
self._start_line = 0
self._required_height = height
self._on_change = on_change
self._on_select = on_select
self._validator = validator
self._search = ""
self._last_search = datetime.now()
self._scroll_bar = None
def reset(self):
pass
def process_event(self, event):
if isinstance(event, KeyboardEvent):
if len(self._options) > 0 and event.key_code in [
ord("k"),
Screen.KEY_UP,
]:
# Move up one line in text - use value to trigger on_select.
self._line = max(0, self._line - 1)
self.value = self._options[self._line][1]
elif len(self._options) > 0 and event.key_code in [
ord("j"),
Screen.KEY_DOWN,
]:
# Move down one line in text - use value to trigger on_select.
self._line = min(len(self._options) - 1, self._line + 1)
self.value = self._options[self._line][1]
elif (
len(self._options) > 0 and event.key_code == Screen.KEY_PAGE_UP
):
# Move up one page.
self._line = max(
0, self._line - self._h + (1 if self._titles else 0)
)
self.value = self._options[self._line][1]
elif (
len(self._options) > 0
and event.key_code == Screen.KEY_PAGE_DOWN
):
# Move down one page.
self._line = min(
len(self._options) - 1,
self._line + self._h - (1 if self._titles else 0),
)
self.value = self._options[self._line][1]
elif event.key_code in [
Screen.ctrl("m"),
Screen.ctrl("j"),
ord("l"),
]:
# Fire select callback.
if self._on_select:
self._on_select()
elif event.key_code > 0:
# Treat any other normal press as a search
now = datetime.now()
if now - self._last_search >= timedelta(seconds=1):
self._search = ""
self._search += chr(event.key_code)
self._last_search = now
# If we find a new match for the search string, update the list selection
new_value = self._find_option(self._search)
if new_value is not None:
self.value = new_value
else:
return event
elif isinstance(event, MouseEvent):
# Mouse event - adjust for scroll bar as needed.
if event.buttons != 0:
# Check for normal widget.
if len(self._options) > 0 and self.is_mouse_over(
event,
include_label=False,
width_modifier=1 if self._scroll_bar else 0,
):
# Figure out selected line
new_line = event.y - self._y + self._start_line
if self._titles:
new_line -= 1
new_line = min(new_line, len(self._options) - 1)
# Update selection and fire select callback if needed.
if new_line >= 0:
self._line = new_line
self.value = self._options[self._line][1]
if (
event.buttons & MouseEvent.DOUBLE_CLICK != 0
and self._on_select
):
self._on_select()
return None
# Check for scroll bar interactions:
if self._scroll_bar:
if self._scroll_bar.process_event(event):
return None
# Ignore other mouse events.
return event
else:
# Ignore other events
return event
# If we got here, we processed the event - swallow it.
return None
def _add_or_remove_scrollbar(self, width, height, dy):
"""
Add or remove a scrollbar from this listbox based on height and available options.
:param width: Width of the Listbox
:param height: Height of the Listbox.
:param dy: Vertical offset from top of widget.
"""
if self._scroll_bar is None and len(self._options) > height:
self._scroll_bar = _ScrollBar(
self._frame.canvas,
self._frame.palette,
self._x + width - 1,
self._y + dy,
height,
self._get_pos,
self._set_pos,
)
elif self._scroll_bar is not None and len(self._options) <= height:
self._scroll_bar = None
def _get_pos(self):
"""
Get current position for scroll bar.
"""
if self._h >= len(self._options):
return 0
return self._start_line / (len(self._options) - self._h)
def _set_pos(self, pos):
"""
Set current position for scroll bar.
"""
if self._h < len(self._options):
pos *= len(self._options) - self._h
pos = int(round(max(0, pos), 0))
self._start_line = pos
@abstractmethod
def _find_option(self, search_value):
"""
Internal function called by the BaseListBox to do a text search on user input.
:param search_value: The string value to search for in the list.
:return: The value of the matching option (or None if nothing matches).
"""
def required_height(self, offset, width):
return self._required_height
@property
def start_line(self):
"""
The line that will be drawn at the top of the visible section of this list.
"""
return self._start_line
@start_line.setter
def start_line(self, new_value):
if 0 <= new_value < len(self._options):
self._start_line = new_value
@property
def value(self):
"""
The current value for this list box.
"""
return self._value
@value.setter
def value(self, new_value):
# Only trigger change notification after we've changed selection
old_value = self._value
self._value = new_value
for i, [_, value] in enumerate(self._options):
if value == new_value:
self._line = i
break
else:
# No matching value - pick a default.
if len(self._options) > 0:
self._line = 0
self._value = self._options[self._line][1]
else:
self._line = -1
self._value = None
if self._validator:
self._is_valid = self._validator(self._value)
if old_value != self._value and self._on_change:
self._on_change()
# Fix up the start line now that we've explicitly set a new value.
self._start_line = max(
0, max(self._line - self._h + 1, min(self._start_line, self._line))
)
def _parse_options(self, options):
"""
Parse a the options list for ColouredText.
:param options: the options list to parse
:returns: the options list parsed and converted to ColouredText as needed.
"""
if self._parser:
parsed_value = []
for option in options:
parsed_value.append((self._parse_option(option[0]), option[1]))
return parsed_value
return options
@abstractmethod
def _parse_option(self, option):
"""
Parse a single option for ColouredText.
:param option: the option to parse
:returns: the option parsed and converted to ColouredText.
"""
@abstractproperty
def options(self):
"""
The list of options available for user selection.
"""
class CustomMultiColumnListBox(_CustomBaseListBox):
"""
A MultiColumnListBox is a widget for displaying tabular data.
It displays a list of related data in columns, from which the user can select a line.
"""
def __init__(
self,
height,
columns,
options,
titles=None,
label=None,
name=None,
add_scroll_bar=False,
parser=None,
on_change=None,
on_select=None,
space_delimiter=" ",
):
"""
:param height: The required number of input lines for this ListBox.
:param columns: A list of widths and alignments for each column.
:param options: The options for each row in the widget.
:param titles: Optional list of titles for each column. Must match the length of
`columns`.
:param label: An optional label for the widget.
:param name: The name for the ListBox.
:param add_scroll_bar: Whether to add optional scrollbar for large lists.
:param parser: Optional parser to colour text.
:param on_change: Optional function to call when selection changes.
:param on_select: Optional function to call when the user actually selects an entry from
:param space_delimiter: Optional parameter to define the delimiter between columns.
The default value is blank space.
The `columns` parameter is a list of integers or strings. If it is an integer, this is
the absolute width of the column in characters. If it is a string, it must be of the
format "[<align>]<width>[%]" where:
* <align> is the alignment string ("<" = left, ">" = right, "^" = centre)
* <width> is the width in characters
* % is an optional qualifier that says the number is a percentage of the width of the
widget.
Column widths need to encompass any space required between columns, so for example, if
your column is 5 characters, allow 6 for an extra space at the end. It is not possible
to do this when you have a right-justified column next to a left-justified column, so
this widget will automatically space them for you.
An integer value of 0 is interpreted to be use whatever space is left available after the
rest of the columns have been calculated. There must be only one of these columns.
The number of columns is for this widget is determined from the number of entries in the
`columns` parameter. The `options` list is then a list of tuples of the form
([val1, val2, ... , valn], index). For example, this data provides 2 rows for a 3 column
widget:
options=[(["One", "row", "here"], 1), (["Second", "row", "here"], 2)]
The options list may be None and then can be set later using the `options` property on
this widget.
"""
super(CustomMultiColumnListBox, self).__init__(
height,
options,
titles=titles,
label=label,
name=name,
parser=parser,
on_change=on_change,
on_select=on_select,
)
self._columns = []
self._align = []
self._spacing = []
self._add_scroll_bar = add_scroll_bar
self._space_delimiter = space_delimiter
for i, column in enumerate(columns):
if isinstance(column, int):
self._columns.append(column)
self._align.append("<")
else:
match = re_match(r"([<>^]?)(\d+)([%]?)", column)
self._columns.append(
float(match.group(2)) / 100
if match.group(3)
else int(match.group(2))
)
self._align.append(match.group(1) if match.group(1) else "<")
if space_delimiter == " ":
self._spacing.append(
1
if i > 0
and self._align[i] == "<"
and self._align[i - 1] == ">"
else 0
)
else:
self._spacing.append(1 if i > 0 else 0)
def _get_width(self, width, max_width):
"""
Helper function to figure out the actual column width from the various options.
:param width: The size of column requested
:param max_width: The maximum width allowed for this widget.
:return: the integer width of the column in characters
"""
if isinstance(width, float):
return int(max_width * width)
if width == 0:
width = (
max_width
- sum(self._spacing)
- sum(
[
self._get_width(x, max_width)
for x in self._columns
if x != 0
]
)
)
return width
def _print_cell(
self, space, text, align, width, x, y, foreground, attr, background
):
# Sort out spacing first.
if space:
self._frame.canvas.print_at(
self._space_delimiter * space,
x,
y,
foreground,
attr,
background,
)
# Now align text, taking into account double space glyphs.
paint_text = _enforce_width(
text, width, self._frame.canvas.unicode_aware
)
text_size = self.string_len(str(paint_text))
if text_size < width:
# Default does no alignment or padding.
buffer_1 = buffer_2 = ""
if align == "<":
buffer_2 = " " * (width - text_size)
elif align == ">":
buffer_1 = " " * (width - text_size)
elif align == "^":
start_len = int((width - text_size) / 2)
buffer_1 = " " * start_len
buffer_2 = " " * (width - text_size - start_len)
paint_text = paint_text.join([buffer_1, buffer_2])
self._frame.canvas.paint(
str(paint_text),
x + space,
y,
foreground,
attr,
background,
colour_map=paint_text.colour_map
if hasattr(paint_text, "colour_map")
else None,
)
def update(self, frame_no):
self._draw_label()
# Calculate new visible limits if needed.
height = self._h
width = self._w
delta_y = 0
# Clear out the existing box content
(colour, attr, background) = self._frame.palette["field"]
for i in range(height):
self._frame.canvas.print_at(
" " * width,
self._x + self._offset,
self._y + i + delta_y,
colour,
attr,
background,
)
# Allow space for titles if needed.
if self._titles:
delta_y += 1
height -= 1
# Decide whether we need to show or hide the scroll bar and adjust width accordingly.
if self._add_scroll_bar:
self._add_or_remove_scrollbar(width, height, delta_y)
if self._scroll_bar:
width -= 1
# Now draw the titles if needed.
if self._titles:
row_dx = 0
colour, attr, background = self._frame.palette["title"]
for i, [title, align, space] in enumerate(
zip(self._titles, self._align, self._spacing)
):
cell_width = self._get_width(self._columns[i], width)
self._print_cell(
space,
title,
align,
cell_width,
self._x + self._offset + row_dx,
self._y,
colour,
attr,
background,
)
row_dx += cell_width + space
# Don't bother with anything else if there are no options to render.
if len(self._options) <= 0:
return
# Render visible portion of the text.
self._start_line = max(
0, max(self._line - height + 1, min(self._start_line, self._line))
)
for i, [row, _] in enumerate(self._options):
if self._start_line <= i < self._start_line + height:
colour, attr, background = self._pick_colours(
"field", i == self._line
)
row_dx = 0
# Try to handle badly formatted data, where row lists don't
# match the expected number of columns.
for text, cell_width, align, space in zip_longest(
row,
self._columns,
self._align,
self._spacing,
fillvalue="",
):
if cell_width == "":
break
cell_width = self._get_width(cell_width, width)
if len(text) > cell_width:
text = text[: cell_width - 3] + "..."
self._print_cell(
space,
text,
align,
cell_width,
self._x + self._offset + row_dx,
self._y + i + delta_y - self._start_line,
colour,
attr,
background,
)
row_dx += cell_width + space
# And finally draw any scroll bar.
if self._scroll_bar:
self._scroll_bar.update()
def _find_option(self, search_value):
for row, value in self._options:
# TODO: Should this be aware of a sort column?
if row[0].startswith(search_value):
return value
return None
def _parse_option(self, option):
"""
Parse a single option for ColouredText.
:param option: the option to parse
:returns: the option parsed and converted to ColouredText.
"""
option_items = []
for item in option:
try:
value = ColouredText(item.raw_text, self._parser)
except AttributeError:
value = ColouredText(item, self._parser)
option_items.append(value)
return option_items
@property
def options(self):
"""
The list of options available for user selection
This is a list of tuples ([<col 1 string>, ..., <col n string>], <internal value>).
"""
return self._options
@options.setter
def options(self, new_value):
# Set net list of options and then force an update to the current value to align with the new options.
self._options = self._parse_options(new_value)
self.value = self._value
class CustomFileBrowser(CustomMultiColumnListBox):
"""
A FileBrowser is a widget for finding a file on the local disk.
"""
def __init__(
self,
height,
root,
name=None,
on_select=None,
on_change=None,
file_filter=None,
):
r"""
:param height: The desired height for this widget.
:param root: The starting root directory to display in the widget.
:param name: The name of this widget.
:param on_select: Optional function that gets called when user selects a file (by pressing
enter or double-clicking).
:param on_change: Optional function that gets called on any movement of the selection.
:param file_filter: Optional RegEx string that can be passed in to filter the files to be displayed.
Most people will want to use a filter to finx files with a particular extension. In this case,
you must use a regex that matches to the end of the line - e.g. use ".*\.txt$" to find files ending
with ".txt". This ensures that you don't accidentally pick up files containing the filter.
"""
super(CustomFileBrowser, self).__init__(
height,
[0, ">8", ">14"],
[],
titles=["Filename", "Size", "Last modified"],
name=name,
on_select=self._on_selection,
on_change=on_change,
)
# Remember the on_select handler for external notification. This allows us to wrap the
# normal on_select notification with a function that will open new sub-directories as
# needed.
self._external_notification = on_select
self._root = root
self._in_update = False
self._initialized = False
self._file_filter = (
None if file_filter is None else re_compile(file_filter)
)
def update(self, frame_no):
# Defer initial population until we first display the widget in order to avoid race
# conditions in the Frame that may be using this widget.
if not self._initialized:
self._populate_list(self._root)
self._initialized = True
super(CustomFileBrowser, self).update(frame_no)
def _on_selection(self):
"""
Internal function to handle directory traversal or bubble notifications up to user of the
Widget as needed.
"""
if self.value and os.path.isdir(self.value):
self._populate_list(self.value)
elif self._external_notification:
self._external_notification()
def clone(self, new_widget):
# Copy the data into the new widget. Notes:
# 1) I don't really want to expose these methods, so am living with the protected access.
# 2) I need to populate the list and then assign the values to ensure that we get the
# right selection on re-sizing.
# pylint: disable=protected-access
new_widget._populate_list(self._root)
new_widget._start_line = self._start_line
new_widget._root = self._root
new_widget.value = self.value
def _populate_list(self, value):
"""
Populate the current multi-column list with the contents of the selected directory.
:param value: The new value to use.
"""
# Nothing to do if the value is rubbish.
if value is None:
return
# Stop any recursion - no more returns from here to end of fn please!
if self._in_update:
return
self._in_update = True
# We need to update the tree view.
self._root = os.path.abspath(
value if os.path.isdir(value) else os.path.dirname(value)
)
# The absolute expansion of "/" or "\" is the root of the disk, so is a cross-platform
# way of spotting when to insert ".." or not.
tree_view = []
if len(self._root) > len(os.path.abspath(os.sep)):
tree_view.append(
(["|-+ .."], os.path.abspath(os.path.join(self._root, "..")))
)
tree_dirs = []
tree_files = []
try:
files = os.listdir(self._root)
except OSError:
# Can fail on Windows due to access permissions
files = []
for my_file in files:
full_path = os.path.join(self._root, my_file)
try:
details = os.lstat(full_path)
except OSError:
# Can happen on Windows due to access permissions
details = namedtuple("stat_type", "st_size st_mtime")
details.st_size = 0
details.st_mtime = 0
name = "|-- {}".format(my_file)
tree = tree_files
if os.path.isdir(full_path):
tree = tree_dirs
if os.path.islink(full_path):
# Show links separately for directories
real_path = os.path.realpath(full_path)
name = "|-+ {} -> {}".format(my_file, real_path)
else:
name = "|-+ {}".format(my_file)
elif self._file_filter and not self._file_filter.match(my_file):
# Skip files that don't match the filter (if present)
continue
elif os.path.islink(full_path):
# Check if link target exists and if it does, show statistics of the
# linked file, otherwise just display the link
try:
real_path = os.path.realpath(full_path)
except OSError:
# Can fail on Linux prof file system.
real_path = None
if real_path and os.path.exists(real_path):
details = os.stat(real_path)
name = "|-- {} -> {}".format(my_file, real_path)
else:
# Both broken directory and file links fall to this case.
# Actually using the files will cause a FileNotFound exception
name = "|-- {} -> {}".format(my_file, real_path)
# Normalize names for MacOS and then add to the list.
tree.append(
(
[
unicodedata.normalize("NFC", name),
readable_mem(details.st_size),
readable_timestamp(details.st_mtime),
],
full_path,
)
)
tree_view.extend(sorted(tree_dirs))
tree_view.extend(sorted(tree_files))
self.options = tree_view
self._titles[0] = self._root
# We're out of the function - unset recursion flag.
self._in_update = False
``` |
{
"source": "JonNixonCodes/football-analytics-platform",
"score": 3
} |
#### File: cloud_functions/load_ftbl_data_uk/libs.py
```python
import requests, re
from bs4 import BeautifulSoup
from google.cloud import storage
# %% Define functions
def load_page(url):
"""Load web page. Return HTML."""
r = requests.get(url)
return r.text
def scrape_urls(html_text, pattern):
"""Extract URLs from raw html based on regex pattern"""
soup = BeautifulSoup(html_text,"html.parser")
anchors = soup.find_all("a")
urls = [a.get("href") for a in anchors]
return [url for url in urls if re.match(pattern, url)!=None]
def download_csv(destination_file_path, source_url):
"""Download CSV to destination file path from URL"""
r = requests.get(source_url)
if r.status_code!=200:
raise Exception(f"GET request failed: {r.status_code}")
open(destination_file_path, 'wb').write(r.content)
def upload_blob(bucket_name, destination_blob_path, source_file_path):
"""Upload blob to Google Cloud Storage"""
# The ID of your GCS bucket
# bucket_name = "your-bucket-name"
# The path to your file to upload
# source_file_name = "local/path/to/file"
# The ID of your GCS object
# destination_blob_name = "storage-object-name"
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(destination_blob_path)
blob.upload_from_filename(source_file_path)
```
#### File: source/fbref/extract.py
```python
import requests, re
from bs4 import BeautifulSoup
# %% Constants
BASE_URL = "https://fbref.com"
SEASONS_URL = "https://fbref.com/en/comps/"
COMPS_URL = "https://fbref.com/en/comps/"
TEAMS_URL = "https://fbref.com/en/squads/"
# %% Define functions
def extract_seasons():
seasons = []
r = requests.get(SEASONS_URL)
soup = BeautifulSoup(r.text, 'html.parser')
# winter seasons
for a in soup.find_all(href=re.compile(r"/comps/season/\d{4}-\d{4}")):
seasons.append(
{
'name':a.string,
'link':BASE_URL + a['href']
}
)
# summer season
for a in soup.find_all(href=re.compile(r"/comps/season/\d{4}$")):
seasons.append(
{
'name':" ".join(["summer",a.string]),
'link':BASE_URL + a['href']
}
)
return seasons
def extract_comps():
comps = []
r = requests.get(COMPS_URL)
soup = BeautifulSoup(r.text, 'html.parser')
for table in soup.find_all("table"):
tbody = table.find("tbody")
for tr in tbody.find_all("tr"):
comp_dict = {}
for th in tr.find_all("th"):
comp_dict.update({
th['data-stat']:th.string,
'link':BASE_URL + th.find("a")["href"]
})
for td in tr.find_all("td"):
comp_dict.update({td['data-stat']:td.string})
comps.append(comp_dict)
return comps
def extract_country_teams(url):
teams = []
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
for table in soup.find_all("table"):
tbody = table.find("tbody")
for tr in tbody.find_all("tr"):
team_dict = {}
for th in tr.find_all("th"):
team_dict.update({
th['data-stat']:th.string,
'link':BASE_URL + th.find("a")["href"]
})
for td in tr.find_all("td"):
team_dict.update({td['data-stat']:td.string})
teams.append(team_dict)
return teams
def extract_teams():
country_team_urls = []
teams = []
r = requests.get(TEAMS_URL)
soup = BeautifulSoup(r.text, 'html.parser')
for table in soup.find_all("table"):
tbody = table.find("tbody")
for tr in tbody.find_all("tr"):
country_team_urls.append(
BASE_URL + tr.find("th").find("a")["href"]
)
for url in country_team_urls:
teams.extend(extract_country_teams(url))
return teams
```
#### File: football-analytics-platform/scripts/landing_to_staging.py
```python
import sys, click, yaml
# %% Import user libraries
sys.path.append("/home/jon-dev/Workbench/Projects/football-analytics-platform")
from football_analytics_platform.source.football_data_uk import transform_csv
from football_analytics_platform.source.google_cloud_platform import set_google_application_credentials, upload_cloud_storage, download_cloud_storage
#%% Define functions
@click.command()
@click.argument("config_path")
def run(config_path):
""" Download data from landing directory. Apply transformations. Upload data to staging directory in Cloud Storage"""
print("BEGIN")
# Read in yaml file
with open(config_path, 'r') as ymlfile:
config = yaml.safe_load(ymlfile)
set_google_application_credentials(config["GOOGLE_CREDENTIAL_PATH"])
print("Starting jobs...")
for job in config["JOBS"]:
download_cloud_storage(job["LOCAL_TEMP_PATH"],config["BUCKET_NAME"],job["SOURCE_BLOB_PATH"])
transform_csv(job["LOCAL_STAGING_PATH"],job["LOCAL_TEMP_PATH"])
upload_cloud_storage(config["BUCKET_NAME"],job["DESTINATION_BLOB_PATH"],job["LOCAL_STAGING_PATH"])
print("Finished jobs!")
print("END")
# %% Main
if __name__ == '__main__':
run()
```
#### File: tests/load_gcs_football_data_uk_full/test_extract_load_0.py
```python
import sys,os
from google.cloud import storage
# %% Import user libraries
from utils import get_project_root, set_google_application_credentials
sys.path.append(str(get_project_root().joinpath("cloud_functions","load_gcs_football_data_uk_full")))
from libs.extract_load import load_page, scrape_urls, download_csv, upload_blob
# %% Define constants
GOOGLE_APPLICATION_CREDENTIALS_FILE_PATH = "C:\\Users\\<NAME>\\Workbench\Projects\\football-analytics-platform\\.credentials\\football-analytics-platform-675fac055f68.json"
TEST_URL_0 = "https://www.football-data.co.uk/englandm.php"
TEST_PATTERN_0 = r"mmz4281/\d{4}/\w{2}.csv"
TEST_TMP_DIR = str(get_project_root().joinpath("tests","tmp"))
SEASON_0 = "9900"
SEASON_1 = "2021"
DIV_0 = "E0"
DIV_1 = "EC"
TEST_DEST_FILE_0 = TEST_TMP_DIR + f"/{SEASON_0}_{DIV_0}.csv"
TEST_DEST_FILE_1 = TEST_TMP_DIR + f"/{SEASON_1}_{DIV_1}.csv"
SOURCE_URL_0 = f"https://www.football-data.co.uk/mmz4281/{SEASON_0}/{DIV_0}.csv"
SOURCE_URL_1 = f"https://www.football-data.co.uk/mmz4281/{SEASON_1}/{DIV_1}.csv"
TEST_BUCKET_NAME = "football-analytics-platform"
TEST_BLOB_PATH_0 = f"test/{SEASON_0}_{DIV_0}.csv"
TEST_BLOB_PATH_1 = f"test/{SEASON_1}_{DIV_1}.csv"
# %% Tests
def test_load_page_0():
assert(len(load_page(url=TEST_URL_0)) > 0)
def test_scrape_urls_0():
html_text = load_page(url=TEST_URL_0)
assert(len(scrape_urls(html_text=html_text, pattern=TEST_PATTERN_0)) > 0)
def test_download_csv_0():
download_csv(destination_file_path=TEST_DEST_FILE_0, source_url=SOURCE_URL_0)
download_csv(destination_file_path=TEST_DEST_FILE_1, source_url=SOURCE_URL_1)
assert((os.path.exists(TEST_DEST_FILE_0)) and (os.path.getsize(TEST_DEST_FILE_0) > 0))
assert((os.path.exists(TEST_DEST_FILE_1)) and (os.path.getsize(TEST_DEST_FILE_1) > 0))
# clean-up test files
os.remove(TEST_DEST_FILE_0)
os.remove(TEST_DEST_FILE_1)
def test_upload_blob_0():
# Setup Cloud Storage client
set_google_application_credentials(GOOGLE_APPLICATION_CREDENTIALS_FILE_PATH)
storage_client = storage.Client()
# Download test files
download_csv(destination_file_path=TEST_DEST_FILE_0, source_url=SOURCE_URL_0)
download_csv(destination_file_path=TEST_DEST_FILE_1, source_url=SOURCE_URL_1)
# Check that files were downloaded
assert((os.path.exists(TEST_DEST_FILE_0)) and (os.path.getsize(TEST_DEST_FILE_0) > 0))
assert((os.path.exists(TEST_DEST_FILE_1)) and (os.path.getsize(TEST_DEST_FILE_1) > 0))
# Upload test files to cloud storage
upload_blob(bucket_name=TEST_BUCKET_NAME, destination_blob_path=TEST_BLOB_PATH_0, source_file_path=TEST_DEST_FILE_0)
upload_blob(bucket_name=TEST_BUCKET_NAME, destination_blob_path=TEST_BLOB_PATH_1, source_file_path=TEST_DEST_FILE_1)
# Check files are in cloud storage
blob_names = [b.name for b in storage_client.list_blobs(TEST_BUCKET_NAME)]
assert(TEST_BLOB_PATH_0 in blob_names)
assert(TEST_BLOB_PATH_1 in blob_names)
# Clean-up test files
storage_client.bucket(TEST_BUCKET_NAME).blob(TEST_BLOB_PATH_0).delete()
storage_client.bucket(TEST_BUCKET_NAME).blob(TEST_BLOB_PATH_1).delete()
os.remove(TEST_DEST_FILE_0)
os.remove(TEST_DEST_FILE_1)
# %% Main
def main():
print("Running tests...")
test_load_page_0()
test_scrape_urls_0()
test_download_csv_0()
test_upload_blob_0()
print("All passed!")
if __name__=="__main__":
main()
``` |
{
"source": "JonnoFTW/keras_lr_optimiser_callback",
"score": 4
} |
#### File: keras_lr_optimiser_callback/keras_lr_optimiser_callback/lr_finder.py
```python
from matplotlib import pyplot as plt
import math
from keras.callbacks import LambdaCallback
import keras.backend as K
import numpy as np
class LRFinder:
"""
Plots the change of the loss function of a Keras model when the learning rate is exponentially increasing.
See for details:
https://towardsdatascience.com/estimating-optimal-learning-rate-for-a-deep-neural-network-ce32f2556ce0
"""
def __init__(self, model):
self.model = model
self.losses = []
self.lrs = []
self.best_loss = math.inf
self.tmp_fname = 'lrfinder_tmp.h5'
def on_batch_end(self, batch, logs):
# Log the learning rate
lr = K.get_value(self.model.optimizer.lr)
self.lrs.append(lr)
# Log the loss
loss = logs['loss']
self.losses.append(loss)
# Check whether the loss got too large or NaN
# if math.isnan(loss) or loss > self.best_loss * 4:
# self.model.stop_training = True
# return
self.best_loss = min(loss, self.best_loss)
# Increase the learning rate for the next batch
lr *= self.lr_mult
K.set_value(self.model.optimizer.lr, lr)
def _reset(self):
self.lrs.clear()
self.losses.clear()
self.best_loss = math.inf
def find(self, x_train, y_train, start_lr, end_lr, batch_size=64, epochs=1):
self._reset()
num_batches = epochs * x_train.shape[0] / batch_size
self.lr_mult = (float(end_lr) / float(start_lr)) ** (float(1) / float(num_batches))
# Save weights into a file
self.model.save_weights(self.tmp_fname)
# Remember the original learning rate
original_lr = K.get_value(self.model.optimizer.lr)
# Set the initial learning rate
K.set_value(self.model.optimizer.lr, start_lr)
callback = LambdaCallback(on_batch_end=lambda batch,
logs: self.on_batch_end(batch, logs))
self.model.fit(x_train, y_train,
batch_size=batch_size, epochs=epochs,
callbacks=[callback])
# Restore the weights to the state before model fitting
self.model.load_weights(self.tmp_fname)
# Restore the original learning rate
K.set_value(self.model.optimizer.lr, original_lr)
def find_generator(self, generator, start_lr, end_lr, epochs=1, steps_per_epoch=None, **kw_fit):
self._reset()
if steps_per_epoch is None:
try:
steps_per_epoch = len(generator)
except (ValueError, NotImplementedError) as e:
raise e('`steps_per_epoch=None` is only valid for a'
' generator based on the '
'`keras.utils.Sequence`'
' class. Please specify `steps_per_epoch` '
'or use the `keras.utils.Sequence` class.')
self.lr_mult = (float(end_lr) / float(start_lr)) ** (1. / float(steps_per_epoch * epochs))
# Save weights into a file
self.model.save_weights(self.tmp_fname)
# Remember the original learning rate
original_lr = K.get_value(self.model.optimizer.lr)
# Set the initial learning rate
K.set_value(self.model.optimizer.lr, start_lr)
callback = LambdaCallback(on_batch_end=self.on_batch_end)
self.model.fit_generator(generator=generator,
epochs=epochs,
steps_per_epoch=steps_per_epoch,
callbacks=[callback],
**kw_fit)
# Restore the weights to the state before model fitting
self.model.load_weights(self.tmp_fname)
# os.unlink(self.tmp_fname)
# Restore the original learning rate
K.set_value(self.model.optimizer.lr, original_lr)
def plot_loss(self, n_skip_beginning=10, n_skip_end=5):
"""
Plots the loss.
Parameters:
n_skip_beginning - number of batches to skip on the left.
n_skip_end - number of batches to skip on the right.
"""
plt.ylabel("loss")
plt.xlabel("learning rate (log scale)")
plt.plot(self.lrs[n_skip_beginning:-n_skip_end], self.losses[n_skip_beginning:-n_skip_end])
plt.xscale('log')
def plot_loss_change(self, sma=1, n_skip_beginning=10, n_skip_end=5, y_lim=(-0.01, 0.01)):
"""
Plots rate of change of the loss function.
Parameters:
sma - number of batches for simple moving average to smooth out the curve.
n_skip_beginning - number of batches to skip on the left.
n_skip_end - number of batches to skip on the right.
y_lim - limits for the y axis.
"""
derivatives = self.get_derivatives(sma)[n_skip_beginning:-n_skip_end]
lrs = self.lrs[n_skip_beginning:-n_skip_end]
plt.ylabel(r"Rate of Loss Change $\frac{dl}{dlr}$")
plt.xlabel("Learning Rate (log scale)")
plt.plot(lrs, derivatives, label="Loss Change")
plt.xscale('log')
plt.ylim(y_lim)
def plot_exp_loss(self, beta=0.98, n_skip_beginning=10, n_skip_end=5):
exp_loss = self.exp_weighted_losses(beta)[n_skip_beginning:-n_skip_end]
exp_der = self.exp_weighted_derivatives(beta)[n_skip_beginning:-n_skip_end]
best_lr_idx = min(enumerate(zip(exp_der[n_skip_beginning:-n_skip_end], self.lrs[n_skip_beginning:-n_skip_end])),
key=lambda x: x[1])[0]
plt.plot(self.lrs[n_skip_beginning:-n_skip_end], exp_loss, label="Loss", markevery=[best_lr_idx])
plt.ylabel("Exponentially Weighted Loss")
plt.xlabel("Learning Rate (log scale)")
plt.plot()
plt.xscale('log')
def plot_exp_loss_change(self, beta=0.98, n_skip_beginning=10, n_skip_end=5):
exp_der = self.exp_weighted_derivatives(beta)[n_skip_beginning:-n_skip_end]
plt.plot(self.lrs[n_skip_beginning:-n_skip_end], exp_der, label=r"exp weighted loss change")
plt.ylabel(r"Exponentially Weighted Loss Change $\frac{dl}{dlr}$")
plt.xlabel("Learning Rate (log scale)")
plt.xscale('log')
def get_best_lr_exp_weighted(self, beta=0.98, n_skip_beginning=10, n_skip_end=5):
derivatives = self.exp_weighted_derivatives(beta)
return min(zip(derivatives[n_skip_beginning:-n_skip_end], self.lrs[n_skip_beginning:-n_skip_end]))[1]
def exp_weighted_losses(self, beta=0.98):
losses = []
avg_loss = 0.
for batch_num, loss in enumerate(self.losses):
avg_loss = beta * avg_loss + (1 - beta) * loss
smoothed_loss = avg_loss / (1 - beta ** batch_num)
losses.append(smoothed_loss)
return losses
def exp_weighted_derivatives(self, beta=0.98):
derivatives = [0]
losses = self.exp_weighted_losses(beta)
for i in range(1, len(losses)):
derivatives.append((losses[i] - losses[i - 1]) / 1)
return derivatives
def get_derivatives(self, sma):
assert sma >= 1
derivatives = [0] * sma
for i in range(sma, len(self.lrs)):
derivatives.append((self.losses[i] - self.losses[i - sma]) / sma)
return derivatives
def get_best_lr(self, sma, n_skip_beginning=10, n_skip_end=5):
derivatives = self.get_derivatives(sma)
return min(zip(derivatives[n_skip_beginning:-n_skip_end], self.lrs[n_skip_beginning:-n_skip_end]))[1]
``` |
{
"source": "JonnoFTW/thriftpy2",
"score": 3
} |
#### File: examples/multiplexer/multiplexed_server.py
```python
import thriftpy2
from thriftpy2.protocol import TBinaryProtocolFactory
from thriftpy2.server import TThreadedServer
from thriftpy2.thrift import TProcessor, TMultiplexedProcessor
from thriftpy2.transport import TBufferedTransportFactory, TServerSocket
dd_thrift = thriftpy2.load("dingdong.thrift", module_name="dd_thrift")
pp_thrift = thriftpy2.load("pingpong.thrift", module_name="pp_thrift")
DD_SERVICE_NAME = "dd_thrift"
PP_SERVICE_NAME = "pp_thrift"
class DingDispatcher(object):
def ding(self):
print("ding dong!")
return 'dong'
class PingDispatcher(object):
def ping(self):
print("ping pong!")
return 'pong'
def main():
dd_proc = TProcessor(dd_thrift.DingService, DingDispatcher())
pp_proc = TProcessor(pp_thrift.PingService, PingDispatcher())
mux_proc = TMultiplexedProcessor()
mux_proc.register_processor(DD_SERVICE_NAME, dd_proc)
mux_proc.register_processor(PP_SERVICE_NAME, pp_proc)
server = TThreadedServer(mux_proc, TServerSocket("127.0.0.1", 9090),
iprot_factory=TBinaryProtocolFactory(),
itrans_factory=TBufferedTransportFactory())
server.serve()
if __name__ == '__main__':
main()
```
#### File: thriftpy2/tests/test_buffered_transport.py
```python
from __future__ import absolute_import
import logging
import multiprocessing
import time
from os import path
from unittest import TestCase
import thriftpy2
from thriftpy2.rpc import client_context, make_server
from thriftpy2.transport.buffered import TBufferedTransportFactory
from thriftpy2.protocol.binary import TBinaryProtocolFactory
from thriftpy2._compat import CYTHON
logging.basicConfig(level=logging.INFO)
addressbook = thriftpy2.load(path.join(path.dirname(__file__),
"addressbook.thrift"))
class Dispatcher(object):
def __init__(self):
self.registry = {}
def add(self, person):
"""
bool add(1: Person person);
"""
if person.name in self.registry:
return False
self.registry[person.name] = person
return True
def get(self, name):
"""
Person get(1: string name)
"""
if name not in self.registry:
raise addressbook.PersonNotExistsError()
return self.registry[name]
class BufferedTransportTestCase(TestCase):
TRANSPORT_FACTORY = TBufferedTransportFactory()
PROTOCOL_FACTORY = TBinaryProtocolFactory()
PORT = 50001
def mk_server(self):
server = make_server(addressbook.AddressBookService, Dispatcher(),
host="localhost", port=self.PORT,
proto_factory=self.PROTOCOL_FACTORY,
trans_factory=self.TRANSPORT_FACTORY)
p = multiprocessing.Process(target=server.serve)
return p
def client(self):
return client_context(addressbook.AddressBookService,
host="localhost", port=self.PORT,
proto_factory=self.PROTOCOL_FACTORY,
trans_factory=self.TRANSPORT_FACTORY)
def setUp(self):
self.server = self.mk_server()
self.server.start()
time.sleep(0.1)
def tearDown(self):
if self.server.is_alive():
self.server.terminate()
def test_able_to_communicate(self):
dennis = addressbook.Person(name='<NAME>')
with self.client() as c:
success = c.add(dennis)
assert success
success = c.add(dennis)
assert not success
def test_zero_length_string(self):
dennis = addressbook.Person(name='')
with self.client() as c:
success = c.add(dennis)
assert success
success = c.get(name='')
assert success
if CYTHON:
from thriftpy2.transport.buffered import TCyBufferedTransportFactory
from thriftpy2.protocol.cybin import TCyBinaryProtocolFactory
class TCyBufferedTransportTestCase(BufferedTransportTestCase):
TRANSPORT_FACTORY = TCyBufferedTransportFactory()
PROTOCOL_FACTORY = TCyBinaryProtocolFactory()
```
#### File: thriftpy2/tests/test_framed_transport.py
```python
from __future__ import absolute_import
import sys
import logging
import socket
import threading
import time
from os import path
from unittest import TestCase
import pytest
from tornado import ioloop
import thriftpy2
from thriftpy2.tornado import make_server
from thriftpy2.rpc import make_client
from thriftpy2.transport.framed import TFramedTransportFactory
from thriftpy2.protocol.binary import TBinaryProtocolFactory
try:
import asyncio
except ImportError:
asyncio = None
from thriftpy2._compat import CYTHON
logging.basicConfig(level=logging.INFO)
addressbook = thriftpy2.load(path.join(path.dirname(__file__),
"addressbook.thrift"))
class Dispatcher(object):
def __init__(self, io_loop):
self.io_loop = io_loop
self.registry = {}
def add(self, person):
"""
bool add(1: Person person);
"""
if person.name in self.registry:
return False
self.registry[person.name] = person
return True
def get(self, name):
"""
Person get(1: string name)
"""
if name not in self.registry:
raise addressbook.PersonNotExistsError()
return self.registry[name]
class FramedTransportTestCase(TestCase):
TRANSPORT_FACTORY = TFramedTransportFactory()
PROTOCOL_FACTORY = TBinaryProtocolFactory()
def mk_server(self):
sock = self.server_sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 0))
sock.setblocking(0)
self.port = sock.getsockname()[-1]
self.server_thread = threading.Thread(target=self.listen)
self.server_thread.setDaemon(True)
self.server_thread.start()
def listen(self):
self.server_sock.listen(128)
if asyncio:
# In Tornado 5.0+, the asyncio event loop will be used
# automatically by default
asyncio.set_event_loop(asyncio.new_event_loop())
self.io_loop = ioloop.IOLoop.current()
server = make_server(addressbook.AddressBookService,
Dispatcher(self.io_loop), io_loop=self.io_loop)
server.add_socket(self.server_sock)
self.io_loop.start()
def mk_client(self):
return make_client(addressbook.AddressBookService,
'127.0.0.1', self.port,
proto_factory=self.PROTOCOL_FACTORY,
trans_factory=self.TRANSPORT_FACTORY)
def mk_client_with_url(self):
return make_client(addressbook.AddressBookService,
proto_factory=self.PROTOCOL_FACTORY,
trans_factory=self.TRANSPORT_FACTORY,
url='thrift://127.0.0.1:{port}'.format(
port=self.port))
def setUp(self):
self.mk_server()
time.sleep(0.1)
self.client = self.mk_client()
self.client_created_using_url = self.mk_client_with_url()
def tearDown(self):
self.io_loop.stop()
@pytest.mark.skipif(sys.version_info[:2] == (2, 6), reason="not support")
def test_make_client(self):
linus = addressbook.Person('<NAME>')
success = self.client_created_using_url.add(linus)
assert success
success = self.client.add(linus)
assert not success
@pytest.mark.skipif(sys.version_info[:2] == (2, 6), reason="not support")
def test_able_to_communicate(self):
dennis = addressbook.Person(name='<NAME>')
success = self.client.add(dennis)
assert success
success = self.client.add(dennis)
assert not success
@pytest.mark.skipif(sys.version_info[:2] == (2, 6), reason="not support")
def test_zero_length_string(self):
dennis = addressbook.Person(name='')
success = self.client.add(dennis)
assert success
success = self.client.get(name='')
assert success
if CYTHON:
from thriftpy2.transport.framed import TCyFramedTransportFactory
from thriftpy2.protocol.cybin import TCyBinaryProtocolFactory
class CyFramedTransportTestCase(FramedTransportTestCase):
PROTOCOL_FACTORY = TCyBinaryProtocolFactory()
TRANSPORT_FACTORY = TCyFramedTransportFactory()
```
#### File: thriftpy2/tests/test_type_mismatch.py
```python
from unittest import TestCase
from thriftpy2.thrift import TType, TPayload
from thriftpy2.transport.memory import TMemoryBuffer
from thriftpy2.protocol.binary import TBinaryProtocol
from thriftpy2._compat import CYTHON
class Struct(TPayload):
thrift_spec = {
1: (TType.I32, 'a', False),
2: (TType.STRING, 'b', False),
3: (TType.DOUBLE, 'c', False)
}
default_spec = [('a', None), ('b', None), ('c', None)]
class TItem(TPayload):
thrift_spec = {
1: (TType.I32, "id", False),
2: (TType.LIST, "phones", TType.STRING, False),
3: (TType.MAP, "addr", (TType.I32, TType.STRING), False),
4: (TType.LIST, "data", (TType.STRUCT, Struct), False)
}
default_spec = [("id", None), ("phones", None), ("addr", None),
("data", None)]
class MismatchTestCase(TestCase):
BUFFER = TMemoryBuffer
PROTO = TBinaryProtocol
def test_list_type_mismatch(self):
class TMismatchItem(TPayload):
thrift_spec = {
1: (TType.I32, "id", False),
2: (TType.LIST, "phones", (TType.I32, False), False),
}
default_spec = [("id", None), ("phones", None)]
t = self.BUFFER()
p = self.PROTO(t)
item = TItem(id=37, phones=["23424", "235125"])
p.write_struct(item)
p.write_message_end()
item2 = TMismatchItem()
p.read_struct(item2)
assert item2.phones == []
def test_map_type_mismatch(self):
class TMismatchItem(TPayload):
thrift_spec = {
1: (TType.I32, "id", False),
3: (TType.MAP, "addr", (TType.STRING, TType.STRING), False)
}
default_spec = [("id", None), ("addr", None)]
t = self.BUFFER()
p = self.PROTO(t)
item = TItem(id=37, addr={1: "hello", 2: "world"})
p.write_struct(item)
p.write_message_end()
item2 = TMismatchItem()
p.read_struct(item2)
assert item2.addr == {}
def test_struct_mismatch(self):
class MismatchStruct(TPayload):
thrift_spec = {
1: (TType.STRING, 'a', False),
2: (TType.STRING, 'b', False)
}
default_spec = [('a', None), ('b', None)]
class TMismatchItem(TPayload):
thrift_spec = {
1: (TType.I32, "id", False),
2: (TType.LIST, "phones", TType.STRING, False),
3: (TType.MAP, "addr", (TType.I32, TType.STRING), False),
4: (TType.LIST, "data", (TType.STRUCT, MismatchStruct), False)
}
default_spec = [("id", None), ("phones", None), ("addr", None)]
t = self.BUFFER()
p = self.PROTO(t)
item = TItem(id=37, data=[Struct(a=1, b="hello", c=0.123),
Struct(a=2, b="world", c=34.342346),
Struct(a=3, b="when", c=25235.14)])
p.write_struct(item)
p.write_message_end()
item2 = TMismatchItem()
p.read_struct(item2)
assert len(item2.data) == 3
assert all([i.b for i in item2.data])
if CYTHON:
from thriftpy2.transport.memory import TCyMemoryBuffer
from thriftpy2.protocol.cybin import TCyBinaryProtocol
class CyMismatchTestCase(MismatchTestCase):
BUFFER = TCyMemoryBuffer
PROTO = TCyBinaryProtocol
```
#### File: aio/transport/framed.py
```python
from __future__ import absolute_import
import struct
import asyncio
from io import BytesIO
from .base import TAsyncTransportBase, readall
from .buffered import TAsyncBufferedTransport
class TAsyncFramedTransport(TAsyncTransportBase):
"""Class that wraps another transport and frames its I/O when writing."""
def __init__(self, trans):
self._trans = trans
self._rbuf = BytesIO()
self._wbuf = BytesIO()
def is_open(self):
return self._trans.is_open()
@asyncio.coroutine
def open(self):
return (yield from self._trans.open())
def close(self):
return self._trans.close()
@asyncio.coroutine
def read(self, sz):
# Important: don't attempt to read the next frame if the caller
# doesn't actually need any data.
if sz == 0:
return b''
ret = self._rbuf.read(sz)
if len(ret) != 0:
return ret
yield from self.read_frame()
return self._rbuf.read(sz)
@asyncio.coroutine
def read_frame(self):
buff = yield from readall(self._trans.read, 4)
sz, = struct.unpack('!i', buff)
frame = yield from readall(self._trans.read, sz)
self._rbuf = BytesIO(frame)
def write(self, buf):
self._wbuf.write(buf)
@asyncio.coroutine
def flush(self):
# reset wbuf before write/flush to preserve state on underlying failure
out = self._wbuf.getvalue()
self._wbuf = BytesIO()
# N.B.: Doing this string concatenation is WAY cheaper than making
# two separate calls to the underlying socket object. Socket writes in
# Python turn out to be REALLY expensive, but it seems to do a pretty
# good job of managing string buffer operations without excessive
# copies
self._trans.write(struct.pack("!i", len(out)) + out)
yield from self._trans.flush()
def getvalue(self):
return self._trans.getvalue()
class TAsyncFramedTransportFactory(object):
def get_transport(self, trans):
return TAsyncBufferedTransport(TAsyncFramedTransport(trans))
```
#### File: thriftpy2/protocol/base.py
```python
class TProtocolBase(object):
"""Base class for Thrift protocol layer."""
def __init__(self, trans):
self.trans = trans # transport is public and used by TClient
def skip(self, ttype):
raise NotImplementedError
def read_message_begin(self):
raise NotImplementedError
def read_message_end(self):
raise NotImplementedError
def write_message_begin(self, name, ttype, seqid):
raise NotImplementedError
def write_message_end(self):
raise NotImplementedError
def read_struct(self, obj):
raise NotImplementedError
def write_struct(self, obj):
raise NotImplementedError
``` |
{
"source": "jonnor/dlock-oslo",
"score": 3
} |
#### File: dlock-oslo/firmware/check_hardware.py
```python
import dlockoslo
import time
import sys
"""Tool for testing the hardware board
Uses I/O utilities and pin definitions from firmware,
to also ensure that these are correct"""
def check_inputs(delay):
print('check inputs')
for number, pin in dlockoslo.ins.items():
print('setup', number, pin)
dlockoslo.setup_gpio_pin(pin, 'in')
while True:
c = []
for number, pin in dlockoslo.ins.items():
p = dlockoslo.gpio_file_path(pin)
s = dlockoslo.read_boolean(p)
c.append(s)
print(c)
time.sleep(delay)
def check_outputs(delay):
print('check outputs')
for number, pin in dlockoslo.outs.items():
print('setup', number, pin)
dlockoslo.setup_gpio_pin(pin, 'out')
state = False
while True:
c = []
for number, pin in dlockoslo.outs.items():
p = dlockoslo.gpio_file_path(pin)
print('writing to', p, state)
dlockoslo.set_gpio(p, state)
time.sleep(delay)
state = not state
def check_status(delay):
print('check status leds')
for number, pin in dlockoslo.status.items():
print('setup', number, pin)
dlockoslo.setup_gpio_pin(pin, 'out')
state = False
while True:
c = []
for number, pin in dlockoslo.status.items():
p = dlockoslo.gpio_file_path(pin)
print('writing to', p, state)
dlockoslo.set_gpio(p, state)
time.sleep(delay)
state = not state
# NOTE: could do an automated test by connecting each output to corresponding input,
# then generating output patterns and ensuring that they are read correctly on input
def main():
prog, args = sys.argv[0], sys.argv[1:]
mode = 'input'
if len(args) >= 1:
mode = args[0]
delay = 0.15
if len(args) >= 2:
delay = float(args[1])
if 'output' in mode:
check_outputs(delay)
elif 'status' in mode:
check_status(delay)
elif 'input' in mode:
check_inputs(delay)
if __name__ == '__main__':
main()
```
#### File: dlock-oslo/gateway/testdevices.py
```python
import os
import os.path
import sys
firmware_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../firmware')
sys.path.insert(0, firmware_path)
import dlockoslo
import msgflo
import gevent
def set_fake_gpio(dev, number, state : bool):
p = os.path.join(dev, 'gpio'+str(number))
with open(p, 'w') as f:
f.write('1' if state else '0')
def create_virtual_lock(name):
os.environ['DLOCK_FAKE_GPIO'] = name
lockdir = os.path.dirname(name)
if not os.path.exists(lockdir):
os.mkdir(lockdir)
virtual = dlockoslo.LockParticipant(role=name)
del os.environ['DLOCK_FAKE_GPIO']
# turn door opener inputs off
virtual.recalculate_state() # ensure files exist
set_fake_gpio(name, 10, True)
set_fake_gpio(name, 24, True)
return virtual
def get_participants():
participants = [
create_virtual_lock('doors/virtual-1'),
create_virtual_lock('doors/virtual-2'),
create_virtual_lock('doors/dlock-2'),
dlockoslo.AlwaysErroringParticipant(role='doors/erroring-1'),
]
# for emulating timeout/device missing, send on MQTT topic which nothing uses
return participants
def run(done_cb=None):
participants = get_participants()
engine = msgflo.run(participants, done_cb=done_cb)
return participants, engine
def main():
participants = get_participants()
waiter = gevent.event.AsyncResult()
engine = msgflo.run(participants, done_cb=waiter.set)
waiter.wait()
if __name__ == '__main__':
main()
``` |
{
"source": "JonNRb/physics506",
"score": 3
} |
#### File: src/zeeman/make_graphs.py
```python
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import data
import regression
def scientific_notation(value):
if value == 0:
return '0'
else:
e = np.log10(np.abs(value))
m = np.sign(value) * 10 ** (e - int(e))
return r'${:.1f} \cdot 10^{{{:d}}}$'.format(m, int(e))
scientific_formatter = mpl.ticker.FuncFormatter(
lambda x, p: scientific_notation(x))
identity_formatter = mpl.ticker.FuncFormatter(lambda x, p: r'${0}$'.format(x))
for name, data_item in data.csv_data.items():
print(name)
plt.figure(figsize=(800 / 96, 600 / 96))
plt.plot(data_item[0], data_item[1], 'bo', linewidth=2.0)
plt.axis('auto')
plt.ylabel('Counts Per Second')
plt.xlabel('Wavelength (nm)')
plt.gca().xaxis.set_major_formatter(identity_formatter)
plt.gca().yaxis.set_major_formatter(scientific_formatter)
plt.savefig(name.replace('csv', 'png'), dpi=240,
bbox_inches='tight', transparent=True)
plt.clf()
for name, d in data.points_data.items():
print(name)
slope, intercept, std_err = regression.regress(d)
plt.figure(figsize=(800 / 96, 600 / 96))
x, y = zip(*d)
plt.plot(x, y, 'bo', linewidth=2.0)
def f(x): return intercept + slope * x
f_x = np.arange(min(x), max(x), 0.001)
plt.plot(f_x, f(f_x), 'r-', linewidth=1.0)
plt.errorbar(x, [f(i) for i in x], fmt='r-', yerr=[std_err/2] * len(x))
plt.axis('auto')
plt.ylabel('$\Delta\lambda / \lambda^2$ (1/nm)')
plt.xlabel('Magnetic Field Strength (T)')
plt.gca().xaxis.set_major_formatter(identity_formatter)
plt.gca().yaxis.set_major_formatter(scientific_formatter)
plt.savefig(name.replace('txt', 'png'), dpi=240,
bbox_inches='tight', transparent=True)
plt.clf()
``` |
{
"source": "jonn-smith/python_cli_template",
"score": 3
} |
#### File: PROJECT_NAME/sub_command_1/command.py
```python
import logging
import click
LOGGER = logging.getLogger(__name__)
@click.command(name="sub_command_1")
def main():
"""Main entry for Sub Command 1"""
click.echo("Sub-command 1")
LOGGER.info("Sub-command 1")
``` |
{
"source": "jonn-smith/TALON",
"score": 3
} |
#### File: talon/post/filter_talon_transcripts.py
```python
from optparse import OptionParser
import sqlite3
from pathlib import Path
from .. import query_utils as qutils
from talon.post import get_read_annotations as read_annot
import pandas as pd
import os
import warnings
def getOptions():
parser = OptionParser(description = ("talon_filter_transcripts is a "
"utility that filters the transcripts inside "
"a TALON database to produce a transcript whitelist. "
"This list can then be used by downstream analysis "
"tools to determine which transcripts and other "
"features should be reported (for example in a GTF file)"))
parser.add_option("--db", dest = "database",
help = "TALON database", metavar = "FILE", type = str)
parser.add_option("--annot", "-a", dest = "annot",
help = """Which annotation version to use. Will determine which
annotation transcripts are considered known or novel
relative to. Note: must be in the TALON database.""",
type = "string")
parser.add_option("--datasets", dest = "datasets", default = None,
help = ("Datasets to include. Can be provided as a "
"comma-delimited list on the command line, "
"or as a file with one dataset per line. "
"If this option is omitted, all datasets will "
"be included."))
parser.add_option("--maxFracA", dest = "max_frac_A", default = 0.5,
help = ("Maximum fraction of As to allow in the window "
"located immediately after any read assigned to "
"a novel transcript (helps to filter out internal "
"priming artifacts). Default = 0.5. Use 1 if you prefer"
"to not filter out internal priming events."),
type = float)
parser.add_option("--minCount", dest = "min_count", default = 5,
type = int,
help = ("Number of minimum occurrences required for a "
"novel transcript PER dataset. Default = 5"))
parser.add_option("--minDatasets", dest = "min_datasets", default = None,
type = int,
help = ("Minimum number of datasets novel transcripts "
"must be found in. Default = all datasets provided"))
parser.add_option("--allowGenomic", dest ="allow_genomic", action='store_true',
help = ("If this option is set, transcripts from the Genomic "
"novelty category will be permitted in the output "
"(provided they pass the thresholds). Default "
"behavior is to filter out genomic transcripts "
"since they are unlikely to be real novel isoforms."),
default = False)
parser.add_option("--o", dest = "outfile", help = "Outfile name",
metavar = "FILE", type = "string")
(options, args) = parser.parse_args()
return options
def get_known_transcripts(database, annot, datasets = None):
""" Fetch gene ID and transcript ID of all known transcripts detected in
the specified datasets """
with sqlite3.connect(database) as conn:
query = """SELECT DISTINCT gene_ID, transcript_ID FROM observed
LEFT JOIN transcript_annotations AS ta
ON ta.ID = observed.transcript_ID
WHERE (ta.attribute = 'transcript_status'
AND ta.value = 'KNOWN'
AND ta.annot_name = '%s')""" % (annot)
if datasets != None:
datasets = qutils.format_for_IN(datasets)
query += " AND observed.dataset IN " + datasets
known = pd.read_sql_query(query, conn)
return known
def fetch_reads_in_datasets_fracA_cutoff(database, datasets, max_frac_A):
""" Selects reads from the database that are from the specified datasets
and which pass the following cutoffs:
- fraction_As <= max_frac_A
Reads with fraction_As value of None will not be included.
If datasets == None, then all datasets are permitted"""
# convert non-iterable datasets to an iterable
if datasets == None:
with sqlite3.connect(database) as conn:
query = """SELECT dataset_name
FROM dataset"""
iter_datasets = pd.read_sql_query(query, conn).dataset_name.tolist()
else:
iter_datasets = datasets
# first check if we have non-null fraction_As columns at all
# (one dataset at a time)
for dataset in iter_datasets:
with sqlite3.connect(database) as conn:
query = """SELECT read_name, gene_ID, transcript_ID, dataset, fraction_As
FROM observed WHERE dataset='{}' LIMIT 0, 10""".format(dataset)
data = pd.read_sql_query(query, conn)
print(data)
nans = all(data.fraction_As.isna().tolist())
print(nans)
if nans and max_frac_A != 1:
print("Reads in dataset {} appear to be unlabelled. "
"Only known transcripts will pass the filter.".format(dataset))
with sqlite3.connect(database) as conn:
query = """SELECT read_name, gene_ID, transcript_ID, dataset, fraction_As
FROM observed
WHERE fraction_As <= %f""" % (max_frac_A)
if datasets != None:
datasets = qutils.format_for_IN(datasets)
query += " AND dataset IN " + datasets
data = pd.read_sql_query(query, conn)
# warn the user if no novel models passed filtering
if len(data.index) == 0:
print('No reads passed maxFracA cutoff. Is this expected?')
return data
def check_annot_validity(annot, database):
""" Make sure that the user has entered a correct annotation name """
conn = sqlite3.connect(database)
cursor = conn.cursor()
cursor.execute("SELECT DISTINCT annot_name FROM gene_annotations")
annotations = [str(x[0]) for x in cursor.fetchall()]
conn.close()
if "TALON" in annotations:
annotations.remove("TALON")
if annot == None:
message = "Please provide a valid annotation name. " + \
"In this database, your options are: " + \
", ".join(annotations)
raise ValueError(message)
if annot not in annotations:
message = "Annotation name '" + annot + \
"' not found in this database. Try one of the following: " + \
", ".join(annotations)
raise ValueError(message)
return
def check_db_version(database):
""" Make sure the user is using a v5 database """
conn = sqlite3.connect(database)
cursor = conn.cursor()
with sqlite3.connect(database) as conn:
query = """SELECT value
FROM run_info
WHERE item='schema_version'"""
ver = pd.read_sql_query(query, conn)
if ver.empty:
message = "Database version is not compatible with v5.0 filtering."
raise ValueError(message)
def parse_datasets(dataset_option, database):
""" Parses dataset names from command line. Valid forms of input:
- None (returns None)
- Comma-delimited list of names
- File of names (One per line)
Also checks to make sure that the datasets are in the database.
"""
if dataset_option == None:
print(("No dataset names specified, so filtering process will use all "
"datasets present in the database."))
return None
elif os.path.isfile(dataset_option):
print("Parsing datasets from file %s..." % (dataset_option))
datasets = []
with open(dataset_option) as f:
for line in f:
line = line.strip()
datasets.append(line)
else:
datasets = dataset_option.split(",")
# Now validate the datasets
with sqlite3.connect(database) as conn:
cursor = conn.cursor()
valid_datasets = qutils.fetch_all_datasets(cursor)
invalid_datasets = []
for dset in datasets:
if dset not in valid_datasets:
invalid_datasets.append(dset)
if len(invalid_datasets) > 0:
raise ValueError(("Problem parsing datasets. The following names are "
"not in the database: '%s'. \nValid dataset names: '%s'")
% (", ".join(invalid_datasets),
", ".join(valid_datasets)))
else:
print("Parsed the following dataset names successfully: %s" % \
(", ".join(datasets)))
return datasets
def get_novelty_df(database):
""" Get the novelty category assignment of each transcript and
store in a data frame """
transcript_novelty_dict = read_annot.get_transcript_novelty(database)
transcript_novelty = pd.DataFrame.from_dict(transcript_novelty_dict,
orient='index')
transcript_novelty = transcript_novelty.reset_index()
transcript_novelty.columns = ['transcript_ID', 'transcript_novelty']
return transcript_novelty
def merge_reads_with_novelty(reads, novelty):
""" Given a data frame of reads and a transcript novelty data frame,
perform a left merge to annotate the reads with their novelty status.
"""
merged = pd.merge(reads, novelty, on = "transcript_ID", how = "left")
return merged
def filter_on_min_count(reads, min_count):
""" Given a reads data frame, compute the number of times that each
transcript ID occurs per dataset.
Keep the rows that meet the min_count threshold and return them. """
cols = ['gene_ID', 'transcript_ID', 'dataset']
counts_df = reads[cols].groupby(cols).size()
counts_df = counts_df.reset_index()
counts_df.columns = cols + ["count"]
filtered = counts_df.loc[counts_df['count'] >= min_count]
return filtered
def filter_on_n_datasets(counts_in_datasets, min_datasets):
""" Given a data frame with columns gene_ID, transcript_ID, dataset,
and count (in that dataset), count the number of datasets that each
transcript appears in. Then, filter the data such that only transcripts
found in at least 'min_datasets' remain. """
cols = ['gene_ID', 'transcript_ID']
dataset_count_df = counts_in_datasets[cols].groupby(cols).size()
dataset_count_df = dataset_count_df.reset_index()
dataset_count_df.columns = cols + ["n_datasets"]
filtered = dataset_count_df.loc[dataset_count_df['n_datasets'] >= min_datasets]
return filtered
def filter_talon_transcripts(database, annot, datasets, options):
""" Filter transcripts belonging to the specified datasets in a TALON
database. The 'annot' parameter specifies which annotation transcripts
are known relative to. Can be tuned with the following options:
- options.max_frac_A: maximum allowable fraction of As recorded for
region after the read (0-1)
- options.allow_genomic: Removes genomic transcripts if set to True
- options.min_count: Transcripts must appear at least this many times
to count as present in a dataset
- options.min_datasets: After the min_count threshold has been
applied, the transcript must be found in at
least this many datasets to pass the filter.
If this option is set to None, then it will
default to the total number of datasets in the
reads.
Please note that known transcripts are allowed through independently
of these parameters.
"""
# Known transcripts automatically pass the filter
known = get_known_transcripts(database, annot, datasets = datasets)
# Get reads that pass fraction A cutoff
reads = fetch_reads_in_datasets_fracA_cutoff(database, datasets,
options.max_frac_A)
# Fetch novelty information and merge with reads
reads = merge_reads_with_novelty(reads, get_novelty_df(database))
# Drop genomic transcripts if desired
if options.allow_genomic == False:
reads = reads.loc[reads.transcript_novelty != 'Genomic']
# Perform counts-based filtering
filtered_counts = filter_on_min_count(reads, options.min_count)
# Perform n-dataset based filtering
if options.min_datasets == None:
options.min_datasets = len(set(list(reads.dataset)))
dataset_filtered = filter_on_n_datasets(filtered_counts, options.min_datasets)
# Join the known transcripts with the filtered ones and return
if len(dataset_filtered.index) != 0:
final_filtered = pd.concat([known[["gene_ID", "transcript_ID"]],
dataset_filtered[["gene_ID", "transcript_ID"]]]).drop_duplicates()
else: final_filtered = known
return final_filtered
def main():
options = getOptions()
database = options.database
annot = options.annot
# Make sure that the input database exists!
if not Path(database).exists():
raise ValueError("Database file '%s' does not exist!" % database)
# Make sure the database is of the v5 schema
check_db_version(database)
# Make sure that the provided annotation name is valid
check_annot_validity(annot, database)
# Parse datasets
datasets = parse_datasets(options.datasets, database)
if datasets != None and len(datasets) == 1:
warnings.warn("Only one dataset provided. For best performance, please "
"run TALON with at least 2 biological replicates if possible.")
# Perform the filtering
filtered = filter_talon_transcripts(database, annot, datasets, options)
# Write gene and transcript IDs to file
print("Writing whitelisted gene-transcript TALON ID pairs to " + options.outfile + "...")
filtered.to_csv(options.outfile, sep = ",", header = False, index = False)
if __name__ == '__main__':
main()
``` |
{
"source": "jonntd/ExocortexCrateVS2010MAYA",
"score": 2
} |
#### File: scripts/ExocortexAlembic/_functions.py
```python
import maya.mel as mel
import maya.cmds as cmds
""" Contains functions and data structures """
############################################################################################################
# general functions needed to import and attach
############################################################################################################
def alembicTimeAndFileNode(filename, multi=False):
cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._functions.alembicTimeAndFileNode")
#print("time control")
timeControl = "AlembicTimeControl"
if not cmds.objExists(timeControl):
timeControl = cmds.createNode("ExocortexAlembicTimeControl", name=timeControl)
alembicConnectAttr("time1.outTime", timeControl+".inTime")
#print("file node")
fileNode = cmds.createNode("ExocortexAlembicFile")
cmds.setAttr(fileNode+".fileName", filename, type="string")
cmds.connectAttr(timeControl+".outTime", fileNode+".inTime")
if multi:
cmds.setAttr(fileNode+".multiFiles", 1);
cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._functions.alembicTimeAndFileNode")
return fileNode, timeControl
def createNamespaces(namespaces):
#print("createNamespaces("+ str(namespaces) + ")")
if len(namespaces) > 1:
# first one!
accum = ":" + namespaces[0]
if not cmds.namespace(exists=accum):
cmds.namespace(add=namespaces[0])
# rest ...
for nspace in namespaces[1:-1]:
curAccum = accum + ":" + nspace
if not cmds.namespace(exists=curAccum):
cmds.namespace(add=nspace, p=accum)
accum = curAccum
pass
def subCreateNode(names, type, parentXform):
#print("subCreateNode(" + str(names) + ", " + type + ", " + str(parentXform) + ")")
accum = None
for name in names[:-1]:
result = name
if accum != None:
result = accum + '|' + result
if not cmds.objExists(result):
createNamespaces(name.split(':'))
#print("create " + name + ", child of: " + str(accum))
result = cmds.createNode("transform", n=name, p=accum)
if accum == None:
accum = result
else:
accum = accum + "|" + result.split('|')[-1]
name = names[-1]
if parentXform != None and len(parentXform) > 0:
accum = parentXform
createNamespaces(name.split(':'))
#print("create " + name + ", child of: " + str(accum))
result = cmds.createNode(type, n=name, p=accum)
if accum != None:
result = accum + "|" + result.split("|")[-1]
#print("--> " + result)
return result
def alembicCreateNode(name, type, parentXform=None):
""" create a node and make sure to return a full name and create namespaces if necessary! """
cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._functions.createAlembicNode")
#print("alembicCreateNode(" + str(name) + ", " + str(type) + ", " + str(parentXform) + ")")
result = subCreateNode(name.split('|'), type, parentXform)
cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._functions.createAlembicNode")
return result
def alembicConnectAttr(source, target):
""" make sure nothing is connected the target and then connect the source to the target """
cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._functions.alembicConnectIfUnconnected")
currentSource = cmds.connectionInfo(target, sfd=True)
if currentSource != "" and currentSource != source:
cmds.disconnectAttr(currentSource, target)
cmds.connectAttr(source, target)
cmds.ExocortexAlembic_profileEnd(f="Python.ExocortexAlembic._functions.alembicConnectIfUnconnected")
pass
############################################################################################################
# poly mesh functions
############################################################################################################
def alembicPolyMeshToSubdiv(mesh=None):
if mesh == None: # if None... refer to the selection list
sel = cmds.ls(sl=True)
if len(sel) != 1:
if len(sel) > 1:
return ("Only one transform or mesh should be selected")
else:
return ("Need to select one transform or mesh")
mesh = sel[0];
xform = cmds.objectType(mesh) # here xform is the type of mesh. below, xform becomes mesh's transform
if xform == "mesh":
xform = cmds.listRelatives(mesh, p=True)[0]
elif xform == "transform":
xform = mesh;
mesh = cmds.listRelatives(xform, s=True)[0]
else:
return ("Type " + xform + " not supported")
try:
newX = cmds.createNode("transform", n=(xform+"_SubD"))
sub = cmds.createNode("subdiv", n=(mesh+"_SubD"), p=newX)
poly = cmds.createNode("polyToSubdiv")
cmds.connectAttr(xform+".translate", newX+".translate")
cmds.connectAttr(xform+".rotate", newX+".rotate")
cmds.connectAttr(xform+".scale", newX+".scale")
cmds.connectAttr(xform+".rotateOrder", newX+".rotateOrder")
cmds.connectAttr(xform+".shear", newX+".shear")
cmds.connectAttr(xform+".rotateAxis", newX+".rotateAxis")
cmds.connectAttr(poly+".outSubdiv", sub+".create")
cmds.connectAttr(mesh+".outMesh", poly+".inMesh")
cmd.setAttr(sub+".dispResolution", 3);
except Exception as ex:
return str(ex.args)
return ""
############################################################################################################
# progress bar
############################################################################################################
__gMainProgressBar = ""
def progressBar_init(_max):
global __gMainProgressBar
try:
__gMainProgressBar = mel.eval('$tmp = $gMainProgressBar')
if __gMainProgressBar != "":
cmds.progressBar(__gMainProgressBar, edit=True, isInterruptable=True, maxValue=_max)
except:
__gMainProgressBar = ""
def progressBar_start():
global __gMainProgressBar
if __gMainProgressBar != "":
cmds.progressBar(__gMainProgressBar, edit=True, beginProgress=True, step=1)
def progressBar_stop():
global __gMainProgressBar
if __gMainProgressBar != "":
cmds.progressBar(__gMainProgressBar, edit=True, endProgress=True)
def progressBar_incr(_step=20):
global __gMainProgressBar
if __gMainProgressBar != "":
cmds.progressBar(__gMainProgressBar, edit=True, step=_step)
def progressBar_isCancelled():
global __gMainProgressBar
if __gMainProgressBar == "":
return 0
if cmds.progressBar(__gMainProgressBar, query=True, isCancelled=True):
return 1
return 0
``` |
{
"source": "jonntd/instanceAlongCurve",
"score": 2
} |
#### File: jonntd/instanceAlongCurve/instanceAlongCurve.py
```python
import sys
import math
import random
import traceback
import maya.mel as mel
import pymel.core as pm
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.OpenMayaRender as OpenMayaRender
kPluginCmdName = "instanceAlongCurve"
kPluginNodeName = 'instanceAlongCurveLocator'
kPluginNodeClassify = 'utility/general'
kPluginNodeId = OpenMaya.MTypeId( 0x55555 )
# InstanceAlongCurve v1.0.3
class instanceAlongCurveLocator(OpenMayaMPx.MPxLocatorNode):
# Simple container class for compound vector attributes
class Vector3CompoundAttribute(object):
def __init__(self):
self.compound = OpenMaya.MObject()
self.x = OpenMaya.MObject()
self.y = OpenMaya.MObject()
self.z = OpenMaya.MObject()
# Input attributes
inputCurveAttr = OpenMaya.MObject()
inputTransformAttr = OpenMaya.MObject()
inputShadingGroupAttr = OpenMaya.MObject()
# Instance count related attributes
instanceCountAttr = OpenMaya.MObject()
instancingModeAttr = OpenMaya.MObject()
instanceLengthAttr = OpenMaya.MObject()
maxInstancesByLengthAttr = OpenMaya.MObject()
displayTypeAttr = OpenMaya.MObject()
bboxAttr = OpenMaya.MObject()
orientationModeAttr = OpenMaya.MObject()
inputOrientationAxisAttr = Vector3CompoundAttribute()
class RampAttributes(object):
def __init__(self):
self.ramp = OpenMaya.MObject() # normalized ramp
self.rampOffset = OpenMaya.MObject() # evaluation offset for ramp
self.rampAxis = OpenMaya.MObject() # ramp normalized axis
self.rampAmplitude = OpenMaya.MObject() # ramp amplitude
self.rampRandomAmplitude = OpenMaya.MObject() # ramp random amplitude
# Simple container class for compound vector attributes
class RampValueContainer(object):
def __init__(self, mObject, dataBlock, rampAttr, normalize):
self.ramp = OpenMaya.MRampAttribute(OpenMaya.MPlug(mObject, rampAttr.ramp))
self.rampOffset = dataBlock.inputValue(rampAttr.rampOffset).asFloat()
self.rampRandomAmplitude = dataBlock.inputValue(rampAttr.rampRandomAmplitude).asFloat()
self.rampAmplitude = dataBlock.inputValue(rampAttr.rampAmplitude).asFloat()
if normalize:
self.rampAxis = dataBlock.inputValue(rampAttr.rampAxis.compound).asVector().normal()
else:
self.rampAxis = dataBlock.inputValue(rampAttr.rampAxis.compound).asVector()
# Ramps base offset
distOffsetAttr = OpenMaya.MObject()
# Ramp attributes
positionRampAttr = RampAttributes()
rotationRampAttr = RampAttributes()
scaleRampAttr = RampAttributes()
# Output vectors
outputTranslationAttr = Vector3CompoundAttribute()
outputRotationAttr = Vector3CompoundAttribute()
outputScaleAttr = Vector3CompoundAttribute()
def __init__(self):
OpenMayaMPx.MPxLocatorNode.__init__(self)
def postConstructor(self):
OpenMaya.MFnDependencyNode(self.thisMObject()).setName("instanceAlongCurveLocatorShape#")
self.callbackId = OpenMaya.MNodeMessage.addAttributeChangedCallback(self.thisMObject(), self.attrChangeCallback)
self.updateInstanceConnections()
# Find original SG to reassign it to instance
def getShadingGroup(self):
inputSGPlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.inputShadingGroupAttr)
sgNode = self.getSingleSourceObjectFromPlug(inputSGPlug)
if sgNode is not None and sgNode.hasFn(OpenMaya.MFn.kSet):
return OpenMaya.MFnSet(sgNode)
return None
def assignShadingGroup(self, fnDagNode):
fnSet = self.getShadingGroup()
if fnSet is not None:
# Easiest, cleanest way seems to be calling MEL.
# sets command handles everything, even nested instanced dag paths
mdgm = OpenMaya.MDGModifier()
mdgm.commandToExecute("sets -e -nw -fe " + fnSet.name() + " " + fnDagNode.name())
mdgm.doIt()
# Helper function to get an array of available logical indices from the sparse array
# TODO: maybe it can be precalculated?
def getAvailableLogicalIndices(self, plug, numIndices):
# Allocate and initialize
outIndices = OpenMaya.MIntArray(numIndices)
indices = OpenMaya.MIntArray(plug.numElements())
plug.getExistingArrayAttributeIndices(indices)
currentAvailableIndex = 0
indicesFound = 0
# Assuming indices are SORTED :)
for i in indices:
connectedPlug = plug.elementByLogicalIndex(i).isConnected()
# Iteratively find available indices in the sparse array
while i > currentAvailableIndex:
outIndices[indicesFound] = currentAvailableIndex
indicesFound += 1
currentAvailableIndex += 1
# Check against this index, add it if it is not connected
if i == currentAvailableIndex and not connectedPlug:
outIndices[indicesFound] = currentAvailableIndex
indicesFound += 1
currentAvailableIndex += 1
if indicesFound == numIndices:
return outIndices
# Fill remaining expected indices
for i in xrange(indicesFound, numIndices):
outIndices[i] = currentAvailableIndex
currentAvailableIndex += 1
return outIndices
def getNodeTransformFn(self):
dagNode = OpenMaya.MFnDagNode(self.thisMObject())
dagPath = OpenMaya.MDagPath()
dagNode.getPath(dagPath)
return OpenMaya.MFnDagNode(dagPath.transform())
def updateInstanceConnections(self):
# If the locator is being instanced, just stop updating its children.
# This is to prevent losing references to the locator instances' children
# If you want to change this locator, prepare the source before instantiating
if OpenMaya.MFnDagNode(self.thisMObject()).isInstanced():
return OpenMaya.kUnknownParameter
# Plugs
outputTranslationPlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.outputTranslationAttr.compound)
outputRotationPlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.outputRotationAttr.compound)
outputScalePlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.outputScaleAttr.compound)
expectedInstanceCount = self.getInstanceCountByMode()
numConnectedElements = outputTranslationPlug.numConnectedElements()
# Only instance if we are missing elements
# TODO: handle mismatches in translation/rotation plug connected elements (user deleted a plug? use connectionBroken method?)
if numConnectedElements < expectedInstanceCount:
inputTransformFn = self.getInputTransformFn()
if inputTransformFn is not None:
transformFn = self.getNodeTransformFn()
newInstancesCount = expectedInstanceCount - numConnectedElements
availableIndices = self.getAvailableLogicalIndices(outputTranslationPlug, newInstancesCount)
displayPlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.displayTypeAttr)
LODPlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.bboxAttr)
mdgModifier = OpenMaya.MDagModifier()
for i in availableIndices:
# Instance transform
# InstanceLeaf must be set to False to prevent crashes :)
trInstance = inputTransformFn.duplicate(True, False)
instanceFn = OpenMaya.MFnTransform(trInstance)
# Parent new instance
transformFn.addChild(trInstance)
instanceTranslatePlug = instanceFn.findPlug('translate', False)
outputTranslationPlugElement = outputTranslationPlug.elementByLogicalIndex(i)
instanceRotationPlug = instanceFn.findPlug('rotate', False)
outputRotationPlugElement = outputRotationPlug.elementByLogicalIndex(i)
instanceScalePlug = instanceFn.findPlug('scale', False)
outputScalePlugElement = outputScalePlug.elementByLogicalIndex(i)
# Enable drawing overrides
overrideEnabledPlug = instanceFn.findPlug("overrideEnabled", False)
overrideEnabledPlug.setBool(True)
instanceDisplayPlug = instanceFn.findPlug("overrideDisplayType", False)
instanceLODPlug = instanceFn.findPlug("overrideLevelOfDetail", False)
if not outputTranslationPlugElement.isConnected():
mdgModifier.connect(outputTranslationPlugElement, instanceTranslatePlug)
if not outputRotationPlugElement.isConnected():
mdgModifier.connect(outputRotationPlugElement, instanceRotationPlug)
if not outputScalePlugElement.isConnected():
mdgModifier.connect(outputScalePlugElement, instanceScalePlug)
if not instanceDisplayPlug.isConnected():
mdgModifier.connect(displayPlug, instanceDisplayPlug)
if not instanceLODPlug.isConnected():
mdgModifier.connect(LODPlug, instanceLODPlug)
mdgModifier.doIt()
# Finally, assign SG to all children
self.assignShadingGroup(transformFn)
# Remove instances if necessary
elif numConnectedElements > expectedInstanceCount:
connections = OpenMaya.MPlugArray()
toRemove = numConnectedElements - expectedInstanceCount
mdgModifier = OpenMaya.MDGModifier()
for i in xrange(toRemove):
outputTranslationPlugElement = outputTranslationPlug.connectionByPhysicalIndex(numConnectedElements - 1 - i)
outputTranslationPlugElement.connectedTo(connections, False, True)
for c in xrange(connections.length()):
mdgModifier.deleteNode(connections[c].node())
mdgModifier.doIt()
def attrChangeCallback(self, msg, plug, otherPlug, clientData):
incomingDirection = (OpenMaya.MNodeMessage.kIncomingDirection & msg) == OpenMaya.MNodeMessage.kIncomingDirection
attributeSet = (OpenMaya.MNodeMessage.kAttributeSet & msg) == OpenMaya.MNodeMessage.kAttributeSet
isCorrectAttribute = (plug.attribute() == instanceAlongCurveLocator.instanceCountAttr)
isCorrectAttribute = isCorrectAttribute or (plug.attribute() == instanceAlongCurveLocator.instancingModeAttr)
isCorrectAttribute = isCorrectAttribute or (plug.attribute() == instanceAlongCurveLocator.instanceLengthAttr)
isCorrectAttribute = isCorrectAttribute or (plug.attribute() == instanceAlongCurveLocator.maxInstancesByLengthAttr)
isCorrectNode = OpenMaya.MFnDependencyNode(plug.node()).typeName() == kPluginNodeName
try:
if isCorrectNode and isCorrectAttribute and attributeSet and incomingDirection:
self.updateInstanceConnections()
except:
sys.stderr.write('Failed trying to update instances. stack trace: \n')
sys.stderr.write(traceback.format_exc())
def getSingleSourceObjectFromPlug(self, plug):
if plug.isConnected():
# Get connected input plugs
connections = OpenMaya.MPlugArray()
plug.connectedTo(connections, True, False)
# Find input transform
if connections.length() == 1:
return connections[0].node()
return None
def getInputTransformFn(self):
inputTransformPlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.inputTransformAttr)
transform = self.getSingleSourceObjectFromPlug(inputTransformPlug)
# Get Fn from a DAG path to get the world transformations correctly
if transform is not None and transform.hasFn(OpenMaya.MFn.kTransform):
path = OpenMaya.MDagPath()
trFn = OpenMaya.MFnDagNode(transform)
trFn.getPath(path)
return OpenMaya.MFnTransform(path)
return None
def getCurveFn(self):
inputCurvePlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.inputCurveAttr)
curve = self.getSingleSourceObjectFromPlug(inputCurvePlug)
# Get Fn from a DAG path to get the world transformations correctly
if curve is not None:
path = OpenMaya.MDagPath()
trFn = OpenMaya.MFnDagNode(curve)
trFn.getPath(path)
path.extendToShape()
if path.node().hasFn(OpenMaya.MFn.kNurbsCurve):
return OpenMaya.MFnNurbsCurve(path)
return None
# Calculate expected instances by the instancing mode
def getInstanceCountByMode(self):
instancingModePlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.instancingModeAttr)
inputCurvePlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.inputCurveAttr)
if inputCurvePlug.isConnected() and instancingModePlug.asInt() == 1:
instanceLengthPlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.instanceLengthAttr)
maxInstancesByLengthPlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.maxInstancesByLengthAttr)
curveFn = self.getCurveFn()
return min(maxInstancesByLengthPlug.asInt(), int(curveFn.length() / instanceLengthPlug.asFloat()))
instanceCountPlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.instanceCountAttr)
return instanceCountPlug.asInt()
def getParamOffset(self):
p = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.distOffsetAttr)
return p.asFloat()
def getRandomizedValue(self, random, randomAmplitude, value):
return (random.random() * 2.0 - 1.0) * randomAmplitude + value
def updateInstancePositions(self, curveFn, dataBlock, count, distOffset ):
point = OpenMaya.MPoint()
curveLength = curveFn.length()
translateArrayHandle = dataBlock.outputArrayValue(instanceAlongCurveLocator.outputTranslationAttr.compound)
# Deterministic random
random.seed(count)
rampValues = instanceAlongCurveLocator.RampValueContainer(self.thisMObject(), dataBlock, instanceAlongCurveLocator.positionRampAttr, False)
# Make sure there are enough handles...
for i in xrange(min(count, translateArrayHandle.elementCount())):
rampValue = self.getRampValueAtPosition(rampValues, i, count)
dist = math.fmod(curveLength * (i / float(count)) + distOffset, curveLength)
# EP curves **really** dont like param at 0.0
param = max( min( curveFn.findParamFromLength( dist ), curveLength ), 0.001 )
curveFn.getPointAtParam(param, point)
try:
normal = curveFn.normal(param).normal()
tangent = curveFn.tangent(param).normal()
bitangent = (normal ^ tangent).normal()
except:
print 'curveFn normal get error. param:%f/length:%f' % ( param, curveLength )
twistNormal = normal * self.getRandomizedValue(random, rampValues.rampRandomAmplitude, rampValue * rampValues.rampAmplitude) * rampValues.rampAxis.x
twistBitangent = bitangent * self.getRandomizedValue(random, rampValues.rampRandomAmplitude, rampValue * rampValues.rampAmplitude) * rampValues.rampAxis.y
twistTangent = tangent * self.getRandomizedValue(random, rampValues.rampRandomAmplitude, rampValue * rampValues.rampAmplitude) * rampValues.rampAxis.z
point += twistNormal + twistTangent + twistBitangent
translateArrayHandle.jumpToArrayElement(i)
translateHandle = translateArrayHandle.outputValue()
translateHandle.set3Double(point.x, point.y, point.z)
translateArrayHandle.setAllClean()
translateArrayHandle.setClean()
def getRampValueAtPosition(self, rampValues, i, count):
util = OpenMaya.MScriptUtil()
util.createFromDouble(0.0)
valuePtr = util.asFloatPtr()
position = math.fmod((i / float(count)) + rampValues.rampOffset, 1.0)
rampValues.ramp.getValueAtPosition(position, valuePtr)
return util.getFloat(valuePtr)
def updateInstanceScale(self, curveFn, dataBlock, count):
point = OpenMaya.MPoint()
scaleArrayHandle = dataBlock.outputArrayValue(instanceAlongCurveLocator.outputScaleAttr.compound)
# Deterministic random
random.seed(count)
rampValues = instanceAlongCurveLocator.RampValueContainer(self.thisMObject(), dataBlock, instanceAlongCurveLocator.scaleRampAttr, False)
# Make sure there are enough handles...
for i in xrange(min(count, scaleArrayHandle.elementCount())):
rampValue = self.getRampValueAtPosition(rampValues, i, count)
point.x = self.getRandomizedValue(random, rampValues.rampRandomAmplitude, rampValue * rampValues.rampAmplitude) * rampValues.rampAxis.x
point.y = self.getRandomizedValue(random, rampValues.rampRandomAmplitude, rampValue * rampValues.rampAmplitude) * rampValues.rampAxis.y
point.z = self.getRandomizedValue(random, rampValues.rampRandomAmplitude, rampValue * rampValues.rampAmplitude) * rampValues.rampAxis.z
scaleArrayHandle.jumpToArrayElement(i)
scaleHandle = scaleArrayHandle.outputValue()
scaleHandle.set3Double(point.x, point.y, point.z)
scaleArrayHandle.setAllClean()
scaleArrayHandle.setClean()
def updateInstanceRotations(self, curveFn, dataBlock, count, distOffset ):
point = OpenMaya.MPoint()
curveLength = curveFn.length()
rotationArrayHandle = dataBlock.outputArrayValue(instanceAlongCurveLocator.outputRotationAttr.compound)
startOrientation = dataBlock.outputValue(instanceAlongCurveLocator.inputOrientationAxisAttr.compound).asVector().normal()
# Deterministic random
random.seed(count)
rampValues = instanceAlongCurveLocator.RampValueContainer(self.thisMObject(), dataBlock, instanceAlongCurveLocator.rotationRampAttr, True)
rotMode = dataBlock.inputValue(instanceAlongCurveLocator.orientationModeAttr).asInt()
inputTransformPlug = OpenMaya.MPlug(self.thisMObject(), instanceAlongCurveLocator.inputTransformAttr)
inputTransformRotation = OpenMaya.MQuaternion()
if inputTransformPlug.isConnected():
self.getInputTransformFn().getRotation(inputTransformRotation, OpenMaya.MSpace.kWorld)
for i in xrange(min(count, rotationArrayHandle.elementCount())):
rampValue = self.getRampValueAtPosition(rampValues, i, count)
dist = math.fmod(curveLength * (i / float(count)) + distOffset, curveLength)
# EP curves **really** dont like param at 0.0
param = max( min( curveFn.findParamFromLength( dist ), curveLength ), 0.002 )
rot = OpenMaya.MQuaternion()
try:
normal = curveFn.normal(param).normal()
tangent = curveFn.tangent(param).normal()
bitangent = (normal ^ tangent).normal()
except:
print 'curveFn normal get error. param:%f/length:%f' % ( param, curveLength )
if rotMode == 1:
rot = inputTransformRotation;
elif rotMode == 2:
rot = startOrientation.rotateTo(normal)
elif rotMode == 3:
rot = startOrientation.rotateTo(tangent)
elif rotMode == 4:
rot = startOrientation.rotateTo(tangent)
if i % 2 == 1:
rot *= OpenMaya.MQuaternion(3.141592 * .5, tangent)
twistNormal = self.getRandomizedValue(random, rampValues.rampRandomAmplitude, rampValue * rampValues.rampAmplitude) * rampValues.rampAxis.x
twistNormal = OpenMaya.MQuaternion(twistNormal * 0.0174532925, normal) # DegToRad
twistTangent = self.getRandomizedValue(random, rampValues.rampRandomAmplitude, rampValue * rampValues.rampAmplitude) * rampValues.rampAxis.y
twistTangent = OpenMaya.MQuaternion(twistTangent * 0.0174532925, tangent) # DegToRad
twistBitangent = self.getRandomizedValue(random, rampValues.rampRandomAmplitude, rampValue * rampValues.rampAmplitude) * rampValues.rampAxis.z
twistBitangent = OpenMaya.MQuaternion(twistBitangent * 0.0174532925, bitangent) # DegToRad
rot = (rot * twistNormal * twistTangent * twistBitangent).asEulerRotation().asVector()
rotationArrayHandle.jumpToArrayElement(i)
rotationHandle = rotationArrayHandle.outputValue()
rotationHandle.set3Double(rot.x, rot.y, rot.z)
rotationArrayHandle.setAllClean()
rotationArrayHandle.setClean()
def isBounded(self):
return True
def boundingBox(self):
return OpenMaya.MBoundingBox(OpenMaya.MPoint(-1,-1,-1), OpenMaya.MPoint(1,1,1))
def compute(self, plug, dataBlock):
try:
curveDataHandle = dataBlock.inputValue(instanceAlongCurveLocator.inputCurveAttr)
curve = curveDataHandle.asNurbsCurveTransformed()
if not curve.isNull():
curveFn = OpenMaya.MFnNurbsCurve(curve)
instanceCount = self.getInstanceCountByMode()
distOffset = self.getParamOffset()
if plug == instanceAlongCurveLocator.outputTranslationAttr.compound:
self.updateInstancePositions(curveFn, dataBlock, instanceCount, distOffset)
if plug == instanceAlongCurveLocator.outputRotationAttr.compound:
self.updateInstanceRotations(curveFn, dataBlock, instanceCount, distOffset)
if plug == instanceAlongCurveLocator.outputScaleAttr.compound:
self.updateInstanceScale(curveFn, dataBlock, instanceCount)
except:
sys.stderr.write('Failed trying to compute locator. stack trace: \n')
sys.stderr.write(traceback.format_exc())
return OpenMaya.kUnknownParameter
@staticmethod
def nodeCreator():
return OpenMayaMPx.asMPxPtr( instanceAlongCurveLocator() )
@classmethod
def addCompoundVector3Attribute(cls, compoundAttribute, attributeName, unitType, arrayAttr, inputAttr, defaultValue):
unitAttr = OpenMaya.MFnUnitAttribute()
nAttr = OpenMaya.MFnNumericAttribute()
compoundAttribute.x = unitAttr.create(attributeName + "X", attributeName + "X", unitType, defaultValue.x)
unitAttr.setWritable( inputAttr )
cls.addAttribute(compoundAttribute.x)
compoundAttribute.y = unitAttr.create(attributeName + "Y", attributeName + "Y", unitType, defaultValue.y)
unitAttr.setWritable( inputAttr )
cls.addAttribute(compoundAttribute.y)
compoundAttribute.z = unitAttr.create(attributeName + "Z", attributeName + "Z", unitType, defaultValue.z)
unitAttr.setWritable( inputAttr )
cls.addAttribute(compoundAttribute.z)
# Output compound
compoundAttribute.compound = nAttr.create(attributeName, attributeName,
compoundAttribute.x, compoundAttribute.y, compoundAttribute.z)
nAttr.setWritable( inputAttr )
nAttr.setArray( arrayAttr )
nAttr.setUsesArrayDataBuilder( arrayAttr )
nAttr.setDisconnectBehavior(OpenMaya.MFnAttribute.kDelete)
cls.addAttribute(compoundAttribute.compound)
@classmethod
def addRampAttributes(cls, rampAttributes, attributeName, unitType, defaultAxisValue):
unitAttr = OpenMaya.MFnUnitAttribute()
nAttr = OpenMaya.MFnNumericAttribute()
rampAttributes.ramp = OpenMaya.MRampAttribute.createCurveRamp(attributeName + "Ramp", attributeName + "Ramp")
cls.addAttribute(rampAttributes.ramp)
rampAttributes.rampOffset = nAttr.create(attributeName + "RampOffset", attributeName + "RampOffset", OpenMaya.MFnNumericData.kFloat, 0.0)
nAttr.setKeyable( True )
cls.addAttribute( rampAttributes.rampOffset )
rampAttributes.rampAmplitude = nAttr.create(attributeName + "RampAmplitude", attributeName + "RampAmplitude", OpenMaya.MFnNumericData.kFloat, 1.0)
nAttr.setKeyable( True )
cls.addAttribute( rampAttributes.rampAmplitude )
rampAttributes.rampRandomAmplitude = nAttr.create(attributeName + "RampRandomAmplitude", attributeName + "RampRandomAmplitude", OpenMaya.MFnNumericData.kFloat, 0.0)
nAttr.setMin(0.0)
nAttr.setSoftMax(1.0)
nAttr.setKeyable( True )
cls.addAttribute( rampAttributes.rampRandomAmplitude )
cls.addCompoundVector3Attribute(rampAttributes.rampAxis, attributeName + "RampAxis", unitType, False, True, defaultAxisValue)
@staticmethod
def nodeInitializer():
# To make things more readable
node = instanceAlongCurveLocator
nAttr = OpenMaya.MFnNumericAttribute()
msgAttributeFn = OpenMaya.MFnMessageAttribute()
curveAttributeFn = OpenMaya.MFnTypedAttribute()
enumFn = OpenMaya.MFnEnumAttribute()
node.inputTransformAttr = msgAttributeFn.create("inputTransform", "it")
node.addAttribute( node.inputTransformAttr )
node.inputShadingGroupAttr = msgAttributeFn.create("inputShadingGroup", "iSG")
node.addAttribute( node.inputShadingGroupAttr )
# Input curve transform
node.inputCurveAttr = curveAttributeFn.create( 'inputCurve', 'curve', OpenMaya.MFnData.kNurbsCurve)
node.addAttribute( node.inputCurveAttr )
## Input instance count
node.instanceCountAttr = nAttr.create("instanceCount", "iic", OpenMaya.MFnNumericData.kInt, 5)
nAttr.setMin(1)
nAttr.setSoftMax(100)
nAttr.setChannelBox( False )
nAttr.setConnectable( False )
node.addAttribute( node.instanceCountAttr)
## curve parameter start offset
node.distOffsetAttr = nAttr.create("distOffset", "pOffset", OpenMaya.MFnNumericData.kFloat, 0.0)
node.addAttribute( node.distOffsetAttr )
## Max instances when defined by instance length
node.maxInstancesByLengthAttr = nAttr.create("maxInstancesByLength", "mibl", OpenMaya.MFnNumericData.kInt, 50)
nAttr.setMin(0)
nAttr.setSoftMax(200)
nAttr.setChannelBox( False )
nAttr.setConnectable( False )
node.addAttribute( node.maxInstancesByLengthAttr)
# Length between instances
node.instanceLengthAttr = nAttr.create("instanceLength", "ilength", OpenMaya.MFnNumericData.kFloat, 1.0)
nAttr.setMin(0.01)
nAttr.setSoftMax(1.0)
nAttr.setChannelBox( False )
nAttr.setConnectable( False )
node.addAttribute( node.instanceLengthAttr)
# Display override options
node.displayTypeAttr = enumFn.create('instanceDisplayType', 'idt')
enumFn.addField( "Normal", 0 );
enumFn.addField( "Template", 1 );
enumFn.addField( "Reference", 2 );
enumFn.setDefault("Reference")
node.addAttribute( node.displayTypeAttr )
# Enum for selection of instancing mode
node.instancingModeAttr = enumFn.create('instancingMode', 'instancingMode')
enumFn.addField( "Count", 0 );
enumFn.addField( "Distance", 1 );
node.addAttribute( node.instancingModeAttr )
# Enum for selection of orientation mode
node.orientationModeAttr = enumFn.create('orientationMode', 'rotMode')
enumFn.addField( "Identity", 0 );
enumFn.addField( "Copy from Source", 1 );
enumFn.addField( "Normal", 2 );
enumFn.addField( "Tangent", 3 );
enumFn.addField( "Chain", 4 );
enumFn.setDefault("Tangent")
node.addAttribute( node.orientationModeAttr )
node.addCompoundVector3Attribute(node.inputOrientationAxisAttr, "inputOrientationAxis", OpenMaya.MFnUnitAttribute.kDistance, False, True, OpenMaya.MVector(0.0, 0.0, 1.0))
node.bboxAttr = nAttr.create('instanceBoundingBox', 'ibb', OpenMaya.MFnNumericData.kBoolean)
node.addAttribute( node.bboxAttr )
node.addRampAttributes(node.positionRampAttr, "position", OpenMaya.MFnUnitAttribute.kDistance, OpenMaya.MVector(0.0, 0.0, 0.0))
node.addRampAttributes(node.rotationRampAttr, "rotation", OpenMaya.MFnUnitAttribute.kAngle, OpenMaya.MVector(0.0, 0.0, 0.0))
node.addRampAttributes(node.scaleRampAttr, "scale", OpenMaya.MFnUnitAttribute.kDistance, OpenMaya.MVector(1.0, 1.0, 1.0))
# Output attributes
node.addCompoundVector3Attribute(node.outputTranslationAttr, "outputTranslation", OpenMaya.MFnUnitAttribute.kDistance, True, False, OpenMaya.MVector(0.0, 0.0, 0.0))
node.addCompoundVector3Attribute(node.outputRotationAttr, "outputRotation", OpenMaya.MFnUnitAttribute.kAngle, True, False, OpenMaya.MVector(0.0, 0.0, 0.0))
node.addCompoundVector3Attribute(node.outputScaleAttr, "outputScale", OpenMaya.MFnUnitAttribute.kDistance, True, False, OpenMaya.MVector(1.0, 1.0, 1.0))
def rampAttributeAffects(rampAttributes, affectedAttr):
node.attributeAffects( rampAttributes.ramp, affectedAttr)
node.attributeAffects( rampAttributes.rampOffset, affectedAttr)
node.attributeAffects( rampAttributes.rampAmplitude, affectedAttr)
node.attributeAffects( rampAttributes.rampAxis.compound, affectedAttr)
node.attributeAffects( rampAttributes.rampRandomAmplitude, affectedAttr)
# Translation affects
node.attributeAffects( node.inputCurveAttr, node.outputTranslationAttr.compound )
node.attributeAffects( node.instanceCountAttr, node.outputTranslationAttr.compound)
node.attributeAffects( node.instanceLengthAttr, node.outputTranslationAttr.compound)
node.attributeAffects( node.instancingModeAttr, node.outputTranslationAttr.compound)
node.attributeAffects( node.maxInstancesByLengthAttr, node.outputTranslationAttr.compound)
node.attributeAffects( node.distOffsetAttr, node.outputTranslationAttr.compound )
rampAttributeAffects(node.positionRampAttr, node.outputTranslationAttr.compound)
# Rotation affects
node.attributeAffects( node.inputCurveAttr, node.outputRotationAttr.compound )
node.attributeAffects( node.instanceCountAttr, node.outputRotationAttr.compound)
node.attributeAffects( node.instanceLengthAttr, node.outputRotationAttr.compound)
node.attributeAffects( node.instancingModeAttr, node.outputRotationAttr.compound)
node.attributeAffects( node.maxInstancesByLengthAttr, node.outputRotationAttr.compound)
node.attributeAffects( node.orientationModeAttr, node.outputRotationAttr.compound)
node.attributeAffects( node.distOffsetAttr, node.outputRotationAttr.compound )
node.attributeAffects( node.inputOrientationAxisAttr.compound, node.outputRotationAttr.compound)
rampAttributeAffects(node.rotationRampAttr, node.outputRotationAttr.compound)
# Scale affects
node.attributeAffects( node.inputCurveAttr, node.outputScaleAttr.compound )
node.attributeAffects( node.instanceCountAttr, node.outputScaleAttr.compound)
node.attributeAffects( node.instanceLengthAttr, node.outputScaleAttr.compound)
node.attributeAffects( node.instancingModeAttr, node.outputScaleAttr.compound)
node.attributeAffects( node.maxInstancesByLengthAttr, node.outputScaleAttr.compound)
node.attributeAffects( node.distOffsetAttr, node.outputScaleAttr.compound )
rampAttributeAffects(node.scaleRampAttr, node.outputScaleAttr.compound)
def initializePlugin( mobject ):
mplugin = OpenMayaMPx.MFnPlugin( mobject )
try:
# Register command
mplugin.registerCommand( kPluginCmdName, instanceAlongCurveCommand.cmdCreator )
if OpenMaya.MGlobal.mayaState() != OpenMaya.MGlobal.kBatch:
mplugin.addMenuItem("Instance Along Curve", "MayaWindow|mainEditMenu", kPluginCmdName, "")
# Register AE template
pm.callbacks(addCallback=loadAETemplateCallback, hook='AETemplateCustomContent', owner=kPluginNodeName)
# Register node
mplugin.registerNode( kPluginNodeName, kPluginNodeId, instanceAlongCurveLocator.nodeCreator,
instanceAlongCurveLocator.nodeInitializer, OpenMayaMPx.MPxNode.kLocatorNode, kPluginNodeClassify )
except:
sys.stderr.write('Failed to register plugin instanceAlongCurve. stack trace: \n')
sys.stderr.write(traceback.format_exc())
raise
def uninitializePlugin( mobject ):
mplugin = OpenMayaMPx.MFnPlugin( mobject )
try:
mplugin.deregisterCommand( kPluginCmdName )
mplugin.deregisterNode( kPluginNodeId )
except:
sys.stderr.write( 'Failed to deregister plugin instanceAlongCurve')
raise
###############
# AE TEMPLATE #
###############
def loadAETemplateCallback(nodeName):
AEinstanceAlongCurveLocatorTemplate(nodeName)
class AEinstanceAlongCurveLocatorTemplate(pm.ui.AETemplate):
def addControl(self, control, label=None, **kwargs):
pm.ui.AETemplate.addControl(self, control, label=label, **kwargs)
def beginLayout(self, name, collapse=True):
pm.ui.AETemplate.beginLayout(self, name, collapse=collapse)
def __init__(self, nodeName):
pm.ui.AETemplate.__init__(self,nodeName)
self.thisNode = None
self.node = pm.PyNode(self.nodeName)
if self.node.type() == kPluginNodeName:
self.beginScrollLayout()
self.beginLayout("Instance Along Curve Settings", collapse=0)
self.addControl("instancingMode", label="Instancing Mode", changeCommand=self.onInstanceModeChanged)
self.addControl("instanceCount", label="Count", changeCommand=self.onInstanceModeChanged)
self.addControl("instanceLength", label="Distance", changeCommand=self.onInstanceModeChanged)
self.addControl("maxInstancesByLength", label="Max Instances", changeCommand=self.onInstanceModeChanged)
self.addControl("distOffset", label="Initial Position Offset", changeCommand=lambda nodeName: self.updateDimming(nodeName, "distOffset"))
self.addSeparator()
self.addControl("orientationMode", label="Orientation Mode", changeCommand=lambda nodeName: self.updateDimming(nodeName, "orientationMode"))
self.addControl("inputOrientationAxis", label="Orientation Axis", changeCommand=lambda nodeName: self.updateDimming(nodeName, "inputOrientationAxis"))
self.addSeparator()
self.addControl("instanceDisplayType", label="Instance Display Type", changeCommand=lambda nodeName: self.updateDimming(nodeName, "instanceDisplayType"))
self.addControl("instanceBoundingBox", label="Use bounding box", changeCommand=lambda nodeName: self.updateDimming(nodeName, "instanceBoundingBox"))
self.addSeparator()
self.addControl("inputTransform", label="Input object", changeCommand=lambda nodeName: self.updateDimming(nodeName, "inputTransform"))
self.addControl("inputShadingGroup", label="Shading Group", changeCommand=lambda nodeName: self.updateDimming(nodeName, "inputShadingGroup"))
def showRampControls(rampName):
self.beginLayout(rampName.capitalize() + " Control", collapse=True)
mel.eval('AEaddRampControl("' + nodeName + "." + rampName + 'Ramp"); ')
self.addControl(rampName + "RampOffset", label= rampName.capitalize() + " Ramp Offset")
self.addControl(rampName + "RampAmplitude", label= rampName.capitalize() + " Ramp Amplitude")
self.addControl(rampName + "RampRandomAmplitude", label= rampName.capitalize() + " Ramp Random")
self.addControl(rampName + "RampAxis", label= rampName.capitalize() + " Ramp Axis")
self.endLayout()
showRampControls("position")
showRampControls("rotation")
showRampControls("scale")
self.addExtraControls()
self.endLayout()
self.endScrollLayout()
def onRampUpdate(self, attr):
pm.gradientControl(attr)
def updateDimming(self, nodeName, attr):
if pm.PyNode(nodeName).type() == kPluginNodeName:
node = pm.PyNode(nodeName)
instanced = node.isInstanced()
hasInputTransform = node.inputTransform.isConnected()
hasInputCurve = node.inputCurve.isConnected()
self.dimControl(nodeName, attr, instanced or (not hasInputCurve) or (not hasInputTransform))
def onInstanceModeChanged(self, nodeName):
self.updateDimming(nodeName, "instancingMode")
if pm.PyNode(nodeName).type() == kPluginNodeName:
nodeAttr = pm.PyNode(nodeName + ".instancingMode")
mode = nodeAttr.get("instancingMode")
# If dimmed, do not update dimming
if mode == 0:
self.dimControl(nodeName, "instanceLength", True)
self.dimControl(nodeName, "maxInstancesByLength", True)
self.updateDimming(nodeName, "instanceCount")
else:
self.updateDimming(nodeName, "instanceLength")
self.updateDimming(nodeName, "maxInstancesByLength")
self.dimControl(nodeName, "instanceCount", True)
# Command
class instanceAlongCurveCommand(OpenMayaMPx.MPxCommand):
def __init__(self):
OpenMayaMPx.MPxCommand.__init__(self)
self.mUndo = []
def isUndoable(self):
return True
def undoIt(self):
OpenMaya.MGlobal.displayInfo( "Undo: instanceAlongCurveCommand\n" )
# Reversed for undo :)
for m in reversed(self.mUndo):
m.undoIt()
def redoIt(self):
OpenMaya.MGlobal.displayInfo( "Redo: instanceAlongCurveCommand\n" )
for m in self.mUndo:
m.doIt()
def hasShapeBelow(self, dagPath):
sutil = OpenMaya.MScriptUtil()
uintptr = sutil.asUintPtr()
sutil.setUint(uintptr , 0)
dagPath.numberOfShapesDirectlyBelow(uintptr)
return sutil.getUint(uintptr) > 0
def findShadingGroup(self, dagPath):
# Search in children first before extending to shape
for child in xrange(dagPath.childCount()):
childDagPath = OpenMaya.MDagPath()
fnDagNode = OpenMaya.MFnDagNode(dagPath.child(child))
fnDagNode.getPath(childDagPath)
fnSet = self.findShadingGroup(childDagPath)
if fnSet is not None:
return fnSet
if self.hasShapeBelow(dagPath):
dagPath.extendToShape()
fnDepNode = OpenMaya.MFnDependencyNode(dagPath.node())
instPlugArray = fnDepNode.findPlug("instObjGroups")
instPlugArrayElem = instPlugArray.elementByLogicalIndex(dagPath.instanceNumber())
if instPlugArrayElem.isConnected():
connectedPlugs = OpenMaya.MPlugArray()
instPlugArrayElem.connectedTo(connectedPlugs, False, True)
if connectedPlugs.length() == 1:
sgNode = connectedPlugs[0].node()
if sgNode.hasFn(OpenMaya.MFn.kSet):
return OpenMaya.MFnSet(sgNode)
return None
def doIt(self,argList):
try:
list = OpenMaya.MSelectionList()
OpenMaya.MGlobal.getActiveSelectionList(list)
if list.length() == 2:
curveDagPath = OpenMaya.MDagPath()
list.getDagPath(0, curveDagPath)
curveDagPath.extendToShape()
shapeDagPath = OpenMaya.MDagPath()
list.getDagPath(1, shapeDagPath)
if(curveDagPath.node().hasFn(OpenMaya.MFn.kNurbsCurve)):
# We need the curve transform
curvePlug = OpenMaya.MFnDagNode(curveDagPath).findPlug("worldSpace", False).elementByLogicalIndex(0)
# We need the shape's transform too
transformFn = OpenMaya.MFnDagNode(shapeDagPath.transform())
transformMessagePlug = transformFn.findPlug("message", True)
shadingGroupFn = self.findShadingGroup(shapeDagPath)
# Create node first
mdagModifier = OpenMaya.MDagModifier()
self.mUndo.append(mdagModifier)
newNode = mdagModifier.createNode(kPluginNodeId)
mdagModifier.doIt()
# Assign new correct name and select new locator
newNodeFn = OpenMaya.MFnDagNode(newNode)
newNodeFn.setName("instanceAlongCurveLocator#")
newNodeTransformName = newNodeFn.name()
# Get the node shape
nodeShapeDagPath = OpenMaya.MDagPath()
newNodeFn.getPath(nodeShapeDagPath)
nodeShapeDagPath.extendToShape()
newNodeFn = OpenMaya.MFnDagNode(nodeShapeDagPath)
def setupRamp(rampAttr):
# Set default ramp values
defaultPositions = OpenMaya.MFloatArray(1, 0.0)
defaultValues = OpenMaya.MFloatArray(1, 1.0)
defaultInterpolations = OpenMaya.MIntArray(1, 3)
plug = newNodeFn.findPlug(rampAttr.ramp)
ramp = OpenMaya.MRampAttribute(plug)
ramp.addEntries(defaultPositions, defaultValues, defaultInterpolations)
setupRamp(instanceAlongCurveLocator.positionRampAttr)
setupRamp(instanceAlongCurveLocator.rotationRampAttr)
setupRamp(instanceAlongCurveLocator.scaleRampAttr)
# Select new node shape
OpenMaya.MGlobal.clearSelectionList()
msel = OpenMaya.MSelectionList()
msel.add(nodeShapeDagPath)
OpenMaya.MGlobal.setActiveSelectionList(msel)
# Connect :D
mdgModifier = OpenMaya.MDGModifier()
self.mUndo.append(mdgModifier)
mdgModifier.connect(curvePlug, newNodeFn.findPlug(instanceAlongCurveLocator.inputCurveAttr))
mdgModifier.connect(transformMessagePlug, newNodeFn.findPlug(instanceAlongCurveLocator.inputTransformAttr))
if shadingGroupFn is not None:
shadingGroupMessagePlug = shadingGroupFn.findPlug("message", True)
mdgModifier.connect(shadingGroupMessagePlug, newNodeFn.findPlug(instanceAlongCurveLocator.inputShadingGroupAttr))
mdgModifier.doIt()
# (pymel) create a locator and make it the parent
locator = pm.createNode('locator', ss=True, p=newNodeTransformName)
# Show AE
mel.eval("openAEWindow")
instanceCountPlug = newNodeFn.findPlug("instanceCount", False)
instanceCountPlug.setInt(10)
else:
sys.stderr.write("Please select a curve first")
else:
sys.stderr.write("Please select a curve and a shape")
except:
sys.stderr.write('Failed trying to create locator. stack trace: \n')
sys.stderr.write(traceback.format_exc())
@staticmethod
def cmdCreator():
return OpenMayaMPx.asMPxPtr( instanceAlongCurveCommand() )
``` |
{
"source": "jonntd/maya-pip",
"score": 2
} |
#### File: jonntd/maya-pip/setup.py
```python
import codecs
import os
import re
import sys
from setuptools import find_packages, setup
# ----------------------------------------------------------------------------
def read(*parts):
with codecs.open(os.path.join(here, *parts), 'r') as fp:
return fp.read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file,
re.M,
)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
here = os.path.abspath(os.path.dirname(__file__))
long_description = read("README.rst")
# ----------------------------------------------------------------------------
setup(
name="mayapip",
version=find_version("src", "mayapip", "__init__.py"),
author="<NAME>",
author_email="<EMAIL>",
package_dir={"": "src"},
packages=find_packages(
where="src",
exclude=["contrib", "docs", "tests*", "tasks"],
),
license="MIT",
description="The Maya wrapper to pip for installing Python packages",
long_description=long_description,
keywords="pip maya",
entry_points={
"console_scripts": [
"mayapip=mayapip._internal:main",
]
}
)
```
#### File: _internal/maya/__init__.py
```python
import platform
# declare variable in case operating system is not supported
get_python_executables = None
# get maya python executables based on platform
if platform.system() == "Windows":
from .maya_windows import get_python_executables
elif platform.system() == "Linux":
from .maya_linux import get_python_executables
def has_python_executables():
"""
:return: If python executables are found
:rtype: bool
"""
return True \
if get_python_executables and get_python_executables() \
else False
``` |
{
"source": "jonntd/maya-ziva-dynamics-utils",
"score": 3
} |
#### File: zManager/items/base.py
```python
from PySide2 import QtWidgets
from .. import widgets
class TreeItem(QtWidgets.QTreeWidgetItem):
def __init__(self, parent):
super(TreeItem, self).__init__(parent)
# variable
self._widget = None
# ------------------------------------------------------------------------
@property
def widget(self):
"""
:return: Widget
:rtype: QWidget
"""
return self._widget
# ------------------------------------------------------------------------
def allParents(self):
"""
:return: All parents
:rtype: list
"""
parents = []
parent = self.parent()
while parent:
parents.append(parent)
parent = parent.parent()
return parents
# ------------------------------------------------------------------------
def addWidget(self, widget):
"""
:param QWidget widget:
"""
self._widget = widget
self.treeWidget().setItemWidget(self, 0, widget)
class LabelItem(TreeItem):
def __init__(self, parent, text):
super(LabelItem, self).__init__(parent)
widget = widgets.Label(self.treeWidget(), text)
self.addWidget(widget)
class CheckBoxItem(TreeItem):
def __init__(self, parent, text):
super(CheckBoxItem, self).__init__(parent)
widget = widgets.CheckBox(self.treeWidget(), text)
self.addWidget(widget)
```
#### File: zManager/items/mesh.py
```python
from PySide2 import QtWidgets, QtGui
from maya import cmds
from .. import icons, widgets
from . import base, nodeTypes
from .nodeMapper import NODE_TYPES_WRAPPER
# ----------------------------------------------------------------------------
NODE_TYPES = cmds.pluginInfo("ziva.mll", query=True, dependNode=True)
NODE_TYPES.sort()
# ----------------------------------------------------------------------------
class MeshItem(base.TreeItem):
def __init__(self, parent, node):
super(MeshItem, self).__init__(parent)
# variable
self._search = node.lower()
# add widgets
widget = widgets.Node(self.treeWidget(), node)
self.addWidget(widget)
self.setIcon(0, QtGui.QIcon(icons.MESH_ICON))
# add types
for t in NODE_TYPES:
# validate node type
w = NODE_TYPES_WRAPPER.get(t)
if not w:
continue
# get nodes
try:
connections = cmds.zQuery(node, type=t) or []
connections.sort()
except:
continue
# validate connections
if not connections:
continue
# create node type container
nodeTypes.ZivaNodeTypeItem(self, t, connections)
# add line of actions
# get fibers
fibers = cmds.zQuery(node, type="zFiber")
if not fibers:
return
# get attached line of actions
lineOfActions = cmds.zQuery(fibers, lineOfAction=True)
if not lineOfActions:
return
# add line of actions
nodeTypes.ZivaNodeTypeItem(self, "zLineOfAction", lineOfActions)
# ------------------------------------------------------------------------
@property
def search(self):
"""
:return: Search string for filtering
:rtype: str
"""
return self._search
```
#### File: zManager/widgets/base.py
```python
from PySide2 import QtWidgets
class Label(QtWidgets.QLabel):
def __init__(self, parent, text):
super(Label, self).__init__(parent)
self.setText(text)
class CheckBox(QtWidgets.QCheckBox):
def __init__(self, parent, text):
super(CheckBox, self).__init__(parent)
self.setText(text)
class Button(QtWidgets.QPushButton):
def __init__(self, parent, text):
super(Button, self).__init__(parent)
self.setText(text)
self.setFlat(True)
self.setFixedHeight(19)
self.setStyleSheet("text-align: left")
```
#### File: zManager/widgets/nodes.py
```python
from PySide2 import QtWidgets
from maya import cmds
from .base import Button
class Node(QtWidgets.QWidget):
def __init__(self, parent, node, text=None):
super(Node, self).__init__(parent)
# variable
self._node = node
text = text if text else node
# create layout
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
# add combo box
button = Button(self, text)
button.released.connect(self.doSelect)
layout.addWidget(button)
# ------------------------------------------------------------------------
@property
def node(self):
"""
:return: Node
:rtype: str
"""
return self._node
# ------------------------------------------------------------------------
def doSelect(self):
if cmds.objExists(self.node):
cmds.select(self.node)
```
#### File: zManager/widgets/search.py
```python
from PySide2 import QtWidgets, QtCore, QtGui
from maya import cmds, mel
from .. import icons
class SearchField(QtWidgets.QWidget):
searchChanged = QtCore.Signal(str)
def __init__(self, parent):
super(SearchField, self).__init__(parent)
# create layout
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(3)
# add line edit
self.le = QtWidgets.QLineEdit(self)
self.le.setPlaceholderText("search...")
self.le.textChanged.connect(self.searchChanged.emit)
layout.addWidget(self.le)
# add clear button
clear = QtWidgets.QPushButton(self)
clear.setFlat(True)
clear.setIcon(QtGui.QIcon(icons.CLOSE_ICON))
clear.setFixedSize(QtCore.QSize(19, 19))
clear.released.connect(self.doClear)
layout.addWidget(clear)
# add select button
select = QtWidgets.QPushButton(self)
select.setFlat(True)
select.setIcon(QtGui.QIcon(icons.SELECT_ICON))
select.setFixedSize(QtCore.QSize(19, 19))
select.released.connect(self.fromSelection)
layout.addWidget(select)
# ------------------------------------------------------------------------
@property
def text(self):
"""
:return: Search text
:rtype: str
"""
return self.le.text()
# ------------------------------------------------------------------------
def doClear(self):
"""
Clear the search line edit of any text, which will still trigger the
searchChanged signal to be triggered.
"""
self.le.setText("")
def fromSelection(self):
"""
Set the search field string to the name of the first node selected.
If nothing is selected a RuntimeError is raised.
"""
# get selection
sel = cmds.ls(sl=True)
# validate selection
if not sel:
raise RuntimeError("Selection is clear!")
# set selection
self.le.setText(sel[0])
``` |
{
"source": "jonntd/MLDeform",
"score": 3
} |
#### File: MLDeform/_maya/writer.py
```python
import csv
import json
import logging
import math
import os
import maya.api.OpenMaya as om
import maya.api.OpenMayaAnim as oma
import maya.cmds as mc
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
from . import skinning
DEFAULT_LOCATION = os.path.join(mc.internalVar(userAppDir=True), 'training')
def write(path, target, skin=None, outdir=None, start=None, end=None):
"""
Write out data for the machine learning algorithm to train from.
:param path: The path to the mesh we're writing data for.
:param target: The target mesh to compare the vertices to.
:param skin: The skin cluster to read weights from.
:param outdir: The directory to write to. If no directory is provided, uses training directory.
:param start: The start frame to write from.
:param end: The end frame to write to
:return: The path to the written data.
"""
# Make sure we can write out the data
if not outdir:
logger.warning('No output directory specified. Using default: %s', DEFAULT_LOCATION)
outdir = DEFAULT_LOCATION
if not os.path.exists(outdir):
os.mkdir(outdir)
# Figure out the start and end range
if start is None:
start = mc.playbackOptions(minTime=True, query=True)
if end is None:
end = mc.playbackOptions(maxTime=True, query=True)
start = int(math.floor(start))
end = int(math.ceil(end))
currentTime = mc.currentTime(query=True)
# Get the meshes
sel = om.MSelectionList()
sel.add(skinning.get_mesh(path))
sel.add(skinning.get_mesh(target))
mesh = om.MFnMesh(sel.getDagPath(0))
target_mesh = om.MFnMesh(sel.getDagPath(1))
# Get the skin cluster
if not skin:
skin = skinning.get_skincluster(mesh.fullPathName())
sel.add(skin)
skin_node = sel.getDependNode(2)
skin_cluster = oma.MFnSkinCluster(skin_node)
# Get the weights
vertices = range(mesh.numVertices)
influence_objects = skin_cluster.influenceObjects()
joints = [i.fullPathName() for i in influence_objects]
joint_transforms = [om.MFnTransform(j) for j in influence_objects]
influence_indexes, vertex_cmpt, weights = skinning.get_weights(mesh, skin_cluster, vertices)
stride = len(influence_indexes)
# Store the weight associations for vertices
weight_map = []
joint_map = []
for i in range(stride):
joint_map.append(list())
for vtx in vertices:
vtx_weights = weights[vtx * stride: (vtx * stride) + stride]
for i, weight in enumerate(vtx_weights):
if weight > 0:
weight_map.append(i)
joint_map[i].append(vtx)
break
# Prepare data for joints
frame_data = {}
for joint in joints:
frame_data[joint] = []
# Go through every frame and write out the data for all the joints and the vertexes
for frame in range(start, end + 1):
logger.debug('Processing frame %s', frame)
mc.currentTime(frame)
points = mesh.getPoints()
target_points = target_mesh.getPoints()
for jidx, vertices in enumerate(joint_map):
xform = joint_transforms[jidx]
rotation = xform.rotation(om.MSpace.kWorld, asQuaternion=True)
translate = xform.translation(om.MSpace.kWorld)
data = []
data += rotation
data += translate
for vtx in vertices:
mpoint = points[vtx]
tpoint = target_points[vtx]
displacement = tpoint - mpoint
data += displacement
frame_data[joints[jidx]].append(data)
# Write the data out to csv files
csv_files = []
for joint in joints:
data = frame_data[joint]
filename = '%s.csv' % joint.replace('|', '_')
if filename.startswith('_'):
filename = filename[1:]
filename = os.path.join(outdir, filename)
logger.info('Wrote data for %s to %s', joint, filename)
heading = ['rx', 'ry', 'rz', 'rw', 'tx', 'ty', 'tz']
verts = joint_map[joints.index(joint)]
for v in verts:
heading.extend(['vtx%sx' % v, 'vtx%sy' % v, 'vtx%sz' % v])
with open(filename, 'w') as f:
writer = csv.writer(f)
writer.writerow(heading)
writer.writerows(data)
csv_files.append(filename)
mc.currentTime(currentTime)
map_data = {
'joint_names': joints,
'joint_indexes': [i for i in influence_indexes],
'weights': weight_map,
'csv_files': csv_files,
'joint_map': joint_map,
'input_fields': ['rx', 'ry', 'rz', 'rw', 'tx', 'ty', 'tz']
}
# Finally write out the data
map_file = os.path.join(outdir, 'input_data.json')
with open(map_file, 'w') as f:
json.dump(map_data, f)
logger.info('Wrote Weight Map to %s', map_file)
return outdir
def test_writer():
mc.file('/Users/dhruv/Projects/MLDeform/TestScenes/Cylinder.ma', open=True, force=True)
mc.currentTime(1)
mesh = skinning.clone_mesh('Tube')
skinning.skin_mesh(mesh)
skinning.simplify_weights(mesh, fast=True)
mc.setAttr('Tube.visibility', False)
return write(mesh, 'Tube', outdir=DEFAULT_LOCATION)
``` |
{
"source": "jonntd/PipelineTools",
"score": 2
} |
#### File: PipelineTools/core/rig_class.py
```python
import os
import pymel.core as pm
import general_utils as ul
import rigging_utils as ru
import math
from pymel.util.enum import Enum
from ..packages.Red9.core import Red9_Meta as meta
import logging
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
# print meta
# log.info('Rig Class Initilize')
class CHRig(meta.MetaHIKCharacterNode):
def __init__(self, name='', hikName='CH'):
super(FacialRigMeta, self).__init__(hikname, **kws)
self.setascurrentcharacter()
self.select()
self.hikProperty = self.getHIKPropertyStateNode()
self.hikControl = self.getHIKControlSetNode()
# self.character.lockState = False
# pm.lockNode(hikName,lock=False)
self.addAttr('CharacterName', name)
self.addAttr('BuildBy', '{} {}'.format(os.environ.get('COMPUTERNAME'), os.environ.get('USERNAME')))
self.addAttr('Branch', os.environ.get('USERDOMAIN'))
self.addAttr('BuildDate', pm.date())
self.addAttr('FacialRig', attrType='messageSimple')
self.addAttr('HairRig', attrType='messageSimple')
self.addAttr('SecondaryRig', attrType='messageSimple')
log.info('%s Initilize' % self.__str__)
def getFacialRig(self):
pass
def getSecondaryRig(self):
pass
class FacialRigMeta(meta.MetaRig):
'''
Facial Rig MetaNode
to get this node use pt.rc.meta.getMetaNodes(mClass='FacialRigMeta')
'''
def __init__(self, *args, **kws):
super(FacialRigMeta, self).__init__(*args, **kws)
self.lockState = False
self.mSystemRoot = False
def __bindData__(self):
'''
build Attribute
'''
###### MetaNode information Attributes
self.addAttr('RigType', 'FacialRig', l=True)
self.addAttr('CharacterName', '')
self.addAttr('BuildBy', '{} {}'.format(os.environ.get('COMPUTERNAME'), os.environ.get('USERNAME')), l=True)
self.addAttr('Branch', os.environ.get('USERDOMAIN'), l=True)
self.addAttr('BuildDate', pm.date(), l=True)
###### Model information Attributes
self.addAttr('FaceGp', attrType='messageSimple')
self.addAttr('EyeGp', attrType='messageSimple')
self.addAttr('FaceRigGp', attrType='messageSimple')
self.addAttr('FaceDeformGp', attrType='message')
self.addAttr('FacialTargetPath', "")
###### Bone Information Attributes
self.addAttr('HeadBone', attrType='messageSimple')
self.addAttr('FacialBone', attrType='messageSimple')
self.addAttr('EyeBone', attrType='messageSimple')
###### Control Hook
# self.addAttr('BlendshapeCtl', attrType='messageSimple')
# self.addAttr('FacialCtl', attrType='message')
# self.addAttr('EyeCtl', attrType='messageSimple')
# self.addAttr('TongueCtl', attrType='messageSimple')
# self.addAttr('JawCtl', attrType='messageSimple')
def connectToPrimary():
pass
def getBlendShapeSystem(self):
BS = self.addSupportMetaNode('BlendshapeCtl', nodeName='facial_panel')
BS.connectChild('facial_panel', 'BSPanel')
BS.connectChild('brow_ctl', 'BrowBSControl')
BS.connectChild('eye_ctl', 'EyeBSControl')
BS.connectChild('mouth_ctl', 'EyeBSControl')
def getProperty(self):
#### connect FaceRigGp to facialGp
if pm.objExists('facialGp'):
self.FaceRigGp = 'facialGp'
#### connect facialGroup
facialGps = []
for gp in ['facial', 'facialGuide', 'jawDeform', 'eyeDeform', 'orig']:
if pm.objExists(gp):
facialGps.append(gp)
self.FaceDeformGp = facialGps
#### get facialTarget External
scenedir = pm.sceneName().dirname()
dir = scenedir.parent
bsdir = pm.util.common.path(dir + '/facialtarget/facialtarget.mb')
if bsdir.isfile():
self.FacialTargetPath = bsdir.replace(pm.workspace.path + '/', '')
def build(self):
pass
class SecondaryRigMeta(meta.MetaRig):
'''
Secondary Rig MetaNode
to get this node use pt.rc.meta.getMetaNodes(mClass='SecondaryRigMeta')
'''
def __init__(self, *args, **kws):
super(SecondaryRigMeta, self).__init__(*args, **kws)
self.lockState = False
self.mSystemRoot = False
def __bindData__(self):
'''
build Attribute
'''
###### MetaNode information Attributes
self.addAttr('RigType', 'SecondaryRig', l=True)
self.addAttr('CharacterName', '')
self.addAttr('BuildBy', '{} {}'.format(os.environ.get('COMPUTERNAME'), os.environ.get('USERNAME')), l=True)
self.addAttr('Branch', os.environ.get('USERDOMAIN'), l=True)
self.addAttr('BuildDate', pm.date(), l=True)
###### Model information Attributes
self.addAttr('secSkinDeformGp', attrType='messageSimple')
###### Bone Information Attributes
self.addAttr('HairControlSet', attrType='messageSimple')
self.addAttr('ClothControlSet', attrType='messageSimple')
###### Control Hook
self.addAttr('ctlGp', attrType='messageSimple')
self.addAttr('bonGp', attrType='message')
self.addAttr('miscGp', attrType='messageSimple')
# self.addAttr('TongueCtl', attrType='messageSimple')
# self.addAttr('JawCtl', attrType='messageSimple')
def connectToPrimary():
pass
def getProperty(self):
#### connect FaceRigGp to facialGp
if pm.ls('_secSkinDeform'):
self.secSkinDeformGp = pm.ls('_secSkinDeform')[0]
if pm.objExists('miscGp'):
self.miscGp = ul.get_node('miscGp')
self.bonGp = ul.get_node('bonGp')
self.ctlGp = ul.get_node('ctlGp')
def build(self):
pass
class HairRigMeta(meta.MetaRig):
'''
Secondary Rig MetaNode
to get this node use pt.rc.meta.getMetaNodes(mClass='SecondaryRigMeta')
'''
def __init__(self, *args, **kws):
super(HairRigMeta, self).__init__(*args, **kws)
self.lockState = False
self.mSystemRoot = False
def __bindData__(self):
'''
build Attribute
'''
###### MetaNode information Attributes
self.addAttr('RigType', 'HairRigMeta', l=True)
def connectToPrimary():
pass
def getProperty(self):
pass
def build(self):
pass
class ClothRigMeta(meta.MetaRig):
'''
Secondary Rig MetaNode
to get this node use meta.getMetaNodes(mClass='SecondaryRigMeta')
'''
def __init__(self, *args, **kws):
# if meta.getMetaNodes(mClass='ClothRigMeta'):
# super(ClothRigMeta, self).__init__(meta.getMetaNodes(mClass='ClothRigMeta'))
# else:
super(ClothRigMeta, self).__init__(*args, **kws)
self.lockState = False
self.mSystemRoot = False
self.controlOb = ControlObject('control')
@property
def controlObject(self, *args, **kwargs):
return self.controlOb
@controlObject.setter
def controlObject(self, *args, **kwargs):
self.controlOb = ControlObject(*args, **kwargs)
def __bindData__(self):
'''
build Attribute
'''
###### MetaNode information Attributes
self.addAttr('RigType', 'ClothRigMeta', l=True)
def connectToPrimary():
pass
def getProperty(self):
pass
def build(self):
pass
class FacialGuide(object):
def __init__(self, name, guide_mesh=None, suffix='loc', root_suffix='Gp'):
self._name = name
self._suffix = suffix
self._root_suffix = root_suffix
self.name = '_'.join([name, suffix])
self.root_name = '_'.join([self.name, root_suffix])
self.constraint_name = '_'.join([self.root_name, 'pointOnPolyConstraint1'])
self.guide_mesh = guide_mesh
self._get()
def __repr__(self):
return self.name
def __call__(self, *args, **kwargs):
self.create(*args, **kwargs)
return self.node
def set_guide_mesh(self, guide_mesh):
if pm.objExists(guide_mesh):
guide_mesh = ul.get_node(guide_mesh)
self.guide_mesh = ul.get_shape(guide_mesh)
else:
'object {} does not contain shape'.format(guide_mesh)
def create(self, pos=[0, 0, 0], parent=None):
self.node = pm.spaceLocator(name=self.name)
if pm.objExists(self.root_name):
self.root = pm.PyNode(self.root_name)
else:
self.root = pm.nt.Transform(name=self.root_name)
self.node.setParent(self.root)
self.root.setTranslation(pos, space='world')
self.root.setParent(parent)
def set_constraint(self, target=None):
if all([self.guide_mesh, self.guide_mesh, self.root]):
pm.delete(self.constraint)
if target is None:
target = self.root
closest_uv = ul.get_closest_component(target, self.guide_mesh)
self.constraint = pm.pointOnPolyConstraint(
self.guide_mesh, self.root, mo=False,
name=self.constraint_name)
stripname = self.guide_mesh.getParent().name().split('|')[-1]
self.constraint.attr(stripname + 'U0').set(closest_uv[0])
self.constraint.attr(stripname + 'V0').set(closest_uv[1])
# pm.select(closest_info['Closest Vertex'])
else:
pm.error('Please set guide mesh')
def _get(self):
self.node = ul.get_node(self.name)
self.root = ul.get_node(self.root_name)
self.constraint = ul.get_node(self.constraint_name)
return self.node
@classmethod
def guides(cls, name='eye', root_suffix='Gp', suffix='loc', separator='_'):
list_all = pm.ls('*%s*%s*' % (name, suffix), type='transform')
guides = []
for ob in list_all:
if root_suffix not in ob.name():
ob_name = ob.name().split(separator)
guide = cls(ob_name[0], suffix=suffix, root_suffix=root_suffix)
guides.append(guide)
return guides
class FacialControl(object):
def __init__(self, name, suffix='ctl', offset_suffix='offset', root_suffix='Gp'):
self._suffix = suffix
self._offset_suffix = offset_suffix
self._root_suffix = root_suffix
self.rename(name)
self.attr_connect_list = ['translate', 'rotate', 'scale']
self._get()
def __repr__(self):
return self.name
def __call__(self, *args, **kwargs):
self.create(*args, **kwargs)
return self
def name(self):
return self.name
def rename(self, new_name):
self._name = new_name
self.name = '_'.join([self._name, self._suffix])
self.offset_name = '_'.join([self._name, self._offset_suffix])
self.root_name = '_'.join([self._name, self._root_suffix])
try:
if self.node:
pm.rename(self.node, self.name)
print self.node
if self.offset:
pm.rename(self.offset, self.offset_name)
print self.offset
if self.root:
pm.rename(self.root, self.root_name)
print self.root
except:
pass
def create(self, shape=None, pos=[0, 0, 0], parent=None, create_offset=True):
if not self.node:
if shape:
self.node = pm.nt.Transform(name=self.name)
shape = ul.get_node(shape)
ul.parent_shape(shape, self.node)
else:
self.node = \
pm.sphere(ax=(0, 1, 0), ssw=0, esw=360, r=0.35, d=3, ut=False, tol=0.01, s=8, nsp=4, ch=False,
n=self.name)[0]
self.node.setTranslation(pos, 'world')
self.WorldPosition = self.node.getTranslation('world')
self.shape = ul.get_shape(self.node)
for atr in ['castsShadows', 'receiveShadows', 'holdOut', 'motionBlur', 'primaryVisibility', 'smoothShading',
'visibleInReflections', 'visibleInRefractions', 'doubleSided']:
self.shape.attr(atr).set(0)
if not self.offset and create_offset:
self.offset = pm.nt.Transform(name=self.offset_name)
self.offset.setTranslation(self.WorldPosition, space='world')
self.node.setParent(self.offset)
if not self.root:
self.root = pm.nt.Transform(name=self.root_name)
self.root.setTranslation(self.WorldPosition, space='world')
if self.offset:
self.offset.setParent(self.root)
else:
self.node.setParent(self.root)
self.root.setParent(parent)
return self.node
def delete(self):
pass
def create_guide(self, *args, **kwargs):
self.guide = FacialGuide(self._name, *args, **kwargs)
return self.guide
def set_constraint(self):
assert self.guide, 'Control object for %s do not have guide locator'%self.name
assert self.root, 'Control object for %s do not have root'%self.name
self.constraint = pm.pointConstraint(self.guide, self.root, o=(0, 0, 0), w=1)
def delete_constraint(self):
if self.constraint:
pm.delete(self.constraint)
def set(self, new_node, rename=True):
if pm.objExists(new_node):
self.node = pm.PyNode(new_node)
if rename:
pm.rename(new_node, self.name)
self._get()
def get_output(self):
results = {}
for atr in self.attr_connect_list:
results[atr] = self.node.attr(atr).outputs()
return results
def _get(self):
self.node = ul.get_node(self.name)
self.offset = ul.get_node(self.offset_name)
self.root = ul.get_node(self.root_name)
self.guide = self.create_guide()
if self.root:
searchConstraint = self.root.listConnections(type=pm.nt.PointConstraint)
if searchConstraint:
self.constraint = searchConstraint[0]
else:
self.constraint = None
@classmethod
def controls(cls, name, offset_suffix='offset', root_suffix='Gp', suffix='ctl', separator='_'):
list_all = pm.ls('*%s*%s*' % (name, suffix), type='transform')
controls = []
for ob in list_all:
if root_suffix not in ob.name():
ob_name = ob.name().split(separator)
control = cls(ob_name[0], offset_suffix=offset_suffix, suffix=suffix, root_suffix=root_suffix)
controls.append(control)
return controls
class FacialBone(object):
def __init__(self, name, suffix='bon', offset_suffix='offset', ctl_suffix='ctl', root_suffix='Gp'):
self._name = name
self._suffix = suffix
self._offset_suffix = offset_suffix
self._ctl_suffix = ctl_suffix
self.name = '_'.join([self._name, suffix])
self.offset_name = '_'.join([self._name, self._offset_suffix, self._suffix])
self.connect_attrs = [
'translate',
'rotate',
'scale']
self.control_name = self.name.replace(suffix, ctl_suffix)
self._get()
def __repr__(self):
return self.name
def __call__(self, new_bone=None, pos=[0, 0, 0], parent=None, create_control=False):
if pm.objExists(newBone):
newBone = pm.PyNode(new_bone)
pm.rename(newBone, self.name)
self._set(newBone, pos=pos, parent=parent)
else:
if self._get():
self._set(self.bone)
else:
newBone = pm.nt.Joint()
newBone.setTranslation(pos, space='world')
newBone.setParent(parent)
self.__call__(newBone=newBone)
if create_control:
self.create_control()
return self.bone
def create_offset(self, pos=[0, 0, 0], space='world', reset_pos=False, parent=None):
boneParent = self.bone.getParent()
if boneParent and self._offset_suffix in boneParent.name():
self.offset_bone = boneParent
elif pm.objExists(self.offset_name):
self.offset_bone = pm.PyNode(self.offset_name)
self.offset_bone.setParent(boneParent)
self.bone.setParent(self.offset_bone)
reset_transform(self.bone)
else:
self.offset_bone = pm.nt.Joint(name=self.offset_name)
self.bone.setParent(self.offset_bone)
if reset_pos:
reset_transform(self.bone)
self.offset_bone.setTranslation(pos, space=space)
if parent:
self.offset_bone.setParent(parent)
else:
self.offset_bone.setParent(parent)
return self.offset_bone
def create_control(self, shape=None, parent=None):
self.get_control()
self.control.create()
def is_connected(self):
if self.control:
connect_state = []
for atr in self.connect_attrs:
input = self.bone.attr(atr).inputs()
if input:
if input[0] == self.control:
connect = True
else:
connect = False
print '%s connection to %s is %s' % (atr, self.control_name, connect)
connect_state.append((atr, connect))
return connect_state
def connect(self):
if self.bone and self.control.node:
if self.offset:
pm.match_transform(self.offset, self.bone, pivots=True)
pm.match_transform(self.control.node, self.bone, pivots=True)
self.control.node.translate >> self.bone.translate
else:
'object {} or {} is not exists'.format(self.bone, self.control.node)
def set_control(self, control_ob, rename=True):
if pm.objExists(control_ob):
self.control = pm.PyNode(control_ob)
if rename:
pm.rename(self.control, self.control_name)
else:
self.create_control()
self.connect()
self.is_connected()
return self.control
def get_control(self, other_name=None):
control_name = self._name
if other_name and any([isinstance(other_name, t) for t in [str, unicode]]):
control_name = other_name
self.control = FacialControl(control_name)
return self.control
def _get(self):
self.bone = ul.get_node(self.name)
# if self.bone:
# self._set(self.bone)
self.offset = ul.get_node(self.offset_name)
self.get_control()
return self.bone
def _set(self, bone):
self.bone = bone
self.create_offset(
pos=self.bone.getTranslation(space='world'),
reset_pos=True)
@classmethod
def bones(
cls,
names=['eye', 'cheek', 'nose', 'lip'],
offset_suffix='offset', root_suffix='Gp',
suffix='bon', separator='_',
directions=['Left', 'Right', 'Center', 'Root']):
'''get all Bone'''
# class facialbones(Enum):
for name in names:
list_all = pm.ls('*%s*%s*' % (name, suffix), type='transform')
# print list_all
allbone = []
for ob in list_all:
if root_suffix not in ob.name() and offset_suffix not in ob.name():
ob_name = ob.name().split(separator)
bone = cls(ob_name[0], offset_suffix=offset_suffix, suffix=suffix, root_suffix=root_suffix)
allbone.append(bone)
bones = {}
bones['All'] = allbone
for direction in directions:
bones[direction] = []
for bone in allbone:
if direction in bone.name:
bones[direction].append(bone)
yield (name,bones)
class FacialEyeRig(object):
pass
class FacialRig(object):
pass
class FacialBsRig(object):
def __init__(self):
self.facebs_name = 'FaceBaseBS'
self.control_name = "ctl"
self.joint_name = 'bon'
self.bs_names = ['eyebrow', 'eye', 'mouth']
self.ctl_names = ['brow', 'eye', 'mouth']
self.direction_name = ['Left', 'Right']
def facectl(self, value=None):
if value is not None:
if isinstance(value, list):
self.ctl_names = value
self.ctl_fullname = ['_'.joint([ctl_name, 'ctl']) for ctl_name in ctl_names]
self.ctl = []
def create_bs_ctl():
pass
try:
for ctl_name in self.ctl_fullname:
ctl = PyNode(ctl)
self.ctl.append(ctl)
except:
create_bs_ctl(ctl)
def facebs(self, value=None):
if value is not None:
self.facebs_name = value
self.facebs = ul.get_blendshape_target(self.facebs_name)
if self.facebs:
self.facebs_def = {}
self.facebs_def['misc'] = []
for bs in self.facebs[0]:
for bs_name in bs_def:
for direction in direction_name:
if bs.startswith(bs_name):
if not self.facebs_def.has_key(bs_name):
self.facebs_def[bs_name] = {}
if bs.endswith(direction[0]):
if not self.facebs_def[bs_name].has_key(direction):
self.facebs_def[bs_name][direction] = []
self.facebs_def[bs_name][direction].append(bs)
else:
self.facebs_def[bs_name] = []
self.facebs_def[bs_name].append(bs)
else:
self.facebs_def['misc'].append(bs)
else:
print "no blendShape with name" % self.facebs_name
return self.facebs_def
def connect_bs_controller(self):
facepart = self.facebs()
bs_control_name = ["_".join([n, self.control_name])
for n in facepart[:3]]
def create_bs_list(part, bs_name_list, add_dir=False):
bs_list = [
'_'.join([part, bs])
for bs in bs_name_list]
if add_dir is True:
bs_list = self.add_direction(bs_list)
return bs_list
bs_controller = {}
eyebrow = facepart[0].replace(facepart[1], '')
bs_controller[
'_'.join([eyebrow, self.control_name])
] = create_bs_list(
facepart[0],
self.eyebs_name[:3],
True)
bs_controller[
'_'.join([facepart[1], self.control_name])
] = create_bs_list(
facepart[1],
self.eyebs_name[1:],
True)
bs_controller[
'_'.join([facepart[2], self.control_name])
] = create_bs_list(
facepart[2],
self.mouthbs_name,
)
for ctl_name, bs_targets in bs_controller.items():
for bs_target in bs_targets:
print '%s.%s >> %s.%s' % (ctl_name, bs_target, self.facebs_name, bs_target)
# print bs_controller
class ControlObject(object):
'''Class to create Control'''
def __init__(
self,
name='ControlObject',
suffix='ctl',
radius=1,
res='high',
length=2.0,
axis='XY',
offset=0.0,
color='red'):
self._suffix = suffix
self._name = '{}_{}'.format(name, suffix)
self._radius = radius
self._length = length
self._axis = axis
self._offset = offset
self._step = res
self._color = color
self.controls = {}
self.controls['all'] = []
self.controlGps = []
self._resolutions = {
'low': 4,
'mid': 8,
'high': 24
}
self._axisList = ['XY', 'XZ', 'YZ']
self._axisList.extend([a[::-1] for a in self._axisList]) ## add reverse asxis
self._axisList.extend(['-%s' % a for a in self._axisList]) ## add minus axis
self._colorData = {
'white': pm.dt.Color.white,
'red': pm.dt.Color.red,
'green': pm.dt.Color.green,
'blue': pm.dt.Color.blue,
'yellow': [1, 1, 0, 0],
'cyan': [0, 1, 1, 0],
'violet': [1, 0, 1, 0],
'orange': [1, 0.5, 0, 0],
'pink': [1, 0, 0.5, 0],
'jade': [0, 1, 0.5, 0]
}
self._controlType = {
'Pin': self.Pin,
'Circle': self.Circle,
'Octa': self.Octa,
'Cylinder': self.Cylinder,
'Sphere': self.Sphere,
'NSphere': self.NSphere,
'Rectangle': self.Rectangle
}
self._currentType = self._controlType.keys()[0]
self._uiOption = {
'group':True,
'pre':False
}
self._uiElement = {}
log.info('Control Object class name:{} initialize'.format(name))
log.debug('\n'.join(['{}:{}'.format(key, value) for key, value in self.__dict__.items()]))
####Define Property
@property
def name(self):
if self._suffix not in self._name:
self._name = '{}_{}'.format(self._name.split('_')[0], self._suffix)
return self._name
@name.setter
def name(self, newName):
if self._suffix not in newName:
self._name = '{}_{}'.format(newName, self._suffix)
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, newradius):
assert any([isinstance(newradius, typ) for typ in [float, int]]), "radius must be of type float"
self._radius = newradius
@property
def length(self):
return self._length
@length.setter
def length(self, newlength):
assert any([isinstance(newlength, typ) for typ in [float, int]]), "length must be of type float"
self._length = newlength
@property
def offset(self):
return self._offset
@offset.setter
def offset(self, newoffset):
if any([isinstance(newoffset, typ) for typ in [list, set, tuple]]):
assert (len(newoffset) == 3), 'offset must be a float3 of type list,set or tuple'
self._offset = newoffset
@property
def color(self):
return pm.dt.Color(self._color)
@color.setter
def color(self, newcolor):
if isinstance(newcolor, str):
assert (self._colorData.has_key(newcolor)), "color data don't have '%s' color.\nAvailable color:%s" % (
newcolor, ','.join(self._colorData))
self._color = self._colorData[newcolor]
if any([isinstance(newcolor, typ) for typ in [list, set, tuple]]):
assert (len(newcolor) >= 3), 'color must be a float4 or float3 of type list,set or tuple'
self._color = pm.dt.Color(newcolor)
@property
def axis(self):
return self._axis
@axis.setter
def axis(self, newaxis):
if isinstance(newaxis, str) or isinstance(newaxis, unicode):
assert (newaxis in self._axisList), "axis data don't have '%s' axis.\nAvailable axis:%s" % (
newaxis, ','.join(self._axisData))
self._axis = newaxis
@property
def step(self):
return self._step
@step.setter
def step(self, newres):
assert (
self._resolutions.has_key(newres)), "step resolution value not valid.\nValid Value:%s" % self._resolutions
self._step = self._resolutions[newres]
# @ul.error_alert
def __setProperty__(func):
'''Wraper that make keywords argument of control type function
to tweak class Attribute'''
@ul.wraps(func)
def wrapper(self, *args, **kws):
# store Class Attribute Value
oldValue = {}
oldValue['offset'] = self.offset
oldValue['res'] = self.step
oldValue['color'] = self.color
fkws = func.__defaults__[0]
# Assign Keyword Argument value to Class Property value
log.debug('Assign KeyWord to ControlObject Class Propety')
if 'offset' in kws:
self.offset = kws['offset']
log.debug('{} set to {}'.format('offset', offset))
if 'res' in kws:
self.step = kws['res']
log.debug('{} set to {}'.format('res', res))
if 'color' in kws:
self.color = kws['color']
log.debug('{} set to {}'.format('color', color))
for key, value in kws.items():
if self.__dict__.has_key(key):
oldValue[key] = self.__dict__[key]
self.__dict__[key] = value
log.debug('{} set to {}'.format(key, value))
if fkws.has_key(key):
fkws[key] = value
if kws.has_key('group'):
groupControl = kws['group']
elif kws.has_key('grp'):
groupControl = kws['grp']
else:
groupControl = True
if kws.has_key('prefixControlName'):
prefixName = kws['prefixControlName']
elif kws.has_key('pre'):
prefixName = kws['pre']
else:
prefixName = False
#### Create and Modify Control object
control = func(self, mode=fkws)
if prefixName is True:
control.rename('_'.join([func.__name__, self.name]))
self.controls['all'].append(control)
if not self.controls.has_key(func.__name__):
self.controls[func.__name__] = []
self.controls[func.__name__].append(control)
if kws.has_key('setAxis') and kws['setAxis'] is True:
self.setAxis(control, self.axis)
self.setColor(control, self.color)
control.setTranslation(self.offset, 'world')
pm.makeIdentity(control, apply=True)
log.info('Control of type:{} name {} created along {}'.format(func.__name__, control.name(), self._axis))
if groupControl is True:
Gp = ru.group(control)
self.controlGps.append(Gp)
else:
pm.xform(control, pivots=(0, 0, 0), ws=True, dph=True, ztp=True)
#### reset Class Attribute Value to __init__ value
for key, value in oldValue.items():
self.__dict__[key] = value
if key == 'offset':
self._offset = value
if key == 'res':
self._step = value
if key == 'color':
self._color = value
return control
return wrapper
#### Control Type
@__setProperty__
def Octa(self, mode={}):
crv = ru.createPinCircle(
self.name,
step=4,
sphere=True,
radius=self.radius,
length=0)
print self
return crv
@__setProperty__
def Pin(self, mode={'mirror': False, 'sphere': False}):
newAxis = self._axis
if mode['mirror']:
newAxis = 'm' + self._axis
else:
newAxis = self._axis.replace('m', '')
crv = ru.createPinCircle(
self.name,
axis=newAxis,
sphere=mode['sphere'],
radius=self.radius,
step=self.step,
length=self.length)
return crv
@__setProperty__
def Circle(self, mode={}):
crv = ru.createPinCircle(
self.name,
axis=self._axis,
radius=self.radius,
step=self.step,
sphere=False,
length=0)
return crv
@__setProperty__
def Cylinder(self, mode={}):
crv = ru.createPinCircle(
self.name,
axis=self._axis,
radius=self.radius,
step=self.step,
cylinder=True,
height=self.length,
length=0,
)
return crv
@__setProperty__
def NSphere(self, mode={'shaderName': 'control_mtl'}):
crv = pm.sphere(r=self.radius, n=self.name)
#### set invisible to render
crvShape = crv[0].getShape()
crvShape.castsShadows.set(False)
crvShape.receiveShadows.set(False)
crvShape.motionBlur.set(False)
crvShape.primaryVisibility.set(False)
crvShape.smoothShading.set(False)
crvShape.visibleInReflections.set(False)
crvShape.visibleInRefractions.set(False)
crvShape.doubleSided.set(False)
#### set Shader
shdr_name = '{}_{}'.format(mode['shaderName'], self.name)
sg_name = '{}{}'.format(shdr_name, 'SG')
if pm.objExists(shdr_name) or pm.objExists(sg_name):
try:
pm.delete(shdr_name)
pm.delete(sg_name)
except:
pass
shdr, sg = pm.createSurfaceShader('surfaceShader')
pm.rename(shdr, shdr_name)
pm.rename(sg, sg_name)
shdr.outColor.set(self.color.rgb)
shdr.outTransparency.set([self.color.a for i in range(3)])
pm.sets(sg, fe=crv[0])
return crv[0]
@__setProperty__
def Sphere(self, mode={}):
crv = ru.createPinCircle(
self.name,
axis=self._axis,
radius=self.radius,
step=self.step,
sphere=True,
length=0)
return crv
@__setProperty__
def Rectangle(self, mode={}):
crv = ru.create_square(
self.name,
length=self.radius,
width=self.length,
offset=self.offset)
return crv
#### control method
def getControls(self):
msg = ['{} contain controls:'.format(self.name)]
for key, ctls in self.controls.items():
msg.append('+' + key)
for ctl in ctls:
msg.append('--' + ctl)
log.info('\n'.join(msg))
return self.controls
def setAxis(self, control, axis='XY'):
axisData = {}
axisData['XY'] = [0, 0, 90]
axisData['YX'] = [0, 0, -90]
axisData['XZ'] = [0, 90, 0]
axisData['ZX'] = [0, -90, 0]
axisData['YZ'] = [90, 0, 0]
axisData['ZY'] = [-90, 0, 0]
assert (axis in axisData), "set axis data don't have '%s' axis.\nAvailable axis:%s" % (axis, ','.join(axisData))
control.setRotation(axisData[axis])
# print control.getRotation()
pm.makeIdentity(control, apply=True)
if not control:
for control in self.controls:
self.setAxis(control)
def setColor(self, control, newColor=None):
print control.name
if newColor:
self.color = newColor
try:
control.overrideEnabled.set(True)
control.overrideRGBColors.set(True)
control.overrideColorRGB.set(self.color)
sg = control.shadingGroups()[0] if control.shadingGroups() else None
if sg:
shdr = sg.inputs()[0]
shdr.outColor.set(self.color.rgb)
shdr.outTransparency.set([self.color.a for i in range(3)])
except AttributeError as why:
log.error(why)
def deleteControl(self, id=None, deleteGp=False):
if id and id < len(self.controls):
pm.delete(self.controls[id])
return self.control[id]
pm.delete(self.controls)
if deleteGp:
pm.delete(self.controlGps)
def createControl(self):
newCtl = self._controlType[self._currentType](**self._uiOption)
return newCtl
def changeControlShape(self, selectControl, *args):
temp = self.createControl()
#temp.setParent(selectControl.getParent())
ru.xformTo(temp, selectControl)
pm.delete(selectControl.getShape(), shape=True)
pm.parent(temp.getShape(), selectControl, r=True, s=True)
pm.delete(temp)
return selectControl
#### Ui contain
@classmethod
def show(cls):
cls()._showUI()
def _getUIValue(self, *args):
self.name = self._uiElement['ctlName'].getText()
self.color = self._uiElement['ctlColor'].getRgbValue()
print self._uiElement['ctlAxis'].getValue()
self.axis = self._uiElement['ctlAxis'].getValue()
self.radius = self._uiElement['ctlRadius'].getValue()[0]
self.length = self._uiElement['ctlLength'].getValue()[0]
self.step = self._uiElement['ctlRes'].getValue()
self.offset = self._uiElement['ctlOffset'].getValue()
self._currentType = self._uiElement['ctlType'].getValue()
for name, value in zip(self._uiElement['ctlOption'].getLabelArray4(),
self._uiElement['ctlOption'].getValueArray4()):
self._uiOption[name] = value
def reset_window_height(self):
#self._window.setSizeable(True)
self._window.setResizeToFitChildren(True)
#self._window.setSizeable(False)
def _showUI(self, parent=None):
self._uiName = 'CreateControlUI'
self._windowSize = (260, 10)
if pm.window(self._uiName + 'Window', ex=True):
pm.deleteUI(self._uiName + 'Window', window=True)
pm.windowPref(self._uiName + 'Window', remove=True)
if parent is not None and isinstance(parent, pm.uitypes.Window):
self._window = parent
else:
self._window = pm.window(
self._uiName + 'Window', title=self._uiName,
rtf=True, widthHeight=self._windowSize)
self._uiTemplate = pm.uiTemplate('CreateControlUITemplace', force=True)
self._uiTemplate.define(
pm.button, width=5, height=40, align='left',
bgc=[0.15,0.25,0.35])
self._uiTemplate.define(pm.columnLayout, adjustableColumn=1, w=10)
self._uiTemplate.define(
pm.frameLayout, borderVisible=False, labelVisible=True,
mh=2, mw=2,
width=self._windowSize[0], bgc=[0.2,0.2,0.2])
self._uiTemplate.define(
pm.rowColumnLayout,
rs=[(1, 5), ],
adj=True, numberOfColumns=2,
cal=[(1, 'left'), ],
columnWidth=[(1, 100), (2, 100)])
with self._window:
with self._uiTemplate:
with pm.frameLayout(label='Create Control'):
with pm.columnLayout():
with pm.rowColumnLayout():
self._uiElement['ctlName'] = pm.textFieldGrp(
cl2=('left', 'right'),
co2=(0, 0),
cw2=(40, 100),
label='Name:', text=self.name,
cc = self._getUIValue)
self._uiElement['ctlType'] = pm.optionMenu(label='Type:', cc = self._getUIValue)
with self._uiElement['ctlType']:
for ct in self._controlType:
pm.menuItem(label=ct)
with pm.rowColumnLayout(
numberOfColumns=3,
columnWidth=[(1, 10), ]):
self._uiElement['ctlLength'] = pm.floatFieldGrp(
cl2=('left', 'right'),
co2=(0, 0),
cw2=(40, 30),
numberOfFields=1,
label='Length:',
value1=3.0,
cc = self._getUIValue)
self._uiElement['ctlRadius'] = pm.floatFieldGrp(
cl2=('left', 'right'),
co2=(0, 0),
cw2=(40, 30),
numberOfFields=1,
label='Radius:',
value1=0.5,
cc = self._getUIValue)
self._uiElement['ctlRes'] = pm.optionMenu(label='Step:', cc = self._getUIValue)
with self._uiElement['ctlRes']:
for ct in self._resolutions:
pm.menuItem(label=ct)
with pm.rowColumnLayout():
self._uiElement['ctlColor'] = pm.colorSliderGrp(
label='Color:',
rgb=(0, 0, 1),
co3=(0, 0, 0),
cw3=(30, 60, 60),
cl3=('left', 'center', 'right'),
cc = self._getUIValue)
self._uiElement['ctlAxis'] = pm.optionMenu(label='Axis:', cc = self._getUIValue)
with self._uiElement['ctlAxis']:
for ct in self._axisList:
pm.menuItem(label=ct)
self._uiElement['ctlOffset'] = pm.floatFieldGrp(
cl4=('left', 'center', 'center', 'center'),
co4=(0, 5, 0, 0),
cw4=(45, 50, 50, 50),
numberOfFields=3,
label='Offset:',
cc = self._getUIValue)
self._uiElement['ctlOption'] = pm.checkBoxGrp(
cl5=('left', 'center', 'center', 'center', 'center'),
co5=(0, 5, 0, 0, 0),
cw5=(45, 50, 50, 50, 50),
numberOfCheckBoxes=4,
label='Options:',
labelArray4=['group', 'setAxis', 'sphere', 'mirror'],
cc = self._getUIValue)
pm.button(label='Create', c=pm.Callback(self.createControl))
pm.button(
label='Change Current Select',
c=lambda x: ul.do_function_on()(self.changeControlShape)(sl=True))
pm.button(
label='Set Color Select',
c=lambda x: ul.do_function_on()(self.setColor)(sl=True))
self._getUIValue()
self.reset_window_height()
#self._window.setHeight(10)
```
#### File: PipelineTools/etc/connector.py
```python
from PipelineTools import ui
window = None
def show():
global window
if window is None:
cont = ui.HierachyConverterController()
window = ui.create_window(cont)
_window.show()
```
#### File: PipelineTools/etc/controlShape.py
```python
import maya.mel as mm
import pymel.core as pm
createSphereCtlmel = '''createNode transform -n "sphere_ctl";
setAttr ".ove" yes;
setAttr ".ovc" 23;
createNode nurbsCurve -n "sphere_ctlShape" -p "sphere_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 52 0 no 3
53 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
53
1.6414698326599991e-006 2.5000000302530538 2.9689054650766197e-007
2.4002848877378454e-006 2.3097001415645648 -0.95670729667575005
2.7936796139264932e-006 1.7677677313243909 -1.7677674211967007
2.7617604729952385e-006 0.95670778586711669 -2.3097000577147804
2.3093885378047716e-006 2.9688893404612974e-007 -2.5000001854458858
1.5054352855951999e-006 -0.95670723728763729 -2.3097002849447095
4.7228999894414808e-007 -1.7677673114600272 -1.7677678410634667
-6.3275739712905504e-007 -2.3096999143360941 -0.95670784525822505
-1.6414698113439104e-006 -2.5000000302533381 -2.9689054428722985e-007
-2.4002848664217759e-006 -2.3097001415648775 0.95670729667575316
-2.7936795926104216e-006 -1.7677677313247036 1.7677674211967014
-2.7617604729954079e-006 -0.95670778586737248 2.3097000577147817
-2.309388530699498e-006 -2.9688916141981296e-007 2.5000001854458889
-1.505435271384518e-006 0.9567072372873815 2.3097002849447117
-4.7228998473346594e-007 1.7677673114597714 1.7677678410634685
6.327574255505687e-007 2.3096999143358099 0.95670784525822861
1.6414698326599991e-006 2.5000000302530538 2.9689054650766197e-007
-0.95670577731741913 2.3097006561127609 -6.0947216232185142e-007
-1.7677659583679914 1.7677686820868006 -1.4230508009838491e-006
-2.3096988741188569 0.95670902809828551 -2.0199821124968874e-006
-2.4999994612736018 1.6414696409585508e-006 -2.3093876663635853e-006
-2.309700130444051 -0.95670599505644005 -2.2472120413914027e-006
-1.7677682797576066 -1.7677663606976743 -1.8429175670665804e-006
-0.95670881035970401 -2.3096993997878981 -1.158054636895729e-006
-1.6414698113439104e-006 -2.5000000302533381 -2.9689054428722985e-007
0.95670577731743334 -2.3097006561130451 6.0947216409818783e-007
1.7677659583679914 -1.7677686820871132 1.4230508027601689e-006
2.3096988741188711 -0.95670902809856972 2.0199821147173127e-006
2.4999994612736156 -1.6414698399105289e-006 2.3093876681399316e-006
2.3097001304440652 0.95670599505618426 2.2472120431677422e-006
1.7677682797576066 1.7677663606973333 1.8429175688428968e-006
0.95670881035971111 2.3096993997876138 1.1580546386720588e-006
1.6414698326599991e-006 2.5000000302530538 2.9689054650766197e-007
6.327574255505687e-007 2.3096999143358099 0.95670784525822861
-4.7228998473346594e-007 1.7677673114597714 1.7677678410634685
-1.505435271384518e-006 0.9567072372873815 2.3097002849447117
-2.309388530699498e-006 -2.9688916141981296e-007 2.5000001854458889
0.95670516024070007 -9.0245255476855184e-007 2.3097010550931469
1.7677654860779997 -1.3706271712630089e-006 1.7677692641142704
2.30969861851773 -1.6301355558039744e-006 0.95670970456406801
2.4999994612736156 -1.6414698399105289e-006 2.3093876681399316e-006
2.3097003860451992 -1.4029067728967838e-006 -0.95670543736990976
1.7677687520476055 -9.5076255193408841e-007 -1.7677659981458989
0.95670942743645149 -3.5387284792947253e-007 -2.3096992875663442
2.3093885378047716e-006 2.9688893404612974e-007 -2.5000001854458858
-0.95670516024068586 9.0245232739486411e-007 -2.3097010550931456
-1.7677654860779997 1.3706269438893307e-006 -1.7677692641142688
-2.3096986185177228 1.6301353000085815e-006 -0.9567097045640649
-2.4999994612736018 1.6414696409585508e-006 -2.3093876663635853e-006
-2.3097003860451779 1.4029065455230916e-006 0.95670543736991198
-1.7677687520475842 9.5076226771697664e-007 1.7677659981458995
-0.95670942743643728 3.5387256371236536e-007 2.3096992875663456
-2.309388530699498e-006 -2.9688916141981296e-007 2.5000001854458889
;
select sphere_ctl;'''
createPinCtlmel = '''
createNode transform -n "pin_ctl";
setAttr ".ove" yes;
setAttr ".ovrgbf" yes;
setAttr ".ovrgb" -type "float3" 0 0.34999999 1 ;
createNode nurbsCurve -n "pin_ctlShape" -p "pin_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 25 0 no 3
26 0 0.37689 0.75376699999999996 1.130657 1.5075460000000001 1.884423 2.2613129999999999
2.6382029999999999 3.0150800000000002 3.3919700000000002 3.768859 4.1457369999999996
4.5226249999999997 4.8995129999999998 5.2763910000000003 5.6532799999999996 6.0301710000000002
6.4070470000000004 6.7839369999999999 7.1608270000000003 7.5377039999999997 7.9145940000000001
8.2914840000000005 8.6683610000000009 9.0452510000000004 19.157319000000001
26
-1.575261882735e-007 4.2054683464182183 0
-0.37349322563385101 4.2559573395113564 0
-0.72168229276648799 4.4001823197814769 0
-1.0214823544731599 4.6285802885367886 0
-1.2498804061955291 4.9283802475243554 0
-1.3941054448074195 5.2765691998923412 0
-1.4445944677487039 5.6500621487987566 0
-1.3941054727876261 6.0235550977051719 0
-1.2498804602602571 6.3717430500732952 0
-1.0214824309974251 6.6715440090607263 0
-0.72168238640113869 6.8999409778161738 0
-0.37349333007318419 7.0441679580860201 0
-2.6574741500836927e-007 7.094643951180938 0
0.37349280235976079 7.0441679580860201 0
0.72168186949247259 6.8999409778161738 0
1.0214819311991072 6.6715440090607263 0
1.2498799829215139 6.3717430500732952 0
1.3941050215333668 6.0235550977051719 0
1.4445940444746512 5.6500621487987566 0
1.3941050495135734 5.2765691998923412 0
1.2498800369862419 4.9283802475243554 0
1.0214820077233724 4.6285802885367886 0
0.72168196312712329 4.4001823197814769 0
0.37349290679909397 4.2559573395113564 0
-1.575261882735e-007 4.2054683464182183 0
0 0 0
;
select pin_ctl;'''
def createSphereCtl(name='sphere_ctl01'):
mm.eval(createSphereCtlmel)
temp = pm.selected()
new = pm.duplicate(temp[0], name=name)[0]
pm.delete(temp)
return new
def createPinCtl(name='pin_ctl01'):
mm.eval(createPinCtlmel)
temp = pm.selected()
new = pm.duplicate(temp[0], name=name)[0]
pm.delete(temp)
return new
```
#### File: PipelineTools/etc/riggingMisc.py
```python
import maya.mel as mm
ctl_root = '''
createNode transform -n "ctlGp";
createNode transform -n "facialRig_Gp" -p "ctlGp";
'''
teeth_upper_ctl = '''
createNode transform -n "teethUpper_ctlGp" -p "facialRig_Gp";
setAttr ".t" -type "double3" 0.0051069147026953114 184.54078924201585 5.2829795741889614 ;
setAttr ".r" -type "double3" 5.226544323578036 0 0 ;
setAttr ".s" -type "double3" 1.0000001228064281 0.99999999999999989 0.99999999999999989 ;
setAttr ".rp" -type "double3" 0 0 -3.1554436208840465e-030 ;
setAttr ".rpt" -type "double3" 0 2.8744182216380069e-031 1.3119378631350618e-032 ;
setAttr ".sp" -type "double3" 0 0 -3.1554436208840472e-030 ;
setAttr ".spt" -type "double3" 0 0 7.0064923216240846e-046 ;
createNode transform -n "teethUpper_ctl" -p "teethUpper_ctlGp";
setAttr -l on -k off ".v";
setAttr ".ove" yes;
setAttr ".ovc" 13;
setAttr ".t" -type "double3" 1.7763568394002548e-015 0 3.4694469519536228e-017 ;
setAttr ".rp" -type "double3" 7.1054239694692128e-015 -2.8421709430404007e-014 1.7763568394002505e-015 ;
setAttr ".sp" -type "double3" 7.1054239694692128e-015 -2.8421709430404007e-014 1.7763568394002505e-015 ;
createNode nurbsCurve -n "teethUpper_ctlShape" -p "teethUpper_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 26 0 no 3
27 0 2 4.0871430000000002 6.1743430000000004 8.2614889999999992 10.348646 12.435838
14.522990999999999 16.610143000000001 18.697337999999998 20.784490000000002 22.871642000000001
24.958836000000002 27.045988999999999 67.401939999999996 68.967304999999996 70.532698999999994
72.098063999999994 73.663428999999994 75.228823000000006 76.794188000000005 78.359554000000003
79.924946000000006 81.490313999999998 83.055674999999994 84.621072999999996 86.186430999999999
27
1.8812674864361643 -0.33844046711310471 0.81528303606732377
3.1918891881378437 -0.21242790092102365 0.8790116951976219
3.0803621459977051 -0.2124279009210237 1.9244324382697795
2.7616722445846165 -0.2124279009210237 2.8990795202765729
2.2570248073234649 -0.2124279009210237 3.7382314127698772
1.5946090136869451 -0.2124279009210237 4.3775279765467134
0.82523856081179037 -0.2124279009210237 4.7812396930909005
-1.3501909041373287e-006 -0.2124279009210237 4.9225590620054591
-0.82524045082690589 -0.2124279009210237 4.7812396930909005
-1.5946121006609364 -0.2124279009210237 4.3775279765467134
-2.2570258993659964 -0.2124279009210237 3.738231412769879
-2.7616769275037756 -0.2124279009210237 2.8990795202765747
-3.0803608441224868 -0.2124279009210237 1.9244324382697815
-3.1919162142893289 -0.21242790092102365 0.8790116951976239
-1.8812894958642357 -0.33844046711310471 0.81528303606732466
-1.8155400052774959 -0.33844046711310477 1.4314449595410021
-1.6277104317238611 -0.33844046711310477 2.0058923359862506
-1.3302736037871401 -0.33844046711310477 2.500481463993951
-0.93985274803918861 -0.33844046711310477 2.8772767759819757
-0.48639268652798895 -0.33844046711310477 3.1152210072493007
-3.9144944939839209e-006 -0.33844046711310477 3.1985130666299986
0.4863854137249406 -0.33844046711310477 3.1152210072493007
0.93984484814571279 -0.33844046711310477 2.8772767759819757
1.3302669580745186 -0.33844046711310477 2.500481463993951
1.6277015911947437 -0.33844046711310477 2.0058923359862488
1.815534300200516 -0.33844046711310477 1.4314449595410004
1.8812674864361643 -0.33844046711310471 0.81528303606732377
;
'''
jaw_ctl = '''
createNode transform -n "jaw_ctlGp" -p "facialRig_Gp";
setAttr ".t" -type "double3" 9.2707663211930046e-014 184.8731928559516 2.0028675946035448 ;
setAttr ".r" -type "double3" 90.000000000000313 -58.88163723596525 -90.000000000001606 ;
setAttr ".s" -type "double3" 1.0000000000000002 1 1.0000001228064281 ;
createNode transform -n "jaw_ctl" -p "jaw_ctlGp";
setAttr -l on -k off ".v";
createNode nurbsCurve -n "jaw_ctlShape" -p "jaw_ctl";
setAttr -k off ".v";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr ".cc" -type "nurbsCurve"
1 8 0 no 3
9 0 1 2 3 4 5 6 7 8
9
10.407687395834232 0.23522755974954143 4.1364643133108938
10.407687395834236 -0.45418315913560825 1.3788214377702945
10.407687395834236 -1.8330045969059079 -5.5511151231241655e-015
10.407687395834236 -0.45418315913560825 -1.3788214377703056
10.407687395834236 0.23522755974954143 -4.1364643133109062
10.407687395834236 0.92463827863469139 -1.3788214377703056
10.407687395834236 2.3034597164049901 -5.5511151231241663e-015
10.407687395834236 0.92463827863469139 1.3788214377702945
10.407687395834232 0.23522755974954143 4.1364643133108938
;
'''
teeth_lower_ctl = '''
createNode transform -n "teethLower_ctlGp" -p "jaw_ctl";
setAttr ".t" -type "double3" 2.9253220830434223 1.1567352077150863 -2.2888183637866058e-005 ;
setAttr ".r" -type "double3" -154.03644981535044 -89.999999999998678 0 ;
setAttr ".rp" -type "double3" 0.84121045744281808 -0.54682176873714106 -4.3419228354849401e-016 ;
setAttr ".rpt" -type "double3" -0.24833548366547287 -0.26259057731676178 0 ;
setAttr ".sp" -type "double3" 0.84121045744281808 -0.54682176873714106 -4.3419228354849401e-016 ;
createNode transform -n "teethLower_ctl" -p "teethLower_ctlGp";
setAttr -l on -k off ".v";
setAttr ".ove" yes;
setAttr ".ovc" 13;
setAttr ".t" -type "double3" 1.7763568394002548e-015 0 3.4694469519536228e-017 ;
setAttr ".rp" -type "double3" 0.84121045744282508 -0.54682176873720323 -1.7763568394002505e-015 ;
setAttr ".sp" -type "double3" 0.84121045744282508 -0.54682176873720323 -1.7763568394002505e-015 ;
createNode nurbsCurve -n "teethLower_ctlShape" -p "teethLower_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 26 0 no 3
27 0 2 4.0871430000000002 6.1743430000000004 8.2614889999999992 10.348646 12.435838
14.522990999999999 16.610143000000001 18.697337999999998 20.784490000000002 22.871642000000001
24.958836000000002 27.045988999999999 67.401939999999996 68.967304999999996 70.532698999999994
72.098063999999994 73.663428999999994 75.228823000000006 76.794188000000005 78.359554000000003
79.924946000000006 81.490313999999998 83.055674999999994 84.621072999999996 86.186430999999999
27
2.6309086637882029 -0.47013482141812035 0.84597169074214928
3.8791135244261765 -0.34358053452043835 0.9233675033707669
3.7730151906308245 -0.34358053452043824 1.9687882464429241
3.4698378904129474 -0.34358053452043813 2.9434353284497168
2.9897547534440445 -0.34358053452043802 3.7825872209430229
2.3595828181366709 -0.34358053452043796 4.4218837847198573
1.627662365885675 -0.34358053452043791 4.8255955012640497
0.84259196628887734 -0.34358053452043785 4.9669148701786012
0.057522337613234588 -0.34358053452043791 4.8255955012640497
-0.67439925333327544 -0.34358053452043796 4.4218837847198573
-1.3045692908147948 -0.34358053452043802 3.7825872209430229
-1.7846558438702331 -0.34358053452043813 2.9434353284497199
-2.0878274506105541 -0.34358053452043824 1.9687882464429265
-2.1939527335329987 -0.34358053452043835 0.92336750337076889
-0.94850148617805208 -0.47013482141812035 0.84597169074214928
-0.88595242843131716 -0.4701348214181203 1.4621336142158263
-0.7072656775849111 -0.47013482141812019 2.0365809906610748
-0.42430693280078691 -0.47013482141812013 2.5311701186687769
-0.05289026578506939 -0.47013482141812007 2.9079654306567999
0.37849710041639717 -0.47013482141812007 3.1459096619241267
0.84121033389994404 -0.47013482141812002 3.2292017213048245
1.3039240964964334 -0.47013482141812007 3.1459096619241267
1.7353108661318286 -0.47013482141812007 2.9079654306567999
2.1067287262796892 -0.47013482141812013 2.5311701186687769
2.3896853830825613 -0.47013482141812019 2.0365809906610748
2.5683751167593272 -0.4701348214181203 1.4621336142158263
2.6309086637882029 -0.47013482141812035 0.84597169074214928
;
'''
toungue_ctl = '''
createNode transform -n "tongue_ctlGp" -p "jaw_ctl";
setAttr ".t" -type "double3" 93.829236816461943 -159.30531451836654 -4.1620968976539797e-012 ;
setAttr ".r" -type "double3" -31.118362764034757 89.999999999998664 0 ;
setAttr ".s" -type "double3" 0.99999987719358696 0.99999999999999989 0.99999999999999978 ;
createNode transform -n "tongue_ctl_offset_Gp" -p "tongue_ctlGp";
setAttr ".t" -type "double3" 2.7457581381895579e-005 184.09530639648437 4.7699456214904785 ;
setAttr ".r" -type "double3" 4.903990989550996e-005 -89.999993743414592 0 ;
setAttr ".s" -type "double3" 1 0.99999999999999989 0.99999999999999989 ;
createNode transform -n "tongueCenterARoot_ctlGp" -p "tongue_ctl_offset_Gp";
setAttr ".t" -type "double3" 0.3198469529821022 -0.76699245952900696 5.3800120673337377e-006 ;
setAttr ".r" -type "double3" -5.3614208018684395e-012 89.999950562590996 0 ;
setAttr ".s" -type "double3" 1.0000001228064284 1.0000000000000002 1 ;
createNode transform -n "tongueCenterARoot_ctl" -p "tongueCenterARoot_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr ".rp" -type "double3" 0 -2.8421709430404007e-014 0 ;
setAttr ".sp" -type "double3" 0 -2.8421709430404007e-014 0 ;
createNode nurbsCurve -n "tongueCenterARoot_ctlShape" -p "tongueCenterARoot_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
1.6244003414351962 0.74656851405275881 7.4140356297110889e-017
-2.6208864187067491e-016 1.0558073178141409 1.048502973945478e-016
-1.6244003414351944 0.74656851405275926 7.4140356297110939e-017
-2.2972489935811389 3.0594654648899971e-016 3.0382993037611627e-032
-1.6244003414351951 -0.74656851405275915 -7.4140356297110865e-017
-6.9220595514922645e-016 -1.0558073178141412 -1.048502973945478e-016
1.6244003414351935 -0.74656851405275948 -7.4140356297110939e-017
2.2972489935811389 -5.6707616999769952e-016 -5.631529926570053e-032
1.6244003414351962 0.74656851405275881 7.4140356297110889e-017
-2.6208864187067491e-016 1.0558073178141409 1.048502973945478e-016
-1.6244003414351944 0.74656851405275926 7.4140356297110939e-017
;
createNode transform -n "tongueCenterA_ctlGp" -p "tongueCenterARoot_ctl";
setAttr ".t" -type "double3" 6.9139968887193528e-007 -2.1090275680535342e-005 -6.0449321601652173e-006 ;
setAttr ".r" -type "double3" -5.3550608275535713e-012 4.9437415062718043e-005 -3.0794304942816335e-021 ;
setAttr ".s" -type "double3" 0.99999987719358707 1.0000000000000002 1.0000000000000002 ;
createNode transform -n "tongueCenterA_ctl" -p "tongueCenterA_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 17;
createNode nurbsCurve -n "tongueCenterA_ctlShape" -p "tongueCenterA_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 1.0284309043264841 -0.21658738559361673
-3.4945260899414864e-017 1.0284309043264841 -0.30630081814542448
-0.21658738559361776 1.0284309043264841 -0.21658738559361687
-0.30630081814542537 1.0284309043264841 7.9942010564300995e-016
-0.21658738559361781 1.0284309043264841 0.21658738559361859
-9.2294414310233125e-017 1.0284309043264841 0.30630081814542631
0.21658738559361762 1.0284309043264841 0.21658738559361868
0.30630081814542537 1.0284309043264841 1.0526931866375961e-015
0.21658738559361795 1.0284309043264841 -0.21658738559361673
-3.4945260899414864e-017 1.0284309043264841 -0.30630081814542448
-0.21658738559361776 1.0284309043264841 -0.21658738559361687
;
createNode transform -n "tongueLeftA_ctlGp" -p "tongueCenterARoot_ctl";
setAttr ".t" -type "double3" 1.2838917048884784 -2.1090275680535342e-005 -7.1527319569497649e-006 ;
setAttr ".r" -type "double3" -5.3550608275535713e-012 4.9437415062718043e-005 -3.0794304942816335e-021 ;
setAttr ".s" -type "double3" 0.99999987719358707 1.0000000000000002 1.0000000000000002 ;
createNode transform -n "tongueLeftA_ctl" -p "tongueLeftA_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 13;
createNode nurbsCurve -n "tongueLeftA_ctlShape" -p "tongueLeftA_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.79306527522919623 -0.21658738559361673
-3.4945260899414864e-017 0.79306527522919623 -0.30630081814542448
-0.21658738559361776 0.79306527522919623 -0.21658738559361687
-0.30630081814542537 0.79306527522919623 7.9942010564300995e-016
-0.21658738559361781 0.79306527522919623 0.21658738559361859
-9.2294414310233125e-017 0.79306527522919623 0.30630081814542631
0.21658738559361762 0.79306527522919623 0.21658738559361868
0.30630081814542537 0.79306527522919623 1.0526931866375961e-015
0.21658738559361795 0.79306527522919623 -0.21658738559361673
-3.4945260899414864e-017 0.79306527522919623 -0.30630081814542448
-0.21658738559361776 0.79306527522919623 -0.21658738559361687
;
createNode transform -n "tongueRightA_ctlGp" -p "tongueCenterARoot_ctl";
setAttr ".t" -type "double3" -1.2839359198984683 -2.1090275680535342e-005 -4.9370930188530338e-006 ;
setAttr ".r" -type "double3" -5.3550608275535713e-012 4.9437415062718043e-005 -3.0794304942816335e-021 ;
setAttr ".s" -type "double3" 0.99999987719358707 1.0000000000000002 1.0000000000000002 ;
createNode transform -n "tongueRightA_ctl" -p "tongueRightA_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 13;
createNode nurbsCurve -n "tongueRightA_ctlShape" -p "tongueRightA_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.79306527522919623 -0.21658738559361673
-3.4945260899414864e-017 0.79306527522919623 -0.30630081814542448
-0.21658738559361776 0.79306527522919623 -0.21658738559361687
-0.30630081814542537 0.79306527522919623 7.9942010564300995e-016
-0.21658738559361781 0.79306527522919623 0.21658738559361859
-9.2294414310233125e-017 0.79306527522919623 0.30630081814542631
0.21658738559361762 0.79306527522919623 0.21658738559361868
0.30630081814542537 0.79306527522919623 1.0526931866375961e-015
0.21658738559361795 0.79306527522919623 -0.21658738559361673
-3.4945260899414864e-017 0.79306527522919623 -0.30630081814542448
-0.21658738559361776 0.79306527522919623 -0.21658738559361687
;
createNode transform -n "tongueCenterBRoot_ctlGp" -p "tongue_ctl_offset_Gp";
setAttr ".t" -type "double3" 1.2657848249150803 -0.64560879253679104 5.3794133493024218e-006 ;
setAttr ".r" -type "double3" -5.3614208018684395e-012 89.999950562590996 0 ;
setAttr ".s" -type "double3" 1.0000001228064284 1.0000000000000002 1 ;
createNode transform -n "tongueCenterBRoot_ctl" -p "tongueCenterBRoot_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr ".rp" -type "double3" -2.7105054312137611e-020 0 -8.8817841970012523e-016 ;
setAttr ".sp" -type "double3" -2.7105054312137611e-020 0 -8.8817841970012523e-016 ;
createNode nurbsCurve -n "tongueCenterBRoot_ctlShape" -p "tongueCenterBRoot_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
1.6244003414351962 0.58236785694157656 1.1060022633379389e-016
-2.6208864187067491e-016 0.82359252157693263 1.5641234008278537e-016
-1.6244003414351944 0.58236785694157689 1.1060022633379396e-016
-2.2972489935811389 2.3865650809496092e-016 4.5324383028206158e-032
-1.6244003414351951 -0.58236785694157678 -1.1060022633379389e-016
-6.9220595514922645e-016 -0.82359252157693286 -1.5641234008278537e-016
1.6244003414351935 -0.582367856941577 -1.1060022633379398e-016
2.2972489935811389 -4.4235314994928838e-016 -8.4009372977406742e-032
1.6244003414351962 0.58236785694157656 1.1060022633379389e-016
-2.6208864187067491e-016 0.82359252157693263 1.5641234008278537e-016
-1.6244003414351944 0.58236785694157689 1.1060022633379396e-016
;
createNode transform -n "tongueCenterB_ctlGp" -p "tongueCenterBRoot_ctl";
setAttr ".t" -type "double3" 6.9080097112419244e-007 -2.1090275708957051e-005 -6.0449321557243252e-006 ;
setAttr ".r" -type "double3" -5.3550608275535737e-012 4.9437415062718009e-005 -3.0794304942787886e-021 ;
setAttr ".s" -type "double3" 0.99999987719358707 0.99999999999999989 1 ;
createNode transform -n "tongueCenterB_ctl" -p "tongueCenterB_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 17;
createNode nurbsCurve -n "tongueCenterB_ctlShape" -p "tongueCenterB_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.79306527522919623 -0.21658738559361673
-3.4945260899414864e-017 0.79306527522919623 -0.30630081814542448
-0.21658738559361776 0.79306527522919623 -0.21658738559361687
-0.30630081814542537 0.79306527522919623 7.9942010564300995e-016
-0.21658738559361781 0.79306527522919623 0.21658738559361859
-9.2294414310233125e-017 0.79306527522919623 0.30630081814542631
0.21658738559361762 0.79306527522919623 0.21658738559361868
0.30630081814542537 0.79306527522919623 1.0526931866375961e-015
0.21658738559361795 0.79306527522919623 -0.21658738559361673
-3.4945260899414864e-017 0.79306527522919623 -0.30630081814542448
-0.21658738559361776 0.79306527522919623 -0.21658738559361687
;
createNode transform -n "tongueLeftB_ctlGp" -p "tongueCenterBRoot_ctl";
setAttr ".t" -type "double3" 1.2170171250357078 -2.1090275680535342e-005 -7.0950295123495266e-006 ;
setAttr ".r" -type "double3" -5.3550608275535737e-012 4.9437415062718009e-005 -3.0794304942787886e-021 ;
setAttr ".s" -type "double3" 0.99999987719358707 0.99999999999999989 1 ;
createNode transform -n "tongueLeftB_ctl" -p "tongueLeftB_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 13;
createNode nurbsCurve -n "tongueLeftB_ctlShape" -p "tongueLeftB_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
-0.30630081814542537 0.60610587390425508 -8.8758314057115255e-017
-0.21658738559361781 0.60610587390425508 0.2165873855936177
-9.2294414310233125e-017 0.60610587390425508 0.30630081814542542
0.21658738559361762 0.60610587390425508 0.21658738559361779
0.30630081814542537 0.60610587390425508 1.6451476693747092e-016
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
;
createNode transform -n "tongueRightB_ctlGp" -p "tongueCenterBRoot_ctl";
setAttr ".t" -type "double3" -1.2170609287098897 -2.1090275737378761e-005 -4.9947958116192126e-006 ;
setAttr ".r" -type "double3" -5.3550608275535737e-012 4.9437415062718009e-005 -3.0794304942787886e-021 ;
setAttr ".s" -type "double3" 0.99999987719358707 0.99999999999999989 1 ;
createNode transform -n "tongueRightB_ctl" -p "tongueRightB_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 13;
createNode nurbsCurve -n "tongueRightB_ctlShape" -p "tongueRightB_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
-0.30630081814542537 0.60610587390425508 -8.8758314057115255e-017
-0.21658738559361781 0.60610587390425508 0.2165873855936177
-9.2294414310233125e-017 0.60610587390425508 0.30630081814542542
0.21658738559361762 0.60610587390425508 0.21658738559361779
0.30630081814542537 0.60610587390425508 1.6451476693747092e-016
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
;
createNode transform -n "tongueCenterCRoot_ctlGp" -p "tongue_ctl_offset_Gp";
setAttr ".t" -type "double3" 2.4804080377294042 -0.62740505718511486 5.4964670452021982e-006 ;
setAttr ".r" -type "double3" -5.3614208018684395e-012 89.999950562590996 0 ;
setAttr ".s" -type "double3" 1.0000001228064284 1.0000000000000002 1 ;
createNode transform -n "tongueCenterCRoot_ctl" -p "tongueCenterCRoot_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr ".rp" -type "double3" 0 0 -8.8817841970012523e-016 ;
setAttr ".sp" -type "double3" 0 0 -8.8817841970012523e-016 ;
createNode nurbsCurve -n "tongueCenterCRoot_ctlShape" -p "tongueCenterCRoot_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
1.3770070964908447 0.52373561260812318 1.2361919986268345e-016
-2.2217301397924177e-016 0.7406740064481897 1.7482394901551732e-016
-1.3770070964908434 0.5237356126081234 1.2361919986268355e-016
-1.9473821113413483 2.1462879686810942e-016 5.065960667482514e-032
-1.3770070964908439 -0.52373561260812329 -1.2361919986268347e-016
-5.8678423548689843e-016 -0.74067400644818981 -1.7482394901551735e-016
1.3770070964908425 -0.52373561260812351 -1.2361919986268357e-016
1.9473821113413483 -3.9781745372163516e-016 -9.3898284051337207e-032
1.3770070964908447 0.52373561260812318 1.2361919986268345e-016
-2.2217301397924177e-016 0.7406740064481897 1.7482394901551732e-016
-1.3770070964908434 0.5237356126081234 1.2361919986268355e-016
;
createNode transform -n "tongueCenterC_ctlGp" -p "tongueCenterCRoot_ctl";
setAttr ".t" -type "double3" 8.0785465294863938e-007 -2.109027579422218e-005 -6.0449322498712377e-006 ;
setAttr ".r" -type "double3" -5.3550608275535809e-012 4.9437415062718022e-005 -9.1458578625526729e-021 ;
setAttr ".s" -type "double3" 0.99999987719358674 0.99999999999999967 0.99999999999999978 ;
createNode transform -n "tongueCenterC_ctl" -p "tongueCenterC_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 17;
createNode nurbsCurve -n "tongueCenterC_ctlShape" -p "tongueCenterC_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
-0.30630081814542537 0.60610587390425508 -8.8758314057115255e-017
-0.21658738559361781 0.60610587390425508 0.2165873855936177
-9.2294414310233125e-017 0.60610587390425508 0.30630081814542542
0.21658738559361762 0.60610587390425508 0.21658738559361779
0.30630081814542537 0.60610587390425508 1.6451476693747092e-016
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
;
createNode transform -n "tongueLeftC_ctlGp" -p "tongueCenterCRoot_ctl";
setAttr ".t" -type "double3" 1.0687414676999385 -2.109027579422218e-005 -6.967090497411732e-006 ;
setAttr ".r" -type "double3" -5.3550608275535809e-012 4.9437415062718022e-005 -9.1458578625526729e-021 ;
setAttr ".s" -type "double3" 0.99999987719358674 0.99999999999999967 0.99999999999999978 ;
createNode transform -n "tongueLeftC_ctl" -p "tongueLeftC_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 13;
createNode nurbsCurve -n "tongueLeftC_ctlShape" -p "tongueLeftC_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
-0.30630081814542537 0.60610587390425508 -8.8758314057115255e-017
-0.21658738559361781 0.60610587390425508 0.2165873855936177
-9.2294414310233125e-017 0.60610587390425508 0.30630081814542542
0.21658738559361762 0.60610587390425508 0.21658738559361779
0.30630081814542537 0.60610587390425508 1.6451476693747092e-016
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
;
createNode transform -n "tongueRightC_ctlGp" -p "tongueCenterCRoot_ctl";
setAttr ".t" -type "double3" -1.0687858298653841 -2.109027579422218e-005 -5.122734330953449e-006 ;
setAttr ".r" -type "double3" -5.3550608275535809e-012 4.9437415062718022e-005 -9.1458578625526729e-021 ;
setAttr ".s" -type "double3" 0.99999987719358674 0.99999999999999967 0.99999999999999978 ;
createNode transform -n "tongueRightC_ctl" -p "tongueRightC_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 13;
createNode nurbsCurve -n "tongueRightC_ctlShape" -p "tongueRightC_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
-0.30630081814542537 0.60610587390425508 -8.8758314057115255e-017
-0.21658738559361781 0.60610587390425508 0.2165873855936177
-9.2294414310233125e-017 0.60610587390425508 0.30630081814542542
0.21658738559361762 0.60610587390425508 0.21658738559361779
0.30630081814542537 0.60610587390425508 1.6451476693747092e-016
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
;
createNode transform -n "tongueCenterDRoot_ctlGp" -p "tongue_ctl_offset_Gp";
setAttr ".t" -type "double3" 3.6366313348485377 -0.77649868511463183 5.7503347156583247e-006 ;
setAttr ".r" -type "double3" -5.3614208018684395e-012 89.999950562590996 0 ;
setAttr ".s" -type "double3" 1.0000001228064284 1.0000000000000002 1 ;
createNode transform -n "tongueCenterDRoot_ctl" -p "tongueCenterDRoot_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr ".rp" -type "double3" 2.7105054312137611e-020 0 -1.7763568394002505e-015 ;
setAttr ".sp" -type "double3" 2.7105054312137611e-020 0 -1.7763568394002505e-015 ;
createNode nurbsCurve -n "tongueCenterDRoot_ctlShape" -p "tongueCenterDRoot_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
1.0971490830928077 0.45831509323914349 1.3814547323995889e-016
-1.7701936264270462e-016 0.64815542069908683 1.953672018363995e-016
-1.0971490830928066 0.45831509323914371 1.3814547323995899e-016
-1.5516031132550532 1.8781922535028139e-016 5.6612527390710642e-032
-1.097149083092807 -0.45831509323914366 -1.3814547323995891e-016
-4.6752829929373208e-016 -0.64815542069908694 -1.9536720183639953e-016
1.0971490830928059 -0.45831509323914382 -1.3814547323995904e-016
1.5516031132550532 -3.4812554083659805e-016 -1.0493210521586435e-031
1.0971490830928077 0.45831509323914349 1.3814547323995889e-016
-1.7701936264270462e-016 0.64815542069908683 1.953672018363995e-016
-1.0971490830928066 0.45831509323914371 1.3814547323995899e-016
;
createNode transform -n "tongueCenterD_ctlGp" -p "tongueCenterDRoot_ctl";
setAttr ".t" -type "double3" 1.0617222921795264e-006 -2.1090275993174146e-005 -6.04493246214588e-006 ;
setAttr ".r" -type "double3" -5.3550608275535745e-012 4.9437415062718029e-005 -3.0794304942799964e-021 ;
setAttr ".s" -type "double3" 0.99999987719358685 0.99999999999999989 1.0000000000000002 ;
createNode transform -n "tongueCenterD_ctl" -p "tongueCenterD_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 17;
createNode nurbsCurve -n "tongueCenterD_ctlShape" -p "tongueCenterD_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
-0.30630081814542537 0.60610587390425508 -8.8758314057115255e-017
-0.21658738559361781 0.60610587390425508 0.2165873855936177
-9.2294414310233125e-017 0.60610587390425508 0.30630081814542542
0.21658738559361762 0.60610587390425508 0.21658738559361779
0.30630081814542537 0.60610587390425508 1.6451476693747092e-016
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
;
createNode transform -n "tongueLeftD_ctlGp" -p "tongueCenterDRoot_ctl";
setAttr ".t" -type "double3" 0.82193818750374648 0.026994595759163076 -0.11806686613690509 ;
setAttr ".r" -type "double3" -5.3550608275535745e-012 4.9437415062718029e-005 -3.0794304942799964e-021 ;
setAttr ".s" -type "double3" 0.99999987719358685 0.99999999999999989 1.0000000000000002 ;
createNode transform -n "tongueLeftD_ctl" -p "tongueLeftD_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 13;
createNode nurbsCurve -n "tongueLeftD_ctlShape" -p "tongueLeftD_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
-0.30630081814542537 0.60610587390425508 -8.8758314057115255e-017
-0.21658738559361781 0.60610587390425508 0.2165873855936177
-9.2294414310233125e-017 0.60610587390425508 0.30630081814542542
0.21658738559361762 0.60610587390425508 0.21658738559361779
0.30630081814542537 0.60610587390425508 1.6451476693747092e-016
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
;
createNode transform -n "tongueRightD_ctlGp" -p "tongueCenterDRoot_ctl";
setAttr ".t" -type "double3" -0.82198170817458127 0.026994595759191498 -0.11806544768774607 ;
setAttr ".r" -type "double3" -5.3550608275535745e-012 4.9437415062718029e-005 -3.0794304942799964e-021 ;
setAttr ".s" -type "double3" 0.99999987719358685 0.99999999999999989 1.0000000000000002 ;
createNode transform -n "tongueRightD_ctl" -p "tongueRightD_ctlGp";
setAttr ".ove" yes;
setAttr ".ovc" 13;
createNode nurbsCurve -n "tongueRightD_ctlShape" -p "tongueRightD_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
3 8 2 no 3
13 -2 -1 0 1 2 3 4 5 6 7 8 9 10
11
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
-0.30630081814542537 0.60610587390425508 -8.8758314057115255e-017
-0.21658738559361781 0.60610587390425508 0.2165873855936177
-9.2294414310233125e-017 0.60610587390425508 0.30630081814542542
0.21658738559361762 0.60610587390425508 0.21658738559361779
0.30630081814542537 0.60610587390425508 1.6451476693747092e-016
0.21658738559361795 0.60610587390425508 -0.21658738559361762
-3.4945260899414864e-017 0.60610587390425508 -0.30630081814542537
-0.21658738559361776 0.60610587390425508 -0.21658738559361776
;
'''
facial_bs_Panel = '''
createNode transform -n "facial_panelGp" -p "ctlGp";
setAttr ".t" -type "double3" 25.301668360178851 191.88146002926575 9.7810824328803392e-008 ;
setAttr ".r" -type "double3" 1.5902773407317584e-014 6.3611093629270304e-015 2.5444437451708134e-014 ;
setAttr ".s" -type "double3" 1.0000002420157659 1.0000001192092984 1.0000001192093109 ;
createNode transform -n "facial_panel" -p "facial_panelGp";
setAttr ".ove" yes;
setAttr ".ovc" 17;
createNode nurbsCurve -n "facial_panelShape" -p "facial_panel";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 4 0 no 3
5 0 1 2 3 4
5
3.9505976766568374 -8.0466389120191746 1.277598371340804e-015
-3.9505976766568374 -8.0466389120191746 1.277598371340804e-015
-3.9505976766568374 5.2174868562978434 -1.2775983713408044e-015
3.9505976766568374 5.2174868562978434 -1.2775983713408044e-015
3.9505976766568374 -8.0466389120191746 1.277598371340804e-015
;
createNode transform -n "facial_ctlGp" -p "facial_panel";
setAttr ".t" -type "double3" 0 0.59392984596704679 0 ;
setAttr ".rp" -type "double3" 0 5.3453686137034424 0 ;
setAttr ".sp" -type "double3" 0 5.3453686137034424 0 ;
createNode transform -n "facial_ctl" -p "facial_ctlGp";
addAttr -is true -ci true -h true -k true -sn "MaxHandle" -ln "MaxHandle" -smn
0 -smx 0 -at "long";
setAttr -l on -k off ".v";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr -l on -k off ".tx";
setAttr -l on -k off ".ty";
setAttr -l on -k off ".tz";
setAttr -l on -k off ".rx";
setAttr -l on -k off ".ry";
setAttr -l on -k off ".rz";
setAttr -l on -k off ".sx";
setAttr -l on -k off ".sy";
setAttr -l on -k off ".sz";
setAttr ".rp" -type "double3" 0 5.3453686137034424 0 ;
setAttr ".sp" -type "double3" 0 5.3453686137034424 0 ;
setAttr -k on ".MaxHandle" 1;
createNode nurbsCurve -n "curveShape1" -p "facial_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 10 0 no 3
11 0 1 2 3 4 5 6 7 8 9 10
11
-2.4231867542743153 5.3453686137033918 -2.0179069540610588e-031
-2.4231867542743153 6.7235962128819775 2.2454178388338578e-007
-1.4900339953620021 6.7235962128819775 2.2454178388338578e-007
-1.4900339953620021 6.5601870412736876 1.9791904873750619e-007
-2.240426459861085 6.5601870412736876 1.9791904873750619e-007
-2.240426459861085 6.13446307775052 1.285598084365495e-007
-1.5910897859916981 6.13446307775052 1.285598084365495e-007
-1.5910897859916981 5.9710538651319238 1.0193707329066993e-007
-2.240426459861085 5.9710538651319238 1.0193707329066993e-007
-2.240426459861085 5.3453686137033918 -2.0179069540610588e-031
-2.4231867542743153 5.3453686137033918 -2.0179069540610588e-031
;
createNode nurbsCurve -n "curveShape2" -p "facial_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 165 0 no 3
166 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
166
-0.62138519785445001 5.4700756422275676 2.0317354108346601e-008
-0.64769261172780435 5.4481263832787681 1.6741364805249994e-008
-0.67380264300025972 5.4281030349231409 1.3479146622829065e-008
-0.69971512763059374 5.4100055971606862 1.0530700783286163e-008
-0.7254302296600289 5.3938340853702691 7.8960278977224664e-009
-0.75094774403703701 5.379588502115034 5.5751279661379767e-009
-0.77626791682345164 5.3672688448318358 3.5680009885326909e-009
-0.80139058397805063 5.3568751212101073 1.8746480343336679e-009
-0.82667581598408602 5.3481179631742535 4.4792570337005241e-010
-0.85248360130419876 5.3407080635233513 -7.593003143990261e-010
-0.87881361185594409 5.3346454209758285 -1.7470300953612147e-009
-0.90566609370115536 5.3299300368132574 -2.5152638686794528e-009
-0.93304096481922172 5.3265619065501362 -3.0640017107413897e-009
-0.96093847127197651 5.3245410263417474 -3.393244690974081e-009
-0.9893582029563639 5.3238674025959529 -3.5029920455010572e-009
-1.0351343982014516 5.3255067293288096 -3.2359118045759003e-009
-1.0777806049018044 5.3304247172168129 -2.4346698595980779e-009
-1.1172969870986449 5.3386213701046774 -1.0992657522417088e-009
-1.1536834627713617 5.3500966796621867 7.702993716785027e-010
-1.1869399498993436 5.3648506516564138 3.174026505201967e-009
-1.2170667765650356 5.3828832956991484 6.1119180163457373e-009
-1.2440636146859927 5.4041945855181659 9.5839675649351202e-009
-1.2676791531094396 5.4280564062056627 1.3471550635219707e-008
-1.2876612604764879 5.4537406326012619 1.7656040267044387e-008
-1.304010264869583 5.4812472185683694 2.2137433404903273e-008
-1.3167262483093365 5.5105762204961559 2.6915736159808127e-008
-1.3258088827133028 5.5417275973743161 3.1990938754140139e-008
-1.3312587422257607 5.5747014004657309 3.7363055854327525e-008
-1.3330752527024317 5.6094975580023663 4.3032067905132667e-008
-1.3323889042277499 5.6301736417609405 4.640062869188222e-008
-1.3303301868861483 5.6503321139472629 4.9684852627626801e-008
-1.3268984445127383 5.6699728105201119 5.2884734823556987e-008
-1.3220943332724089 5.6890959570361677 5.6000289946101002e-008
-1.3159175250827153 5.7077013894542077 5.9031503328830624e-008
-1.308368101964269 5.7257892718154553 6.1978389638174087e-008
-1.29944606391707 5.7433593990683818 6.4840929318893768e-008
-1.2894127286084622 5.7601822775427953 6.7581727867868838e-008
-1.2785290856233453 5.7760281264963673 7.0163341893884481e-008
-1.2667952169823304 5.7908969049187897 7.2585766508131303e-008
-1.2542111226854176 5.8047886538203697 7.4849035932275079e-008
-1.2407769667738291 5.8177034552217188 7.6953115944650021e-008
-1.2264927492475655 5.82964126811253 7.8898030989303168e-008
-1.2113582240447922 5.8406019694618871 8.068375662218748e-008
-1.1955182395649231 5.8507094924133423 8.2330473848517047e-008
-1.1791175621867598 5.860087483038309 8.3858353895887193e-008
-1.1621556997866349 5.868735900326481 8.526735765382271e-008
-1.1446331444882156 5.8766549083190815 8.6557524232798794e-008
-1.1265496502296686 5.8838443429748866 8.7728834077577826e-008
-1.1079056271140495 5.8903043683351202 8.8781306743397438e-008
-1.0887005830176915 5.8960347793482528 8.971491289740121e-008
-1.0733081029926341 5.899781275817217 9.032530030655868e-008
-1.055830494989163 5.9034929135264127 9.0929987363952707e-008
-1.0362672668836108 5.9071658785174179 9.1528397190073712e-008
-1.0146181726141437 5.9107967259245626 9.2119933350174619e-008
-0.99088255601587205 5.9143816827997302 9.2703999409508286e-008
-0.9650602530475737 5.9179171812463327 9.3280008710946385e-008
-0.93715060754435831 5.9213994893265598 9.3847345264504197e-008
-0.8803759404584468 5.9286144323924539 9.5022800819656689e-008
-0.82804490402655651 5.9361860830965414 9.6256384318606574e-008
-0.78015831845479944 5.9441217002629125 9.754926907561052e-008
-0.73671749607295522 5.9524289528187184 9.8902677293019178e-008
-0.69772284698408005 5.9611151405983573 1.00317840950802e-007
-0.663175601497342 5.9701878505083661 1.0179598225130967e-007
-0.63307641577763085 5.9796543413728376 1.0333826473118002e-007
-0.63213580340816933 6.0238326110701541 1.1053582415183874e-007
-0.63312324954663701 6.0521386621873914 1.1514745761658875e-007
-0.63608484977653901 6.0779475957960614 1.1935228347332602e-007
-0.64101994793298533 6.1012605601847198 1.2315045816395155e-007
-0.64792776482016967 6.1220785396007038 1.2654212835274741e-007
-0.65680752124228536 6.1404022722295117 1.2952744070399566e-007
-0.66765852002413706 6.1562327423184797 1.3210654188197836e-007
-0.68047989994930691 6.1695705240118848 1.3427953944050235e-007
-0.70047143968664571 6.1847782115998653 1.3675719782338017e-007
-0.72305220607895138 6.197649460056657 1.3885419395093072e-007
-0.74822318337355853 6.2081830390730905 1.4057031271554025e-007
-0.77598551985902398 6.2163779644018318 1.4190543678578301e-007
-0.80634011776207171 6.2222328416924899 1.4285932172118894e-007
-0.83928828941248079 6.2257467687183414 1.4343180130223833e-007
-0.8748306909751411 6.2269182691083849 1.4362267019893631e-007
-0.90793724442581436 6.2260677973906535 1.4348410178522782e-007
-0.938471877570488 6.223516300216847 1.4306841609933994e-007
-0.96643467242977332 6.2192636135457446 1.4237558380841629e-007
-0.9918258750655039 6.2133100654597895 1.4140560491245688e-007
-1.0146451573952349 6.2056552458559269 1.4015848918908047e-007
-1.0348927654807998 6.1962996468578222 1.3863427574876226e-007
-1.0525685352809764 6.1852428583624217 1.3683288637055193e-007
-1.0683485626940443 6.1720257289881193 1.3467955160344533e-007
-1.0829088615976721 6.1561889433120882 1.320993944426317e-007
-1.0962494319918592 6.1377320912312712 1.2909240511049213e-007
-1.1083701918559949 6.1166557468899478 1.2565862271750195e-007
-1.1192711411900791 6.0929594181644502 1.2179800815318585e-007
-1.1289526900971678 6.0666434331372239 1.175105907504003e-007
-1.1374142644329828 6.0377076277670456 1.1279635095390766e-007
-1.302973606364384 6.0592088388744845 1.1629933933280167e-007
-1.295917537222421 6.0887347005217727 1.2110970289976907e-007
-1.2876692164757761 6.1165902944421946 1.2564795533538538e-007
-1.2782283980626157 6.1427755386151386 1.299140966396506e-007
-1.2675953280447732 6.1672908431436593 1.3390812681256484e-007
-1.2557698423810266 6.190135797924702 1.3763005563174675e-007
-1.2427523511744318 6.2113107310407107 1.410798928748152e-007
-1.2285424443219324 6.2308153964298523 1.4425759943129501e-007
-1.2127942409060175 6.2488710857011966 1.4719923515934008e-007
-1.1951621880916208 6.2656987623813674 1.4994082080662896e-007
-1.1756456297138522 6.2812983444497528 1.524823172626865e-007
-1.154245303958213 6.2956701599887985 1.5482377341560676e-007
-1.1309607187010355 6.3088137988954482 1.5696515015491451e-007
-1.105792202024765 6.3207296712727583 1.5890650614632247e-007
-1.0787395078675679 6.3314175310588956 1.6064776316888038e-007
-1.0501095573566257 6.3407719817684418 1.6217180061206002e-007
-1.0202091075778987 6.3486872168129258 1.6346134142343262e-007
-0.98903807651077535 6.3551631541717359 1.6451643449109197e-007
-0.95659671021708959 6.3602001219273161 1.6533703092694431e-007
-0.92288476263500763 6.3637977919972233 1.659231796190835e-007
-0.88790247982636306 6.3659566565051229 1.6627490012274715e-007
-0.85164969774993349 6.366676141306737 1.6639211421698492e-007
-0.81602092848365948 6.3660622170317618 1.662920891766069e-007
-0.78235368213469192 6.3642203621862237 1.6599203361071029e-007
-0.75064779466180842 6.3611503307082904 1.6549184974310718e-007
-0.72090367616806517 6.3568525327010175 1.6479165490522313e-007
-0.69312108059162836 6.3513266400819592 1.6389138065372658e-007
-0.66730008995310919 6.3445729809335614 1.6279106609909274e-007
-0.64344070425250799 6.3365912271733782 1.6149067213084632e-007
-0.6214270693764774 6.3276792776613595 1.6003871529349924e-007
-0.6011431261601422 6.3181342930719504 1.5848366324346914e-007
-0.58258907965503071 6.3079565194669858 1.5682547687028102e-007
-0.5657648068302259 6.297145874825854 1.550641952844099e-007
-0.55067038970633908 6.285702359148555 1.531998184858559e-007
-0.53730582828337026 6.273626218496922 1.5123236602985658e-007
-0.52567108155101372 6.2609170427679004 1.4916177925069911e-007
-0.51536277214329362 6.2474027527191511 1.4696002571526877e-007
-0.50597727663240055 6.232910776984669 1.4459896543664394e-007
-0.49751451299772315 6.2174407874820092 1.4207860819244339e-007
-0.48997472730109504 6.2009933583554515 1.3939898331552354e-007
-0.4833577555012939 6.18356824354316 1.3656005169540926e-007
-0.47766372062923645 6.1651654430451366 1.3356185244257568e-007
-0.47289245864370033 6.1457847928201588 1.304043562241664e-007
-0.47064636521576891 6.1320168130209085 1.2816126291642732e-007
-0.46874586563320941 6.1154199423407087 1.2545726243582596e-007
-0.4671907958547995 6.0959940167383371 1.2229240367045625e-007
-0.46598131992176162 6.0737393642962392 1.1866664750984311e-007
-0.46511739682379005 6.0486556569319694 1.1458000373160525e-007
-0.46459910858149611 6.0207432227279725 1.1003249189098032e-007
-0.4644262911536573 5.9900018156224153 1.0502408265511191e-007
-0.4644262911536573 5.7649110118414146 6.8352135786393596e-008
-0.46421381676029405 5.7011684477706011 5.7967145967353199e-008
-0.46357614751837056 5.644457613225371 4.8727789966109137e-008
-0.46251340645880379 5.5947785492160298 4.0634038449805038e-008
-0.46102567560220475 5.5521312967528837 3.3685918306892605e-008
-0.45911266787643445 5.5165157943204743 2.7883414870943611e-008
-0.45677475237424314 5.4879320624239547 2.3226535475172177e-008
-0.45401164202349159 5.4663801215684771 1.9715277675173602e-008
-0.45062054086294051 5.4484510208579735 1.6794255611974829e-008
-0.44639840686951676 5.4307358452803935 1.3908085871007487e-008
-0.44134540408444278 5.4132345486991449 1.1056764785664527e-008
-0.43546136846649619 5.3959472028822617 8.2402972447553549e-009
-0.42874638203628807 5.3788737540037168 5.4586801927740919e-009
-0.42120044479381857 5.3620142187239486 2.7119133241701528e-009
-0.41282351572878195 5.3453686137033918 -2.0179069540610588e-031
-0.58698312884956982 5.3453686137033918 -2.0179069540610588e-031
-0.59423440704623454 5.3609707050898523 2.5419037549909196e-009
-0.60070669448784497 5.3773105359902109 5.2039988891458e-009
-0.60640011420531836 5.3943880935887494 7.9862869302175745e-009
-0.61131466619865438 5.4122033753223215 1.0888765739352131e-008
-0.61545035046785301 5.4307563965697927 1.3911437149852994e-008
-0.61880729004383139 5.4500471727100273 1.7054301161720174e-008
-0.62138519785445001 5.4700756422275676 2.0317354108346601e-008
;
createNode nurbsCurve -n "curveShape3" -p "facial_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 64 0 no 3
65 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64
65
-0.63643598001316815 5.8463468571129003 8.1619719182323311e-008
-0.66473907838840196 5.8358861944198406 7.9915465558134034e-008
-0.69681660125071943 5.8258879639328347 7.8286543598030104e-008
-0.73266781041461992 5.8163488028068224 7.6732415532977163e-008
-0.77229245981826955 5.8072653892070498 7.5252543593940961e-008
-0.81568989329677888 5.7986344423090674 7.3846390011887178e-008
-0.862859864788314 5.7904527222987321 7.2513412128972169e-008
-0.91380163610737397 5.7827167022897621 7.1253052620924013e-008
-0.94247103853231251 5.7783797804509378 7.0546482775578932e-008
-0.96863618765550719 5.773882385286262 6.9813757799929747e-008
-0.99229732953879168 5.7692263622594888 6.9055190577778173e-008
-1.0134547922646111 5.7644135978446762 6.8271093992926004e-008
-1.0321088218947987 5.7594459785158811 6.7461766262746811e-008
-1.0482599925736333 5.754325472767774 6.6627530048661125e-008
-1.0619080582392812 5.7490538440434955 6.5768673790423767e-008
-1.0739007019086926 5.7433542727801807 6.48400982212953e-008
-1.0850851964957615 5.7369484630439631 6.3796459634066254e-008
-1.0954608858355981 5.7298364558451489 6.2637767806355444e-008
-1.1050284260930923 5.7220183332043479 6.136402762697225e-008
-1.1137876532270212 5.7134939310803396 5.9975224429488477e-008
-1.1217385672373854 5.7042633725040393 5.8471372880332308e-008
-1.1288810040829624 5.6943265754548369 5.6852468090694361e-008
-1.1351381104510392 5.6838742173486629 5.5149568666709614e-008
-1.1404324588846257 5.6730969345911442 5.3393718548084862e-008
-1.1447640493837214 5.661994542635906 5.1584912846010684e-008
-1.1481332920513827 5.6505672260293229 4.9723161338105903e-008
-1.1505398588051643 5.6388149027507835 4.7808468913179891e-008
-1.1519837496450667 5.6267376138105938 4.584083068242327e-008
-1.1524650465917008 5.6143353387036017 4.3820241757026643e-008
-1.1514089492016426 5.5955481896214048 4.0759429077768704e-008
-1.1482404109696349 5.5776777028901936 3.7847959748142684e-008
-1.1429592678544549 5.5607238990151213 3.5085826434934489e-008
-1.1355658479385473 5.544686777996187 3.2473048693381698e-008
-1.12605998718069 5.5295663193282376 3.0009614301460831e-008
-1.1144417676014942 5.5153625640215802 2.7695530592385969e-008
-1.1007110251597374 5.5020754915710608 2.5530792677347722e-008
-1.0849460895391339 5.4901631153223036 2.3590020898663329e-008
-1.0672251263821755 5.4800833871054753 2.1947820932221798e-008
-1.0475478896270285 5.4718363376783037 2.060420744445133e-008
-1.0259147073561379 5.4654219567882141 1.9559173102137839e-008
-1.0023254975488927 5.4608402649403587 1.8812721571888365e-008
-0.97678009616407002 5.4580912621347366 1.8364851631500561e-008
-0.94927866724289256 5.4571749176136199 1.8215559614367374e-008
-0.9215132959948118 5.4580470325201365 1.8357644304238717e-008
-0.89463850454334892 5.4606633977448409 1.8783904484864493e-008
-0.86865429288850371 5.465023951772273 1.9494331600828238e-008
-0.84356066103027616 5.4711287663704695 2.0488930540939377e-008
-0.81935769098927791 5.478977790276546 2.1767697638590844e-008
-0.79604546478611971 5.4885710850059635 2.3330645115806148e-008
-0.77362381837957916 5.4999085685381086 2.5177754639550026e-008
-0.75247496781793788 5.5127495206316306 2.7269813069603882e-008
-0.73298506613881553 5.5268550665089302 2.9567893261099199e-008
-0.71515977276438647 5.5422280051233646 3.2072466984143296e-008
-0.69900532126110304 5.5588713199746671 3.4784006008843571e-008
-0.68452728903052829 5.5767877997636184 3.770296743887914e-008
-0.67173190963911489 5.5959803767270717 4.0829840155190257e-008
-0.66062484250903686 5.616451860070959 4.4165069039432597e-008
-0.65328879601067724 5.6338336680005261 4.6996921663531887e-008
-0.64709390227621 5.653435384277893 5.0190448407238643e-008
-0.64203544512048993 5.675254753336251 5.3745272832228866e-008
-0.63810899543051125 5.6992896016294035 5.7661052721844356e-008
-0.63531004207265696 5.7255377966214578 6.1937421415379954e-008
-0.63363407391331006 5.7539971032507582 6.6574036696177421e-008
-0.63307641577763085 5.7846652249401904 7.157050257067518e-008
-0.63643598001316815 5.8463468571129003 8.1619719182323311e-008
;
createNode nurbsCurve -n "curveShape4" -p "facial_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 121 0 no 3
122 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
122
0.44937518091249418 5.7108892025298523 5.9550865995720318e-008
0.61493444082328441 5.6893879914224135 5.6047872728016916e-008
0.60541594889129946 5.6419067517113017 4.8312192278790536e-008
0.59242954349635657 5.5974662211096122 4.1071914441571488e-008
0.57597518362815026 5.556066420122499 3.4327026994336293e-008
0.55605299231759731 5.5177073692551142 2.8077547047917825e-008
0.53266284653378093 5.4823890787600336 2.2323467269102014e-008
0.50580491031792341 5.4501115588898346 1.7064792546698239e-008
0.47547906063910816 5.4208748198970929 1.230152288070651e-008
0.44237435265218733 5.3951381361943307 8.1084833323377913e-009
0.40717984151201314 5.3733609513615805 4.560530434513572e-009
0.36989540418766886 5.355543256427838 1.6576594511997457e-009
0.33052128674098802 5.3416850658107879 -6.0012671487310276e-010
0.28905736614105398 5.3317863618888151 -2.2128300497837958e-009
0.24550372440847784 5.325847139215238 -3.1804522340605638e-009
0.19986027952264837 5.3238674025959529 -3.5029920455010572e-009
0.14300446329451189 5.3265996193708602 -3.0578576995246194e-009
0.089426621298902498 5.3347962684140091 -1.7224538977188385e-009
0.039126717651802742 5.3484573580556178 5.0322027656804889e-010
-0.0078951835681848551 5.3675828761207525 3.6191626844819293e-009
-0.0516391105556454 5.3921728245317713 7.6253742426745661e-009
-0.092105086378875808 5.4222272321240448 1.2521859076078892e-008
-0.12929302645412077 5.4577460373821154 1.8308607101525514e-008
-0.16230280583613182 5.49836455103706 2.4926205840546472e-008
-0.19023417654874378 5.543718012051924 3.2315218370626802e-008
-0.21308708732907461 5.5938063794164021 4.0475648358373537e-008
-0.23086158944000634 5.6486296531304925 4.9407500692596091e-008
-0.2435576623763861 5.7081878536993491 5.9110760706866261e-008
-0.25117532664336684 5.7724810631435828 6.958545528963575e-008
-0.25371452072548994 5.8415090764116657 8.0831545330429362e-008
-0.25262098092641033 5.8868547044581581 8.8219289214469689e-008
-0.24934025900340745 5.9305513081160894 9.5338363688978435e-008
-0.24387235495648127 5.9725989283957652 1.0218879808681195e-007
-0.23621735080624306 6.0129977293384069 1.0877058263035154e-007
-0.22637516453208159 6.0517475058924868 1.1508372709721589e-007
-0.21434589865976086 6.0888484631095343 1.2112825104264269e-007
-0.20012947116866966 6.12430039593802 1.2690409580091905e-007
-0.18367790000124479 6.157691150806567 1.3234413801894679e-007
-0.1649431723421938 6.1886080820201332 1.3738114678982061e-007
-0.14392528819151676 6.2170511895787186 1.4201512211354067e-007
-0.12062431931724837 6.243020555502933 1.462460737677257e-007
-0.095040204203930306 6.2665161797927773 1.5007400175237572e-007
-0.067172963356715354 6.2875383085100847 1.5349893540034718e-007
-0.0370226275333327 6.3060864495311888 1.5652080626830837e-007
-0.0053378042990609616 6.3221613410415891 1.5913974146530375e-007
0.027132751400035474 6.3357632291031205 1.6135576054657102e-007
0.060389043729065769 6.3468917856333382 1.631688341792537e-007
0.094431047376981908 6.3555475027559085 1.6457901125144588e-007
0.12925876234378395 6.3617299703677759 1.6558630154076621e-007
0.16487223476606566 6.3654396805926083 1.6619065615912089e-007
0.20127136211806299 6.366676141306737 1.6639211421698492e-007
0.24653056094548345 6.3649734754384388 1.6611470361624141e-007
0.28937289943241418 6.3598653137923193 1.6528249136924841e-007
0.3297983980840079 6.3513514103065472 1.6389539925505559e-007
0.36780707740541752 6.3394321750841769 1.6195351527223208e-007
0.4033988963863373 6.3241072800427638 1.5945679053268386e-007
0.43657397805768428 6.3053772173059768 1.5640525436926751e-007
0.46733211736793018 6.2832414127295344 1.527988774491264e-007
0.49536561399408641 6.2579731589900218 1.4868214793782473e-007
0.52036668559255295 6.2298450105785186 1.440994953352136e-007
0.54233508610149628 6.1988570495156363 1.3905091964129305e-007
0.56127097956213867 6.1650094398425983 1.3353644041130072e-007
0.57717440698478573 6.1283020175181804 1.275560478676178e-007
0.59004536836943766 6.0887349465836067 1.2110975178786306e-007
0.59988365866456628 6.0463081450182656 1.1419755217203655e-007
0.43647432301505296 6.0248068929005205 1.1069455401552374e-007
0.42900618232232485 6.0525288342349608 1.1521103169406069e-007
0.42005912798870382 6.0782171975451389 1.1939619475938058e-007
0.40963316001418981 6.1018719418207477 1.2325004321148342e-007
0.39772831940908859 6.1234930670617889 1.2677256727275036e-007
0.38434456516309445 6.1430805732682625 1.2996379627603786e-007
0.36948193828651299 6.1606347885226125 1.3282373022134593e-007
0.35314039776903866 6.1761553027217824 1.3535233977581814e-007
0.3355496833426963 6.1896230870839712 1.3754652543429317e-007
0.31693947322405241 6.2010188667655406 1.394031388035158e-007
0.29730964438219021 6.2103425597458797 1.4092215055062958e-007
0.27666031984802653 6.2175944941074341 1.4210361934134732e-007
0.25499145861125566 6.2227743417677583 1.4294753539805021e-007
0.23230308117703047 6.2258823487886872 1.4345389872073828e-007
0.20859514653504538 6.2269182691083849 1.4362267019893631e-007
0.17298481140114283 6.22505238222376 1.4331868403027998e-007
0.13933466634961447 6.2194547215698854 1.4240669619145472e-007
0.10764467037015471 6.2101249590643155 1.4088669690484161e-007
0.077914915735951162 6.1970634227894958 1.3875870572567832e-007
0.050145356310410033 6.1802700307248148 1.3602271287634605e-007
0.024336002346107711 6.1597448648908841 1.3267874768970118e-007
0.00048687434819701027 6.1354877612464813 1.2872675150003093e-007
-0.020748637397057589 6.1071931930148144 1.2411697578285396e-007
-0.038717155419112109 6.0745548952335913 1.1879954490464451e-007
-0.053418680999538587 6.0375732780058682 1.1277445886540265e-007
-0.064853200041044501 5.9962481772904228 1.060417469979847e-007
-0.073020715106773909 5.9505796751078659 9.8601409302390734e-008
-0.077921241575591438 5.9005677714581974 9.0453436001001924e-008
-0.079554743563479677 5.8462124663414183 8.1597822205008896e-008
-0.077982603245359786 5.7911180324866365 7.2621797033428756e-008
-0.073266177164711885 5.7405013908704499 6.4375304444957905e-008
-0.065405460195247789 5.6943625414928567 5.6858324884358727e-008
-0.05440046258954389 5.6527015253641624 5.0070887684487628e-008
-0.040251189473888394 5.6155183424843687 4.4012983067725799e-008
-0.022957643411425407 5.5828129928534738 3.8684603700859156e-008
-0.00251983721787543 5.5545854764714786 3.4085754472697085e-008
0.020448621380082459 5.5304531876921983 3.0154105507760614e-008
0.045334088771751761 5.5100335721323299 2.6827324486166045e-008
0.072136563675560428 5.4933265580238393 2.4105411407913371e-008
0.1008560294310718 5.4803322581450669 2.1988366273002612e-008
0.13149251166972689 5.471050590475401 2.0476192748040795e-008
0.16404601039152572 5.4654816062777236 1.956888961082559e-008
0.19851645382843341 5.463625274794305 1.9266455639154639e-008
0.22630524196101726 5.4648631811217072 1.9468138582251236e-008
0.25275084005912307 5.4685768795987597 2.0073173967315182e-008
0.27785330963820937 5.4747663702254634 2.1081572794167622e-008
0.30161258918281764 5.4834316530018166 2.2493324062987414e-008
0.32402874020840639 5.4945727176752452 2.4308436329190992e-008
0.34510180372528121 5.5081895847509008 2.6526904703968979e-008
0.36483161569221956 5.5242822029659013 2.9148724298511953e-008
0.38289271832390387 5.5429452958736283 3.2189331528508756e-008
0.39895936676287713 5.5642734229862425 3.5664123699173027e-008
0.41303147898852821 5.5882665432934369 3.9573095921695348e-008
0.42510913702146824 5.6149246773003636 4.3916257973694529e-008
0.43519225884108609 5.6442477839967191 4.8693602521956464e-008
0.44328096747829843 5.6762360274237249 5.3905146677314066e-008
0.44937518091249418 5.7108892025298523 5.9550865995720318e-008
;
createNode nurbsCurve -n "curveShape5" -p "facial_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 4 0 no 3
5 0 1 2 3 4
5
0.7589924896266359 6.5300853949356394 1.9301486891810212e-007
0.7589924896266359 6.7235962128819775 2.2454178388338578e-007
0.92885225422486983 6.7235962128819775 2.2454178388338578e-007
0.92885225422486983 6.5300853949356394 1.9301486891810212e-007
0.7589924896266359 6.5300853949356394 1.9301486891810212e-007
;
createNode nurbsCurve -n "curveShape6" -p "facial_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 4 0 no 3
5 0 1 2 3 4
5
0.7589924896266359 5.3453686137033918 -2.0179069540610588e-031
0.7589924896266359 6.345174930199299 1.6288912583809093e-007
0.92885225422486983 6.345174930199299 1.6288912583809093e-007
0.92885225422486983 5.3453686137033918 -2.0179069540610588e-031
0.7589924896266359 5.3453686137033918 -2.0179069540610588e-031
;
createNode nurbsCurve -n "curveShape7" -p "facial_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 165 0 no 3
166 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
166
1.8405034739472994 5.4700756422275676 2.0317354108346601e-008
1.8141963471460842 5.4481263832787681 1.6741364805249994e-008
1.7880860698117953 5.4281030297968522 1.3479145400626715e-008
1.7621736261917671 5.4100055869081096 1.0530699561083811e-008
1.7364585241623318 5.3938340751176925 7.8960260644189418e-009
1.7109407637234899 5.3795884918624575 5.5751255217332762e-009
1.685620836998909 5.3672688371424035 3.567999155229166e-009
1.6604980878236988 5.3568751212101073 1.8746480343336679e-009
1.6352129378382747 5.3481179542032491 4.4792432839240772e-010
1.6094054806006066 5.3407080507076303 -7.593021477025524e-010
1.5830750599458054 5.3346454094416798 -1.7470320814400343e-009
1.5562224960799829 5.329930027842253 -2.5152652436570979e-009
1.5288474609206939 5.3265619014238474 -3.0640026273931532e-009
1.500950282550384 5.3245410250601752 -3.3932449965246686e-009
1.4725304688453855 5.3238674025959529 -3.5029920455010572e-009
1.4267544376415202 5.3255067293288096 -3.2359114990253127e-009
1.3841081489205562 5.3304247210615285 -2.4346692484969024e-009
1.3445916026824933 5.3386213752309661 -1.0992646828146524e-009
1.3082052090303877 5.3500966854292606 7.7030059388085294e-010
1.2749485578611832 5.3648506580642739 3.1740277274043172e-009
1.2448218952367138 5.3828833008254371 6.1119186274469124e-009
1.2178249750951455 5.4041945855181659 9.5839675649351202e-009
1.1942097647541436 5.4280564062056627 1.3471553079624407e-008
1.1742274933458727 5.4537406326012619 1.7656043933651436e-008
1.1578782428909438 5.4812472288209459 2.2137435849307973e-008
1.1451623414718017 5.5105762204961559 2.6915736159808127e-008
1.1360794610060019 5.5417275973743161 3.1990941198544837e-008
1.1306298475553775 5.5747014004657309 3.7363055854327525e-008
1.1288132550580952 5.6094975580023663 4.3032067905132667e-008
1.1294996855533885 5.6301736417609405 4.640062869188222e-008
1.1315587309774346 5.6503321139472629 4.9684852627626801e-008
1.1349900632477887 5.6699728105201119 5.2884734823556987e-008
1.1397943385293405 5.6890959570361677 5.6000289946101002e-008
1.1459710646984229 5.7077013894542077 5.9031503328830624e-008
1.1535206518580916 5.7257892718154553 6.1978389638174087e-008
1.1624426899052906 5.7433593990683818 6.4840929318893768e-008
1.1724762712757322 5.7601822775427953 6.7581722979059443e-008
1.1833598322402379 5.7760281264963673 7.0163332116265679e-008
1.1950935368400304 5.7908969459290951 7.2585766508131303e-008
1.2076773850751095 5.8047887358409813 7.4849035932275079e-008
1.2211113769454753 5.8177034962320242 7.6953115944650035e-008
1.2353958405335728 5.82964126811253 7.8898030989303168e-008
1.2505302016951234 5.8406019694618871 8.068375662218748e-008
1.2663705142574375 5.8507094924133423 8.2330473848517047e-008
1.2827713556768234 5.8600875240486152 8.3858353895887206e-008
1.2997328899945031 5.8687359823470926 8.5267367431441525e-008
1.3172554452929224 5.8766549083190815 8.6557524232798794e-008
1.3353386934896361 5.8838443429748866 8.7728834077577826e-008
1.3539831267083111 5.8903043683351202 8.8781306743397438e-008
1.3731880887840582 5.8960347793482528 8.971491289740121e-008
1.3885808968915603 5.899781275817217 9.032530030655868e-008
1.4060581768125862 5.9034929135264127 9.0929987363952707e-008
1.4256212408769162 5.9071658785174179 9.1528397190073712e-008
1.4472704171669946 5.9107967259245626 9.2119933350174619e-008
1.4710058697240436 5.9143816827997302 9.2703999409508286e-008
1.4968284187541758 5.9179171812463327 9.3280008710946385e-008
1.5247379002161687 5.9213994893265598 9.3847345264504197e-008
1.581512895384525 5.9286144323924539 9.5022800819656689e-008
1.6338438497958041 5.9361860830965414 9.6256394096225363e-008
1.6817301072851163 5.9441217002629125 9.754926907561052e-008
1.7251710116875718 5.9524289528187184 9.8902687070637967e-008
1.7641655787558359 5.9611151405983573 1.0031785072842082e-007
1.7987131523250186 5.9701878505083661 1.0179598225130967e-007
1.8288122560241185 5.9796543413728376 1.0333826473118002e-007
1.8297528683935802 6.0238326110701541 1.1053582415183874e-007
1.8287655042757236 6.0521386621873914 1.1514745761658875e-007
1.8258039040458218 6.0779475137754497 1.1935228347332602e-007
1.820868723868764 6.1012605601847198 1.2315045816395155e-007
1.8139607839506631 6.1220785396007038 1.2654212835274741e-007
1.8050810685388528 6.1404022722295117 1.2952743092637684e-007
1.7942300697570011 6.1562326602978681 1.3210653210435952e-007
1.7814086078112201 6.1695705240118848 1.3427953944050235e-007
1.7614170680738814 6.1847782115998653 1.367571782681426e-007
1.7388364657227982 6.197649460056657 1.3885419395093072e-007
1.713665488428191 6.2081830390730905 1.4057031271554025e-007
1.6859031519427252 6.2163779644018318 1.4190542700816419e-007
1.6555483079778441 6.2222328416924899 1.4285932172118894e-007
1.6226003003686573 6.2257467687183414 1.4343180130223833e-007
1.5870578167853862 6.2269182691083849 1.4362267019893631e-007
1.5539515093965464 6.2260677973906535 1.4348410178522782e-007
1.5234168762518727 6.223516300216847 1.4306841609933994e-007
1.4954539173513648 6.2192636135457446 1.4237557403079748e-007
1.470062632695023 6.2133100654597895 1.4140559513483809e-007
1.4472433503652922 6.2056552458559269 1.4015848918908047e-007
1.4269959063209494 6.1962996468578222 1.3863427574876226e-007
1.409320136520773 6.1852428583624217 1.3683288637055193e-007
1.3935401911283163 6.1720257289881193 1.3467955160344533e-007
1.3789800562659109 6.1561889433120882 1.320993944426317e-007
1.3656393218305012 6.1377320912312712 1.2909240511049213e-007
1.3535185619663657 6.1166557468899478 1.2565861293988316e-007
1.3426173665704479 6.0929594181644502 1.2179800815318585e-007
1.332936145745804 6.0666434331372239 1.175105907504003e-007
1.3244744073687666 6.0377076277670456 1.1279635095390766e-007
1.1589151474579766 6.0592088388744845 1.1629933933280167e-007
1.1659712986205508 6.0887347005217727 1.2110970289976907e-007
1.1742197013878068 6.1165902944421946 1.2564795533538538e-007
1.1836602737391337 6.1427755386151386 1.299140966396506e-007
1.194293343756976 6.1672907611230485 1.3390812681256481e-007
1.2061185013382778 6.190135797924702 1.3763005563174675e-007
1.2191363206273178 6.2113107310407107 1.410798928748152e-007
1.233346227479817 6.2308153964298523 1.4425759943129501e-007
1.2490944308957317 6.248871003680585 1.4719923515934005e-007
1.266726647751351 6.2656987623813674 1.4994080125139136e-007
1.2862427960260636 6.2812983444497528 1.524823172626865e-007
1.3076432858229254 6.2956701599887985 1.5482376363798797e-007
1.3309277070388801 6.3088137168748375 1.5696515015491448e-007
1.356096305735762 6.3207296712727583 1.5890650614632247e-007
1.3831489998929591 6.3314175310588956 1.6064776316888038e-007
1.4117791144451237 6.3407719817684418 1.6217180061206002e-007
1.4416795642238509 6.3486872168129258 1.6346134142343262e-007
1.4728503492291403 6.3551631541717359 1.6451643449109197e-007
1.5052917975434374 6.3602001219273161 1.6533703092694431e-007
1.539003581084297 6.3637977919972233 1.659231796190835e-007
1.573986027934164 6.3659566565051229 1.6627490012274715e-007
1.6102388100105935 6.366676141306737 1.6639211421698492e-007
1.6458679073593125 6.3660622170317618 1.662920891766069e-007
1.6795352357288911 6.3642203621862237 1.6599203361071029e-007
1.7112406310781072 6.3611502486876788 1.6549184974310716e-007
1.7409847495718505 6.3568525327010175 1.6479165490522313e-007
1.7687674271688985 6.3513266400819592 1.6389138065372658e-007
1.794588499828029 6.3445729809335614 1.6279106609909274e-007
1.8184478035080189 6.3365912271733782 1.6149067213084632e-007
1.8404616434355778 6.3276791136201371 1.6003871529349919e-007
1.8607456686725241 6.3181342930719504 1.5848366324346914e-007
1.879299551136413 6.3079565194669858 1.5682547687028102e-007
1.8961237829509123 6.297145874825854 1.550641952844099e-007
1.9112180360335769 6.2857024411691658 1.531998184858559e-007
1.9245828025080736 6.273626218496922 1.5123236602985658e-007
1.9362175902507355 6.2609170427679004 1.4916177925069911e-007
1.9465259406687614 6.2474028347397619 1.4696002571526879e-007
1.9559115592105714 6.232910776984669 1.4459896543664394e-007
1.964374281834943 6.2174407874820092 1.4207860819244339e-007
1.971913780459432 6.2009934403760623 1.3939898331552359e-007
1.9785307112489274 6.18356824354316 1.3656005169540926e-007
1.9842249101622071 6.1651654430451366 1.3356185244257568e-007
1.9889962131580492 6.1457847928201588 1.304043562241664e-007
1.9912422655756747 6.1320168130209085 1.2816126291642732e-007
1.9931430112200679 6.1154199423407087 1.2545726243582596e-007
1.9946979579675612 6.0959940167383371 1.2229240367045625e-007
1.9959072698593765 6.0737393642962392 1.1866664750984311e-007
1.996771110936737 6.0486556569319694 1.1458000373160525e-007
1.9972896452408646 6.0207432227279725 1.1003249189098032e-007
1.997462380648092 5.9900018156224153 1.0502408265511191e-007
1.997462380648092 5.7649110118414146 6.8352135786393596e-008
1.9976749780723722 5.7011684477706011 5.7967145967353199e-008
1.9983127703452124 5.644457613225371 4.8727789966109137e-008
1.9993752653429455 5.5947785492160298 4.0634038449805038e-008
2.0008631192304618 5.5521312967528837 3.3685918306892605e-008
2.0027760039253151 5.5165157943204743 2.7883414870943611e-008
2.0051139194275063 5.4879320624239547 2.3226535475172177e-008
2.0078770297782578 5.4663801215684771 1.9715277675173602e-008
2.0112682539697255 5.4484510208579735 1.6794255611974829e-008
2.0154905109940664 5.4307358452803935 1.3908085871007487e-008
2.0205433087276123 5.4132345486991449 1.1056764785664527e-008
2.0264273033352529 5.3959472028822617 8.2402972447553549e-009
2.0331420026933218 5.3788737540037168 5.4586801927740919e-009
2.040688227007931 5.3620142187239486 2.7119133241701528e-009
2.0490651560729676 5.3453686137033918 -2.0179069540610588e-031
1.8749055429521797 5.3453686137033918 -2.0179069540610588e-031
1.8676544287967372 5.3609707050898523 2.5419037549909196e-009
1.86118201832421 5.3773105359902109 5.2039988891458e-009
1.8554886396170422 5.3943880935887494 7.9862869302175745e-009
1.8505739645927897 5.4122033753223215 1.0888765739352131e-008
1.8464379932514516 5.4307563965697927 1.3911437149852994e-008
1.8430815457991403 5.4500471727100273 1.7054301161720174e-008
1.8405034739472994 5.4700756422275676 2.0317354108346601e-008
;
createNode nurbsCurve -n "curveShape8" -p "facial_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 64 0 no 3
65 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64
65
1.8254526917885814 5.8463468571129003 8.1619719182323311e-008
1.7971496754339589 5.8358861944198406 7.9915465558134034e-008
1.7650722345922527 5.8258879639328347 7.8286543598030104e-008
1.7292208613871296 5.8163488028068224 7.6732415532977163e-008
1.6895962119834798 5.8072653892070498 7.5252553371559736e-008
1.6461986144637479 5.7986344423090674 7.3846390011887178e-008
1.5990287249928241 5.7904527222987321 7.2513412128972169e-008
1.5480868716531528 5.7827167022897621 7.1253052620924013e-008
1.5194175512488259 5.7783797804509378 7.0546482775578932e-008
1.4932526481874646 5.773882385286262 6.9813757799929747e-008
1.4695911782217352 5.7692263212491834 6.9055190577778173e-008
1.4484337975165271 5.76441355683437 6.8271093992925991e-008
1.4297796858657283 5.7594459785158811 6.7461766262746811e-008
1.4136288432693387 5.7543254317574686 6.6627530048661125e-008
1.3999806135624682 5.7490538440434955 6.5768673790423767e-008
1.387988051913668 5.7433542727801807 6.4840088443676511e-008
1.3768037213678217 5.7369484630439631 6.3796464522875662e-008
1.3664276219249287 5.7298364558451489 6.2637772695164838e-008
1.3568602457086574 5.7220182921940426 6.1364022738162843e-008
1.348100936554117 5.7134939310803396 5.9975224429488477e-008
1.3401501045643638 5.7042633725040393 5.8471377769141702e-008
1.3330075036775646 5.6943265754548369 5.6852468090694361e-008
1.3267504793300988 5.6838742173486629 5.5149573555519002e-008
1.3214562129171237 5.6730969345911442 5.3393718548084862e-008
1.3171243763561944 5.6619945631410591 5.1584917734820085e-008
1.3137552977297555 5.6505672465344761 4.9723166226915304e-008
1.3113486489553625 5.6388149027507835 4.7808468913179891e-008
1.3099049221566827 5.6267376138105938 4.584083068242327e-008
1.3094236252100486 5.6143353387036017 4.3820241757026643e-008
1.3104798866413292 5.5955481896214048 4.0759429077768704e-008
1.3136485068939483 5.5776777028901936 3.7847959748142684e-008
1.3189294039472945 5.5607238990151213 3.5085826434934489e-008
1.3263229058838133 5.544686777996187 3.2473048693381698e-008
1.3358286846210592 5.5295663193282376 3.0009614301460831e-008
1.3474470682414776 5.5153625640215802 2.7695530592385969e-008
1.361177646642012 5.5020754915710608 2.5530792677347722e-008
1.376942664283227 5.4901631153223036 2.3590020898663329e-008
1.3946638735020189 5.4800833871054753 2.1947820932221798e-008
1.4143406181334985 5.4718363376783037 2.060420744445133e-008
1.4359738824250001 5.4654219567882141 1.9559173102137839e-008
1.4595630102116344 5.4608402649403587 1.8812721571888365e-008
1.4851086576582906 5.4580912621347366 1.8364851631500561e-008
1.5126100045588569 5.4571749176136199 1.8215559614367374e-008
1.5403754578275488 5.4580470325201365 1.8357644304238717e-008
1.5672504953408453 5.4606633977448409 1.8783905707066838e-008
1.5932344609338569 5.4650239825300027 1.9494334045232945e-008
1.6183278467302507 5.4711287868756218 2.0488934207546433e-008
1.6425308167712491 5.4789778312868522 2.1767702527400251e-008
1.6658432070156297 5.4885711055111157 2.3330647560210851e-008
1.6882646893809476 5.4999085685381086 2.5177754639550026e-008
1.7094137039838113 5.5127495206316306 2.7269815514008583e-008
1.7289037697041563 5.5268550665089302 2.9567898149908597e-008
1.7467288170167516 5.5422280051233646 3.2072469428548e-008
1.7628832685200351 5.558871299469514 3.4784006008843564e-008
1.7773610546887764 5.5767877792584661 3.7702972327688521e-008
1.7901567621626346 5.5959803767270717 4.0829840155190257e-008
1.8012638292927123 5.616451860070959 4.4165069039432597e-008
1.8085999168013778 5.6338336269902207 4.699692166353188e-008
1.8147950976079843 5.653435384277893 5.0190448407238643e-008
1.8198533087018707 5.675254753336251 5.3745272832228866e-008
1.8237796353609326 5.6992896016294035 5.7661052721844356e-008
1.8265785066981755 5.7255377966214578 6.1937421415379954e-008
1.8282546799090507 5.7539971032507582 6.6574036696177421e-008
1.8288122560241185 5.7846652249401904 7.157050257067518e-008
1.8254526917885814 5.8463468571129003 8.1619719182323311e-008
;
createNode nurbsCurve -n "curveShape9" -p "facial_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 4 0 no 3
5 0 1 2 3 4
5
2.2533266615936363 5.3453686137033918 -2.0179069540610588e-031
2.2533266615936363 6.7235962128819775 2.2454178388338578e-007
2.4231864261918705 6.7235962128819775 2.2454178388338578e-007
2.4231864261918705 5.3453686137033918 -2.0179069540610588e-031
2.2533266615936363 5.3453686137033918 -2.0179069540610588e-031
;
'''
brow_bs_ctl = '''
createNode transform -n "brow_ctlGp" -p "facial_ctl";
setAttr ".t" -type "double3" 0 -0.50699352193160507 0 ;
setAttr ".rp" -type "double3" 0 0.78242691631899675 0 ;
setAttr ".sp" -type "double3" 0 0.78242691631899675 0 ;
createNode transform -n "brow_ctl" -p "brow_ctlGp";
addAttr -ci true -sn "eyebrow_smile_L" -ln "eyebrow_smile_L" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eyebrow_smile_R" -ln "eyebrow_smile_R" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eyebrow_sad_L" -ln "eyebrow_sad_L" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eyebrow_sad_R" -ln "eyebrow_sad_R" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eyebrow_anger_L" -ln "eyebrow_anger_L" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eyebrow_anger_R" -ln "eyebrow_anger_R" -min 0 -max 1 -at "double";
setAttr -l on -k off ".v";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr -l on -k off ".tx";
setAttr -l on -k off ".ty";
setAttr -l on -k off ".tz";
setAttr -l on -k off ".rx";
setAttr -l on -k off ".ry";
setAttr -l on -k off ".rz";
setAttr -l on -k off ".sx";
setAttr -l on -k off ".sy";
setAttr -l on -k off ".sz";
setAttr ".rp" -type "double3" 0 0.78242691631899675 0 ;
setAttr ".sp" -type "double3" 0 0.78242691631899675 0 ;
setAttr -k on ".eyebrow_smile_L";
setAttr -k on ".eyebrow_smile_R";
setAttr -k on ".eyebrow_sad_L";
setAttr -k on ".eyebrow_sad_R";
setAttr -k on ".eyebrow_anger_L";
setAttr -k on ".eyebrow_anger_R";
createNode nurbsCurve -n "curveShape10" -p "brow_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 80 0 no 3
81 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
81
-2.1119454380732363 0.78242691631894701 -1.9788495938411218e-031
-2.1119454380732363 2.1585457357239575 6.0152064043699848e-008
-1.5967729204465191 2.1585457357239575 6.0152064043699848e-008
-1.5530853165964627 2.1576932075847615 6.0114798855182094e-008
-1.511940392253202 2.1551352955867173 6.000298897063228e-008
-1.4733376560460525 2.1508719997298247 5.9816634390050408e-008
-1.4372777631359279 2.1449035656994262 5.9555745852683877e-008
-1.4037600583619141 2.1372297478101792 5.9220312619285293e-008
-1.3727851968849252 2.1278507917474268 5.881034542910205e-008
-1.3443526054391617 2.1167664518258258 5.8325833542886761e-008
-1.3180322527797703 2.1039099016321599 5.776385588534349e-008
-1.2933941076618984 2.0892138233825266 5.7121469902681496e-008
-1.2704378425050897 2.0726780532866984 5.6398668435402524e-008
-1.2491635392044578 2.0543029189251318 5.5595465802503104e-008
-1.229571279655117 2.0340883384027126 5.4711858424234097e-008
-1.211661145752182 2.0120345574047835 5.3747857039842931e-008
-1.1954328918103094 1.9881410845606586 5.2703440170834773e-008
-1.1811448969149141 1.963165122096564 5.1611706177731737e-008
-1.1690549668856103 1.9378631351826963 5.0505721203313698e-008
-1.1591631017223982 1.9122352057141696 4.9385488827329795e-008
-1.1514694652155062 1.8862814974812123 4.8251016209278288e-008
-1.1459739754698202 1.8600020104838246 4.7102303349159204e-008
-1.1426767962755684 1.8333967447220068 4.5939350246972518e-008
-1.1415776819474084 1.8064654545104155 4.4762146163470835e-008
-1.1425492036875888 1.781460746861224 4.3669155678420662e-008
-1.1454633594325594 1.7568775533650047 4.2594590162179407e-008
-1.1503203948676624 1.7327161197071004 4.1538460353994483e-008
-1.1571203099928979 1.7089763639923965 4.0500762674116753e-008
-1.1658629410180374 1.6856582862208933 3.9481497122546236e-008
-1.1765486155235383 1.6627620501828195 3.8480670858781181e-008
-1.1891769240338288 1.6402873282977177 3.7498269563825058e-008
-1.2037667024251837 1.6186370445276288 3.6551905603432639e-008
-1.2203362133080771 1.5982132219883369 3.565915196611821e-008
-1.2388854566825092 1.5790163520505271 3.4820030130376601e-008
-1.2594143506533659 1.5610461890288572 3.4034529356960402e-008
-1.2819232228011042 1.5443028148184408 3.3302653225618742e-008
-1.3064119912306094 1.5287863113143927 3.262440531610076e-008
-1.3328804102565392 1.5144964328313699 3.1999774889159048e-008
-1.2985534179636462 1.5029865658961992 3.1496662626427113e-008
-1.2665710827913275 1.4893697833570809 3.090145415764365e-008
-1.2369332409493536 1.4736456757384448 3.0214131584062993e-008
-1.2096403019132969 1.4558145296731901 2.9434707434807103e-008
-1.1846919381026995 1.4358762223186456 2.8563176340252287e-008
-1.1620882314126764 1.413830876517483 2.7599543670022247e-008
-1.1418292637383411 1.389678287531916 2.6543800474744138e-008
-1.1241060144860922 1.363820478477729 2.5413519742932245e-008
-1.1091092992720992 1.3366592677329205 2.4226265513728e-008
-1.0968391180963624 1.3081944915072621 2.298203062763314e-008
-1.0872958804344524 1.2784263954860964 2.1680825823895069e-008
-1.0804791768107984 1.2473548568267518 2.0322645732890075e-008
-1.0763892529107433 1.2149798755292289 1.8907490354618164e-008
-1.0750258630489438 1.1813014515935272 1.7435359689079344e-008
-1.0758573441437811 1.1539581470622153 1.6240145887668643e-008
-1.0783517055331782 1.1271707056187794 1.5069229633526363e-008
-1.0825087015317927 1.1009390453681056 1.3922607346903368e-008
-1.0883285778249672 1.0752633301004222 1.2800286187297933e-008
-1.0958111706224734 1.0501434779206151 1.1702262574960919e-008
-1.104956889399882 1.0255795093024627 1.0628537404829613e-008
-1.1157653246816224 1.001571424245965 9.579110676904012e-009
-1.1277975186553899 0.97861691983411225 8.5757374216278737e-009
-1.1406141859284231 0.95721365220233734 7.6401708795703933e-009
-1.1542152446056078 0.9373615906399726 6.77240970832564e-009
-1.1686008584771721 0.91906081704213216 5.9724574876427537e-009
-1.1837711094382311 0.90231128022436968 5.2403119801785236e-009
-1.1997259155936699 0.88711301089735284 4.5759745283388745e-009
-1.2164651950483742 0.87346597835041406 3.9794437897178816e-009
-1.2342176808564054 0.86104469557046726 3.4364922751042519e-009
-1.2532119422815955 0.8495236192415353 2.9328900342091649e-009
-1.2734478155337161 0.83890274936361842 2.4686370670326197e-009
-1.2949257100883385 0.82918210641049506 2.0437342685119006e-009
-1.3176453802601198 0.82036168526372055 1.6581814149126863e-009
-1.3416071536295171 0.81244148080485035 1.3119782825006564e-009
-1.3668104569307307 0.80542149303388433 1.0051248712758098e-009
-1.3934661700829181 0.79932089052599842 7.3845906627056216e-010
-1.4217848454247797 0.79415884441559081 5.128188643844885e-010
-1.45176599158563 0.7899353489444112 3.2820401391647758e-010
-1.4834102637263835 0.78665040955080712 1.8461475258424547e-010
-1.516717170476354 0.78430402447531311 8.2051003479119394e-011
-1.5516872032062272 0.78289619295816004 2.0512733390536013e-011
-1.5883198705453179 0.78242691631894701 -1.9788495938411218e-031
-2.1119454380732363 0.78242691631894701 -1.9788495938411218e-031
;
createNode nurbsCurve -n "curveShape11" -p "brow_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 45 0 no 3
46 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
46
-1.9294647790500541 1.5810481698347199 3.4908843706469356e-008
-1.6325646887526357 1.5810481698347199 3.4908843706469356e-008
-1.5994469597165502 1.581372802067551 3.4923033832049029e-008
-1.5691182506908823 1.5823462073953589 3.4965582730293221e-008
-1.5415783978854041 1.5839685496083722 3.5036497560700209e-008
-1.5168274013001155 1.5862399106017051 3.5135781903019129e-008
-1.4948654247252446 1.5891603722704715 3.5263439336999119e-008
-1.4756926319510202 1.5927297708244434 3.5419462703141905e-008
-1.4593086953969856 1.5969481062636206 3.5603852001447485e-008
-1.4402056772600902 1.6033769546262535 3.5884865888463082e-008
-1.4224978242893174 1.6109136800942694 3.6214306621806073e-008
-1.4061849726944395 1.6195577094018689 3.6592149143232503e-008
-1.3912672862656841 1.6293094520246234 3.7018411351488057e-008
-1.3777447650030517 1.6401688260674185 3.74930896668236e-008
-1.3656175726967708 1.6521359953204826 3.8016191248737385e-008
-1.3548854636614982 1.6652106322033591 3.8587701778232896e-008
-1.3455677651441937 1.6793355739263105 3.920512259041239e-008
-1.337683558706475 1.6944532482240298 3.9865937121632433e-008
-1.3312326805581129 1.7105631637258314 4.0570123893398229e-008
-1.3262153763844502 1.7276658936975147 4.1317707963953712e-008
-1.322631646185487 1.7457612743488515 4.210868217380062e-008
-1.3204814080661094 1.764849387574956 4.2943050102688093e-008
-1.3197646620263166 1.7849300695855996 4.3820804591117847e-008
-1.3204335813193955 1.8041088407031634 4.4659135302300146e-008
-1.3224403391986319 1.8226189382129905 4.5468237361777585e-008
-1.3257841167128839 1.8404598707443964 4.6248089291055354e-008
-1.3304658966035221 1.857632129668066 4.6998712568628282e-008
-1.3364853512900896 1.8741354692986569 4.7720096455248952e-008
-1.3438426445628147 1.8899701353215117 4.8412251690164769e-008
-1.3525373669461263 1.9051358001561733 4.907516395437919e-008
-1.3624745201075108 1.9192991506877017 4.9694263668904006e-008
-1.3735593513997975 1.9321261367451286 5.0254949037008765e-008
-1.3857912875571863 1.9436166764333398 5.0757216478944336e-008
-1.399170656160134 1.9537708516474492 5.1201069574459851e-008
-1.4136973753135273 1.962588826177686 5.1586515483053597e-008
-1.4293716088075938 1.970070681919164 5.1913557784474699e-008
-1.4461928652716485 1.9762160912914259 5.2182182159726606e-008
-1.4653653304654159 1.9813021873610468 5.240450247988946e-008
-1.488091879826793 1.9856057756141436 5.2592618297046809e-008
-1.5143725133557799 1.9891268560507165 5.274652961119868e-008
-1.5442077224230621 1.9918654286707649 5.2866236422345048e-008
-1.5775971794481825 1.9938215753694037 5.2951742310235069e-008
-1.6145412120115978 1.9949953780417469 5.300305085461788e-008
-1.6550393287426233 1.9953865910024517 5.302015131624605e-008
-1.9294647790500541 1.9953865910024517 5.302015131624605e-008
-1.9294647790500541 1.5810481698347199 3.4908843706469356e-008
;
createNode nurbsCurve -n "curveShape12" -p "brow_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 52 0 no 3
53 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
53
-1.9294647790500541 0.94558609175112029 7.1319140698597228e-009
-1.5871793991844685 0.94558609175112029 7.1319140698597228e-009
-1.5630725895677595 0.94572028713268508 7.1377799362895898e-009
-1.5411075009785478 0.94612282209293308 7.1553752982359777e-009
-1.5212831506754627 0.94679368639497508 7.184699708230245e-009
-1.5036006851901031 0.94773292098636808 7.2257549561469612e-009
-1.4880594493615558 0.94894051563022286 7.2785405945174835e-009
-1.4746597707702771 0.95041648056342876 7.3430570708104538e-009
-1.4634011580455819 0.9521607646015392 7.4193021476826614e-009
-1.4458715088433869 0.95567746364950024 7.5730219452556896e-009
-1.4291834138350799 0.95980612393858911 7.7534914182560874e-009
-1.4133373643913463 0.96454682736391995 7.9607141464329937e-009
-1.3983333605121864 0.96989953297793585 8.1946883399118399e-009
-1.3841717297780569 0.97586422030685793 8.4554131037553417e-009
-1.3708518170280444 0.98244095077202198 8.7428911227753504e-009
-1.3583740317377191 0.9896296834258711 9.057120607097299e-009
-1.3466237207471519 0.99761222542200878 9.4060485998056644e-009
-1.3354861490012973 1.0065702405975889 9.797615879423938e-009
-1.3249608251294704 1.01650374942639 1.0231823340889399e-008
-1.3150485680828137 1.0274128338035262 1.070867456395119e-008
-1.3057489683857555 1.0392974118338834 1.1228165968860172e-008
-1.2970620260382961 1.0521575449387972 1.1790300240428191e-008
-1.28898782293555 1.0659931512231535 1.2395073798906121e-008
-1.2817749107492229 1.0806324966323995 1.3034979910353346e-008
-1.2756715954656777 1.095903724269311 1.3702506471205557e-008
-1.270677795189801 1.1118067317649958 1.4397649006776328e-008
-1.2667938375020491 1.1283416419621246 1.5120412886689367e-008
-1.2640195586121936 1.1455083729655833 1.5870794531195535e-008
-1.262355122310463 1.1633070476180434 1.6648799309918544e-008
-1.2618002010164007 1.1817375430768333 1.7454421853234678e-008
-1.2626114540180213 1.203283246786043 1.8396214473978955e-008
-1.265045213022884 1.2240060683874106 1.9302037775393119e-008
-1.2691012323456454 1.2439060488284925 2.0171893547351747e-008
-1.2747797576716489 1.262983106214175 2.1005778210105704e-008
-1.2820807071057796 1.2812372814920154 2.1803693553529549e-008
-1.2910042444382663 1.2986686975046844 2.2565644947246991e-008
-1.3015501239837666 1.3152771495143971 2.329162344188519e-008
-1.3135199138804863 1.3307859548777072 2.3969534854984283e-008
-1.3267152641617461 1.3449180214755974 2.4587267105338701e-008
-1.3411356834568611 1.3576733493080679 2.5144820192948451e-008
-1.3567817450316304 1.3690520202702325 2.5642197697562677e-008
-1.3736531213055976 1.3790539934145349 2.6079397829306797e-008
-1.3917501398592191 1.3876793915836458 2.6456425957804523e-008
-1.4110721455315811 1.3949279690922229 2.6773271343808444e-008
-1.4322590667453232 1.4010197371646607 2.7039550983375524e-008
-1.4559503405523997 1.4061742566022255 2.7264862183942464e-008
-1.4821456393723524 1.4103915274049177 2.7449204945509261e-008
-1.5108447994149543 1.4136716314678512 2.7592582847825052e-008
-1.5420486396313469 1.4160145687910259 2.7694995890889848e-008
-1.5757566686508448 1.4174204212695569 2.7756447654452775e-008
-1.6119685588929913 1.4178889841656575 2.7776929189140986e-008
-1.9294647790500541 1.4178889841656575 2.7776929189140986e-008
-1.9294647790500541 0.94558609175112029 7.1319140698597228e-009
;
createNode nurbsCurve -n "curveShape13" -p "brow_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 55 0 no 3
56 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55
56
-0.84746177984866811 0.78242691631894701 -1.9788495938411218e-031
-0.84746177984866811 1.7807034627398846 4.3636053738149411e-008
-0.69503679154029085 1.7807034627398846 4.3636053738149411e-008
-0.69503679154029085 1.6292177294966792 3.701440203245445e-008
-0.67862861403244212 1.6579292557015304 3.8269422702699551e-008
-0.66258380514645809 1.6837032041587396 3.9396037771394989e-008
-0.64690252867256715 1.7065396567634215 4.0394250818289934e-008
-0.63158474366321249 1.7264384497253471 4.1264054683886072e-008
-0.6166304910659508 1.7433999106249736 4.2005463687179973e-008
-0.60203985277589656 1.7574237937769581 4.2618467088924204e-008
-0.58781266500282137 1.7685101810764152 4.3103068468867935e-008
-0.57356692798637166 1.7774408432838404 4.3493440112274402e-008
-0.55892084670397979 1.7849976330548443 4.3823757884156e-008
-0.54387405262763155 1.7911802228089697 4.4094007465516175e-008
-0.52842695523289818 1.7959891039169018 4.4304210334849758e-008
-0.51257930883443714 1.79942386690307 4.4454348593411067e-008
-0.49633127722247677 1.8014848393479306 4.4544436560196647e-008
-0.47968277850190277 1.8021717755661415 4.4574463495959084e-008
-0.45528176068730114 1.8010806050640622 4.4526766918455662e-008
-0.43076568023719813 1.7978070935578248 4.4383677185945406e-008
-0.40613457809915077 1.792350913466972 4.4145179979431771e-008
-0.38138853616827334 1.7847123104768465 4.3811286038162162e-008
-0.35652747254945161 1.7748913664825627 4.3381998941885712e-008
-0.33155142819024258 1.7628881633792348 4.285732227035157e-008
-0.3064603621430893 1.7487022916912913 4.2237238124814036e-008
-0.36633682838507098 1.592889302506975 3.5426436054461078e-008
-0.38384764171099195 1.6022782497736645 3.5836839974039043e-008
-0.40135972441118356 1.6102228948056894 3.6184111437834196e-008
-0.41887319932831713 1.6167228281274788 3.6468232547100838e-008
-0.43638806646239281 1.6217783773194898 3.668921762083553e-008
-0.45390432581341039 1.625389542381722 3.684706665903826e-008
-0.47142201832892716 1.6275563233141752 3.6941779661709034e-008
-0.48894102116627169 1.6282784744315075 3.6973345889600446e-008
-0.50436481940100486 1.6275976803468646 3.6943587435023298e-008
-0.5193347958601997 1.6255553799880498 3.6854315651040996e-008
-0.53385082770118508 1.6221511638794914 3.6705512638907841e-008
-0.54791311966174627 1.6173855233918757 3.6497199877118677e-008
-0.56152138510898375 1.6112581309447456 3.6229363046676935e-008
-0.57467591067579715 1.6037693141185576 3.5902016466579177e-008
-0.58737649162440086 1.5949187453328548 3.5515145817828847e-008
-0.59934120402403801 1.5848598960317157 3.5075459550308973e-008
-0.61028796015372277 1.5737463195543326 3.4589669693651716e-008
-0.62021667811834102 1.5615774426349054 3.4057751189613113e-008
-0.62912743981300701 1.5483538385392339 3.3479729096437119e-008
-0.63702024523772061 1.5340752615819759 3.2855592674876335e-008
-0.6438951762875964 1.5187417936582448 3.2185345504679886e-008
-0.64975206917240547 1.5023533528729269 3.1468984006098647e-008
-0.657209847750298 1.4762272554245033 3.0326976016113442e-008
-0.66352027577774564 1.4494110278484136 2.9154801480149455e-008
-0.66868331230719102 1.4219047520397723 2.7952463977955822e-008
-0.6726989982861914 1.393708427998579 2.6719963509532546e-008
-0.67556737466230388 1.3648219738297198 2.5457296495130482e-008
-0.67728844143552858 1.3352455533234231 2.4164470094247908e-008
-0.67786207576319391 1.3049790845845748 2.2841480727135695e-008
-0.67786207576319391 0.78242691631894701 -1.9788495938411218e-031
-0.84746177984866811 0.78242691631894701 -1.9788495938411218e-031
;
createNode nurbsCurve -n "curveShape14" -p "brow_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 63 0 no 3
64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63
64
-0.26781733353973575 1.2815651895294158 2.1818026869074706e-008
-0.26467585743142502 1.3576955838315827 2.5145792094839188e-008
-0.25525126531626441 1.4279687576684839 2.8217530082565404e-008
-0.23954363908936818 1.4923845881974476 3.1033235462629639e-008
-0.21755297875073629 1.550943280156259 3.3592917184404742e-008
-0.18927930477414728 1.6036446697546904 3.5896568088392436e-008
-0.15472259668582264 1.65048892078297 3.7944195334090982e-008
-0.11388285448576232 1.6914757875557549 3.9735788182252987e-008
-0.075997678151103212 1.7208442763670067 4.1019525600076339e-008
-0.035813700841397622 1.7456942841454066 4.2105753939006429e-008
0.0066690787229655834 1.7660261384714118 4.2994487518039832e-008
0.051450631110929727 1.7818399212401363 4.368572991692568e-008
0.098530980635106846 1.7931353048711234 4.4179466816667416e-008
0.147910151608109 1.7999126988399441 4.4475716116010727e-008
0.19958805701637727 1.8021717755661415 4.4574463495959084e-008
0.2567865120752878 1.7994246858542122 4.4454384390902442e-008
0.31091940779678434 1.7911830891379679 4.4094132756735979e-008
0.36198676465464541 1.7774469854174082 4.3493708593459683e-008
0.40998852122753532 1.7582165384827617 4.2653119060571842e-008
0.45492473893678975 1.7334915845438001 4.1572356998574187e-008
0.49679549967752301 1.7032724511809803 4.0251436726463234e-008
0.53560059871194932 1.6675587289187308 3.8690340345493331e-008
0.57021086620498429 1.6270018114956843 3.6917541180301381e-008
0.59949647716062926 1.5822524374895588 3.4961483917531178e-008
0.62345722684109861 1.533310606900355 3.2822168557182748e-008
0.64209348377440645 1.4801765654134154 3.0499605838503476e-008
0.65540504322276716 1.422850067343397 2.799378502224597e-008
0.66339198708129499 1.361331358375643 2.5304716847657637e-008
0.66605427440243292 1.2956202337723672 2.2432392365365635e-008
0.66487621318414947 1.2423588453827907 2.0104263136778097e-008
0.66134174289639924 1.1924464348472199 1.7922522379530702e-008
0.65545094543429649 1.1458828383754269 1.5887162934125167e-008
0.64720386174539812 1.1026682811789754 1.3998194644871625e-008
0.63660045088214745 1.0628026608889727 1.2255613037083655e-008
0.62364079473965839 1.0262859979791972 1.0659419005698544e-008
0.60832477047525968 0.99311829244964933 9.209612550716283e-009
0.59075822752410123 0.96263037932190709 7.8769435419372069e-009
0.57104685153110446 0.93415300148554559 6.6321578219438643e-009
0.54919068344382638 0.90768623059878972 5.4752585230167496e-009
0.52518976420982433 0.88323008713541817 4.4062465400931439e-009
0.49904401193398396 0.86078454038476293 3.4251205307671243e-009
0.47075350851141945 0.84034959546526877 2.5318807187730112e-009
0.44031825394213087 0.82192525749538026 1.7265273278451254e-009
0.4083989370602164 0.8057504324378798 1.0195032692866638e-009
0.37565608290954566 0.79206403969146699 4.2125204170341661e-010
0.34208956864744733 0.78086608037580141 -6.8226305962733439e-011
0.30769953759037133 0.77215655944937656 -4.4893155696916287e-010
0.27248592831698193 0.76593547451292121 -7.2086381619133464e-010
0.23644878177483625 0.76220281932833134 -8.8402335630545269e-010
0.19958805701637727 0.76095860349269029 -9.3840975780966465e-010
0.14142166312853399 0.76369622408203586 -8.1874456124700967e-010
0.086531657312815827 0.77190908457046159 -4.597490274926247e-010
0.034918006299332581 0.78559719391524552 1.3857723498855199e-010
-0.013419227210968913 0.80476053548144266 9.7623349905997699e-010
-0.058480072649145329 0.82939911822633094 2.053220156256712e-009
-0.10026454665014173 0.85951296518291131 3.3695382133832018e-009
-0.13877258139456666 0.89510201237062592 4.9251848737604335e-009
-0.17300893626977901 0.93584046055126557 6.7059190003835302e-009
-0.20197818639913068 0.98140247977595363 8.6974981138416897e-009
-0.22568029083506447 1.0317879574389079 1.0899917291979849e-008
-0.24411524957758052 1.0869969959090213 1.3313181009484426e-008
-0.2572830421529001 1.1470295337649581 1.5937286581543573e-008
-0.26518379140369469 1.2118856324280538 1.8772236692969135e-008
-0.26781733353973575 1.2815651895294158 2.1818026869074706e-008
;
createNode nurbsCurve -n "curveShape15" -p "brow_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 56 0 no 3
57 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56
57
-0.093924032405101762 1.2820348170620015 2.1838554940501707e-008
-0.092220808529891285 1.2293570132564702 1.9535935004265512e-008
-0.08711111643048125 1.1806011664716962 1.740474925420755e-008
-0.07859496634376098 1.1357672357601225 1.5444995900453246e-008
-0.066672363388175074 1.0948552415955275 1.365667583793988e-008
-0.051343307563723573 1.0578651430303543 1.2039787276792886e-008
-0.032607803988851096 1.0247970629072742 1.0594335586635976e-008
-0.010465868018891555 0.99565087838361599 9.3203153978454357e-009
0.014259657906258636 0.97040748742398397 8.2168917339350287e-009
0.04074590063603524 0.94904768562408981 7.2832251437320889e-009
0.068992866568494057 0.93157146274704428 6.5193151797679794e-009
0.099000556983246238 0.91797884950351527 5.925163184448624e-009
0.1307689718802918 0.90826983565661334 5.5007687103053807e-009
0.16429817268096641 0.90244444168011717 5.2461326522755337e-009
0.19958805701637727 0.90050263686335896 5.1612536679531566e-009
0.23462878570361467 0.90245403364537213 5.2465519303932222e-009
0.26794717824335679 0.90830819328074364 5.5024453753074948e-009
0.29954309131915369 0.91806511576947347 5.9289340026959712e-009
0.32941662729989818 0.93172479087467241 6.5260173650900125e-009
0.35756774523803314 0.94928724930700836 7.2936968048955443e-009
0.38399652702867282 0.97075251154025988 8.2319732170498503e-009
0.40870280888158872 0.99612048544242326 9.34084257433515e-009
0.43084487281266426 1.0254871316136045 1.0624499447802905e-008
0.44958038662442601 1.0589482263899028 1.2087130354069011e-008
0.46490939126443115 1.0965036878762033 1.3728731713384335e-008
0.47683192768023674 1.1381536593889565 1.5549309790309862e-008
0.48534803681939986 1.1838980590330479 1.7548861005096464e-008
0.49045775962947769 1.233736968703592 1.9727388937493267e-008
0.49216097326779895 1.2876702655579169 2.208488821787657e-008
0.49044817790111211 1.338603826272895 2.4311264867115116e-008
0.48530979180105172 1.3858837593089095 2.6377936378223325e-008
0.47674569212494633 1.4295100646659606 2.8284902751201178e-008
0.46475604266302439 1.4694827832916055 3.0032165775923264e-008
0.44934072057261465 1.5058018742382866 3.1619723662514995e-008
0.43049988964394553 1.5384675422437901 3.3047585360349226e-008
0.4082333860867885 1.5674795416227725 3.4315740130178546e-008
0.38342158237917967 1.5927229735299617 3.5419165583963523e-008
0.3569449328942691 1.6140828572249704 3.6352835753915596e-008
0.32880325336804983 1.6315589470224552 3.7116739900787359e-008
0.2989967894858645 1.6451514886077594 3.7710888763826217e-008
0.2675254184050419 1.6548604819808828 3.8135282343032178e-008
0.23438918107313897 1.6606860090369393 3.8389924218154365e-008
0.19958805701637727 1.6626277421954727 3.8474800070196255e-008
0.16429814197029854 1.6606955088701909 3.8390339469054276e-008
0.13076899235407036 1.6548990545796878 3.8136968404875776e-008
0.099000546746356971 1.6452378060581641 3.7714661819416766e-008
0.068992851213160136 1.6317122546763048 3.7123441191172106e-008
0.040745890399145959 1.6143223185389961 3.6363302940392631e-008
0.014259642550924717 1.5930679976462376 3.543424706707834e-008
-0.010465868018891555 1.5679491282078013 3.4336266411730972e-008
-0.03260781678496269 1.5389276289955673 3.3067696391001749e-008
-0.051343322919057494 1.5059649274107303 3.1626850943047071e-008
-0.066672368506619728 1.4690611053484046 3.0013733647616064e-008
-0.07859496634376098 1.4282161628085905 2.8228344504708741e-008
-0.08711111643048125 1.3834301407388447 2.627068530419967e-008
-0.092220808529891285 1.3347030391391677 2.4140756046088842e-008
-0.093924032405101762 1.2820348170620015 2.1838554940501707e-008
;
createNode nurbsCurve -n "curveShape16" -p "brow_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 18 0 no 3
19 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
19
1.0419846240495547 0.78242691631894701 -1.9788495938411218e-031
0.74226685045173579 1.7807034627398846 4.3636053738149411e-008
0.91948099846863574 1.7807034627398846 4.3636053738149411e-008
1.077340382767479 1.2041786470175415 1.8435353661170006e-008
1.1336947039364029 0.9901663830570161 9.0805804930676283e-009
1.18562112006882 1.1953900318857582 1.8051191092641934e-008
1.3453251099207131 1.7807034627398846 4.3636053738149411e-008
1.5175747761126324 1.7807034627398846 4.3636053738149411e-008
1.6680878410840583 1.2009919443323938 1.8296058462745136e-008
1.7169284493120665 1.0108296464365554 9.9838004219217995e-009
1.7742219436510478 1.2028368774659004 1.8376703051306904e-008
1.9477462254009348 1.7807034627398846 4.3636053738149411e-008
2.1119452742830078 1.7807034627398846 4.3636053738149411e-008
1.7956902564773045 0.78242691631894701 -1.9788495938411218e-031
1.6233062822980382 0.78242691631894701 -1.9788495938411218e-031
1.4645080524095944 1.3792460374574183 2.6087792341033419e-008
1.4249592638427919 1.5503887683377677 3.3568678702997083e-008
1.2215134555752181 0.78242691631894701 -1.9788495938411218e-031
1.0419846240495547 0.78242691631894701 -1.9788495938411218e-031
;
'''
eye_bs_ctl = '''
createNode transform -n "eye_ctlGp" -p "facial_ctl";
setAttr ".t" -type "double3" 0 -0.75699352193160507 0 ;
setAttr ".rp" -type "double3" 0 -1.4675730836810033 0 ;
setAttr ".sp" -type "double3" 0 -1.4675730836810033 0 ;
createNode transform -n "eye_ctl" -p "facial_ctl|eye_ctlGp";
addAttr -ci true -sn "eye_close_L" -ln "eye_close_L" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eye_close_R" -ln "eye_close_R" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eye_smile_L" -ln "eye_smile_L" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eye_smile_R" -ln "eye_smile_R" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eye_anger_L" -ln "eye_anger_L" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eye_anger_R" -ln "eye_anger_R" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eye_open_L" -ln "eye_open_L" -min 0 -max 1 -at "double";
addAttr -ci true -sn "eye_open_R" -ln "eye_open_R" -min 0 -max 1 -at "double";
setAttr -l on -k off ".v";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr -l on -k off ".tx";
setAttr -l on -k off ".ty";
setAttr -l on -k off ".tz";
setAttr -l on -k off ".rx";
setAttr -l on -k off ".ry";
setAttr -l on -k off ".rz";
setAttr -l on -k off ".sx";
setAttr -l on -k off ".sy";
setAttr -l on -k off ".sz";
setAttr ".rp" -type "double3" 0 -1.4675730836810033 0 ;
setAttr ".sp" -type "double3" 0 -1.4675730836810033 0 ;
setAttr -k on ".eye_close_L";
setAttr -k on ".eye_close_R";
setAttr -k on ".eye_smile_L";
setAttr -k on ".eye_smile_R";
setAttr -k on ".eye_anger_L";
setAttr -k on ".eye_anger_R";
setAttr -k on ".eye_open_L";
setAttr -k on ".eye_open_R";
createNode nurbsCurve -n "curveShape17" -p "eye_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 12 0 no 3
13 0 1 2 3 4 5 6 7 8 9 10 11 12
13
-1.539278127916746 -1.4675730836810521 -1.9595902943972494e-031
-1.539278127916746 -0.091454264276041863 6.0152064043699848e-008
-0.54744197706954723 -0.091454264276041863 6.0152064043699848e-008
-0.54744197706954723 -0.25461340899754736 5.302015131624605e-008
-1.3567973869984495 -0.25461340899754736 5.302015131624605e-008
-1.3567973869984495 -0.67324550910955328 3.4721161038957598e-008
-0.59896596061060903 -0.67324550910955328 3.4721161038957598e-008
-0.59896596061060903 -0.8364046947786159 2.7589246521629228e-008
-1.3567973869984495 -0.8364046947786159 2.7589246521629228e-008
-1.3567973869984495 -1.3044139082488788 7.1319140698597228e-009
-0.51523950783016204 -1.3044139082488788 7.1319140698597228e-009
-0.51523950783016204 -1.4675730836810521 -1.9595902943972494e-031
-1.539278127916746 -1.4675730836810521 -1.9595902943972494e-031
;
createNode nurbsCurve -n "curveShape18" -p "eye_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 78 0 no 3
79 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
79
-0.29196902167904609 -1.8506818267238501 -1.6746215023187867e-008
-0.31129053598072287 -1.6930239248798058 -9.8547692592104275e-009
-0.29573634025034762 -1.6970020210013721 -1.0028657363422173e-008
-0.28075850186018608 -1.7003680944604747 -1.0175793107394692e-008
-0.26635704128401677 -1.7031220838357781 -1.0296173806316135e-008
-0.25253199946939692 -1.7052641324437325 -1.0389805724747492e-008
-0.23928337641632647 -1.7067941583892234 -1.0456685282939626e-008
-0.22661119259858403 -1.7077122026198077 -1.0496814270767105e-008
-0.21451540706861238 -1.7080181832403718 -1.051018910848079e-008
-0.1988649436314528 -1.707634484156398 -1.0493417088835946e-008
-0.18413526791120458 -1.7064833869044767 -1.0443101029901417e-008
-0.1703263184865321 -1.7045648505370508 -1.0359239141802633e-008
-0.15743814654188168 -1.7018788955278987 -1.0241832319476879e-008
-0.14547074184036413 -1.698425542350799 -1.0090881457861437e-008
-0.13442412485575794 -1.6942048114795305 -9.9063874518935949e-009
-0.12429827511428458 -1.6892166414927572 -9.6883476167615003e-009
-0.11488226151234018 -1.6835384642209894 -9.4401466052743245e-009
-0.10596531673654941 -1.6772475067569514 -9.1651601208684097e-009
-0.097547389602465812 -1.6703439124170933 -8.8633944281047415e-009
-0.089628551768314371 -1.6628275993063006 -8.534845947234184e-009
-0.082208772523427259 -1.654698587898352 -8.17951557319402e-009
-0.075288062104693743 -1.6459568986670261 -7.7974042009215355e-009
-0.068866420512113821 -1.6366025009016549 -7.388510488010804e-009
-0.063901186275771293 -1.6278132408458472 -7.0043197289582759e-009
-0.058129515494213899 -1.6159557086769665 -6.4860105362018401e-009
-0.051551408167441644 -1.6010298736843447 -5.8335815673355708e-009
-0.04416687965078845 -1.5830357665786499 -5.0470341647653937e-009
-0.035975917148142703 -1.5619734180705498 -4.1263696708972354e-009
-0.026978530896393696 -1.5378427820940428 -3.0715860721222061e-009
-0.01717471577709679 -1.5106438893597964 -1.8826847108462327e-009
-0.0021467985245799807 -1.4692838398274042 -7.4779526177118146e-011
-0.38213595192834732 -0.46929653726011444 4.3636053738149411e-008
-0.2008630001548018 -0.46929653726011444 4.3636053738149411e-008
0.0075474537279808882 -1.044982747012682 1.8472010292334448e-008
0.018961403569825262 -1.0765040536394102 1.7094170219068216e-008
0.030028952433785686 -1.1084839729058591 1.5696283550633929e-008
0.040750100319862148 -1.1409227095498147 1.4278341337658746e-008
0.05112484722805466 -1.1738200178859344 1.284035431939008e-008
0.0611531905991409 -1.2071760207568891 1.1382317126204222e-008
0.070835168821455657 -1.2409906567413438 9.9042324429130302e-009
0.080170730710552557 -1.2752639667868551 8.4060984796419297e-009
0.088844303680612802 -1.2431566391964335 9.8095543427963397e-009
0.097958758998162032 -1.211124655111109 1.1209716836744572e-008
0.10751406595253241 -1.1791679326357674 1.2606589541235757e-008
0.11751027572817034 -1.1472865331917441 1.4000169771458049e-008
0.12794732690374014 -1.1154804363052608 1.5390458422348727e-008
0.13882527066368819 -1.0837496010287602 1.6777457283782367e-008
0.15014404558667885 -1.0520941502049139 1.8161160986135257e-008
0.36281451952178478 -0.46929653726011444 4.3636053738149411e-008
0.53160919463431988 -0.46929653726011444 4.3636053738149411e-008
0.15413577724476527 -1.4850831765858901 -7.6539046990022383e-010
0.13724863616130786 -1.5297449420139502 -2.7176182400973716e-009
0.12147324172738139 -1.5702472200404674 -4.4880290414118845e-009
0.10680959394298589 -1.6065900093858307 -6.0766228179101817e-009
0.093257723518789165 -1.638773294694706 -7.4833988983893004e-009
0.080817589507234125 -1.6667971169146505 -8.7083590727238099e-009
0.069489207263654665 -1.6906614555718857 -9.7515024459764244e-009
0.059272571669606165 -1.7103662799557435 -1.0612827675741221e-008
0.046123614970560819 -1.7332376608266469 -1.1612567485643148e-008
0.032438608682839716 -1.754295576761689 -1.2533038225589257e-008
0.018217563043332149 -1.7735400482346482 -1.3374240790516834e-008
0.0034604921277608721 -1.7909710342979677 -1.4136173390551308e-008
-0.011832600225040632 -1.8065886373205402 -1.4818840500379104e-008
-0.027661712735461207 -1.8203927958810298 -1.5422239435188367e-008
-0.044026813413221851 -1.8323834690318797 -1.5946368405104529e-008
-0.061120371132110864 -1.8426757194085912 -1.6396256957665286e-008
-0.079134680738798785 -1.8513846096466655 -1.6776934640408343e-008
-0.098069716641062399 -1.8585099759558745 -1.7088394293835419e-008
-0.11792552490490349 -1.8640519821264467 -1.7330643077444792e-008
-0.13870205946432029 -1.8680105053157103 -1.7503675621612759e-008
-0.16039936126686988 -1.8703857093138943 -1.7607499085837585e-008
-0.18301739960188451 -1.8711773893832127 -1.7642104520746439e-008
-0.1972017971777715 -1.8707591100872529 -1.7623820952028433e-008
-0.21184624055787871 -1.8695043540944876 -1.7568973825623552e-008
-0.22695068879464897 -1.8674129166671309 -1.7477554192158956e-008
-0.24251520330941798 -1.8644850025429689 -1.7349571001007485e-008
-0.25853976362840714 -1.8607204479317729 -1.7185017092670867e-008
-0.2750243902253951 -1.8561194575713285 -1.698390141652194e-008
-0.29196902167904609 -1.8506818267238501 -1.6746215023187867e-008
;
createNode nurbsCurve -n "curveShape19" -p "eye_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 87 0 no 3
88 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
82 83 84 85 86 87
88
1.3592123920221522 -1.1455483912872013 1.407614636714497e-008
1.5336424337354881 -1.167016704113458 1.3137736609335304e-008
1.5204080194847378 -1.2093406314688155 1.1287698986885581e-008
1.5043002332559063 -1.2488673697761101 9.5599303810271488e-009
1.4853194026294507 -1.2855969599828987 7.9544290018854398e-009
1.4634652000249146 -1.3195293509047352 6.4711970868036622e-009
1.4387379530227542 -1.3506645630153982 5.1102337408445342e-009
1.4111376616229698 -1.3790026065517764 3.8715385165394135e-009
1.3806639982451046 -1.4045434559216472 2.7551125325599055e-009
1.3474900072655391 -1.4269612734984667 1.7751986039182936e-009
1.311787586529054 -1.4459302011819122 9.4604044056414717e-010
1.2735569817209926 -1.4614502351331506 2.6763821029820689e-010
1.232798438526697 -1.4735213683143207 -2.600077792448357e-010
1.1895114655754826 -1.4821436064836722 -6.3689777976609181e-010
1.143696554238034 -1.4873169515606219 -8.6303187516593206e-010
1.0953535407241231 -1.4890413965073088 -9.3840975780966465e-010
1.0347146309686051 -1.4862941916303753 -8.1832561873080223e-010
0.97777353130618083 -1.4780525782791858 -4.5807325742779523e-010
0.92453056931730726 -1.4643165487760734 1.4234766170083797e-010
0.87498574500198445 -1.4450861159171497 9.8293657931929465e-010
0.82913889456998391 -1.4203612720247478 2.0636938310290564e-009
0.78699026370664826 -1.3901420055823672 3.3846199202323458e-009
0.74853968862174902 -1.3544283600967875 4.9457129451874338e-009
0.71455256105293519 -1.3137569942515961 6.7235148097985602e-009
0.68579423179029808 -1.2686646332701617 8.6945645094237937e-009
0.66226457799116645 -1.219151236204927 1.0858863833937701e-008
0.64396380439332601 -1.1652169361354527 1.3216406966247934e-008
0.63089178815410529 -1.1068616306928458 1.5767198381040916e-008
0.62304869306373278 -1.0440852175082136 1.8511242553003069e-008
0.62043427343686575 -0.97688794226689901 2.1448528742886975e-008
0.62307743824882955 -0.90735317572750607 2.4487989922518056e-008
0.63100697363227809 -0.84241378973323244 2.7326580638816108e-008
0.64422255200675438 -0.78207015281209202 2.9964284782910013e-008
0.66272462379538666 -0.72632206022629942 3.2401111304172608e-008
0.68651290236527518 -0.67516955292341163 3.4637058412729337e-008
0.71558755150664843 -0.62861242616564306 3.6672135057953034e-008
0.74994844837683505 -0.58665100753345079 3.8506326920847149e-008
0.78852366782560135 -0.549820317808138 4.0116247500298683e-008
0.83024120280759905 -0.51865611482703566 4.1478478077452358e-008
0.87510072574237163 -0.49315807100968689 4.2593032971304744e-008
0.9231024823152616 -0.47332626825120627 4.3459908602106697e-008
0.97424655442138308 -0.45916070655159369 4.4079104969858211e-008
1.0285328601656221 -0.45066130401573457 4.4450625654308429e-008
1.0859611538626357 -0.44782822443385761 4.4574463495959084e-008
1.141587918836688 -0.45060823598170963 4.4452945331749301e-008
1.1942255121411296 -0.45894835252037991 4.4088387259370851e-008
1.2438744251466463 -0.47284881973521098 4.3480778539576292e-008
1.2905344940630092 -0.49230922815063183 4.2630137071111327e-008
1.3342056369951047 -0.51732990534709933 4.1536448534979405e-008
1.3748880996282751 -0.54791044184904236 4.0199730829926206e-008
1.412581472486949 -0.58405132902714618 3.861996247745692e-008
1.4461948307543901 -0.62523474407409751 3.6819778231365749e-008
1.4746370039285195 -0.67094310986792527 3.4821802106199498e-008
1.4979078282191085 -0.72117675398908598 3.2626019782961621e-008
1.516007303626157 -0.7759354307522377 3.023244200089952e-008
1.5289354301496654 -0.83521901731470849 2.764107412963692e-008
1.5366925353700902 -0.89902763651916984 2.4851910799550101e-008
1.539278127916746 -0.96736137026073621 2.1864948430889929e-008
1.5383386271662318 -1.0124448353853868 1.9894287581514719e-008
0.79432757457149972 -1.0124448353853868 1.9894287581514719e-008
0.79852691034417411 -1.0575662998430426 1.7921965728539872e-008
0.80575734808494792 -1.0995626057938994 1.6086248892513325e-008
0.81601905158404942 -1.1384339170281856 1.4387129913936806e-008
0.82931210273659284 -1.1741801107032297 1.2824614162434021e-008
0.84563650154257819 -1.20680120729281 1.1398700743067684e-008
0.86499224800200558 -1.2362971863231484 1.0109390550775084e-008
0.88737926021976066 -1.2626680887418018 8.9566817956816456e-009
0.91212534309819526 -1.2857044063727763 7.9497323710174963e-009
0.93855821964454678 -1.3051967026983027 7.0976970377322526e-009
0.96667788985881509 -1.3211449572446026 6.4005766907632046e-009
0.99648427184588617 -1.3335491290641188 5.8583731199849186e-009
1.0279775293959883 -1.3424092591044083 5.4710845355228292e-009
1.0611576625091217 -1.3477253371285822 5.2387113848455743e-009
1.0960244254999436 -1.34949736313664 5.1612536679531566e-009
1.1220545418744827 -1.3485043746396406 5.2046585737097704e-009
1.1469721131221273 -1.3455254398593095 5.3348719485736875e-009
1.1707771392428772 -1.3405605485587579 5.5518942400135486e-009
1.1934697021318466 -1.3336097109748748 5.8557250005607106e-009
1.2150499655792637 -1.3246729168707712 6.2463646776838183e-009
1.2355178476900146 -1.3137501457726681 6.723814166320155e-009
1.2548731027787565 -1.3008414386281231 7.2880716765951522e-009
1.2731162222161749 -1.2857564507178731 7.9474574404408339e-009
1.2902466327364701 -1.2683048680333235 8.7102903473833041e-009
1.3062645800249848 -1.24848674175892 9.5765681600793488e-009
1.3211702278719473 -1.2263020309471062 1.0546292668403538e-008
1.3349634124871295 -1.2017507355978818 1.1619463872355872e-008
1.3476442157656452 -1.1748328147636897 1.2796083561810915e-008
1.3592123920221522 -1.1455483912872013 1.407614636714497e-008
;
createNode nurbsCurve -n "curveShape20" -p "eye_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 29 0 no 3
30 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29
30
0.80291493246004819 -0.87290080201471798 2.599395100727754e-008
1.3610910659427236 -0.87290080201471798 2.599395100727754e-008
1.3570166202192591 -0.83833643673321234 2.7504807398982077e-008
1.3512525144988792 -0.80633260409340646 2.8903739354164412e-008
1.3437986668864699 -0.77688893556728622 3.019076298169566e-008
1.3346555687527166 -0.75000563589263736 3.1365869332202979e-008
1.3238226468318199 -0.7256826231743454 3.2429061985435499e-008
1.3113006381798074 -0.70391989741241079 3.3380340941393226e-008
1.2970887238455373 -0.68471762239706147 3.4219699040577879e-008
1.2729822418092851 -0.65889117917162687 3.5348608728470247e-008
1.246914781262654 -0.6370381230986899 3.6303836147726258e-008
1.2188867516812159 -0.61915845417825044 3.7085381298345899e-008
1.1888981530649698 -0.60525200862008 3.7693251339827464e-008
1.1569489035188021 -0.59531886831929304 3.812744269242181e-008
1.1230391668329411 -0.58935886948566085 3.8387962515627211e-008
1.0871686154269298 -0.58737225780452629 3.8474800070196255e-008
1.0545841873747483 -0.58895799290147621 3.8405485387653573e-008
1.0235169482089015 -0.59371536198255415 3.8197534180527251e-008
0.99396648845381752 -0.60164461073310271 3.7850935709569884e-008
0.96593313568995376 -0.61274541157266527 3.7365704293778029e-008
0.9394167261270816 -0.62701776450124158 3.6741839933151664e-008
0.91441742355542976 -0.64446175141394613 3.5979339047941667e-008
0.89093498228965518 -0.6650774542058927 3.5078198058398893e-008
0.86966108846459445 -0.68834860607693871 3.406098370308396e-008
0.85128710063462698 -0.71375894022694053 3.2950262720557466e-008
0.83581293690463876 -0.74130886613146973 3.1746017212073731e-008
0.82323859727462978 -0.77099789241984085 3.0448268656127578e-008
0.81356416363971396 -0.80282626477739627 2.905700631347159e-008
0.80678963599989151 -0.83679386036146486 2.7572235553729481e-008
0.80291493246004819 -0.87290080201471798 2.599395100727754e-008
;
'''
mouth_bs_ctl = '''
createNode transform -n "moutl_ctlGp" -p "facial_ctl";
setAttr ".t" -type "double3" 0 -1.0069935219316051 0 ;
setAttr ".rp" -type "double3" 0 -3.7175730836810033 0 ;
setAttr ".sp" -type "double3" 0 -3.7175730836810033 0 ;
createNode transform -n "mouth_ctl" -p "moutl_ctlGp";
addAttr -ci true -sn "mouth_A" -ln "mouth_A" -min 0 -max 1 -at "double";
addAttr -ci true -sn "mouth_I" -ln "mouth_I" -min 0 -max 1 -at "double";
addAttr -ci true -sn "mouth_U" -ln "mouth_U" -min 0 -max 1 -at "double";
addAttr -ci true -sn "mouth_E" -ln "mouth_E" -min 0 -max 1 -at "double";
addAttr -ci true -sn "mouth_O" -ln "mouth_O" -min 0 -max 1 -at "double";
addAttr -ci true -sn "mouth_shout" -ln "mouth_shout" -min 0 -max 1 -at "double";
addAttr -ci true -sn "mouth_open" -ln "mouth_open" -min 0 -max 1 -at "double";
addAttr -ci true -sn "mouth_smileClose" -ln "mouth_smileClose" -min 0 -max 1 -at "double";
addAttr -ci true -sn "mouth_angerClose" -ln "mouth_angerClose" -min 0 -max 1 -at "double";
setAttr -l on -k off ".v";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr -l on -k off ".tx";
setAttr -l on -k off ".ty";
setAttr -l on -k off ".tz";
setAttr -l on -k off ".rx";
setAttr -l on -k off ".ry";
setAttr -l on -k off ".rz";
setAttr -l on -k off ".sx";
setAttr -l on -k off ".sy";
setAttr -l on -k off ".sz";
setAttr ".rp" -type "double3" 0 -3.7175730836810033 0 ;
setAttr ".sp" -type "double3" 0 -3.7175730836810033 0 ;
setAttr -k on ".mouth_A";
setAttr -k on ".mouth_I";
setAttr -k on ".mouth_U";
setAttr -k on ".mouth_E";
setAttr -k on ".mouth_O";
setAttr -k on ".mouth_shout";
setAttr -k on ".mouth_open";
setAttr -k on ".mouth_smileClose";
setAttr -k on ".mouth_angerClose";
createNode nurbsCurve -n "curveShape21" -p "mouth_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 15 0 no 3
16 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16
-2.5343343946557004 -3.7175730836810521 -1.940330994953377e-031
-2.5343343946557004 -2.3414542642760416 6.0152064043699848e-008
-2.2615861562878212 -2.3414542642760416 6.0152064043699848e-008
-1.9338589432994957 -3.3152770114812529 1.7584919818154999e-008
-1.8677432158843374 -3.5188905614165602 8.6846888764916757e-009
-1.7944156409193368 -3.2984042839379009 1.8322450163258793e-008
-1.4643737444222475 -2.3414542642760416 6.0152064043699848e-008
-1.2183267528900708 -2.3414542642760416 6.0152064043699848e-008
-1.2183267528900708 -3.7175730836810521 -1.940330994953377e-031
-1.3943668525492847 -3.7175730836810521 -1.940330994953377e-031
-1.3943668525492847 -2.5647246685320431 5.0392604710328817e-008
-1.7957574104709781 -3.7175730836810521 -1.940330994953377e-031
-1.9596544301717491 -3.7175730836810521 -1.940330994953377e-031
-2.3582941312062582 -2.5454031542303666 5.1237174924257173e-008
-2.3582941312062582 -3.7175730836810521 -1.940330994953377e-031
-2.5343343946557004 -3.7175730836810521 -1.940330994953377e-031
;
createNode nurbsCurve -n "curveShape22" -p "mouth_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 63 0 no 3
64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63
64
-1.0100841839914714 -3.2184348104705833 2.1818026869074706e-008
-1.0069427693044966 -3.1423044161684164 2.5145792094839188e-008
-0.99751827955822869 -3.0720312423315153 2.8217530082565404e-008
-0.9818104690673255 -3.0076154118025515 3.1033235462629639e-008
-0.959819829202472 -2.9490567198437398 3.3592917184404742e-008
-0.93154611427832601 -2.8963553302453087 3.5896568088392436e-008
-0.89698948808511547 -2.8495110792170291 3.7944195334090982e-008
-0.8561497049374982 -2.8085242124442442 3.9735788182252987e-008
-0.8182645337212836 -2.7791557236329925 4.1019525600076339e-008
-0.7780806485435815 -2.7543057158545925 4.2105753939006429e-008
-0.73559780371904915 -2.7339738615285873 4.2994487518039832e-008
-0.69081624493302918 -2.7181600787598628 4.368572991692568e-008
-0.64373584934285033 -2.7068646951288757 4.4179466816667416e-008
-0.59435673979118397 -2.700087301160055 4.4475716116010727e-008
-0.54267879343535852 -2.6978282244338576 4.4574463495959084e-008
-0.48548037932400506 -2.7005753141457869 4.4454384390902442e-008
-0.43134746312873001 -2.7088169108620312 4.4094132756735979e-008
-0.38028008579709038 -2.7225530145825907 4.3493708593459683e-008
-0.33227826780286485 -2.7417834615172376 4.2653119060571842e-008
-0.28734198867227467 -2.7665084154561992 4.1572356998574187e-008
-0.24547126887909859 -2.7967275488190189 4.0251436726463234e-008
-0.20666608794955796 -2.8324412710812683 3.8690340345493331e-008
-0.17205598424675148 -2.8729981885043148 3.6917541180301381e-008
-0.14277050637066718 -2.9177475625104403 3.4961483917531178e-008
-0.11880964408441574 -2.9666893930996441 3.2822168557182748e-008
-0.10017341786177573 -3.0198234345865838 3.0499605838503476e-008
-0.086861827702747169 -3.0771499326566021 2.799378502224597e-008
-0.078874894081108565 -3.1386686416243563 2.5304716847657637e-008
-0.076212576049302858 -3.2043797662276319 2.2432392365365635e-008
-0.077390734518034493 -3.2576411546172084 2.0104263136778097e-008
-0.080925209924229385 -3.3075535651527792 1.7922522379530702e-008
-0.0868159869125536 -3.354117161624572 1.5887162934125167e-008
-0.095063080838341113 -3.3973317188210239 1.3998194644871625e-008
-0.10566648146470257 -3.4371973391110267 1.2255613037083655e-008
-0.11862621950230587 -3.4737140020208019 1.0659419005698544e-008
-0.13394224376670461 -3.5068817075503498 9.209612550716283e-009
-0.15150882766542018 -3.537369620678092 7.8769435419372069e-009
-0.1712201524739706 -3.5658469985144534 6.6321578219438643e-009
-0.19307626937680217 -3.5923137694012093 5.4752585230167496e-009
-0.21707714766324712 -3.6167699128645809 4.4062465400931439e-009
-0.24322279757019474 -3.6392154596152362 3.4251205307671243e-009
-0.27151323957142354 -3.6596504045347302 2.5318807187730112e-009
-0.30194843271937644 -3.6780747425046187 1.7265273278451254e-009
-0.33386789291774083 -3.6942495675621192 1.0195032692866638e-009
-0.36661084943730438 -3.7079359603085322 4.2125204170341661e-010
-0.40017732275184559 -3.7191339196241975 -6.8226305962733439e-011
-0.43456733333514302 -3.7278434405506227 -4.4893155696916287e-010
-0.46978092213475386 -3.7340645254870779 -7.2086381619133464e-010
-0.50581813009823517 -3.7377971806716679 -8.8402335630545269e-010
-0.54267879343535852 -3.739041396507309 -9.3840975780966465e-010
-0.60084524874453749 -3.7363037759179631 -8.1874456124700967e-010
-0.65573528527092351 -3.7280909154295374 -4.597490274926247e-010
-0.70734882111940234 -3.7144028060847534 1.3857723498855199e-010
-0.75568602008020247 -3.6952394645185564 9.7623349905997699e-010
-0.80074684120576678 -3.6706008817736682 2.053220156256712e-009
-0.84253144828632387 -3.6404870348170877 3.3695382133832018e-009
-0.8810394318463024 -3.6048979876293732 4.9251848737604335e-009
-0.91527576624773621 -3.5641595394487333 6.7059190003835302e-009
-0.9442451801673164 -3.5185975202240454 8.6974981138416897e-009
-0.967947018444129 -3.4682120425610909 1.0899917291979849e-008
-0.98638210002931626 -3.413003004090978 1.3313181009484426e-008
-0.99954985165707877 -3.3529704662350412 1.5937286581543573e-008
-1.0074506009078734 -3.2881143675719451 1.8772236692969135e-008
-1.0100841839914714 -3.2184348104705833 2.1818026869074706e-008
;
createNode nurbsCurve -n "curveShape23" -p "mouth_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 56 0 no 3
57 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56
57
-0.83619088285683751 -3.2179651829379976 2.1838554940501707e-008
-0.83448771016607348 -3.2706429867435292 1.9535935004265512e-008
-0.82937802830355278 -3.3193988335283029 1.740474925420755e-008
-0.82086175537416106 -3.3642327642398766 1.5444995900453246e-008
-0.80893921895835552 -3.4051447584044716 1.365667583793988e-008
-0.79361017337079331 -3.4421348569696448 1.2039787276792886e-008
-0.77487470050658869 -3.4752029370927247 1.0594335586635976e-008
-0.75273271847062728 -3.5043491216163831 9.3203153978454357e-009
-0.72800719126586599 -3.529592512576015 8.2168917339350287e-009
-0.70152100100014703 -3.5509523143759094 7.2832251437320889e-009
-0.67327398388324178 -3.5684285372529549 6.5193151797679794e-009
-0.6432662218102646 -3.5820211504964838 5.925163184448624e-009
-0.61149775572877263 -3.5917301643433857 5.5007687103053807e-009
-0.57796862658632298 -3.5975555583198817 5.2461326522755337e-009
-0.54267879343535852 -3.5994973631366403 5.1612536679531566e-009
-0.5076381261694568 -3.5975459663546272 5.2465519303932222e-009
-0.47431979505105032 -3.5916918067192554 5.5024453753074948e-009
-0.44272371818502498 -3.5819348842305256 5.9289340026959712e-009
-0.41285022315183761 -3.5682752091253267 6.5260173650900125e-009
-0.38469898237103128 -3.5507127506929907 7.2936968048955443e-009
-0.35827024152794873 -3.5292474884597391 8.2319732170498503e-009
-0.33356387777991858 -3.5038795145575756 9.34084257433515e-009
-0.31142205953418578 -3.4745128683863946 1.0624499447802905e-008
-0.29268656619620254 -3.4410517736100963 1.2087130354069011e-008
-0.27735750013486177 -3.4034963121237958 1.3728731713384335e-008
-0.26543492277149905 -3.3618463406110424 1.5549309790309862e-008
-0.25691877268477881 -3.3161019409669512 1.7548861005096464e-008
-0.25180913176981518 -3.2662630312964072 1.9727388937493267e-008
-0.25010587718393684 -3.2123297344420823 2.208488821787657e-008
-0.2518187134981808 -3.1613961737271041 2.4311264867115116e-008
-0.25695716101957689 -3.1141162406910894 2.6377936378223325e-008
-0.26552121974812515 -3.0704899353340385 2.8284902751201178e-008
-0.27751088968382565 -3.0305172167083936 3.0032165775923264e-008
-0.29292619130045683 -2.9941981257617125 3.1619723662514995e-008
-0.3117671245980187 -2.961532457756209 3.3047585360349226e-008
-0.33403362815517568 -2.9325204583772266 3.4315740130178546e-008
-0.35884543186278461 -2.9072770264700374 3.5419165583963523e-008
-0.38532204040013807 -2.8859171427750288 3.6352835753915596e-008
-0.41346353566235028 -2.8684410529775439 3.7116739900787359e-008
-0.44326999954453555 -2.8548485113922397 3.7710888763826217e-008
-0.47474130920402258 -2.8451395180191161 3.8135282343032178e-008
-0.50787762843103967 -2.8393139909630598 3.8389924218154365e-008
-0.54267879343535852 -2.8373722578045264 3.8474800070196255e-008
-0.5779686675338801 -2.8393044911298082 3.8390339469054276e-008
-0.611497878571444 -2.8451009454203113 3.8136968404875776e-008
-0.64326626275782173 -2.8547621939418351 3.7714661819416766e-008
-0.67327394293568465 -2.8682877453236943 3.7123441191172106e-008
-0.70152091910503267 -2.885677681461003 3.6363302940392631e-008
-0.72800727316098013 -2.9069320023537615 3.543424706707834e-008
-0.75273271847062728 -2.9320508717921978 3.4336266411730972e-008
-0.77487461861147433 -2.9610723710044318 3.3067696391001749e-008
-0.79361017337079331 -2.994035072589269 3.1626850943047071e-008
-0.80893921895835552 -3.0309388946515945 3.0013733647616064e-008
-0.82086183726927531 -3.0717838371914086 2.8228344504708741e-008
-0.82937786451332429 -3.1165698592611544 2.627068530419967e-008
-0.83448771016607348 -3.1652969608608315 2.4140756046088842e-008
-0.83619088285683751 -3.2179651829379976 2.1838554940501707e-008
;
createNode nurbsCurve -n "curveShape24" -p "mouth_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 85 0 no 3
86 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
82 83 84 85
86
0.77393257911241875 -3.7175730836810521 -1.940330994953377e-031
0.77393257911241875 -3.5696094443264581 6.467696092147526e-009
0.73898089088813446 -3.6145607716842889 4.502811168005113e-009
0.7006199909533235 -3.6525965121864705 2.8402161461406383e-009
0.6588498383604291 -3.6837166837475595 1.4799102434839811e-009
0.6136705559521225 -3.7079212454199983 4.2189524990970853e-010
0.56508202088573234 -3.7252102170377603 -3.33829701552673e-010
0.51308439695148711 -3.7355836056387064 -7.872649185378551e-010
0.45767756130671544 -3.739041396507309 -9.3840975780966465e-010
0.43271101678075785 -3.7383516873717144 -9.0826161397879009e-010
0.40822372246330868 -3.7362825561260982 -8.178170146854253e-010
0.38421559645925385 -3.7328340002112368 -6.6707584806240992e-010
0.36068672066370755 -3.7280060260251875 -4.5603839377764522e-010
0.3376370541291126 -3.7217986294092129 -1.8470447004699534e-010
0.31506661732924762 -3.7142118097235075 1.4692595109632978e-010
0.29297534884277687 -3.7052455759253502 5.3885247811726841e-010
0.27192771074457145 -3.6952346710951516 9.7644302625166088e-010
0.25248814463572361 -3.6845138610264212 1.4450645179142978e-009
0.23465656862111917 -3.6730831482783817 1.9447168412380192e-009
0.21843306459587242 -3.6609425302918104 2.4754001080899844e-009
0.20381765303376184 -3.6480920096259299 3.0371142066030343e-009
0.19081031346100896 -3.6345315709254065 3.6298598079801311e-009
0.17941106635139226 -3.6202612449009073 4.253635569815349e-009
0.16926675949854797 -3.605167013079638 4.9134253978448875e-009
0.16002405643210532 -3.5891349184101391 5.6142105129930958e-009
0.1516828445462822 -3.5721649506555213 6.3559913627286144e-009
0.14424320573619287 -3.5542571302895634 7.1387670521141591e-009
0.13770511952805878 -3.5354114470753757 7.9625380286183728e-009
0.13206860639565848 -3.5156278600654018 8.8273060821158243e-009
0.12733363562832412 -3.4949064306809765 9.7330685277946588e-009
0.12459261639173769 -3.4794959404023067 1.0406682452054597e-008
0.12227330580901977 -3.4617099390187742 1.1184133264598629e-008
0.12037564245883468 -3.4415485084254942 1.2065417385677612e-008
0.11889970823629667 -3.4190115462535733 1.305053928997798e-008
0.11784546219384862 -3.3940991548719044 1.4139494502813303e-008
0.11721293504215832 -3.3668112319115941 1.5332287498870004e-008
0.11700207559677944 -3.3371478797415364 1.6628913803461663e-008
0.11700207559677944 -2.7192965372601146 4.3636053738149411e-008
0.28660194347248191 -2.7192965372601146 4.3636053738149411e-008
0.28660194347248191 -3.2720720564869454 1.9473468381822205e-008
0.28681280291786082 -3.308119091864135 1.7897802421864093e-008
0.28744534030644037 -3.3406418938428537 1.6476185596399625e-008
0.28849961705955629 -3.3696405852657731 1.5208612535805096e-008
0.28997551033453717 -3.3951150637640004 1.4095087714766927e-008
0.29187314297405442 -3.4170653498113142 1.3135610238347836e-008
0.29419249450432944 -3.4354913615125997 1.233018368629696e-008
0.29693350350402664 -3.4503932217105291 1.1678802688990593e-008
0.30221436662907897 -3.4688521143001805 1.0871938867661151e-008
0.30895202099371666 -3.4861417698701072 1.0116184019700115e-008
0.31714630280771128 -3.5022621884203096 9.4115381451074891e-009
0.326797437282627 -3.5172133290032304 8.7580030337578387e-009
0.33790530157579235 -3.5309952325664264 8.1555768957765973e-009
0.35046997758232162 -3.5436078581623405 7.6042615210383335e-009
0.36449140388087914 -3.5550512467385307 7.1040551196684769e-009
0.37973904572489087 -3.565134357467262 6.6633083514667216e-009
0.39598208173488292 -3.5736662416528047 6.2903678490149795e-009
0.41322034812062675 -3.5806468685844912 5.985234954719177e-009
0.4314540086723509 -3.5860762484992104 5.7479092211106721e-009
0.45068302244249825 -3.589954371160073 5.5783910956581084e-009
0.47090747132618294 -3.5922812365670791 5.476680578361482e-009
0.49212723248073376 -3.5930568651940074 5.4427767742835118e-009
0.5136531994674125 -3.5922620628734587 5.4775186871282184e-009
0.5347956925816818 -3.5898776763855911 5.5817435307250507e-009
0.55555479371865568 -3.5859037262041831 5.7554504101367259e-009
0.57593054382589115 -3.5803401611447883 5.9986415627064541e-009
0.59592282006071706 -3.5731870426287426 6.3113143036223847e-009
0.61553182716091903 -3.5644443092347102 6.6934713176963667e-009
0.63475740133626846 -3.5541120019102483 7.1451108150538354e-009
0.6529969173886605 -3.5424101830641979 7.6566135622946175e-009
0.66964775011999023 -3.529558956052957 8.2183585361439758e-009
0.68470936721201503 -3.5155583720609727 8.8303434992586979e-009
0.69818213719274924 -3.5004083696669084 9.4925711364506368e-009
0.71006601911463529 -3.4841089488707651 1.0205041447719796e-008
0.72036105392523087 -3.4666600891987636 1.0967755328003454e-008
0.72906715972942127 -3.4480618930197968 1.1780708302615192e-008
0.73641364284706734 -3.4276536305522098 1.2672781787593558e-008
0.742630055283372 -3.4047747153307966 1.3672850934416103e-008
0.74771598756276436 -3.3794252087768935 1.4780913058270977e-008
0.75167176726570128 -3.3516050699429432 1.5996969949032745e-008
0.75449739439218266 -3.3213143193027239 1.7321020711764128e-008
0.75619278704709425 -3.2885528340135641 1.8753070716088825e-008
0.75675786333532202 -3.2533208188132505 2.0293111012634e-008
0.75675786333532202 -2.7192965372601146 4.3636053738149411e-008
0.92635740363056762 -2.7192965372601146 4.3636053738149411e-008
0.92635740363056762 -3.7175730836810521 -1.940330994953377e-031
0.77393257911241875 -3.7175730836810521 -1.940330994953377e-031
;
createNode nurbsCurve -n "curveShape25" -p "mouth_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 68 0 no 3
69 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68
69
1.56181959431995 -3.566355649068973 6.6099240000530106e-009
1.5832879071462069 -3.7155268851467897 8.9442178642894149e-011
1.5631813462794648 -3.7194871594839261 -8.3666910629667014e-011
1.5436894901401774 -3.7228381605631271 -2.3014381995190772e-010
1.5248123387283448 -3.7255798883843934 -3.4998854932382803e-010
1.5065495644635096 -3.727712344387287 -4.4320116167070572e-010
1.4889019862968147 -3.7292355250528777 -5.0978150317519496e-010
1.4718691128575745 -3.7301494361394156 -5.4972982553840718e-010
1.4554509441457888 -3.7304540718886505 -5.6304587705923094e-010
1.4299774688627112 -3.729859176821563 -5.3704218779189447e-010
1.4061916880938066 -3.728074485222244 -4.590308403219835e-010
1.3840940932097612 -3.7250999990101104 -3.2901191854986864e-010
1.3636848480008033 -3.7209357223438988 -1.4698560425968565e-010
1.3449636248864758 -3.7155816504250669 8.7048312299491475e-011
1.3279307514472354 -3.7090377829337124 3.7308984511105772e-010
1.3125859001026257 -3.7013041278674046 7.111386445901365e-010
1.2986990274767576 -3.6926011059261095 1.0915598159340823e-009
1.2860396807181718 -3.6831491582835718 1.5047175694029651e-009
1.2746073684561823 -3.6729482874990138 1.9506117931296247e-009
1.2644027458517031 -3.6619984910132128 2.4292425989812214e-009
1.2554255672193921 -3.6502997688261694 2.9406099869577546e-009
1.2476757506641343 -3.6378521107009938 3.4847144045278682e-009
1.241153378081044 -3.6246555422299096 4.0615547330199554e-009
1.2356670605881523 -3.6089451929904652 4.7482759087455747e-009
1.2310245084572333 -3.5889562539815443 5.6220201832044364e-009
1.2272260492687435 -3.5646886842555903 6.6827893462711054e-009
1.2242719287080259 -3.5361425452339383 7.9305807131337293e-009
1.2221616554043953 -3.5033178164428103 9.3653951787295949e-009
1.2208956388334224 -3.4662144159870918 1.0987236322807838e-008
1.2204735514146505 -3.4248325076570114 1.2796096985870182e-008
1.2204735514146505 -2.8502532127422349 3.7911755647410105e-008
1.09595727150627 -2.8502532127422349 3.7911755647410105e-008
1.09595727150627 -2.7192965372601146 4.3636053738149411e-008
1.2204735514146505 -2.7192965372601146 4.3636053738149411e-008
1.2204735514146505 -2.4725450839552803 5.4421902323873898e-008
1.390073091709896 -2.3712414828063819 5.8850023368538257e-008
1.390073091709896 -2.7192965372601146 4.3636053738149411e-008
1.56181959431995 -2.7192965372601146 4.3636053738149411e-008
1.56181959431995 -2.8502532127422349 3.7911755647410105e-008
1.390073091709896 -2.8502532127422349 3.7911755647410105e-008
1.390073091709896 -3.4352647577315092 1.234008885215946e-008
1.3902570281364701 -3.4549285321893564 1.1480557971649665e-008
1.3908085098357346 -3.4724782866420965 1.0713433840429035e-008
1.3917273730174615 -3.487914123458622 1.0038711983811148e-008
1.3930139452621073 -3.5012360221651551 9.4563932967332918e-009
1.3946683903599011 -3.5124439213403598 8.9664804640073185e-009
1.3966903807303856 -3.521537800510457 8.5689743805705091e-009
1.399079916373561 -3.5285177415705617 8.263871466673731e-009
1.40188597056774 -3.5342674951721715 8.0125417544406851e-009
1.4051575165912358 -3.5396708529143424 7.7763534861205113e-009
1.4088945544440485 -3.5447278352708524 7.5553057667759221e-009
1.4130970841261781 -3.5494384012941445 7.3494003862814879e-009
1.4177649418473961 -3.5538025816948866 7.1586360022312812e-009
1.4228989465588449 -3.5578203457624107 6.9830139570312295e-009
1.4284979517289254 -3.561491734444274 6.8225324608067631e-009
1.4346879120433318 -3.564740032492216 6.6805448435621104e-009
1.4415928167050178 -3.5674886065530909 6.5604008555523606e-009
1.44921299329444 -3.569737456626898 6.4621004967775153e-009
1.4575489331822844 -3.5714865417660806 6.3856455571121415e-009
1.466599817417408 -3.5727359029181955 6.3310342466816731e-009
1.4763664649509534 -3.5734855093725755 6.2982679078920324e-009
1.4868482206220066 -3.5737353816029986 6.2873456458059383e-009
1.4953530282354053 -3.5735847560141401 6.2939296994064457e-009
1.5045925988137285 -3.5731329509057899 6.3136787279274733e-009
1.5145675875178899 -3.5723799253303907 6.3465945212435891e-009
1.5252778305576613 -3.5713256792879426 6.3926770793547939e-009
1.5367230003525858 -3.5699702025415565 6.4519268497297281e-009
1.5489039158538058 -3.5683135360387892 6.5243420424938249e-009
1.56181959431995 -3.566355649068973 6.6099240000530106e-009
;
createNode nurbsCurve -n "curveShape26" -p "mouth_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 71 0 no 3
72 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
72
1.7249785752512272 -3.7175730836810521 -1.940330994953377e-031
1.7249785752512272 -2.3414542642760416 6.0152064043699848e-008
1.8945784431269297 -2.3414542642760416 6.0152064043699848e-008
1.8945784431269297 -2.835326026480228 3.8564243682137141e-008
1.9294577360702299 -2.7988469124803297 4.0158796398542869e-008
1.9668533382935418 -2.7679800706590183 4.1508028906579555e-008
2.0067654135870949 -2.742725501016293 4.2611941206247185e-008
2.0491941257411175 -2.7230828759716972 4.3470547616542316e-008
2.0941389833849238 -2.7090526050008021 4.4083830238719254e-008
2.1416008054696563 -2.7006342786280366 4.4451806971523687e-008
2.1915789368344014 -2.6978282244338576 4.4574463495959084e-008
2.222472230777611 -2.6987190794865157 4.4535522984845137e-008
2.2521847609637682 -2.7013919722249473 4.4418687132506756e-008
2.2807160360221861 -2.7058469026491521 4.4223955938943938e-008
2.3080665473235511 -2.7120837888640157 4.3951332983905829e-008
2.3342362948678623 -2.7201026308695386 4.3600818267392422e-008
2.3592252786551207 -2.729903264875492 4.3172418948901992e-008
2.3830330073146402 -2.7414860184623326 4.2666120709437982e-008
2.4053068404845215 -2.7546400936060174 4.2091137823279434e-008
2.4256934826419503 -2.7691551017580749 4.1456666665959695e-008
2.4441921148357846 -2.7850312067087328 4.076270007798047e-008
2.4608035560171668 -2.8022681627726493 4.0009248798589198e-008
2.47552747860564 -2.8208661337400516 3.9196305668287578e-008
2.4883647015523462 -2.8408248739255981 3.8323881426323043e-008
2.4993139145354584 -2.8621446290146304 3.7391965333448178e-008
2.5086050790357501 -2.8855629464059582 3.636831816893378e-008
2.5164668462121682 -2.9118172916032758 3.5220704291799793e-008
2.522899216064713 -2.9409082378723821 3.3949098643802261e-008
2.5279020248031561 -2.9728350481572487 3.2553533442683421e-008
2.5314752724274969 -3.0075982957236764 3.1033983630199305e-008
2.53361961409865 -3.0451976120436504 2.9390465315221038e-008
2.5343342308654728 -3.0856331609073995 2.7622971338250341e-008
2.5343342308654728 -3.7175730836810521 -1.940330994953377e-031
2.3647343629897701 -3.7175730836810521 -1.940330994953377e-031
2.3647343629897701 -3.0859350672460302 2.7609774593056227e-008
2.3636232100798171 -3.0511438934456478 2.9130545099996112e-008
2.360289096189045 -3.0191682736726966 3.0528243831600697e-008
2.3547316937369969 -2.9900084536125178 3.1802860048622575e-008
2.3469518216748142 -2.9636642694748838 3.2954400910560015e-008
2.3369491524220409 -2.9401357212597947 3.3982866417413023e-008
2.3247238497689051 -2.91942280896725 3.4888256569181593e-008
2.3102754223447217 -2.901525614492364 3.5670567786116594e-008
2.2937943581852029 -2.8862139306690198 3.6339862743042556e-008
2.2754688522628634 -2.8732579598066712 3.6906186216038333e-008
2.2553000511093018 -2.862657783800433 3.736953462535479e-008
2.2332879547245188 -2.8544130750698473 3.7729922289988455e-008
2.2094319079476001 -2.8485240793002577 3.7987338470691944e-008
2.1837327297296878 -2.8449904689112069 3.8141797486461785e-008
2.1561897649098687 -2.8438127352733806 3.8193277858803174e-008
2.1350847388103626 -2.8446074454619259 3.815853997317625e-008
2.1143418529060072 -2.8469919036080182 3.8054311997298929e-008
2.0939607796163466 -2.8509659459214296 3.7880601090669473e-008
2.0739421741022936 -2.8565293267168173 3.76374179925353e-008
2.0542853812029351 -2.8636826192599809 3.7324737644652461e-008
2.0349910560791846 -2.8724253321802351 3.6942581525515755e-008
2.0160587073603571 -2.8827576292678074 3.6490942475626934e-008
1.9980771609178081 -2.8944497128321531 3.5979865271064832e-008
1.9816342598815231 -2.9072721946582973 3.5419376789162613e-008
1.9667303318319596 -2.9212249928511254 3.4809480609669419e-008
1.953365376769117 -2.9363078617252945 3.4150187471832657e-008
1.941539230902767 -2.9525210469661474 3.3441486636404921e-008
1.9312522218133668 -2.9698644666785698 3.2683381683135349e-008
1.9225040219204592 -2.9883381208625623 3.1875872612023933e-008
1.9150952985159939 -3.008410859047125 3.0998465359260478e-008
1.908826391311464 -3.0305517764466012 3.0030655121787382e-008
1.9036969727264121 -3.0547607502183198 2.8972447269228347e-008
1.8997075341315246 -3.0810379441525084 2.7823834642085095e-008
1.8968579117365718 -3.1093831944589398 2.6584824399855905e-008
1.8951484331220116 -3.1397965011376128 2.5255416542540773e-008
1.8945784431269297 -3.1722779460836428 2.3835607490390565e-008
1.8945784431269297 -3.7175730836810521 -1.940330994953377e-031
1.7249785752512272 -3.7175730836810521 -1.940330994953377e-031
;
'''
eye_ctl = '''
createNode transform -n "eye_ctlGp" -p "ctlGp";
setAttr ".t" -type "double3" 6.9848352402786429e-006 189.36139382939413 16.444739488566082 ;
setAttr ".r" -type "double3" 1.5902773407317584e-014 6.3611093629270304e-015 2.5444437451708134e-014 ;
setAttr ".s" -type "double3" 1.0000001192093231 1.0000001192092984 1.0000001192093109 ;
createNode transform -n "eyeRoot_ctl" -p "ctlGp|eye_ctlGp";
addAttr -ci true -sn "_____" -ln "_____" -min 0 -max 0 -en "FreeBlend" -at "enum";
addAttr -ci true -sn "FreeBlendVis" -ln "FreeBlendVis" -min 0 -max 1 -at "bool";
addAttr -ci true -sn "FreeBlendA" -ln "FreeBlendA" -min 0 -max 1 -at "double";
addAttr -ci true -sn "FreeBlendB" -ln "FreeBlendB" -min 0 -max 1 -at "double";
addAttr -ci true -sn "FreeBlendC" -ln "FreeBlendC" -min 0 -max 1 -at "double";
addAttr -ci true -sn "FreeBlendD" -ln "FreeBlendD" -min 0 -max 1 -at "double";
addAttr -ci true -sn "__________" -ln "__________" -min 1000 -max -1 -at "enum";
addAttr -ci true -sn "EyeLidAim" -ln "EyeLidAim" -min 0 -max 100 -at "double";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr -l on -k off ".rx";
setAttr -l on -k off ".ry";
setAttr -l on -k off ".rz";
setAttr -l on -k off ".sx";
setAttr -l on -k off ".sy";
setAttr -l on -k off ".sz";
setAttr ".rp" -type "double3" -1.9058241313221758e-021 0 -5.1514348342607263e-014 ;
setAttr ".sp" -type "double3" -1.9058241313221758e-021 0 -5.1514348342607263e-014 ;
setAttr -l on "._____";
setAttr -l on ".FreeBlendVis";
setAttr -l on ".FreeBlendA";
setAttr -l on ".FreeBlendB";
setAttr -l on ".FreeBlendC";
setAttr -l on ".FreeBlendD";
setAttr -l on -k on ".__________";
setAttr -k on ".EyeLidAim" 50;
createNode nurbsCurve -n "eyeRoot_ctlShape" -p "eyeRoot_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 4 0 no 3
5 0 1 2 3 4
5
5.5438679263782689 -2.7719341592515545 0
-5.543867926378268 -2.7719341592515545 0
-5.543867926378268 2.7719341592517592 0
5.5438679263782689 2.7719341592517592 0
5.5438679263782689 -2.7719341592515545 0
;
createNode transform -n "eyeLeft_frmGp" -p "eyeRoot_ctl";
setAttr ".t" -type "double3" 0.38 0 0 ;
setAttr ".rp" -type "double3" 2.356 0 0 ;
setAttr ".sp" -type "double3" 2.356 0 0 ;
createNode transform -n "eyeLeft_frm" -p "eyeLeft_frmGp";
setAttr -l on -k off ".v";
setAttr ".ovdt" 2;
setAttr ".ove" yes;
setAttr -k on ".ovc" 2;
setAttr ".rp" -type "double3" 2.356 0 -2.4868995751603507e-014 ;
setAttr ".sp" -type "double3" 2.356 0 -2.4868995751603507e-014 ;
createNode nurbsCurve -n "eyeLeft_frmShape" -p "eyeLeft_frm";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 4 0 no 3
5 0 1 2 3 4
5
4.8003780325981893 -2.4443782054923302 0
-0.088378032598189937 -2.4443782054923302 -2.540190280342358e-014
-0.088378032598189937 2.4443782054923302 -2.540190280342358e-014
4.8003780325981893 2.4443782054923302 0
4.8003780325981893 -2.4443782054923302 0
;
createNode transform -n "eyeLeft_ctlGp" -p "eyeLeft_frm";
setAttr ".rp" -type "double3" 2.356 0 0 ;
setAttr ".sp" -type "double3" 2.356 0 0 ;
createNode transform -n "eyeLeft_ctl" -p "eyeLeft_ctlGp";
setAttr -l on -k off ".v";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr -l on -k off ".rx";
setAttr -l on -k off ".ry";
setAttr -l on -k off ".rz";
setAttr ".rp" -type "double3" 2.356 0 -2.4868995751603507e-014 ;
setAttr ".sp" -type "double3" 2.356 0 -2.4868995751603507e-014 ;
createNode nurbsCurve -n "eyeLeft_ctlShape" -p "eyeLeft_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 16 0 no 3
17 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17
2.3560000000000061 1.161136074923661 2.540190280342358e-014
1.9116526045902116 1.072749894726553 2.540190280342358e-014
1.5349527560404486 0.82104730203311649 2.540190280342358e-014
1.2832501811504475 0.44434742683922651 2.540190280342358e-014
1.1948640072049916 0 2.540190280342358e-014
1.2832501811504475 -0.44434742683922651 2.540190280342358e-014
1.5349527560404486 -0.82104730203311649 2.540190280342358e-014
1.9116526045902116 -1.072749894726553 2.540190280342358e-014
2.3560000000000061 -1.1611360749234563 2.540190280342358e-014
2.8003473954097879 -1.072749894726553 2.540190280342358e-014
3.1770472439595507 -0.82104730203311649 2.540190280342358e-014
3.4287498188495649 -0.44434742683922651 2.540190280342358e-014
3.5171359927950205 0 2.540190280342358e-014
3.4287498188495649 0.44434742683922651 2.540190280342358e-014
3.1770472439595507 0.82104730203311649 2.540190280342358e-014
2.8003473954097879 1.072749894726553 2.540190280342358e-014
2.3560000000000061 1.161136074923661 2.540190280342358e-014
;
createNode transform -n "eyeRight_frmGp" -p "eyeRoot_ctl";
setAttr ".t" -type "double3" -0.38 0 0 ;
setAttr ".rp" -type "double3" -2.3559999999999994 0 0 ;
setAttr ".sp" -type "double3" -2.3559999999999994 0 0 ;
createNode transform -n "eyeRight_frm" -p "eyeRight_frmGp";
setAttr -l on -k off ".v";
setAttr ".ovdt" 2;
setAttr ".ove" yes;
setAttr -k on ".ovc" 2;
setAttr ".rp" -type "double3" -2.3559999999999994 0 0 ;
setAttr ".sp" -type "double3" -2.3559999999999994 0 0 ;
createNode nurbsCurve -n "eyeRight_frmShape" -p "eyeRight_frm";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 4 0 no 3
5 0 1 2 3 4
5
0.088378032598215833 -2.4443782054925354 0
-4.8003780325981573 -2.4443782054925354 0
-4.8003780325981573 2.4443782054921259 0
0.088378032598215833 2.4443782054921259 0
0.088378032598215833 -2.4443782054925354 0
;
createNode transform -n "eyeRight_ctlGp" -p "eyeRight_frm";
setAttr ".rp" -type "double3" -2.3559999999999994 0 0 ;
setAttr ".sp" -type "double3" -2.3559999999999994 0 0 ;
createNode transform -n "eyeRight_ctl" -p "eyeRight_ctlGp";
setAttr -l on -k off ".v";
setAttr ".ove" yes;
setAttr ".ovc" 17;
setAttr -l on -k off ".rx";
setAttr -l on -k off ".ry";
setAttr -l on -k off ".rz";
setAttr ".rp" -type "double3" -2.3559999999999994 0 0 ;
setAttr ".sp" -type "double3" -2.3559999999999994 0 0 ;
createNode nurbsCurve -n "eyeRight_ctlShape" -p "eyeRight_ctl";
setAttr -k off ".v";
setAttr ".cc" -type "nurbsCurve"
1 16 0 no 3
17 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17
-2.3559999999999741 1.1611360749234565 0
-2.8003473954097622 1.0727498947263485 0
-3.1770472439595188 0.8210473020331166 0
-3.4287498188495262 0.44434742683902195 0
-3.5171359927949823 -2.0463630789890888e-013 0
-3.4287498188495262 -0.44434742683922657 0
-3.1770472439595188 -0.82104730203332121 0
-2.8003473954097622 -1.0727498947265532 0
-2.3559999999999741 -1.1611360749236612 0
-1.9116526045901858 -1.0727498947265532 0
-1.534952756040423 -0.82104730203332121 0
-1.2832501811504153 -0.44434742683922657 0
-1.1948640072049594 -2.0463630789890888e-013 0
-1.2832501811504153 0.44434742683902195 0
-1.534952756040423 0.8210473020331166 0
-1.9116526045901858 1.0727498947263485 0
-2.3559999999999741 1.1611360749234565 0
;
'''
bone_root = '''
createNode transform -n "bonGp";
rename -uid "9DC90176-44BD-DCB4-B609-6786A263A772";
createNode transform -n "facial_bonGp" -p "bonGp";
rename -uid "9696F020-4661-DD69-1E81-ABAEBA1F7BFA";
createNode joint -n "facialRoot_bon" -p "facial_bonGp";
rename -uid "A9020D7A-445A-2B0C-228F-DC93CD73B32A";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -4.8940192021578504e-007 185.69181823730477 0.53225386142731868 ;
setAttr ".r" -type "double3" 90 3.1805546814635168e-015 90.000000000000014 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" -2.2204460492503131e-016 1 0 0 -2.2204460492503131e-016 0 1 0
1 2.2204460492503131e-016 2.2204460492503131e-016 0 -4.8940192021578504e-007 185.69181823730477 0.53225386142731868 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
'''
eyebrow_bone = '''
createNode joint -n "eyebrowLeftA_offset_bon" -p "facialRoot_bon";
rename -uid "CF15D2EE-49F6-B528-7797-1F85C0290EA3";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 4.3700408935546022 9.3891161445138209 0.93904424970160794 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
0.93904376029968262 190.06185913085937 9.9213700059411387 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyebrowLeftA_bon" -p "eyebrowLeftA_offset_bon";
rename -uid "D68A8B61-48FA-FB48-8766-39957CB2F853";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 8.8817841970012523e-016 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
0.93904376029968262 190.06185913085937 9.9213700059411387 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyebrowLeftB_offset_bon" -p "facialRoot_bon";
rename -uid "24EF6A85-41CC-1648-3785-57AE4C44DC2E";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 5.144528049407711 8.5830792833505818 3.1711116983238563 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
3.1711112089219311 190.83634628671248 9.1153331447778996 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyebrowLeftB_bon" -p "eyebrowLeftB_offset_bon";
rename -uid "767DAF6A-45D3-21AD-A7B2-D0B7744ADD01";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 8.8817841970012523e-016 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
3.1711112089219311 190.83634628671248 9.1153331447778996 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyebrowLeftC_offset_bon" -p "facialRoot_bon";
rename -uid "E7E8DB3C-427F-69B4-DF48-EF8118B94354";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 4.7370827280976755 7.1677465615003193 4.4118418734479228 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
4.4118413840459967 190.42890096540245 7.7000004229276371 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyebrowLeftC_bon" -p "eyebrowLeftC_offset_bon";
rename -uid "012840AE-48C7-ACFF-3CFA-ECB7F68A0DE6";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -8.8817841970012523e-016 0 -8.8817841970012523e-016 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
4.4118413840459967 190.42890096540245 7.7000004229276371 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
'''
eye_fc_bone = '''
createNode joint -n "eyeLeftA_offset_bon" -p "facialRoot_bon";
rename -uid "FFD1781F-481C-A022-1905-0D9F1DF48E58";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 4.2028270904422413 8.1791566610336197 2.9427504665137421 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.9427499771118164 189.89464532774701 8.7114105224609375 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeLeftA_bon" -p "eyeLeftA_offset_bon";
rename -uid "11471C59-48AE-9DE4-9272-9F8A76701A1B";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -8.8817841970012523e-016 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.9427499771118164 189.89464532774701 8.7114105224609375 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeLeftB_offset_bon" -p "facialRoot_bon";
rename -uid "A04FCBD1-467C-B75C-1AE3-90882874E468";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 3.8930053710936647 7.1629733232281119 4.165570179915294 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
4.1655696905133697 189.58482360839844 7.6952271846554297 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeLeftB_bon" -p "eyeLeftB_offset_bon";
rename -uid "E6AEA894-455E-B024-CA58-5B9B70C207DE";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 0 0 -1.7763568394002505e-015 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
4.1655696905133697 189.58482360839844 7.6952271846554297 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeLeftC_offset_bon" -p "facialRoot_bon";
rename -uid "29B4A74A-422F-F358-E8B4-FF9968C8E88E";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 3.3165229719751039 8.0441717781224842 2.835086358237374 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.8350858688354492 189.00834120927988 8.5764256395498037 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeLeftC_bon" -p "eyeLeftC_offset_bon";
rename -uid "EAA7EB7C-4A4D-2D21-3746-56B2A1144EA5";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.8350858688354492 189.00834120927988 8.5764256395498037 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeLeftD_offset_bon" -p "facialRoot_bon";
rename -uid "FED65DF1-412D-034B-9903-B4AA332F2C9A";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 3.4484592881457843 7.7909554190995429 1.3197728336453549 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.3197723442434308 189.14027752545056 8.3232092805268589 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeLeftD_bon" -p "eyeLeftD_offset_bon";
rename -uid "7BC3BD1F-4193-AA48-624B-3DB64DAFF54B";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 4.4408920985006262e-016 0 -1.7763568394002505e-015 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.3197723442434308 189.14027752545056 8.3232092805268589 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeSubLeftA_offset_bon" -p "facialRoot_bon";
rename -uid "8B5C2D65-406B-AC09-5E88-9B818E827F5C";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 3.9960021972655397 7.9960590875146416 1.8888613111258628 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.888860821723938 189.68782043457031 8.5283129489419576 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeSubLeftA_bon" -p "eyeSubLeftA_offset_bon";
rename -uid "C6A37E85-4DC1-81C4-2958-3CB918BBE3E5";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 0 0 -1.7763568394002505e-015 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.888860821723938 189.68782043457031 8.5283129489419576 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeSubLeftB_offset_bon" -p "facialRoot_bon";
rename -uid "6ACAC2A5-4E1D-CD46-D591-05919323B9E6";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 4.1313323987752142 7.6542381010593825 3.7249675015357933 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
3.7249670121338685 189.82315063607999 8.1864919624867021 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeSubLeftB_bon" -p "eyeSubLeftB_offset_bon";
rename -uid "7052DEFA-4B7B-62AF-2A22-C3AB1FB5BA38";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
3.7249670121338685 189.82315063607999 8.1864919624867021 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeSubLeftC_offset_bon" -p "facialRoot_bon";
rename -uid "2208B800-45FF-412C-556C-5CAD9ED0559D";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 3.4052998472531897 7.5782944965480237 3.6767301689254399 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
3.6767296795235147 189.09711808455796 8.1105483579753432 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeSubLeftC_bon" -p "eyeSubLeftC_offset_bon";
rename -uid "4630D801-4BC6-A7E7-98E7-50AD60E498CB";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -8.8817841970012523e-016 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
3.6767296795235147 189.09711808455796 8.1105483579753432 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeSubLeftD_offset_bon" -p "facialRoot_bon";
rename -uid "E3446D38-40DD-0868-A71F-76A462FB8144";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 3.3950400425088105 7.9269634255869477 1.9175675451785996 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.9175670557766751 189.08685827981358 8.4592172870142655 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "eyeSubLeftD_bon" -p "eyeSubLeftD_offset_bon";
rename -uid "47A18964-4EF3-896E-2CA9-EC91DAE6E4A8";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 0 0 -3.5527136788005009e-015 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.9175670557766751 189.08685827981358 8.4592172870142655 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
'''
nose_bone = '''
createNode joint -n "noseLeftA_offset_bon" -p "facialRoot_bon";
rename -uid "5C57838C-4BD5-B5C6-2518-ECB0344CEF6C";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 0.19924926757803973 8.7479861974716062 1.2978750592948072 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.2978745698928831 185.89106750488281 9.2802400588989258 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "noseLeftA_bon" -p "noseLeftA_offset_bon";
rename -uid "7D001000-4AE4-826A-D3D7-A8AD4660573E";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 0 0 -3.5527136788005009e-015 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.2978745698928831 185.89106750488281 9.2802400588989258 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "noseTop_offset_bon" -p "facialRoot_bon";
rename -uid "3E1D6F29-4EAA-E482-10C6-69B86EDFAD58";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -0.48492431640633527 10.560554862022389 2.3287028950081802e-005 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
-1.2978700000000003 185.89099999999999 9.2802399999999992 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "noseTop_bon" -p "noseTop_offset_bon";
rename -uid "470A5001-469E-6210-47E0-59AB42687434";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 1.0164395367051604e-020 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
-1.2978700000000003 185.89099999999999 9.2802399999999992 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
'''
cheek_bone = '''
createNode joint -n "cheekLeftA_offset_bon" -p "facialRoot_bon";
rename -uid "F9FF7B0C-4E20-C3B3-1D0C-B5B7DF180307";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 2.1912994384764772 8.3927787542343033 1.5038372403861158 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.5038367509841917 187.88311767578125 8.9250326156616211 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "cheekLeftA_bon" -p "cheekLeftA_offset_bon";
rename -uid "01C49EC0-4CC0-D543-3A69-D1B6D5E8B2EB";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 4.4408920985006262e-016 0 -3.5527136788005009e-015 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.5038367509841917 187.88311767578125 8.9250326156616211 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "cheekLeftB_offset_bon" -p "facialRoot_bon";
rename -uid "43A4AB9B-48A1-10C2-8FF7-0985479B95E1";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 1.6036598991513529 7.5628490941211606 3.6919666818481605 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
3.6919661924462361 187.29547813645613 8.0951029555484801 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "cheekLeftB_bon" -p "cheekLeftB_offset_bon";
rename -uid "667684C7-46F8-D6BF-5EC4-C3A00F8AFBDF";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -8.8817841970012523e-016 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
3.6919661924462361 187.29547813645613 8.0951029555484801 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "cheekLeftC_offset_bon" -p "facialRoot_bon";
rename -uid "A85991B3-4471-9FE8-6F05-ADAC92B990B5";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -0.63150126416718422 6.5287568310138262 3.7080446188021203 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
3.7080441294001969 185.06031697313759 7.0610106924411458 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "cheekLeftC_bon" -p "cheekLeftC_offset_bon";
rename -uid "1A18EAD6-4ECA-3A04-481F-84B2DD653CE5";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
3.7080441294001969 185.06031697313759 7.0610106924411458 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
'''
lip_bone = '''
createNode joint -n "lipLeftA_offset_bon" -p "facialRoot_bon";
rename -uid "DF835898-4A60-F94E-7751-1B9C44A28685";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -1.6905054884016408 8.4643116097504549 1.0765872127295597 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.0765867233276365 184.00131274890313 8.9965654711777745 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "lipLeftA_bon" -p "lipLeftA_offset_bon";
rename -uid "632848E2-4A42-A9F1-316F-2996A26D2E51";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 4.4408920985006262e-016 0 -3.5527136788005009e-015 ;
setAttr ".s" -type "double3" 1.0000000000000002 1.0000000000000002 1.0000000000000002 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1.0000000000000002 4.4408920985006271e-016 3.3306690738754706e-016 0
-5.5511151231257837e-016 1.0000000000000002 -7.3955709864469879e-032 0 -4.4408920985006271e-016 -1.1102230246251573e-016 1.0000000000000002 0
1.0765867233276436 184.00131274890313 8.9965654711777745 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "lipLeftB_offset_bon" -p "facialRoot_bon";
rename -uid "3DA12B7F-4BBA-A66F-905A-DB90AB54C111";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -1.7418365478516478 7.1799685383810639 1.9758502370596991 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.9758497476577759 183.94998168945312 7.7122223998083843 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "lipLeftB_bon" -p "lipLeftB_offset_bon";
rename -uid "045FCBD1-4FA9-1FC0-180B-74B4C6BD1072";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 0 0 1.7763568394002505e-015 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.9758497476577723 183.94998168945315 7.7122223998083834 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "lipLeftC_offset_bon" -p "facialRoot_bon";
rename -uid "4CB3BC2B-4FD0-D18D-C63F-DC86F3EEF93E";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -2.2716700583363263 8.4810701556833354 1.0168132907630072 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.0168128013610838 183.42014817896845 9.013324017110655 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "lipLeftC_bon" -p "lipLeftC_offset_bon";
rename -uid "3AD72BA8-48C9-15DA-888C-AA91C8A0A699";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.0168128013610802 183.42014817896842 9.013324017110655 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "lipCenterA_offset_bon" -p "facialRoot_bon";
rename -uid "2F9905B9-4152-2674-3639-1D83632CD3FF";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -1.6843776850639927 9.1481983225482431 2.3287028949188267e-005 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2797627025283873e-005 184.00744055224078 9.6804521839755608 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "lipCenterA_bon" -p "lipCenterA_offset_bon";
rename -uid "60C83173-4BE8-9A26-7606-A18FC767FF72";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2797627021731159e-005 184.00744055224078 9.6804521839755608 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "lipCenterB_offset_bon" -p "facialRoot_bon";
rename -uid "04EAD646-44D0-605F-C253-79AA45F04547";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -2.2480827585481507 8.9049012561671983 2.3287028948955055e-005 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2797627025283873e-005 183.44373547875662 9.4371551175945179 1;
setAttr ".ds" 2;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
createNode joint -n "lipCenterB_bon" -p "lipCenterB_offset_bon";
rename -uid "AE94A749-44C1-9416-0590-EA947160FD98";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.27976270323893e-005 183.44373547875662 9.4371551175945179 1;
setAttr ".radi" 0.5;
setAttr ".liw" yes;
'''
eyelid_bone = '''
createNode joint -n "eyeLidLeft_bon" -p "facialRoot_bon";
rename -uid "0C1ECB96-4D1A-1858-97DC-D9A96FF2BAF3";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 3.900497436523267 6.3337520360946549 2.726737929034341 ;
setAttr ".r" -type "double3" -3.6005454175737145e-016 1.0551790517689789e-017 -9.9218256450371638e-017 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" 180 7.062250076880252e-031 89.999999999999986 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1.6653345369377348e-015 0 1 0 -0 1 0 0 -1 -0 1.6653345369377348e-015 0
2.7267374396324167 189.59231567382804 6.8660058975219727 1;
createNode joint -n "eyeLidLeftEnd_bon" -p "eyeLidLeft_bon";
rename -uid "12667617-4277-B26C-9D05-B3ADEC04C3E6";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 1.8066778182983398 5.6843418860808015e-014 5.3290705182007514e-015 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1.6653345369377348e-015 0 1 0 0 1 0 0 -1 0 1.6653345369377348e-015 0
2.7267374396324127 189.59231567382804 8.6726837158203125 1;
'''
teeth_U_bon = '''
createNode joint -n "teethUpper_offset_bon" -p "facialRoot_bon";
rename -uid "D3AA3D39-4577-B69C-1794-54AF69AC9E46";
setAttr ".t" -type "double3" -1.1693911500134391 4.7501369728222116 2.3377585515815611e-005 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -90 -89.999999999999986 0 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 0 0 0 0 0.99595556801980001 0.089847128670634491 0
0 -0.089847128670634491 0.99595556801980001 0 2.288818359375e-005 184.52242708729133 5.2823908342495303 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "teethUpper_bon" -p "teethUpper_offset_bon";
rename -uid "33299837-485D-AAF2-BE2A-1AAF5AB66862";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 1.7763568394002505e-015 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 0 0 0 0 0.99595556801980001 0.089847128670634491 0
0 -0.089847128670634491 0.99595556801980001 0 2.288818359375e-005 184.52242708729133 5.2823908342495303 1;
setAttr ".radi" 0.98751911037463325;
'''
jaw_bone = '''
createNode joint -n "jawRoot_offset_bon" -p "facialRoot_bon";
rename -uid "B2D4914D-441B-C538-CA90-9ABDD0842CB0";
setAttr ".t" -type "double3" -0.81864647162456095 1.4706076882441188 4.8940192068709005e-007 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -180 0 121.11836276403479 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" -1.4435828252834047e-014 -0.51680772796489749 0.85610149650363332 0
1.7393622996050378e-014 0.85610149650363332 0.51680772796489749 0 -1 2.2351254277177376e-014 -3.3693753888538699e-015 0
0 184.87317176568021 2.0028615496714379 1;
setAttr ".radi" 2;
createNode joint -n "jawRoot_bon" -p "jawRoot_offset_bon";
rename -uid "D9C162F0-472A-9052-5676-0DB8754A8EAB";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -2.646589102075096e-045 -1.5976817074682986e-045 -2.5243548967072378e-029 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" -1.4435828252834047e-014 -0.51680772796489749 0.85610149650363332 0
1.7393622996050378e-014 0.85610149650363332 0.51680772796489749 0 -1 2.2351254277177376e-014 -3.3693753888538699e-015 0
0 184.87317176568021 2.0028615496714379 1;
setAttr ".radi" 2;
createNode joint -n "jawTop_offset_bon" -p "jawRoot_bon";
rename -uid "BFA7ADBE-460C-5863-61D9-ABB364308B93";
setAttr ".t" -type "double3" 8.6667734551066502 -2.8421709430404007e-014 4.7466714032194199e-014 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".radi" 2;
createNode joint -n "jawTop_bon" -p "jawTop_offset_bon";
rename -uid "63F470C1-4382-D738-E57A-29B88EDBAA23";
setAttr ".t" -type "double3" 0 0 3.2426313349664275e-013 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".radi" 2;
'''
teeth_L_bone = '''
createNode joint -n "teethLower_offset_bon" -p "jawRoot_bon";
rename -uid "3C57978C-4E04-AAC0-3410-3DB99834DFC2";
setAttr ".t" -type "double3" 3.5181970568207532 0.34732286166118342 -2.2888183506205276e-005 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -154.03644981535044 -89.999999999998721 0 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 0 0 0 0 1 0 0 0 0 1 0 -0.82196000000000002 183.34580230712891 8.288510799407959 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "teethLower_bon" -p "teethLower_offset_bon";
rename -uid "0C40BC56-48E5-5D96-3EC9-DFAA6D191937";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 1.7763636156638285e-015 0 1.4210854715202004e-014 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 0 0 0 0 1 0 0 0 0 1 0 -0.82196000000000002 183.34580230712891 8.288510799407959 1;
setAttr ".radi" 0.98751911037463325;
'''
tongue_bone = '''
createNode joint -n "tongueRoot_offset_bon" -p "jawRoot_bon";
rename -uid "3618C3E9-4E85-3941-9FBB-7684B45A1F22";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 3.0561527679174816 0.040374242355227352 -2.2768974218610087e-005 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" -31.118362764034746 89.999999999998678 0 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974304113696e-005 183.32829284667969 4.6401042282892666 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueRoot_bon" -p "tongueRoot_offset_bon";
rename -uid "606C21B9-4178-28AE-DB36-05836AEFD940";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 3.3881317890172014e-021 2.8421709430404007e-014 4.3520742565306136e-014 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974304113696e-005 183.32829284667969 4.6401042282892666 1;
setAttr ".radi" 0.98751911037463325;
setAttr ".liw" yes;
createNode joint -n "tongueCenterARoot_offset_bon" -p "tongueRoot_bon";
rename -uid "485574A4-4AFB-4C68-8B70-66BC5FF4546F";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -4.0606725610053268e-015 0 0.44968230125174902 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974303913996e-005 183.32829284667969 5.0897865295410156 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
setAttr ".liw" yes;
createNode joint -n "tongueCenterARoot_bon" -p "tongueCenterARoot_offset_bon";
rename -uid "FB2D1BF9-4620-3E4A-FBB1-1F837F5EAD0F";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974303913996e-005 183.32829284667969 5.0897865295410156 1;
setAttr ".radi" 0.98751911037463325;
setAttr ".liw" yes;
createNode joint -n "tongueCenterA_offset_bon" -p "tongueCenterARoot_bon";
rename -uid "BDC48385-4955-6D4D-AE22-6386D1588B72";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974303913996e-005 183.32829284667969 5.0897865295410156 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueCenterA_bon" -p "tongueCenterA_offset_bon";
rename -uid "B39AB329-4090-6071-311D-F084F23B7FB8";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974303913996e-005 183.32829284667969 5.0897865295410156 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueLeftA_offset_bon" -p "tongueCenterARoot_bon";
rename -uid "17418E97-451E-A394-9C4D-ED96E10B8E0B";
setAttr ".t" -type "double3" 1.2838911711593375 -8.5265128291212022e-014 1.0658141036401503e-014 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.2839139401336415 183.32829284667969 5.0897865295410156 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueLeftA_bon" -p "tongueLeftA_offset_bon";
rename -uid "1B62E5F2-4988-670A-1F39-91B61FA07DA4";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.2839139401336415 183.32829284667969 5.0897865295410156 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueRightA_offset_bon" -p "tongueCenterARoot_bon";
rename -uid "ED15A94A-4E63-1EAA-9390-10A1D517C5D9";
setAttr ".t" -type "double3" -1.2839367689743042 8.5265128291212022e-014 -1.0658141036401503e-014 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
-1.2839140000000002 183.32829284667969 5.0897865295410156 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueRightA_bon" -p "tongueRightA_offset_bon";
rename -uid "E2481F8D-46C7-0B7C-9B00-81970BCBA904";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
-1.2839140000000002 183.32829284667969 5.0897865295410156 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueCenterBRoot_offset_bon" -p "tongueRoot_bon";
rename -uid "92EE2529-4521-D897-FD8C-1EA4D656D96B";
setAttr ".t" -type "double3" -4.3442829086685897e-015 0.1213836669921875 1.3956201731847333 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974303426535e-005 183.44967651367188 6.035724401473999 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueCenterBRoot_bon" -p "tongueCenterBRoot_offset_bon";
rename -uid "6134A278-4D3A-3FEC-9903-AFBF0793A6AA";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 0 0 -8.8817841970012523e-016 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974303426535e-005 183.44967651367188 6.035724401473999 1;
setAttr ".radi" 0.98751911037463325;
setAttr ".liw" yes;
createNode joint -n "tongueCenterB_offset_bon" -p "tongueCenterBRoot_bon";
rename -uid "30A82E46-4021-D3D1-382B-529838536D12";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974303426535e-005 183.44967651367188 6.035724401473999 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueCenterB_bon" -p "tongueCenterB_offset_bon";
rename -uid "8DAA18D1-43A1-8EC7-A80D-8DA8E4FE07F3";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974303426535e-005 183.44967651367188 6.035724401473999 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueLeftB_offset_bon" -p "tongueCenterBRoot_bon";
rename -uid "5607CDDE-4C0D-A3AB-6B90-FDAE4964E7FD";
setAttr ".t" -type "double3" 1.2170165836926314 -2.8421709430404007e-014 1.2434497875801753e-014 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.2170393526669347 183.44967651367188 6.035724401473999 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueLeftB_bon" -p "tongueLeftB_offset_bon";
rename -uid "210A1EE2-4630-51B7-1B93-DF939A30C9FB";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -2.2204460492503131e-016 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.2170393526669347 183.44967651367188 6.035724401473999 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueRightB_offset_bon" -p "tongueCenterBRoot_bon";
rename -uid "885D9B3A-46B1-9B88-BCB3-8DB490D0C1E6";
setAttr ".t" -type "double3" -1.217061768974304 2.8421709430404007e-014 -1.1546319456101628e-014 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
-1.2170390000000006 183.44967651367188 6.035724401473999 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueRightB_bon" -p "tongueRightB_offset_bon";
rename -uid "219D0AB5-4430-2A95-53EE-22AAAF054D49";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -2.2204460492503131e-016 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
-1.2170390000000006 183.44967651367188 6.035724401473999 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueCenterCRoot_offset_bon" -p "tongueRoot_bon";
rename -uid "174AB1C5-4635-58E3-1379-AB8B0766E75B";
setAttr ".t" -type "double3" -1.404394179074786e-014 0.13958740234375 2.6102433859990626 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974302907039e-005 183.46788024902344 7.2503476142883301 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueCenterCRoot_bon" -p "tongueCenterCRoot_offset_bon";
rename -uid "E1DDA430-48FF-72FC-26E3-1D8D8C95BA62";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974302907039e-005 183.46788024902344 7.2503476142883301 1;
setAttr ".radi" 0.98751911037463325;
setAttr ".liw" yes;
createNode joint -n "tongueCenterC_offset_bon" -p "tongueCenterCRoot_bon";
rename -uid "F05E3333-474E-0D79-22CA-6F9EB35501A0";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974302907039e-005 183.46788024902344 7.2503476142883301 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueCenterC_bon" -p "tongueCenterC_offset_bon";
rename -uid "21691E33-4C42-08EA-65DB-DDAC5FB70846";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974302907039e-005 183.46788024902344 7.2503476142883301 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueLeftC_offset_bon" -p "tongueCenterCRoot_bon";
rename -uid "8EDA1593-4999-9004-0DE4-508AA5C6B403";
setAttr ".t" -type "double3" 1.0687407910939069 -8.5265128291212022e-014 1.0658141036401503e-014 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.0687635600682097 183.46788024902344 7.2503476142883301 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueLeftC_bon" -p "tongueLeftC_offset_bon";
rename -uid "3ABECAF9-40ED-7DD1-5F07-9B90028C43B3";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
1.0687635600682097 183.46788024902344 7.2503476142883301 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueRightC_offset_bon" -p "tongueCenterCRoot_bon";
rename -uid "6F31D996-4F9D-5E01-9C76-E9A360C9CEA7";
setAttr ".t" -type "double3" -1.0687867689743042 8.5265128291212022e-014 -1.0658141036401503e-014 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
-1.0687640000000014 183.46788024902344 7.2503476142883301 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueRightC_bon" -p "tongueRightC_offset_bon";
rename -uid "3F13C7C8-488E-478E-5D0B-CB91B8CD18D9";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
-1.0687640000000014 183.46788024902344 7.2503476142883301 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueCenterDRoot_offset_bon" -p "tongueRoot_bon";
rename -uid "5C51CB48-4DB2-8D19-0A73-549B12357AC8";
setAttr ".t" -type "double3" -3.4933525934173829e-014 -0.0095062255859375 3.7664666831182059 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974302171025e-005 183.31878662109375 8.4065709114074707 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueCenterDRoot_bon" -p "tongueCenterDRoot_offset_bon";
rename -uid "BE072F38-4FAE-9B5D-DED8-B0AAEAAA9012";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 0 0 -3.5527136788005009e-015 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974302171025e-005 183.31878662109375 8.4065709114074707 1;
setAttr ".radi" 0.98751911037463325;
setAttr ".liw" yes;
createNode joint -n "tongueCenterD_offset_bon" -p "tongueCenterDRoot_bon";
rename -uid "DF8DE99B-4AC2-1780-7CC5-7D83C972F537";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974302171025e-005 183.31878662109375 8.4065709114074707 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueCenterD_bon" -p "tongueCenterD_offset_bon";
rename -uid "1B736002-4531-A1B9-E45C-0C8A3B2CF676";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
2.2768974302171025e-005 183.31878662109375 8.4065709114074707 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueLeftD_offset_bon" -p "tongueCenterDRoot_bon";
rename -uid "CAB210BE-40A3-7570-5613-E5B9680B2C7F";
setAttr ".t" -type "double3" 0.82193732858856949 0.027015686035070985 -0.11806011199950639 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
0.8219600975628687 183.34580230712891 8.288510799407959 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueLeftD_bon" -p "tongueLeftD_offset_bon";
rename -uid "032222DF-44D9-BFC9-4759-E5B015BE2081";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" -1.1102230246251565e-016 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
0.8219600975628687 183.34580230712891 8.288510799407959 1;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueRightD_offset_bon" -p "tongueCenterDRoot_bon";
rename -uid "B3A9D2E5-471F-7F82-B26F-8FA70EFF8269";
setAttr ".t" -type "double3" -0.82198276897430089 0.027015686035241515 -0.11806011199952238 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
-0.82196000000000169 183.34580230712891 8.288510799407959 1;
setAttr ".ds" 2;
setAttr ".radi" 0.98751911037463325;
createNode joint -n "tongueRightD_bon" -p "tongueRightD_offset_bon";
rename -uid "8E3A0148-4E4B-6C6D-D943-29BA367D979A";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 1.1102230246251565e-016 0 0 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1 4.4408920985006262e-016 3.3306690738754696e-016 0
-5.5511151231257827e-016 1 -7.3955709864469857e-032 0 -4.4408920985006262e-016 -1.110223024625157e-016 1 0
-0.82196000000000169 183.34580230712891 8.288510799407959 1;
setAttr ".radi" 0.98751911037463325;
'''
eye_bone = '''
createNode transform -n "eye_bonGp" -p "bonGp";
rename -uid "CA84D2A8-4B7E-8DCC-84BF-7984057B35BC";
setAttr ".r" -type "double3" 1.2722218725854067e-014 1.2722218725854061e-014 2.8624992133171648e-014 ;
createNode joint -n "eyeLeft_bon" -p "eye_bonGp";
rename -uid "E6AD0197-43CF-2CE9-DF1A-029CB9F3CE3A";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 2.7267374396324167 189.59231567382804 6.8660058975219727 ;
setAttr ".r" -type "double3" -7.2010910588921589e-016 2.110358161571733e-017 -1.9843651157604337e-016 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr ".jo" -type "double3" 0 -89.999999999999915 0 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1.6653345369377348e-015 0 1 0 -0 1 0 0 -1 -0 1.6653345369377348e-015 0
2.7267374396324167 189.59231567382804 6.8660058975219727 1;
createNode joint -n "eyeLeftEnd_bon" -p "eyeLeft_bon";
rename -uid "ADEF3125-46A6-4222-0D61-97BDD9386E37";
addAttr -ci true -sn "liw" -ln "lockInfluenceWeights" -min 0 -max 1 -at "bool";
setAttr ".t" -type "double3" 1.8066778182983407 0 7.1054273576010019e-015 ;
setAttr ".mnrl" -type "double3" -360 -360 -360 ;
setAttr ".mxrl" -type "double3" 360 360 360 ;
setAttr -k on ".jox";
setAttr -k on ".joy";
setAttr -k on ".joz";
setAttr -k on ".ssc";
setAttr ".bps" -type "matrix" 1.6653345369377348e-015 0 1 0 0 1 0 0 -1 0 1.6653345369377348e-015 0
2.7267374396324127 189.59231567382804 8.6726837158203125 1;
'''
#Create Bone
def create_bone_root():
mm.eval(bone_root)
def create_eyeBrow_bone():
mm.eval(eyebrow_bone)
def create_eye_bone():
mm.eval(eye_fc_bone)
def create_nose_bone():
mm.eval(nose_bone)
def create_cheek_bone():
mm.eval(cheek_bone)
def create_lip_bone():
mm.eval(lip_bone)
def create_teeth_U_bone():
mm.eval(teeth_U_bon)
def create_jaw_bone():
mm.eval(jaw_bone)
def create_teeth_L_bone():
mm.eval(teeth_L_bone)
def create_tongue_bone():
mm.eval(tongue_bone)
def create_eyeball_bone():
mm.eval(eye_bone)
mm.eval(eyelid_bone)
def create_bone():
create_bone_root()
create_eyeBrow_bone()
create_eye_bone()
create_nose_bone()
create_cheek_bone()
create_lip_bone()
create_teeth_U_bone()
create_jaw_bone()
create_teeth_L_bone()
create_tongue_bone()
create_eyeball_bone()
#Create Ctl
def create_ctrl_root():
mm.eval(ctl_root)
def create_jaw_ctl():
mm.eval(jaw_ctl)
def create_tongue_ctl():
mm.eval(toungue_ctl)
def create_teeth_U_ctl():
mm.eval(teeth_upper_ctl)
def create_teeth_L_ctl():
mm.eval(teeth_lower_ctl)
def create_facial_panel():
mm.eval(facial_bs_Panel)
def create_brow_bs_ctl():
mm.eval(brow_bs_ctl)
def create_eye_bs_ctl():
mm.eval(eye_bs_ctl)
def create_mouth_bs_ctl():
mm.eval(mouth_bs_ctl)
def create_eye_ctl():
mm.eval(eye_ctl)
def create_ctl():
create_ctrl_root()
create_jaw_ctl()
create_tongue_ctl()
create_teeth_U_ctl()
create_teeth_L_ctl()
create_eye_ctl()
def create_bs_ctl():
create_facial_panel()
create_brow_bs_ctl()
create_eye_bs_ctl()
create_mouth_bs_ctl()
```
#### File: Red9/core/Red9_PoseSaver.py
```python
from ..startup import setup as r9Setup
import Red9_CoreUtils as r9Core
import Red9_General as r9General
import Red9_AnimationUtils as r9Anim
import Red9_Meta as r9Meta
import maya.cmds as cmds
import os
from ..packages import configobj as configobj
import time
import getpass
import json
import logging
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
def getFolderPoseHandler(posePath):
'''
Check if the given directory contains a poseHandler.py file
if so return the filename. PoseHandlers are a way of extending or
over-loading the standard behaviour of the poseSaver, see Vimeo for
a more detailed explanation.
TODO: have this also accept a pointer to a handler file rather than a direct
poseHnadler.py file in each folder. This means we could point a folder to a generic handler
inside our presets folder rather than having the code logic in each folder.
'''
poseHandler=None
poseHandlers=[py for py in os.listdir(posePath) if py.endswith('poseHandler.py')]
if poseHandlers:
poseHandler=poseHandlers[0]
return poseHandler
class DataMap(object):
'''
New base class for handling data storage and reloading with intelligence
'''
def __init__(self, filterSettings=None, *args, **kws):
'''
The idea of the DataMap is to make the node handling part of any system generic.
This allows us to use this baseClass to build up things like poseSavers and all
we have to worry about is the data save / extraction part, all the node handling
and file handling is already done by this class ;)
Note that we're not passing any data in terms of nodes here, We'll deal with
those in the Save and Load calls.
'''
self.poseDict={}
self.infoDict={}
self.skeletonDict={}
self.file_ext = '' # extension the file will be saved as
self.filepath='' # path to load / save
self.__filepath = ''
self.filename='' # short name of the pose
self.dataformat='config'
self._dataformat_resolved=None
self.mayaUpAxis = r9Setup.mayaUpAxis()
self.thumbnailRes=[128,128]
self.__metaPose=False
self.metaRig=None # filled by the code as we process
self.matchMethod='base' # method used to match nodes internally in the poseDict
self.useFilter=True
self.prioritySnapOnly=False # mainly used by any load relative calls, determines whether to use the internal filters priority list
self.skipAttrs=[] # attrs to completely ignore in any pose handling
self.nodesToStore=[] # built by the buildDataMap func
self.nodesToLoad=[] # build in the processPoseFile func
# make sure we have a settings object
if filterSettings:
if issubclass(type(filterSettings), r9Core.FilterNode_Settings):
self.settings=filterSettings
self.__metaPose=self.settings.metaRig
else:
raise StandardError('filterSettings param requires an r9Core.FilterNode_Settings object')
self.settings.printSettings()
else:
self.settings=r9Core.FilterNode_Settings()
self.__metaPose=self.settings.metaRig
@property
def metaPose(self):
'''
this flag adds in the additional MetaData block for all the matching code and info extraction.
True if self.metaRig is filled, self.settings.metaRig=True or self.metaPose=True
'''
if self.metaRig:
return True
if self.settings.metaRig:
return True
return self.__metaPose
@metaPose.setter
def metaPose(self, val):
self.__metaPose=val
self.settings.metaRig=val
@property
def filepath(self):
return self.__filepath
@filepath.setter
def filepath(self, path):
if path and self.file_ext:
self.__filepath='%s%s' % (os.path.splitext(path)[0], self.file_ext)
else:
self.__filepath=path
self.filename=os.path.splitext(os.path.basename(self.filepath))[0]
def _pre_load(self,*args, **kws):
'''
called directly before the loadData call so you have access
to manage the undoQueue etc if subclassing
'''
pass
def _post_load(self,*args, **kws):
'''
called directly after the loadData call so you have access
to manage the undoQueue etc if subclassing
'''
pass
def setMetaRig(self, node):
'''
Master call to bind and set the mRig for the DataMap
:param node: node to set the mRig from or instance of an mRig object
'''
log.debug('setting internal metaRig from given node : %s' % node)
if r9Meta.isMetaNodeInherited(node,'MetaRig'):
self.metaRig=r9Meta.MetaClass(node)
else:
self.metaRig=r9Meta.getConnectedMetaSystemRoot(node)
log.debug('setting internal metaRig : %s' % self.metaRig)
return self.metaRig
def hasFolderOverload(self):
'''
modified so you can now prefix the poseHandler.py file
makes it easier to keep track of in a production environment
'''
self.poseHandler=None
if self.filepath:
self.poseHandler = getFolderPoseHandler(os.path.dirname(self.filepath))
return self.poseHandler
def getNodesFromFolderConfig(self, rootNode, mode):
'''
if the poseFolder has a poseHandler.py file use that to
return the nodes to use for the pose instead
:param rootNode: rootNode passed to the search poseHandlers
poseGetNodesLoad or poseGetNodesSave functions
:param mode: 'save' or 'load'
'''
import imp
log.debug('getNodesFromFolderConfig - useFilter=True : custom poseHandler running')
posedir=os.path.dirname(self.filepath)
print 'imp : ', self.poseHandler.split('.py')[0], ' : ', os.path.join(posedir, self.poseHandler)
tempPoseFuncs = imp.load_source(self.poseHandler.split('.py')[0], os.path.join(posedir, self.poseHandler))
if mode=='load':
nodes=tempPoseFuncs.poseGetNodesLoad(self,rootNode)
if mode=='save':
nodes=tempPoseFuncs.poseGetNodesSave(self,rootNode)
del(tempPoseFuncs)
return nodes
def getNodes(self, nodes):
'''
get the nodes to process
This is designed to allow for specific hooks to be used from user
code stored in the pose folder itself.
:param nodes: nodes passed to the filter calls
.. note::
Update : Aug 2016
Because this calls FilterNode to get the data when useFilter=True it
allows for any mRig with internal filterSettings bound to it to dynamically
modify the settings on the fly to suit. This is a big update in handling
for ProPack to integrate without having to massively restructure
'''
if not type(nodes)==list:
nodes=[nodes]
if self.useFilter:
log.debug('getNodes - useFilter=True : filteActive=True - no custom poseHandler')
if self.settings.filterIsActive():
return r9Core.FilterNode(nodes, self.settings).processFilter() # main node filter
else:
log.debug('getNodes - useFilter=True : filteActive=False - no custom poseHandler')
return nodes
else:
log.debug('getNodes - useFilter=False : no custom poseHandler')
return nodes
def getSkippedAttrs(self, rootNode=None):
'''
the returned list of attrs from this function will be
COMPLETELY ignored by the pose system. They will not be saved
or loaded.
.. note::
Currently only supported under MetaRig
'''
if self.metaRig and self.metaRig.hasAttr('poseSkippedAttrs'):
return self.metaRig.poseSkippedAttrs
return []
def getMaintainedAttrs(self, nodesToLoad, parentSpaceAttrs):
'''
Attrs returned here will be cached prior to pose load, then restored in-tact afterwards
:param nodesToLoad: nodes that the pose is about to load the data too,
this is the already processed nodeList
:param parentSpaceAttrs: attributes we want to be ignored by the load system
'''
parentSwitches=[]
if not type(parentSpaceAttrs)==list:
parentSpaceAttrs=[parentSpaceAttrs]
for child in nodesToLoad:
for attr in parentSpaceAttrs:
if cmds.attributeQuery(attr, exists=True, node=child):
parentSwitches.append((child, attr, cmds.getAttr('%s.%s' % (child,attr))))
log.debug('parentAttrCache : %s > %s' % (child,attr))
return parentSwitches
# --------------------------------------------------------------------------------
# Data Collection - Build ---
# --------------------------------------------------------------------------------
def _collectNodeData_attrs(self, node, key):
'''
Capture and build attribute data from this node and fill the
data to the datamap[key]
'''
channels=r9Anim.getSettableChannels(node,incStatics=True)
if channels:
self.poseDict[key]['attrs']={}
for attr in channels:
if attr in self.skipAttrs:
log.debug('Skipping attr as requested : %s' % attr)
continue
try:
if cmds.getAttr('%s.%s' % (node,attr),type=True)=='TdataCompound': # blendShape weights support
attrs=cmds.aliasAttr(node, q=True)[::2] # extract the target channels from the multi
for attr in attrs:
self.poseDict[key]['attrs'][attr]=cmds.getAttr('%s.%s' % (node,attr))
else:
self.poseDict[key]['attrs'][attr]=cmds.getAttr('%s.%s' % (node,attr))
except:
log.debug('%s : attr is invalid in this instance' % attr)
def _collectNodeData(self, node, key):
'''
To Be Overloaded : what data to push into the main dataMap
for each node found collected. This is the lowest level collect call
for each node in the array.
'''
self._collectNodeData_attrs(node, key)
def _buildBlock_info(self):
'''
Generic Info block for the data file, this could do with expanding
'''
self.infoDict['author']=getpass.getuser()
self.infoDict['date']=time.ctime()
self.infoDict['timeUnit']=cmds.currentUnit(q=True, fullName=True, time=True)
self.infoDict['sceneUnits']=cmds.currentUnit(q=True, fullName=True, linear=True)
self.infoDict['upAxis'] = cmds.upAxis(q=True, axis=True)
self.infoDict['metaPose']=self.metaPose
if self.metaRig:
self.infoDict['metaRigNode']=self.metaRig.mNode
self.infoDict['metaRigNodeID']=self.metaRig.mNodeID
if self.metaRig.hasAttr('version'):
self.infoDict['version'] = self.metaRig.version
if self.metaRig.hasAttr('rigType'):
self.infoDict['rigType'] = self.metaRig.rigType
self.infoDict.update(self.metaRig.gatherInfo())
if self.rootJnt:
self.infoDict['skeletonRootJnt']=self.rootJnt
def _buildBlock_poseDict(self, nodes):
'''
Build the internal poseDict up from the given nodes. This is the
core of the Pose System and the main dataMap used to store and retrieve data
'''
getMirrorID=r9Anim.MirrorHierarchy().getMirrorCompiledID
if self.metaPose:
getMetaDict=self.metaRig.getNodeConnectionMetaDataMap # optimisation
for i,node in enumerate(nodes):
key=r9Core.nodeNameStrip(node)
self.poseDict[key]={}
self.poseDict[key]['ID']=i # selection order index
self.poseDict[key]['longName']=node # longNode name
mirrorID=getMirrorID(node)
if mirrorID:
self.poseDict[key]['mirrorID']=mirrorID # add the mirrorIndex
if self.metaPose:
self.poseDict[key]['metaData']=getMetaDict(node) # metaSystem the node is wired too
# the above blocks are the generic info used to map the data on load
# this call is the specific collection of data for this node required by this map type
self._collectNodeData(node, key)
def buildBlocks_fill(self, nodes=None):
'''
To Be Overloaded : What capture routines to run in order to build the DataMap up.
Note that the self._buildBlock_poseDict(nodes) calls the self._collectNodeData per node
as a way of gathering what info to be stored against each node.
'''
if not nodes:
nodes=self.nodesToStore
self.poseDict={}
self._buildBlock_info()
self._buildBlock_poseDict(nodes)
def buildDataMap(self, nodes):
'''
build the internal dataMap dict, useful as a separate func so it
can be used in the PoseCompare class easily. This is the main internal call
for managing the actual pose data for save
.. note::
this replaces the original pose call self.buildInternalPoseData()
'''
self.nodesToStore=[]
self.metaRig=None
self.rootJnt=None
if not type(nodes)==list:
nodes=[nodes] # cast to list for consistency
rootNode=nodes[0]
if self.settings.filterIsActive() and self.useFilter:
if self.metaPose:
if self.setMetaRig(rootNode):
self.rootJnt=self.metaRig.getSkeletonRoots()
if self.rootJnt:
self.rootJnt=self.rootJnt[0]
else:
if cmds.attributeQuery('exportSkeletonRoot',node=rootNode, exists=True):
connectedSkel=cmds.listConnections('%s.%s' % (rootNode,'exportSkeletonRoot'),destination=True,source=True)
if connectedSkel and cmds.nodeType(connectedSkel)=='joint':
self.rootJnt=connectedSkel[0]
elif cmds.nodeType(rootNode)=='joint':
self.rootJnt=rootNode
# elif cmds.attributeQuery('animSkeletonRoot',node=rootNode, exists=True):
# connectedSkel=cmds.listConnections('%s.%s' % (rootNode,'animSkeletonRoot'),destination=True,source=True)
# if connectedSkel and cmds.nodeType(connectedSkel)=='joint':
# self.rootJnt=connectedSkel[0]
# elif cmds.nodeType(rootNode)=='joint':
# self.rootJnt=rootNode
elif self.settings.nodeTypes==['joint']:
self.rootJnt=rootNode
else:
if self.metaPose:
self.setMetaRig(rootNode)
#fill the skip list, these attrs will be totally ignored by the code
self.skipAttrs=self.getSkippedAttrs(rootNode)
if self.hasFolderOverload(): # and self.useFilter:
self.nodesToStore=self.getNodesFromFolderConfig(nodes,mode='save')
else:
self.nodesToStore=self.getNodes(nodes)
if not self.nodesToStore:
raise IOError('No Matching Nodes found to store the pose data from')
return self.nodesToStore
# removed from this func so we can just process the node data
#self.buildBlocks_fill(nodesToStore)
# --------------------------------------------------------------------------------
# Data Mapping - Apply ---
# --------------------------------------------------------------------------------
@r9General.Timer
def _applyData_attrs(self, *args, **kws):
'''
Load Example for attrs :
use self.matchedPairs for the process list of pre-matched
tuples of (poseDict[key], node in scene)
'''
for key, dest in self.matchedPairs:
log.debug('Applying Key Block : %s' % key)
try:
if not 'attrs' in self.poseDict[key]:
continue
for attr, val in self.poseDict[key]['attrs'].items():
try:
val = eval(val)
except:
pass
log.debug('node : %s : attr : %s : val %s' % (dest, attr, val))
try:
cmds.setAttr('%s.%s' % (dest, attr), val)
except StandardError, err:
log.debug(err)
except:
log.debug('Pose Object Key : %s : has no Attr block data' % key)
def _applyData(self, *args, **kws):
'''
To Be Overloaded:
Main apply block run after we've read the data and matched all nodes
'''
self._applyData_attrs()
# --------------------------------------------------------------------------------
# Process the data ---
# --------------------------------------------------------------------------------
def _writePose(self, filepath=None, force=False):
'''
Write the Pose ConfigObj to file
'''
if not filepath:
filepath=self.filepath
if not force:
if os.path.exists(filepath) and not os.access(filepath,os.W_OK):
raise IOError('File is Read-Only - write aborted : %s' % filepath)
# =========================
# write to ConfigObject
# =========================
if self.dataformat=='config':
ConfigObj = configobj.ConfigObj(indent_type='\t')
ConfigObj['info']=self.infoDict
ConfigObj['filterNode_settings']=self.settings.__dict__
ConfigObj['poseData']=self.poseDict
if self.skeletonDict:
ConfigObj['skeletonDict']=self.skeletonDict
ConfigObj.filename = filepath
ConfigObj.write()
self._dataformat_resolved='config'
# =========================
# write to JSON format
# =========================
elif self.dataformat=='json':
data={}
data['info']=self.infoDict
data['filterNode_settings']=self.settings.__dict__
data['poseData']=self.poseDict
if self.skeletonDict:
data['skeletonDict']=self.skeletonDict
with open(filepath, 'w') as f:
f.write(json.dumps(data, sort_keys=True, indent=4))
f.close()
self._dataformat_resolved='json'
@r9General.Timer
def _readPose(self, filename=None):
'''
Read the pose file and build up the internal poseDict
TODO: do we allow the data to be filled from the pose filter thats stored???????
'''
if not filename:
filename=self.filepath
if filename:
if os.path.exists(filename):
# =========================
# write to JSON format
# =========================
if self.dataformat=='json':
try:
with open(filename, 'r') as f:
data=json.load(f)
self.poseDict=data['poseData']
if 'info' in data.keys():
self.infoDict=data['info']
if 'skeletonDict' in data.keys():
self.skeletonDict=data['skeletonDict']
self._dataformat_resolved='json'
except IOError, err:
self._dataformat_resolved='config'
log.info('JSON : DataMap format failed to load, reverting to legacy ConfigObj')
# =========================
# write to ConfigObject
# =========================
if self._dataformat_resolved=='config' or self.dataformat=='config':
#for key, val in configobj.ConfigObj(filename)['filterNode_settings'].items():
# self.settings.__dict__[key]=decodeString(val)
self.poseDict=configobj.ConfigObj(filename)['poseData']
if 'info' in configobj.ConfigObj(filename):
self.infoDict=configobj.ConfigObj(filename)['info']
if 'skeletonDict' in configobj.ConfigObj(filename):
self.skeletonDict=configobj.ConfigObj(filename)['skeletonDict']
self._dataformat_resolved='config'
else:
raise StandardError('Given filepath doesnt not exist : %s' % filename)
else:
raise StandardError('No FilePath given to read the pose from')
def processPoseFile(self, nodes):
'''
pre-loader function that processes all the nodes and data prior to
actually calling the load... why? this is for the poseMixer for speed.
This reads the file, matches the nodes to the internal file data and fills
up the self.matchedPairs data [(src,dest),(src,dest)]
.. note::
this replaced the original call self._poseLoad_buildcache()
'''
self.nodesToLoad=[]
if not type(nodes)==list:
nodes=[nodes] # cast to list for consistency
if self.filepath and not os.path.exists(self.filepath):
raise StandardError('Given Path does not Exist')
if self.metaPose:
# set the mRig in a consistent manner
self.setMetaRig(nodes[0])
if 'metaPose' in self.infoDict and self.metaRig:
try:
if eval(self.infoDict['metaPose']):
self.matchMethod = 'metaData'
except:
self.matchMethod = 'metaData'
else:
log.debug('Warning, trying to load a NON metaPose to a MRig - switching to NameMatching')
if self.filepath and self.hasFolderOverload(): # and useFilter:
self.nodesToLoad = self.getNodesFromFolderConfig(nodes, mode='load')
else:
self.nodesToLoad=self.getNodes(nodes)
if not self.nodesToLoad:
raise StandardError('Nothing selected or returned by the filter to load the pose onto')
if self.filepath:
self._readPose(self.filepath)
log.info('Pose Read Successfully from : %s' % self.filepath)
# fill the skip list, these attrs will be totally ignored by the code
self.skipAttrs=self.getSkippedAttrs(nodes[0])
# build the master list of matched nodes that we're going to apply data to
#Note: this is built up from matching keys in the poseDict to the given nodes
self.matchedPairs = self._matchNodesToPoseData(self.nodesToLoad)
return self.nodesToLoad
@r9General.Timer
def _matchNodesToPoseData(self, nodes):
'''
Main filter to extract matching data pairs prior to processing
return : tuple such that : (poseDict[key], destinationNode)
NOTE: I've changed this so that matchMethod is now an internal PoseData attr
:param nodes: nodes to try and match from the poseDict
'''
matchedPairs=[]
log.info('using matchMethod : %s' % self.matchMethod)
if self.matchMethod=='stripPrefix' or self.matchMethod=='base':
log.info('matchMethodStandard : %s' % self.matchMethod)
matchedPairs=r9Core.matchNodeLists([key for key in self.poseDict.keys()], nodes, matchMethod=self.matchMethod)
if self.matchMethod=='index':
for i, node in enumerate(nodes):
for key in self.poseDict.keys():
if int(self.poseDict[key]['ID'])==i:
matchedPairs.append((key,node))
log.debug('poseKey : %s %s >> matchedSource : %s %i' % (key, self.poseDict[key]['ID'], node, i))
break
if self.matchMethod=='mirrorIndex':
getMirrorID=r9Anim.MirrorHierarchy().getMirrorCompiledID
for node in nodes:
mirrorID=getMirrorID(node)
if not mirrorID:
continue
for key in self.poseDict.keys():
if 'mirrorID' in self.poseDict[key] and self.poseDict[key]['mirrorID']:
poseID=self.poseDict[key]['mirrorID']
if poseID==mirrorID:
matchedPairs.append((key,node))
log.debug('poseKey : %s %s >> matched MirrorIndex : %s' % (key, node, self.poseDict[key]['mirrorID']))
break
# unlike 'mirrorIndex' this matches JUST the ID's, the above matches SIDE_ID
if self.matchMethod=='mirrorIndex_ID':
getMirrorID=r9Anim.MirrorHierarchy().getMirrorIndex
for node in nodes:
mirrorID=getMirrorID(node)
if not mirrorID:
continue
for key in self.poseDict.keys():
if 'mirrorID' in self.poseDict[key] and self.poseDict[key]['mirrorID']:
poseID=self.poseDict[key]['mirrorID'].split('_')[-1]
if not poseID=='None':
if int(poseID)==mirrorID:
matchedPairs.append((key,node))
log.debug('poseKey : %s %s >> matched MirrorIndex : %s' % (key, node, self.poseDict[key]['mirrorID']))
break
else:
log.debug('poseKey SKIPPED : %s:%s : as incorrect MirrorIDs' % (key,self.poseDict[key]['mirrorID']))
if self.matchMethod=='metaData':
getMetaDict=self.metaRig.getNodeConnectionMetaDataMap # optimisation
poseKeys=dict(self.poseDict) # optimisation
for node in nodes:
try:
metaDict=getMetaDict(node)
for key in poseKeys:
if poseKeys[key]['metaData']==metaDict:
matchedPairs.append((key,node))
log.debug('poseKey : %s %s >> matched MetaData : %s' % (key, node, poseKeys[key]['metaData']))
poseKeys.pop(key)
break
except:
log.info('FAILURE to load MetaData pose blocks - Reverting to Name')
matchedPairs=r9Core.matchNodeLists([key for key in self.poseDict.keys()], nodes)
return matchedPairs
def matchInternalPoseObjects(self, nodes=None, fromFilter=True):
'''
This is a throw-away and only used in the UI to select for debugging!
from a given poseFile return or select the internal stored objects
'''
InternalNodes=[]
if not fromFilter:
#no filter, we just pass in the longName thats stored
for key in self.poseDict.keys():
if cmds.objExists(self.poseDict[key]['longName']):
InternalNodes.append(self.poseDict[key]['longName'])
elif cmds.objExists(key):
InternalNodes.append(key)
elif cmds.objExists(r9Core.nodeNameStrip(key)):
InternalNodes.append(r9Core.nodeNameStrip(key))
else:
#use the internal Poses filter and then Match against scene nodes
if self.settings.filterIsActive():
filterData=r9Core.FilterNode(nodes,self.settings).processFilter()
matchedPairs=self._matchNodesToPoseData(filterData)
if matchedPairs:
InternalNodes=[node for _,node in matchedPairs]
if not InternalNodes:
raise StandardError('No Matching Nodes found!!')
return InternalNodes
# --------------------------------------------------------------------------------
#Main Calls ----
# --------------------------------------------------------------------------------
#@r9General.Timer
def saveData(self, nodes, filepath=None, useFilter=True, storeThumbnail=True, force=False):
'''
Generic entry point for the Data Save.
:param nodes: nodes to store the data against OR the rootNode if the
filter is active.
:param filepath: posefile to save - if not given the pose is cached on this
class instance.
:param useFilter: use the filterSettings or not.
:param storeThumbnail: save a thumbnail or not
:param force: force write the data even if the file is read-only
'''
#push args to object - means that any poseHandler.py file has access to them
if filepath:
self.filepath=filepath
self.useFilter=useFilter
if self.filepath:
log.debug('PosePath given : %s' % self.filepath)
self.buildDataMap(nodes) # generate the main node mapping
self.buildBlocks_fill(self.nodesToStore) # fill in all the data to collect
if self.filepath:
self._writePose(self.filepath, force=force)
if storeThumbnail:
sel=cmds.ls(sl=True,l=True)
cmds.select(cl=True)
r9General.thumbNailScreen(filepath,self.thumbnailRes[0],self.thumbnailRes[1])
if sel:
cmds.select(sel)
log.info('Data Saved Successfully to : %s' % self.filepath)
#@r9General.Timer
def loadData(self, nodes, filepath=None, useFilter=True, *args, **kws):
'''
Generic entry point for the Data Load.
:param nodes: if given load the data to only these. If given and filter=True
this is the rootNode for the filter.
:param filepath: file to load - if not given the pose is loaded from a
cached instance on this class.
:param useFilter: If the pose has an active Filter_Settings block and this
is True then use the filter on the destination hierarchy.
'''
# push args to object - means that any poseHandler.py file has access to them
if filepath:
self.filepath = filepath
if not type(nodes)==list:
nodes=[nodes] # cast to list for consistency
self.useFilter = useFilter # used in the getNodes call
try:
self._pre_load()
# main process to match and build up the data
self.processPoseFile(nodes)
if not self.matchedPairs:
raise StandardError('No Matching Nodes found in the PoseFile!')
else:
if self.prioritySnapOnly:
#we've already filtered the hierarchy, may as well just filter the results for speed
self.nodesToLoad=r9Core.prioritizeNodeList(self.nodesToLoad, self.settings.filterPriority, regex=True, prioritysOnly=True)
self.nodesToLoad.reverse()
# nodes now matched, apply the data in the dataMap
self._applyData()
except StandardError,err:
log.info('Pose Load Failed! : , %s' % err)
finally:
self._post_load()
class PoseData(DataMap):
'''
The PoseData is stored per node inside an internal dict as follows:
>>> node = '|group|Rig|Body|TestCtr'
>>> poseDict['TestCtr']
>>> poseDict['TestCtr']['ID'] = 0 index in the Hierarchy used to build the data up
>>> poseDict['TestCtr']['longName'] = '|group|Rig|Body|TestCtr'
>>> poseDict['TestCtr']['attrs']['translateX'] = 0.5
>>> poseDict['TestCtr']['attrs']['translateY'] = 1.0
>>> poseDict['TestCtr']['attrs']['translateZ'] = 22
>>>
>>> # if we're storing as MetaData we also include:
>>> poseDict['TestCtr']['metaData']['metaAttr'] = CTRL_L_Thing = the attr that wires this node to the MetaSubsystem
>>> poseDict['TestCtr']['metaData']['metaNodeID'] = L_Arm_System = the metaNode this node is wired to via the above attr
Matching of nodes against this dict is via either the nodeName, nodeIndex (ID) or
the metaData block.
New functionality allows you to use the main calls to cache a pose and reload it
from this class instance, wraps things up nicely for you:
>>> pose=r9Pose.PoseData()
>>> pose.metaPose=True
>>>
>>> # cache the pose (just don't pass in a filePath)
>>> pose.poseSave(cmds.ls(sl=True))
>>> # reload the cache you just stored
>>> pose.poseLoad(cmds.ls(sl=True))
We can also load in a percentage of a pose by running the PoseData._applyData(percent) as follows:
>>> pose=r9Pose.PoseData()
>>> pose.metaPose=True
>>> pose.filepath='C:/mypose.pose'
>>>
>>> # processPoseFile does just that, processes and build up the list of data but doesn't apply it
>>> pose.processPoseFile(nodes='myRootNode')
>>>
>>> # now we can dial in a percentage of the pose, we bind this to a floatSlider in the UI
>>> pose._applyData(percent=20)
.. note::
If the root node of the hierarchy passed into the poseSave() has a message attr
'exportSkeletonRoot' or 'animSkeletonRoot' and that message is connected to a
skeleton then the pose will also include an internal 'skeleton' pose, storing all
child joints into a separate block in the poseFile that can be used by the
PoseCompare class/function.
For metaData based rigs this calls a function on the metaRig class getSkeletonRoots()
which wraps the 'exportSkeletonRoot' attr, allowing you to overload this behaviour
in your own MetaRig subclasses.
'''
def __init__(self, filterSettings=None, *args, **kws):
'''
I'm not passing any data in terms of nodes here, We'll deal with
those in the PoseSave and PoseLoad calls. Leaves this open for
expansion
'''
super(PoseData, self).__init__(filterSettings=filterSettings, *args,**kws)
self.file_ext = '.pose'
self.poseDict={}
self.infoDict={}
self.skeletonDict={}
self.posePointCloudNodes=[]
self.poseCurrentCache={} # cached dict storing the current state of the objects prior to applying the pose
self.relativePose=False
self.relativeRots='projected'
self.relativeTrans='projected'
self.mirrorInverse=False # when loading do we inverse the attrs values being loaded (PRO-PACK finger systems)
def _collectNodeData(self, node, key):
'''
collect the attr data from the node and add it to the poseDict[key]
'''
self._collectNodeData_attrs(node, key)
def _buildBlock_skeletonData(self, rootJnt):
'''
:param rootNode: root of the skeleton to process
TODO : strip the longname from the root joint upwards and remove namespaces on all
'''
self.skeletonDict={}
if not rootJnt:
log.info('skeleton rootJnt joint was not found - [skeletonDict] pose section will not be propagated')
return
fn=r9Core.FilterNode(rootJnt)
fn.settings.nodeTypes='joint'
fn.settings.incRoots=False
skeleton=fn.processFilter()
parentNode=cmds.listRelatives(rootJnt,p=True,f=True)
for jnt in skeleton:
key=r9Core.nodeNameStrip(jnt)
self.skeletonDict[key]={}
self.skeletonDict[key]['attrs']={}
if parentNode:
self.skeletonDict[key]['longName']=jnt.replace(parentNode[0],'')
else:
self.skeletonDict[key]['longName']=jnt
for attr in ['translateX','translateY','translateZ', 'rotateX','rotateY','rotateZ','jointOrientX','jointOrientY','jointOrientZ']:
try:
self.skeletonDict[key]['attrs'][attr]=cmds.getAttr('%s.%s' % (jnt,attr))
except:
log.debug('%s : attr is invalid in this instance' % attr)
def buildBlocks_fill(self, nodes=None):
'''
What capture routines to run in order to build the poseDict data
'''
if not nodes:
nodes=self.nodesToStore
self.poseDict={}
self._buildBlock_info()
self._buildBlock_poseDict(nodes)
self._buildBlock_skeletonData(self.rootJnt)
def _cacheCurrentNodeStates(self):
'''
this is purely for the _applyPose with percent and optimization for the UI's
'''
log.info('updating the currentCache')
self.poseCurrentCache={}
for key, dest in self.matchedPairs:
log.debug('caching current node data : %s' % key)
self.poseCurrentCache[key]={}
if not 'attrs' in self.poseDict[key]:
continue
for attr, _ in self.poseDict[key]['attrs'].items():
try:
self.poseCurrentCache[key][attr]=cmds.getAttr('%s.%s' % (dest, attr))
except:
log.debug('Attr mismatch on destination : %s.%s' % (dest, attr))
@r9General.Timer
def _applyData(self, percent=None):
'''
:param percent: percent of the pose to load
'''
mix_percent=False # gets over float values of zero from failing
if percent or type(percent)==float:
mix_percent=True
if not self.poseCurrentCache:
self._cacheCurrentNodeStates()
for key, dest in self.matchedPairs:
log.debug('Applying Key Block : %s' % key)
try:
if not 'attrs' in self.poseDict[key]:
continue
for attr, val in self.poseDict[key]['attrs'].items():
if attr in self.skipAttrs:
log.debug('Skipping attr as requested : %s' % attr)
continue
try:
val = eval(val)
# =====================================================================
# inverse the correct mirror attrs if the mirrorInverse flag was thrown
# =====================================================================
# this is mainly for the ProPack finger systems support hooks
if self.mirrorInverse and 'mirrorID' in self.poseDict[key] and self.poseDict[key]['mirrorID']:
axis=r9Anim.MirrorHierarchy().getMirrorAxis(dest)
side=r9Anim.MirrorHierarchy().getMirrorSide(dest)
if attr in axis:
poseSide=self.poseDict[key]['mirrorID'].split('_')[0]
if not poseSide==side:
val = 0-val
log.debug('Inversing Pose Values for Axis: %s, stored side: %s, nodes side: %s, node: %s' % (attr,
poseSide,
side,
r9Core.nodeNameStrip(dest)))
except:
pass
log.debug('node : %s : attr : %s : val %s' % (dest, attr, val))
try:
if not mix_percent:
cmds.setAttr('%s.%s' % (dest, attr), val)
else:
current = self.poseCurrentCache[key][attr]
blendVal = ((val - current) / 100) * percent
# print 'loading at percent : %s (current=%s , stored=%s' % (percent,current,current+blendVal)
cmds.setAttr('%s.%s' % (dest, attr), current + blendVal)
except StandardError, err:
log.debug(err)
except:
log.debug('Pose Object Key : %s : has no Attr block data' % key)
#Main Calls ----------------------------------------
#@r9General.Timer
def poseSave(self, nodes, filepath=None, useFilter=True, storeThumbnail=True):
'''
Entry point for the generic PoseSave.
:param nodes: nodes to store the data against OR the rootNode if the
filter is active.
:param filepath: posefile to save - if not given the pose is cached on this
class instance.
:param useFilter: use the filterSettings or not.
:param storeThumbnail: generate and store a thu8mbnail from the screen to go alongside the pose
'''
#push args to object - means that any poseHandler.py file has access to them
if filepath:
self.filepath=filepath
self.useFilter=useFilter
if self.filepath:
log.debug('PosePath given : %s' % self.filepath)
self.buildDataMap(nodes) # generate the main node mapping
self.buildBlocks_fill(self.nodesToStore) # fill in all the data to collect
if self.filepath:
self._writePose(self.filepath)
if storeThumbnail:
sel=cmds.ls(sl=True,l=True)
cmds.select(cl=True)
r9General.thumbNailScreen(self.filepath, self.thumbnailRes[0], self.thumbnailRes[1])
if sel:
cmds.select(sel)
log.info('Pose Saved Successfully to : %s' % self.filepath)
#@r9General.Timer
def poseLoad(self, nodes, filepath=None, useFilter=True, relativePose=False, relativeRots='projected',
relativeTrans='projected', maintainSpaces=False, percent=None):
'''
Entry point for the generic PoseLoad.
:param nodes: if given load the data to only these. If given and filter=True
this is the rootNode for the filter.
:param filepath: posefile to load - if not given the pose is loaded from a
cached instance on this class.
:param useFilter: If the pose has an active Filter_Settings block and this
is True then use the filter on the destination hierarchy.
:param relativePose: kick in the posePointCloud to align the loaded pose
relatively to the selected node.
:param relativeRots: 'projected' or 'absolute' - how to calculate the offset.
:param relativeTrans: 'projected' or 'absolute' - how to calculate the offset.
:param maintainSpaces: this preserves any parentSwitching mismatches between
the stored pose and the current rig settings, current spaces are maintained.
This only checks those nodes in the snapList and only runs under relative mode.
:param percent: percentage of the pose to apply, used by the poseBlender in the UIs
'''
objs=cmds.ls(sl=True, l=True)
if relativePose and not objs:
raise StandardError('Nothing selected to align Relative Pose too')
if not type(nodes)==list:
nodes=[nodes] # cast to list for consistency
#push args to object - means that any poseHandler.py file has access to them
self.relativePose = relativePose
self.relativeRots = relativeRots
self.relativeTrans = relativeTrans
self.PosePointCloud = None
if filepath:
self.filepath=filepath
self.useFilter = useFilter # used in the getNodes call
self.maintainSpaces = maintainSpaces
self.mayaUpAxis = r9Setup.mayaUpAxis()
try:
self._pre_load()
# main process to match and build up the data
self.processPoseFile(nodes)
if not self.matchedPairs:
raise StandardError('No Matching Nodes found in the PoseFile!')
else:
if self.relativePose:
if self.prioritySnapOnly:
if not self.settings.filterPriority:
log.warning('Internal filterPriority list is empty, switching "SnapPriority" flag OFF!')
else:
# we've already filtered the hierarchy, may as well just filter the results for speed
self.nodesToLoad=r9Core.prioritizeNodeList(self.nodesToLoad, self.settings.filterPriority, regex=True, prioritysOnly=True)
self.nodesToLoad.reverse()
#setup the PosePointCloud -------------------------------------------------
reference=objs[0]
self.PosePointCloud=PosePointCloud(self.nodesToLoad)
self.PosePointCloud.buildOffsetCloud(reference, raw=True)
resetCache=[cmds.getAttr('%s.translate' % self.PosePointCloud.posePointRoot),
cmds.getAttr('%s.rotate' % self.PosePointCloud.posePointRoot)]
if self.maintainSpaces:
if self.metaRig:
parentSpaceCache=self.getMaintainedAttrs(self.nodesToLoad, self.metaRig.parentSwitchAttr)
elif 'parentSpaces' in self.settings.rigData:
parentSpaceCache=self.getMaintainedAttrs(self.nodesToLoad, self.settings.rigData['parentSpaces'])
self._applyData(percent)
if self.relativePose:
#snap the poseCloud to the new xform of the referenced node, snap the cloud
#to the pose, reset the clouds parent to the cached xform and then snap the
#nodes back to the cloud
r9Anim.AnimFunctions.snap([reference,self.PosePointCloud.posePointRoot])
if self.relativeRots=='projected':
if self.mayaUpAxis=='y':
cmds.setAttr('%s.rx' % self.PosePointCloud.posePointRoot,0)
cmds.setAttr('%s.rz' % self.PosePointCloud.posePointRoot,0)
elif self.mayaUpAxis=='z': # fucking Z!!!!!!
cmds.setAttr('%s.rx' % self.PosePointCloud.posePointRoot,0)
cmds.setAttr('%s.ry' % self.PosePointCloud.posePointRoot,0)
self.PosePointCloud.snapPosePntstoNodes()
if not self.relativeTrans=='projected':
cmds.setAttr('%s.translate' % self.PosePointCloud.posePointRoot,
resetCache[0][0][0],
resetCache[0][0][1],
resetCache[0][0][2])
if not self.relativeRots=='projected':
cmds.setAttr('%s.rotate' % self.PosePointCloud.posePointRoot,
resetCache[1][0][0],
resetCache[1][0][1],
resetCache[1][0][2])
if self.relativeRots=='projected':
if self.mayaUpAxis=='y':
cmds.setAttr('%s.ry' % self.PosePointCloud.posePointRoot,resetCache[1][0][1])
elif self.mayaUpAxis=='z': # fucking Z!!!!!!
cmds.setAttr('%s.rz' % self.PosePointCloud.posePointRoot,resetCache[1][0][2])
if self.relativeTrans=='projected':
if self.mayaUpAxis=='y':
cmds.setAttr('%s.tx' % self.PosePointCloud.posePointRoot,resetCache[0][0][0])
cmds.setAttr('%s.tz' % self.PosePointCloud.posePointRoot,resetCache[0][0][2])
elif self.mayaUpAxis=='z': # fucking Z!!!!!!
cmds.setAttr('%s.tx' % self.PosePointCloud.posePointRoot,resetCache[0][0][0])
cmds.setAttr('%s.ty' % self.PosePointCloud.posePointRoot,resetCache[0][0][1])
#if maintainSpaces then restore the original parentSwitch attr values
#BEFORE pushing the point cloud data back to the rig
if self.maintainSpaces and parentSpaceCache: # and self.metaRig:
for child,attr,value in parentSpaceCache:
log.debug('Resetting parentSwitches : %s.%s = %f' % (r9Core.nodeNameStrip(child),attr,value))
cmds.setAttr('%s.%s' % (child,attr), value)
self.PosePointCloud.snapNodestoPosePnts()
self.PosePointCloud.delete()
cmds.select(reference)
else:
if objs:
cmds.select(objs)
except StandardError,err:
log.info('Pose Load Failed! : , %s' % err)
finally:
self._post_load()
class PosePointCloud(object):
'''
PosePointCloud is the technique inside the PoseSaver used to snap the pose into
relative space. It's been added as a tool in it's own right as it's sometimes
useful to be able to shift poses in global space.
'''
def __init__(self, nodes, filterSettings=None, meshes=[], *args, **kws):
'''
:param nodes: feed the nodes to process in as a list, if a filter is given
then these are the rootNodes for it
:param filterSettings: pass in a filterSettings object to filter the given hierarchy
:param meshes: this is really for reference, rather than make a locator, pass in a reference geo
which is then shapeSwapped for the PPC root node giving great reference!
'''
self.meshes = meshes
if self.meshes and not isinstance(self.meshes, list):
self.meshes=[meshes]
self.refMesh = 'posePointCloudGeoRef' # name for the duplicate meshes used
self.mayaUpAxis = r9Setup.mayaUpAxis()
self.inputNodes = nodes # inputNodes for processing
self.posePointCloudNodes = [] # generated ppc nodes
self.posePointRoot = None # generated rootnode of the ppc
self.settings = None
self.prioritySnapOnly=False # ONLY make ppc points for the filterPriority nodes
self.rootReference = None # root node used as the main pivot for the cloud
self.isVisible = True # Do we build the visual reference setup or not?
self.ppcMeta=None # MetaNode to cache the data
if filterSettings:
if not issubclass(type(filterSettings), r9Core.FilterNode_Settings):
raise StandardError('filterSettings param requires an r9Core.FilterNode_Settings object')
elif filterSettings.filterIsActive():
self.settings=filterSettings
else:
self.settings=r9Core.FilterNode_Settings()
def __connectdataToMeta__(self):
'''
on build push the data to a metaNode so it's cached in the scene incase we need to
reconstruct anything at a later date. This is used extensivly in the AnimReDirect calls
'''
#self.ppcMeta = r9Meta.MetaClass(name='PPC_Root')
#self.ppcMeta.mClassGrp='PPCROOT'
self.ppcMeta.connectChild(self.posePointRoot, 'posePointRoot')
self.ppcMeta.addAttr('posePointCloudNodes', self.posePointCloudNodes)
def syncdatafromCurrentInstance(self):
'''
pull existing data back from the metaNode
'''
self.ppcMeta=self.getCurrentInstances()
if self.ppcMeta:
self.ppcMeta=self.ppcMeta[0]
self.posePointCloudNodes=self.ppcMeta.posePointCloudNodes
self.posePointRoot=self.ppcMeta.posePointRoot[0]
def getInputNodes(self):
'''
handler to build up the list of nodes to generate the cloud against.
This uses the filterSettings and the inputNodes variables to process the
hierarchy and is designed for overloading if required.
'''
if self.settings.filterIsActive():
__searchPattern_cached=self.settings.searchPattern
# if self.prioritySnapOnly:
# self.settings.searchPattern=self.settings.filterPriority
# self.inputNodes=r9Core.FilterNode(self.inputNodes, self.settings).processFilter()
flt=r9Core.FilterNode(self.inputNodes, self.settings)
if self.prioritySnapOnly:
# take from the flt instance as that now manages metaRig specific settings internally
self.settings.searchPattern=flt.settings.filterPriority
self.inputNodes=flt.processFilter()
self.settings.searchPattern=__searchPattern_cached # restore the settings back!!
# auto logic for MetaRig - go find the renderMeshes wired to the systems
if self.settings.metaRig:
if not self.meshes:
mRig=r9Meta.getConnectedMetaSystemRoot(self.inputNodes)
else:
mRig=r9Meta.getMetaRigs()[0]
self.meshes=mRig.renderMeshes
if self.inputNodes:
self.inputNodes.reverse() # for the snapping operations
return self.inputNodes
def getPPCNodes(self):
'''
return a list of the PPC nodes
'''
return [ppc for ppc,_ in self.posePointCloudNodes]
def getTargetNodes(self):
'''
return a list of the target controllers
'''
return [target for _, target in self.posePointCloudNodes]
@staticmethod
def getCurrentInstances():
'''
get any current PPC nodes in the scene
'''
return r9Meta.getMetaNodes(mClassGrps=['PPCROOT'])
def snapPosePntstoNodes(self):
'''
snap each pntCloud point to their respective Maya nodes
'''
for pnt,node in self.posePointCloudNodes:
log.debug('snapping PPT : %s' % pnt)
r9Anim.AnimFunctions.snap([node,pnt])
def snapNodestoPosePnts(self):
'''
snap each MAYA node to it's respective pntCloud point
'''
for pnt, node in self.posePointCloudNodes:
log.debug('snapping Ctrl : %s > %s : %s' % (r9Core.nodeNameStrip(node), pnt, node))
r9Anim.AnimFunctions.snap([pnt,node])
def generateVisualReference(self):
'''
Generic call that's used to overload the visual handling
of the PPC is other instances such as the AnimationPPC
'''
if self.meshes and self.isVisible:
self.shapeSwapMeshes()
def buildOffsetCloud(self, rootReference=None, raw=False, projectedRots=False, projectedTrans=False):
'''
Build a point cloud up for each node in nodes
:param nodes: list of objects to be in the cloud
:param rootReference: the node used for the initial pivot location
:param raw: build the cloud but DON'T snap the nodes into place - an optimisation for the PoseLoad sequence
:param projectedRots: project the rotates of the root node of the cloud
:param projectedTrans: project the translates of the root node of the cloud
'''
self.deleteCurrentInstances()
# moved the mNode generation earlier so the rest of the code can bind to it during build
self.ppcMeta = r9Meta.MetaClass(name='PPC_Root')
self.ppcMeta.mClassGrp='PPCROOT'
self.posePointRoot=cmds.ls(cmds.spaceLocator(name='posePointCloud'),sl=True,l=True)[0]
print self.posePointRoot
cmds.setAttr('%s.visibility' % self.posePointRoot, self.isVisible)
ppcShape=cmds.listRelatives(self.posePointRoot,type='shape',f=True)[0]
cmds.setAttr("%s.localScaleZ" % ppcShape, 30)
cmds.setAttr("%s.localScaleX" % ppcShape, 30)
cmds.setAttr("%s.localScaleY" % ppcShape, 30)
if rootReference:
self.rootReference=rootReference
#run the filterCode based on the settings object
self.getInputNodes()
if self.mayaUpAxis=='y':
cmds.setAttr('%s.rotateOrder' % self.posePointRoot, 2)
if self.rootReference: # and not mesh:
r9Anim.AnimFunctions.snap([self.rootReference,self.posePointRoot])
#reset the PPTCloudRoot to projected ground plane
if projectedRots:
cmds.setAttr('%s.rx' % self.posePointRoot, 0)
cmds.setAttr('%s.rz' % self.posePointRoot, 0)
if projectedTrans:
cmds.setAttr('%s.ty' % self.posePointRoot, 0)
for node in self.inputNodes:
pnt=cmds.spaceLocator(name='pp_%s' % r9Core.nodeNameStrip(node))[0]
if not raw:
r9Anim.AnimFunctions.snap([node,pnt])
cmds.parent(pnt,self.posePointRoot)
self.posePointCloudNodes.append((pnt,node))
cmds.select(self.posePointRoot)
# generate the mesh references if required
self.generateVisualReference()
self.__connectdataToMeta__()
return self.posePointCloudNodes
def shapeSwapMeshes(self, selectable=True):
'''
Swap the mesh Geo so it's a shape under the PPC transform root
TODO: Make sure that the duplicate message link bug is covered!!
'''
currentCount = len(cmds.listRelatives(self.posePointRoot, type='shape'))
for i,mesh in enumerate(self.meshes):
dupMesh = cmds.duplicate(mesh, rc=True, n=self.refMesh+str(i + currentCount))[0]
dupShape = cmds.listRelatives(dupMesh, type='shape')[0]
r9Core.LockChannels().processState(dupMesh,['tx','ty','tz','rx','ry','rz','sx','sy','sz'],\
mode='fullkey',hierarchy=False)
try:
if selectable:
#turn on the overrides so the duplicate geo can be selected
cmds.setAttr("%s.overrideDisplayType" % dupShape, 0)
cmds.setAttr("%s.overrideEnabled" % dupShape, 1)
cmds.setAttr("%s.overrideLevelOfDetail" % dupShape, 0)
else:
cmds.setAttr("%s.overrideDisplayType" % dupShape, 2)
cmds.setAttr("%s.overrideEnabled" % dupShape, 1)
except:
log.debug('Couldnt set the draw overrides for the refGeo')
cmds.parent(dupMesh,self.posePointRoot)
cmds.makeIdentity(dupMesh,apply=True,t=True,r=True)
cmds.parent(dupShape,self.posePointRoot,r=True,s=True)
cmds.delete(dupMesh)
def applyPosePointCloud(self):
self.snapNodestoPosePnts()
def updatePosePointCloud(self):
self.snapPosePntstoNodes()
if self.meshes:
cmds.delete(cmds.listRelatives(self.posePointRoot, type=['mesh','nurbsCurve']))
self.generateVisualReference()
cmds.refresh()
def delete(self):
root=self.posePointRoot
if not root:
root=self.ppcMeta.posePointRoot[0]
self.ppcMeta.delete()
cmds.delete(root)
def deleteCurrentInstances(self):
'''
delete any current instances of PPC clouds
'''
PPCNodes=self.getCurrentInstances()
if PPCNodes:
log.info('Deleting current PPC nodes in the scene')
for ppc in PPCNodes:
cmds.delete(ppc.posePointRoot)
try:
ppc.delete()
except:
pass # metaNode should be cleared by default when it's only connection is deleted
class PoseCompare(object):
'''
This is aimed at comparing a rigs current pose with a given one, be that a
pose file on disc, a pose class object, or even a poseObject against another.
It will compare either the main [poseData].keys or the ['skeletonDict'].keys
and for key in keys compare, with tolerance, the [attrs] block.
>>> #build an mPose object and fill the internal poseDict
>>> mPoseA=r9Pose.PoseData()
>>> mPoseA.metaPose=True
>>> mPoseA.buildDataMap(cmds.ls(sl=True))
>>> mPoseA.buildBlocks_fill()
>>>
>>> mPoseB=r9Pose.PoseData()
>>> mPoseB.metaPose=True
>>> mPoseB.buildDataMap(cmds.ls(sl=True))
>>> mPoseB.buildBlocks_fill()
>>>
>>> compare=r9Pose.PoseCompare(mPoseA,mPoseB)
>>>
>>> #.... or ....
>>> compare=r9Pose.PoseCompare(mPoseA,'H:/Red9PoseTests/thisPose.pose')
>>> #.... or ....
>>> compare=r9Pose.PoseCompare('H:/Red9PoseTests/thisPose.pose','H:/Red9PoseTests/thatPose.pose')
>>>
>>> compare.compare() #>> bool, True = same
>>> compare.fails['failedAttrs']
'''
def __init__(self, currentPose, referencePose, angularTolerance=0.1, linearTolerance=0.01,
compareDict='poseDict', filterMap=[], ignoreBlocks=[], ignoreStrings=[], ignoreAttrs=[]):
'''
Make sure we have 2 PoseData objects to compare
:param currentPose: either a PoseData object or a valid pose file
:param referencePose: either a PoseData object or a valid pose file
:param tolerance: tolerance by which floats are matched
:param angularTolerance: the tolerance used to check rotate attr float values
:param linearTolerance: the tolerance used to check all other float attrs
:param compareDict: the internal main dict in the pose file to compare the data with
:param filterMap: if given this is used as a high level filter, only matching nodes get compared
others get skipped. Good for passing in a master core skeleton to test whilst ignoring extra nodes
:param ignoreBlocks: allows the given failure blocks to be ignored. We mainly use this for ['missingKeys']
:param ignoreStrings: allows you to pass in a list of strings, if any of the keys in the data contain
that string it will be skipped, note this is a partial match so you can pass in wildcard searches ['_','_end']
:param ignoreAttrs: allows you to skip given attrs from the poseCompare calls
.. note::
In the new setup if the skeletonRoot jnt is found we add a whole
new dict to serialize the current skeleton data to the pose, this means that
we can compare a pose on a rig via the internal skeleton transforms as well
as the actual rig controllers...makes validation a lot more accurate for export
* 'poseDict' = [poseData] main controller data
* 'skeletonDict' = [skeletonDict] block generated if exportSkeletonRoot is connected
* 'infoDict' = [info] block
'''
self.status = False
self.compareDict = compareDict
self.angularTolerance = angularTolerance
self.angularAttrs = ['rotateX', 'rotateY', 'rotateZ', 'jointOrientX', 'jointOrientY', 'jointOrientZ']
self.linearTolerance = linearTolerance
self.linearAttrs = ['translateX', 'translateY', 'translateZ']
self.filterMap = filterMap
self.ignoreBlocks = ignoreBlocks
self.ignoreStrings = ignoreStrings
self.ignoreAttrs = ignoreAttrs
if isinstance(currentPose, PoseData):
self.currentPose = currentPose
elif os.path.exists(currentPose):
self.currentPose = PoseData()
self.currentPose._readPose(currentPose)
elif not os.path.exists(referencePose):
raise IOError('Given CurrentPose Path is invalid!')
if isinstance(referencePose, PoseData):
self.referencePose = referencePose
elif os.path.exists(referencePose):
self.referencePose = PoseData()
self.referencePose._readPose(referencePose)
elif not os.path.exists(referencePose):
raise IOError('Given ReferencePose Path is invalid!')
def __addFailedAttr(self, key, attr):
'''
add failed attrs data to the dict
'''
if not 'failedAttrs' in self.fails:
self.fails['failedAttrs'] = {}
if not key in self.fails['failedAttrs']:
self.fails['failedAttrs'][key] = {}
if not 'attrMismatch' in self.fails['failedAttrs'][key]:
self.fails['failedAttrs'][key]['attrMismatch'] = []
self.fails['failedAttrs'][key]['attrMismatch'].append(attr)
def compare(self):
'''
Compare the 2 PoseData objects via their internal [key][attrs] blocks
return a bool. After processing self.fails is a dict holding all the fails
for processing later if required
'''
self.fails = {}
logprint = 'PoseCompare returns : %s ========================================\n' % self.compareDict
currentDic = getattr(self.currentPose, self.compareDict)
referenceDic = getattr(self.referencePose, self.compareDict)
if not currentDic or not referenceDic:
raise StandardError('missing pose section <<%s>> compare aborted' % self.compareDict)
for key, attrBlock in currentDic.items():
if self.filterMap and not key in self.filterMap:
log.debug('node not in filterMap - skipping key %s' % key)
continue
if self.ignoreStrings:
for istr in self.ignoreStrings:
if istr in key:
continue
if key in referenceDic:
referenceAttrBlock = referenceDic[key]
else:
if not 'missingKeys' in self.ignoreBlocks:
logprint += 'ERROR: Key Mismatch : %s\n' % key
if not 'missingKeys' in self.fails:
self.fails['missingKeys'] = []
self.fails['missingKeys'].append(key)
else:
log.debug('missingKeys in ignoreblock : node is missing from data but being skipped "%s"' % key)
continue
if not 'attrs' in attrBlock:
log.debug('%s node has no attrs block in the pose' % key)
continue
for attr, value in attrBlock['attrs'].items():
if attr in self.ignoreAttrs:
continue
# attr missing completely from the key
if not attr in referenceAttrBlock['attrs']:
if not 'failedAttrs' in self.fails:
self.fails['failedAttrs'] = {}
if not key in self.fails['failedAttrs']:
self.fails['failedAttrs'][key] = {}
if not 'missingAttrs' in self.fails['failedAttrs'][key]:
self.fails['failedAttrs'][key]['missingAttrs'] = []
self.fails['failedAttrs'][key]['missingAttrs'].append(attr)
# log.info('missing attribute in data : "%s.%s"' % (key,attr))
logprint += 'ERROR: Missing attribute in data : "%s.%s"\n' % (key, attr)
continue
# test the attrs value matches
#print 'key : ', key, 'Value : ', value
value = r9Core.decodeString(value) # decode as this may be a configObj
refValue = r9Core.decodeString(referenceAttrBlock['attrs'][attr]) # decode as this may be a configObj
if type(value) == float:
matched = False
if attr in self.angularAttrs:
matched = r9Core.floatIsEqual(value, refValue, self.angularTolerance, allowGimbal=True)
else:
matched = r9Core.floatIsEqual(value, refValue, self.linearTolerance, allowGimbal=False)
if not matched:
self.__addFailedAttr(key, attr)
# log.info('AttrValue float mismatch : "%s.%s" currentValue=%s >> expectedValue=%s' % (key,attr,value,refValue))
logprint += 'ERROR: AttrValue float mismatch : "%s.%s" currentValue=%s >> expectedValue=%s\n' % (key, attr, value, refValue)
continue
elif not value == refValue:
self.__addFailedAttr(key, attr)
# log.info('AttrValue mismatch : "%s.%s" currentValue=%s >> expectedValue=%s' % (key,attr,value,refValue))
logprint += 'ERROR: AttrValue mismatch : "%s.%s" currentValue=%s >> expectedValue=%s\n' % (key, attr, value, refValue)
continue
if 'missingKeys' in self.fails or 'failedAttrs' in self.fails:
logprint += 'PoseCompare returns : ========================================'
print logprint
return False
self.status = True
return True
def batchPatchPoses(posedir, config, poseroot, load=True, save=True, patchfunc=None,\
relativePose=False, relativeRots=False, relativeTrans=False):
'''
whats this?? a fast method to run through all the poses in a given dictionary and update
or patch them. If patchfunc isn't given it'll just run through and resave the pose - updating
the systems if needed. If it is then it gets run between the load and save calls.
:param posedir: directory of poses to process
:param config: hierarchy settings cfg to use to ID the nodes (hierarchy tab preset = filterSettings object)
:param poseroot: root node to the filters - poseTab rootNode/MetaRig root
:param patchfunc: optional function to run between the load and save call in processing, great for
fixing issues on mass with poses. Note we now pass pose file back into this func as an arg
:param load: should the batch load the pose
:param save: should the batch resave the pose
'''
filterObj=r9Core.FilterNode_Settings()
filterObj.read(os.path.join(r9Setup.red9ModulePath(), 'presets', config))
mPose=PoseData(filterObj)
mPose.setMetaRig(poseroot)
files=os.listdir(posedir)
files.sort()
for f in files:
if f.lower().endswith('.pose'):
if load:
print 'Loading Pose : %s' % os.path.join(posedir,f)
mPose.poseLoad(nodes=poseroot,
filepath=os.path.join(posedir,f),
useFilter=True,
relativePose=relativePose,
relativeRots=relativeRots,
relativeTrans=relativeTrans)
if patchfunc:
print 'Applying patch'
patchfunc(f)
if save:
print 'Saving Pose : %s' % os.path.join(posedir,f)
mPose.poseSave(nodes=poseroot,
filepath=os.path.join(posedir,f),
useFilter=True,
storeThumbnail=False)
log.info('Processed Pose File : %s' % f)
```
#### File: rjTools/delinearWeights/__init__.py
```python
from maya import cmds, mel, OpenMayaAnim
from rjSkinningTools import utils
from . import tweening
__author__ = "<NAME>"
__version__ = "0.7.0"
__email__ = "<EMAIL>"
# ----------------------------------------------------------------------------
def getTweeningMethod(method):
"""
Get the tweening method from a string, if the function doesn't exists
None will be returned.
:return: Tweening function
:rtype: func/None
"""
if method in dir(tweening):
return getattr(tweening, method)
# ----------------------------------------------------------------------------
def getSelectedVertices():
"""
Get all of the selected vertices. If no component mode selection is made
all vertices of a selected mesh will be appended to the selection.
:return: List of selected vertices
:rtype: list of strings
"""
# get vertices
vertices = [
vtx
for vtx in cmds.ls(sl=True, fl=True, l=True)
if vtx.count(".vtx")
]
# append meshes
meshes = utils.getMeshesFromSelection()
for mesh in meshes:
vertices.extend(
cmds.ls(
"{0}.vtx[*]".format(mesh),
fl=True,
l=True
)
)
return vertices
# ----------------------------------------------------------------------------
def getIndexFromString(vtx):
"""
Get the index from a component string.
:param str vtx: Path to component
:return: Index of component string
:rtype: int
"""
return int(vtx.split("[")[-1][:-1])
def splitByInfluences(weights, num):
"""
Split a list of weights into the size of the number of influences.
:param list weights: List of weights
:param int num: Size of split
:return: Index of component string
:rtype: int
"""
chunks = []
for i in xrange(0, len(weights), num):
chunks.append(weights[i:i + num])
return chunks
# ----------------------------------------------------------------------------
def deLinearSkinWeightsOnSelection(method):
"""
All of the selected vertices will be queried with the
:func:`getSelectedVertices` function, these vertices will then be parsed
to the :func:`deLinearSkinWeights` function that will process the weights.
:param str method: De-linearization method
"""
vertices = getSelectedVertices()
deLinearSkinWeights(vertices, method)
def deLinearSkinWeights(vertices, method):
"""
Loop over all of the provided vertices. Loop over all of the vertices and
see if these vertices are deformed by a skin cluster. If this is the case,
the weights will be de-linearized by the function provided. This function
is found in the tweening module using :func:`getTweeningMethod`.
:param list vertices: List of vertices
:param str method: De-linearization method
"""
func = getTweeningMethod(method)
if not func:
raise ValueError("Tweening method is not supported.")
data = {}
objects = list(set([vtx.split(".")[0] for vtx in vertices]))
with utils.UndoChunkContext():
for obj in objects:
# get skin cluster
sk = utils.getSkinCluster(obj)
if not sk:
continue
# get indices
indices = [
getIndexFromString(vtx)
for vtx in vertices
if vtx.startswith(obj)
]
# get api objects
meshObj = utils.asMObject(obj)
meshDag = utils.asMDagPath(meshObj)
meshDag.extendToShape()
skObj = utils.asMObject(sk)
skMfn = OpenMayaAnim.MFnSkinCluster(skObj)
# get weights
components = utils.asComponent(indices)
weightsAll, num = utils.getSkinWeights(
meshDag,
skMfn,
components
)
# split weights
weightChunks = splitByInfluences(weightsAll, num)
for i, weights in enumerate(weightChunks):
# calculate per vertex weights
weights = utils.normalizeWeights(weights)
weights = [func(w) for w in weights]
weights = utils.normalizeWeights(weights)
# set weights
for j, w in enumerate(weights):
cmds.setAttr(
"{0}.weightList[{1}].weights[{2}]".format(
sk,
indices[i],
j
),
w
)
```
#### File: rjTools/paintRemoveInfluenceCtx/ui.py
```python
from maya import cmds, OpenMaya
from functools import partial
from .. import ui
from .. import utils
from .. import paintRemoveInfluenceCtx
# ------------------------------------------------------------------------
WINDOW_TITLE = "Paint : Remove Influences"
WINDOW_ICON = "paintRemoveInfluenceCtx.png"
ITEM_STYLESHEET = """
QPushButton {text-align: left}
QPushButton::pressed, QPushButton::hover {color: orange}
"""
# ------------------------------------------------------------------------
class PaintRemoveInfluencesWidget(ui.QWidget):
def __init__(self, parent):
ui.QWidget.__init__(self, parent)
# ui
self.setParent(parent)
self.setWindowFlags(ui.Qt.Window)
self.setWindowTitle(WINDOW_TITLE)
self.resize(250, 400)
# set icon
path = ui.findIcon(WINDOW_ICON)
if path:
self.setWindowIcon(ui.QIcon(path))
# create layout
layout = ui.QVBoxLayout(self)
layout.setContentsMargins(3, 3, 3, 3)
layout.setSpacing(3)
# create tree
self.tree = ui.QTreeWidget(self)
self.tree.setRootIsDecorated(True)
self.tree.setSelectionMode(ui.QAbstractItemView.NoSelection)
self.tree.setFocusPolicy(ui.Qt.NoFocus)
self.tree.header().setVisible(False)
self.tree.setFont(ui.FONT)
layout.addWidget(self.tree)
# create button
self.button = ui.QPushButton( self )
self.button.setText("Load")
self.button.setFixedHeight(35)
self.button.setFont(ui.BOLT_FONT)
self.button.pressed.connect(self.load)
layout.addWidget(self.button)
# ------------------------------------------------------------------------
def paint(self, mesh, influence):
paintRemoveInfluenceCtx.paint(mesh, influence)
# ------------------------------------------------------------------------
def load( self ):
# clear ui
self.tree.clear()
# get selected meshes
meshes = utils.getSkinnedMeshesFromSelection()
if not meshes:
self.setWindowTitle(WINDOW_TITLE)
raise RuntimeError("Select a smooth bound mesh!")
# update window title
mesh = meshes[0]
self.setWindowTitle(mesh.split("|")[-1])
# get skinCluster
obj = utils.asMObject(mesh)
skinCluster = utils.asMFnSkinCluster(obj)
# get influences
influencesPrev = []
influencesSort = []
infDag, _, _ = utils.getInfluences(skinCluster)
# sort influences
for i in range(infDag.length()):
influencesSort.append((i, infDag[i]))
influencesSort.sort(key=lambda x: len(x[1].fullPathName().split("|")))
def getParent(path):
for p, button in influencesPrev:
if path.startswith(p):
return button
return self.tree
# create buttons
for i, dag in influencesSort:
# get influence names
path = dag.fullPathName()
partialPath = dag.partialPathName()
# get parent
parent = getParent(path)
# create button
button = ui.QPushButton(self.tree)
button.setFlat(True)
button.setText(partialPath)
button.setFont(ui.FONT)
button.setStyleSheet(ITEM_STYLESHEET)
# connect command
button.pressed.connect(
partial(
self.paint,
mesh,
path
)
)
# create item
item = ui.QTreeWidgetItem(parent)
# add to tree
self.tree.setItemWidget(item, 0, button)
# update item
item.setIcon( 0, self.getInfluenceIcon(dag.apiType()))
item.setExpanded(True)
# store previous
influencesPrev.insert(0, (path, item))
def getInfluenceIcon(self, t):
if t == OpenMaya.MFn.kJoint:
return ui.QIcon(":/out_joint.png")
elif t == OpenMaya.MFn.kTransform:
return u.QIcon(":/out_transform.png")
# ---------------------------------------------------------------------------------------------------------------------
def show():
paintRemoveInfluences = PaintRemoveInfluencesWidget(ui.mayaWindow())
paintRemoveInfluences.show()
return paintRemoveInfluences
```
#### File: rjTools/paintSmoothWeightsCtx/__init__.py
```python
__author__ = "<NAME>"
__version__ = "0.9.0"
__email__ = "<EMAIL>"
from maya import cmds
import os
# ----------------------------------------------------------------------------
CONTEXT = "paintSmoothWeightsCtx"
CONTEXT_INITIALIZE = "paintSmoothWeightsCtxInitialize"
CONTEXT_UPDATE = "paintSmoothWeightsCtxUpdate"
# ----------------------------------------------------------------------------
def paint():
"""
Initialize the smooth weight context, make sure to have a mesh selected
with a skin cluster attached to it. Once this command is run the context
will be set as the active tool.
"""
if not cmds.artUserPaintCtx(CONTEXT, query=True, exists=True):
cmds.artUserPaintCtx(CONTEXT)
cmds.artUserPaintCtx(
CONTEXT,
edit=True,
ic=CONTEXT_INITIALIZE,
svc=CONTEXT_UPDATE,
whichTool="userPaint",
fullpaths=True,
outwhilepaint=True,
brushfeedback=False,
selectedattroper="additive"
)
cmds.setToolTo(CONTEXT)
# ----------------------------------------------------------------------------
def loadPlugin():
"""
When this script is imported the following code will make sure the
accompanying plugin is loaded that registers the commands used by the
context.
"""
plugin = os.path.join(
os.path.dirname(__file__),
"plug-ins",
"paintSmoothWeightsCtxCommands.py"
)
loaded = cmds.pluginInfo(plugin, q=True, loaded=True)
registered = cmds.pluginInfo(plugin, q=True, registered=True)
if not registered or not loaded:
cmds.loadPlugin(plugin)
if __name__ != "__builtin__":
loadPlugin()
```
#### File: paintSmoothWeightsCtx/plug-ins/paintSmoothWeightsCtxCommands.py
```python
from maya import cmds, OpenMaya, OpenMayaMPx, OpenMayaAnim
import utils
__author__ = "<NAME>"
__version__ = "0.9.0"
__email__ = "<EMAIL>"
# ----------------------------------------------------------------------------
CONTEXT_INITIALIZE = "paintSmoothWeightsCtxInitialize"
CONTEXT_UPDATE = "paintSmoothWeightsCtxUpdate"
# ----------------------------------------------------------------------------
class SmoothWeightsCtxManager(object):
def __init__(self):
self.reset()
# ------------------------------------------------------------------------
def reset(self):
self._obj = None
self._dag = None
self._skinCluster = None
self._maxInfluences = 0
self._normalizeMode = 0
self._maintainMaxInfluences = False
self._influences = OpenMaya.MDagPathArray()
self._influencesLocked = []
def initialize(self, obj):
# if no obj reset variables
if not obj:
self.reset()
return
# get object data
self._obj = utils.asMObject(obj)
self._dag = utils.asMDagPath(self.obj)
# get skin cluster
self._skinCluster = utils.asMFnSkinCluster(self.obj)
# get skin cluster data
maxPlug = self.skinCluster.findPlug("maxInfluences")
normalPlug = self.skinCluster.findPlug("normalizeWeights")
maintainPlug = self.skinCluster.findPlug("maintainMaxInfluences")
self._maxInfluences = maxPlug.asInt()
self._normalizeMode = normalPlug.asInt()
self._maintainMaxInfluences = maintainPlug.asBool()
# get influences
self._influences = OpenMaya.MDagPathArray()
self.skinCluster.influenceObjects(self._influences)
# get locked influences
self._influencesLocked = []
for i in range(self.influences.length()):
path = self.influences[i].fullPathName()
locked = cmds.getAttr("{0}.liw".format(path))
self._influencesLocked.append(locked)
# ------------------------------------------------------------------------
@property
def obj(self):
return self._obj
@property
def dag(self):
return self._dag
@property
def skinCluster(self):
return self._skinCluster
# ------------------------------------------------------------------------
@property
def maxInfluences(self):
return self._maxInfluences
@property
def normalizeMode(self):
return self._normalizeMode
@property
def maintainMaxInfluences(self):
return self._maintainMaxInfluences
# ------------------------------------------------------------------------
@property
def influences(self):
return self._influences
@property
def influencesLocked(self):
return self._influencesLocked
# ------------------------------------------------------------------------
def calculateWeights(self, value, weightsO, weightsC, numI, numC):
"""
Calculate the new weights of the parsed index. The new weights are
calculated by blending the weights of the connected vertices, this is
done with the factor of the value. The value is parsed by the context
and can range from 0-1 depending on where the point is in the paint
brush. Locked influences, normalization and maintaining maximum
influences are taken into account as they are set on the skin cluster.
:param float value: Blend factor
:param OpenMaya.MDoubleArray weightsO: Weights of original
:param OpenMaya.MDoubleArray weightsC: Weights of connected
:param int numI: Influences of original
:param int numC: Influences of connected
:return: New weights, new influences
:rtype: tuple(OpenMaya.MDoubleArray, OpenMaya.MIntArray)
"""
# weight variables
weightsNew = OpenMaya.MDoubleArray()
influenceNew = OpenMaya.MIntArray()
# blend weights
for i in range(numI):
influenceNew.append(i)
weightsNew.append(0.0)
# if influence is locked dont change value
if self.influencesLocked[i]:
weightsNew[i] = weightsO[i]
continue
# blend weights with connected vertices
for j in range(i, len(weightsC), numI):
w = ((weightsO[i]/numC)*(1-value))+((weightsC[j]/numC)*value)
weightsNew[i] += w
# force max influences by removing excess weights
if self.maintainMaxInfluences:
weights = zip(weightsNew, influenceNew)
excess = sorted(weights, reverse=True)[self.maxInfluences:]
for e in excess:
weightsNew[e[1]] = 0.0
# normalize weights to one
if self.normalizeMode == 1:
# get total locked weights
lockedTotal = sum(
[
weightsNew[i]
for i in range(weightsNew.length())
if self.influencesLocked[i]
]
)
# get total to blend
total = sum(weightsNew) - lockedTotal
# get multiply factor
if lockedTotal >= 1.0 or total == 0.0:
factor = 0
else:
factor = (1.0-lockedTotal)/total
# apply multiply factor
for i in range(weightsNew.length()):
if self.influencesLocked[i]:
continue
weightsNew[i] = weightsNew[i] * factor
return weightsNew, influenceNew
# ------------------------------------------------------------------------
def setWeights(self, index, value):
"""
Calculate and set new weights of the vertex with the blend factor.
This function will return the previous weights data for undo purposes.
:param int index: Vertex number
:param float value: Blend factor
:return: Skin cluster, dag, component, influences, old weights
:rtype: list(
OpenMayaAnim.MFnSkinCluster,
OpenMaya.MDagPath,
OpenMaya.MFn.kMeshVertComponent,
OpenMaya.MIntArray,
OpenMaya.MDoubleArray
)
"""
# check if manager is initialized
if not self.obj:
return [None]*5
# get components
component = utils.asComponent(index)
componentConnected, componentCount = utils.getConnectedVertices(
self.dag,
component
)
# get current weights
weightsO, _ = utils.getSkinWeights(
self.dag,
self.skinCluster,
component,
)
# get connected weights
weightsC, influences = utils.getSkinWeights(
self.dag,
self.skinCluster,
componentConnected
)
# calculate new weights
weightsN, influencesN = self.calculateWeights(
value,
weightsO,
weightsC,
influences,
componentCount
)
# set new weights
self.skinCluster.setWeights(
self.dag,
component,
influencesN,
weightsN,
1
)
# return data for undo
return [self.skinCluster, self.dag, component, influencesN, weightsO]
# ----------------------------------------------------------------------------
manager = SmoothWeightsCtxManager()
# ----------------------------------------------------------------------------
class SmoothWeightsCtxInitialize(OpenMayaMPx.MPxCommand):
def __init__(self):
OpenMayaMPx.MPxCommand.__init__(self)
def doIt( self, args ):
obj = args.asString(0)
manager.initialize(obj)
def creatorInitialize():
return OpenMayaMPx.asMPxPtr(SmoothWeightsCtxInitialize())
def syntaxInitialize():
syntax = OpenMaya.MSyntax()
syntax.addArg(OpenMaya.MSyntax.kLong)
return syntax
# ----------------------------------------------------------------------------
class SmoothWeightsCtxUpdate(OpenMayaMPx.MPxCommand):
def __init__(self):
OpenMayaMPx.MPxCommand.__init__(self)
def doIt( self, args ):
self.index = args.asInt(1)
self.value = args.asDouble(2)
self.data = manager.setWeights(self.index, self.value)
def undoIt(self):
if not all(self.data):
return
skinCluster, dag, component, influences, weights = self.data
skinCluster.setWeights(dag, component, influences, weights, 1)
def redoIt(self):
if not self.index or not self.value:
return
self.data = manager.setWeights(self.index, self.value)
# ------------------------------------------------------------------------
def isUndoable(self):
return True
def creatorUpdate():
return OpenMayaMPx.asMPxPtr(SmoothWeightsCtxUpdate())
def syntaxUpdate():
syntax = OpenMaya.MSyntax()
syntax.addArg(OpenMaya.MSyntax.kLong)
syntax.addArg(OpenMaya.MSyntax.kLong)
syntax.addArg(OpenMaya.MSyntax.kDouble)
return syntax
# ----------------------------------------------------------------------------
def initializePlugin( obj ):
plugin = OpenMayaMPx.MFnPlugin(obj, __author__, __version__, "Any")
# get all commands
commands = [
(CONTEXT_INITIALIZE, creatorInitialize, syntaxInitialize),
(CONTEXT_UPDATE, creatorUpdate, syntaxUpdate),
]
# register all commands
for command, creator, syntax in commands:
try:
plugin.registerCommand(command, creator, syntax)
except:
raise RuntimeError("Failed to register : {0}".format(command))
def uninitializePlugin(obj):
plugin = OpenMayaMPx.MFnPlugin(obj)
# get all commands
commands = [
CONTEXT_INITIALIZE,
CONTEXT_UPDATE
]
# unregister all commands
for command in commands:
try:
plugin.deregisterCommand(command)
except:
raise RuntimeError("Failed to unregister : {0}".format(command))
```
#### File: PipelineTools/sample/core.py
```python
try:
from PySide2 import QtWidgets, QtCore, QtGui
except ImportError:
from PySide import QtCore, QtGui
QtWidgets = QtGui
class Ui_InsertBlock(object):
def setupUi(self, InsertBlock):
InsertBlock.setObjectName("InsertBlock")
InsertBlock.resize(400, 107)
self.gridLayout = QtGui.QGridLayout(InsertBlock)
self.gridLayout.setContentsMargins(5, 5, 5, 5)
self.gridLayout.setHorizontalSpacing(0)
self.gridLayout.setVerticalSpacing(2)
self.gridLayout.setObjectName("gridLayout")
self.listWidget = QtGui.QListWidget(InsertBlock)
self.listWidget.setObjectName("listWidget")
self.gridLayout.addWidget(self.listWidget, 1, 0, 1, 2)
self.lineEdit = QtGui.QLineEdit(InsertBlock)
self.lineEdit.setObjectName("lineEdit")
self.gridLayout.addWidget(self.lineEdit, 0, 0, 1, 2)
self.retranslateUi(InsertBlock)
QtCore.QMetaObject.connectSlotsByName(InsertBlock)
InsertBlock.setTabOrder(self.lineEdit, self.listWidget)
return InsertBlock
def retranslateUi(self, InsertBlock):
InsertBlock.setWindowTitle(QtGui.QApplication.translate("InsertBlock", "Insert Block", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == 'main':
app = QtWidgets.QApplication([])
win = Ui_InsertBlock().setupUi(QtWidgets.QMainWindow())
win.show()
app.exec_()
``` |
{
"source": "jonny21099/CryptoNotifier",
"score": 3
} |
#### File: src/coinbase/crypto.py
```python
from datetime import datetime
from coinbase.wallet.client import Client
from colorama import Fore, Back, Style
class Crypto:
def __init__(self, environment):
self.api_key = environment["api_key"]
self.api_secret = environment["api_secret"]
self.currency = environment["currency"]
self.cryptos = environment["cryptos"]
def connect_coinbase(self):
client = Client(self.api_key, self.api_secret)
return client
def get_crypto_data(self, client):
current_price_list = []
total_profit = 0
total_balance = 0
print("Fetching prices...")
print("Retrieval time: {}\n".format(datetime.now()))
for crypto in self.cryptos:
price = client.get_spot_price(currency_pair=crypto + "-" + self.currency)
holding = client.get_account(crypto)
buy_history = client.get_buys(crypto)
sell_history = client.get_sells(crypto)
crypto_profit = self.get_profit(holding, buy_history, sell_history)
message = self.format_log_message(price, holding, crypto_profit)
print(message)
print(Style.RESET_ALL)
current_price_list.append(price['amount'])
total_balance += float(holding.native_balance.amount)
total_profit += crypto_profit
print("Total Balance: ${}".format(total_balance))
if total_profit >= 0:
profit_message = Fore.GREEN + "Total Profit: ${}".format(total_profit)
else:
profit_message = Fore.RED + "Total Profit: ${}".format(total_profit)
print(profit_message)
print(Style.RESET_ALL)
return current_price_list
@staticmethod
def get_profit(holding, buy_history, sell_history):
buy_total = 0
sell_total = 0
crypto_balance = float(holding.native_balance.amount)
for index, purchase in enumerate(buy_history.data):
buy_total += float(purchase.total.amount) if purchase.status == "completed" else 0
for index, sold in enumerate(sell_history.data):
sell_total += float(sold.total.amount) if sold.status == "completed" else 0
return crypto_balance + (sell_total - buy_total)
@staticmethod
def format_log_message(price, holding, crypto_profit):
if crypto_profit >= 0:
profit_message = Fore.GREEN + "Profit: ${}".format(crypto_profit)
else:
profit_message = Fore.RED + "Profit: ${}".format(crypto_profit)
message = "Asset: {}\n".format(price.base) \
+ "Currency: {}\n".format(price.__currency) \
+ "Holding: {}\n".format(holding.balance.amount) \
+ "Price: ${}\n".format(price.amount) \
+ "Balance: ${}\n".format(holding.native_balance.amount) \
+ profit_message
return message
```
#### File: src/coinmarketcap/notification_smtp.py
```python
import smtplib
import datetime
import os
from email.mime.text import MIMEText
from notification_utils import NotificationUtils
class NotificationSMTP:
def __init__(self, current_price_list, environment):
self.__current_price_list = current_price_list
self.__email_sender = environment["email_sender"]
self.__email_sender_password = environment["email_sender_password"]
self.__smtp_server = environment["smtp_server"]
self.__email_receiver = environment["email_receiver"]
self.__cryptos = environment["cryptos"]
self.__buy_notification_value = environment["buy_notification_value"]
self.__sell_notification_value = environment["sell_notification_value"]
self.__notification_cd_timer = environment["notification_cd_timer"]
self.__notification_interval = environment["notification_interval"]
def create_email_connection(self):
try:
server = smtplib.SMTP_SSL(self.__smtp_server, 465)
server.ehlo()
server.login(self.__email_sender, self.__email_sender_password)
return server
except smtplib.SMTPAuthenticationError:
print("Failed to authenticate user.")
def compare_price_and_notify(self):
emails_sent = 0
for i in range(len(self.__current_price_list)):
buy = NotificationUtils.compare_price(self.__current_price_list[i], self.__sell_notification_value[i],
self.__buy_notification_value[i], self.__cryptos[i])
if buy is None:
continue
if self.__notification_cd_timer[i] is None or self.__notification_cd_timer[i] + datetime.timedelta(
hours=self.__notification_interval) <= datetime.datetime.now():
self.send_email(buy, self.__cryptos[i], self.__current_price_list[i])
self.__notification_cd_timer[i] = datetime.datetime.now()
emails_sent += 1
return emails_sent
def send_email(self, buy, crypto, price):
email_css = open(f"{os.getenv('EMAIL_PATH')}/email.css").read()
email_html = open(f"{os.getenv('EMAIL_PATH')}/email.html").read()
if buy:
subject = "[B]Jmartins Crypto Notifier"
body = email_html.format(email_css, crypto, price, "buying")
else:
subject = "[S]Jmartins Crypto Notifier"
body = email_html.format(email_css, crypto, price, "selling")
msg = MIMEText(body, 'html')
msg['Subject'] = subject
try:
server = self.create_email_connection()
server.send_message(msg, self.__email_sender, self.__email_receiver)
server.close()
except smtplib.SMTPRecipientsRefused:
print("All recipients failed to receive email notification.")
```
#### File: CryptoNotifier/tests/test_coinbase_crypto.py
```python
import unittest
from src.coinbase.crypto import Crypto
class TestCoinbaseCrypto(unittest.TestCase):
test_environment = dict()
test_environment["api_key"] = "test_api_key"
test_environment["api_secret"] = "test_api_secret"
test_environment["currency"] = "CAD"
test_environment["cryptos"] = ["XLM"]
def test_crypto_instantiation(self):
crypto_test = Crypto(self.test_environment)
assert(crypto_test.api_key == self.test_environment["api_key"]
and crypto_test.api_secret == self.test_environment["api_secret"])
assert(crypto_test.currency == self.test_environment["currency"]
and crypto_test.cryptos == self.test_environment["cryptos"])
def test_coinbase_connection_success(self):
crypto_test = Crypto(self.test_environment)
crypto_test.connect_coinbase()
def test_coinbase_connection_failure(self):
empty_environment = {"api_key": "", "api_secret": "", "currency": "", "cryptos": ""}
crypto_test = Crypto(empty_environment)
self.assertRaises(ValueError, crypto_test.connect_coinbase)
```
#### File: CryptoNotifier/tests/test_coinbase_notification.py
```python
import unittest
import dotenv
import os
from src.coinbase.notification import Notification
from unittest.mock import MagicMock
dotenv.load_dotenv()
class TestCoinbaseNotification(unittest.TestCase):
test_environment = dict()
price_list = ["4"]
test_environment["email_sender"] = os.getenv("EMAIL_SENDER")
test_environment["email_sender_password"] = os.getenv("EMAIL_SENDER_PASSWORD")
test_environment["smtp_server"] = os.getenv("SMTP_SERVER")
test_environment["email_receiver"] = ["test_receiver"]
test_environment["cryptos"] = ["test_cryptos"]
test_environment["buy_notification_value"] = ["5"]
test_environment["sell_notification_value"] = ["3"]
test_notification = Notification(price_list, test_environment)
def test_notification_instantiation(self):
assert(self.test_notification.current_price_list == self.price_list and
self.test_notification.email_sender == self.test_environment["email_sender"] and
self.test_notification.email_sender_password == self.test_environment["email_sender_password"] and
self.test_notification.smtp_server == self.test_environment["smtp_server"] and
self.test_notification.email_receiver == self.test_environment["email_receiver"] and
self.test_notification.cryptos == self.test_environment["cryptos"] and
self.test_notification.buy_notification_value == self.test_environment["buy_notification_value"] and
self.test_notification.sell_notification_value == self.test_environment["sell_notification_value"])
``` |
{
"source": "jonny21099/DataBase-Email-Search",
"score": 3
} |
#### File: jonny21099/DataBase-Email-Search/phase1.py
```python
import prepDF as df
import sys
import os
def main():
print("The file name is: %s" %(sys.argv[1]))
if sys.argv[1][-4:] != ".xml": #checks that the argument is an xml file
print("File name does not have .xml extension.")
return
inFile = sys.argv[1] #input file is the argument
#calls preparation files to create output files
df.prepTerms(inFile)
df.prepEmails(inFile)
df.prepDates(inFile)
df.prepRecs(inFile)
print("Done outputting")
input("Press Enter to Terminate")
os.system("cls")
main()
```
#### File: jonny21099/DataBase-Email-Search/phase3.py
```python
import query as q
import re
#GLOBALS
keywords = ["subj", "body", "date", "from", "to", "cc", "bcc", "output"] #reserved keywords
def term(condition): #function to match terms in subj/body
match = re.match("((subj|body)\s*:)?\s*([0-9a-zA-Z_-]+)", condition) #regex to match format of subj/body : term, or a single term. With possibility of % for partial matching
#partial = re.split("(?=%)", match.groups()[2]) <----started partial matching but could not finish
#print("partial: %s" %partial)
if match.groups()[2] == None:
return
if match.groups()[1] == "subj": #if keyword is subj, return term and s-term
return ["term", "s-%s" %(match.groups()[2])]
elif match.groups()[1] == "body": #elif keyword is body, return term and b-term
return ["term", "b-%s" %(match.groups()[2])]
elif match.groups()[1] == None: #elif no keyword, return term ,s-term, and b-term. Use '|' to check for OR in query.py
return ["term", "s-%s" %(match.groups()[2]), "|"],["term", "b-%s" %(match.groups()[2]), "|"]
def dates(condition): #function to match date
match = re.match("(date)\s*(<=|<|>|>=|:)\s*(\d{4}/\d{2}/\d{2})$", condition) #regex to match format date '<=' or'<' or '>' or '>=' or ':' xxxx/xx/xx
return [match.groups()[0], match.groups()[2], match.groups()[1]] #return in format [date, xxxx/xx/xx, '<=' or'<' or '>' or '>=' or ':']
def email(condition): #function to match emails in from/to/cc/bcc
match = re.match("(from|to|cc|bcc)\s*:\s*([0-9a-zA-Z_.-]+@[0-9a-zA-Z_.-]+)",condition) #regex to match format from/to/cc/bcc : alphanum@alphanum, allowing periods in the email
if match.groups()[1] in keywords: #if email is a keyword, return
return
if match.groups()[0] == "from": #if keyword is from, return email and from-email
return ["email", "from-%s" %(match.groups()[1])]
elif match.groups()[0] == "to": #if keyword is to, return email and to-email
return ["email", "to-%s" %(match.groups()[1])]
elif match.groups()[0] == "cc": #if keyword is cc, return email and ccemail
return ["email", "cc-%s" %(match.groups()[1])]
elif match.groups()[0] == "bcc": #if keyword is bcc, return email and bcc-email
return ["email", "bcc-%s" %(match.groups()[1])]
def main():
output = "brief" #output mode
while True: #while loop until quit
conditions = [] #list to pass to query.py
outputChange = False #checks if output mode haas changed in the iteration
query = input("\nEnter a query: ").lower() #asks for user input
if query == "" or query == "quit": #if input is blank or "quit", terminate
print("Please enter something.")
return
condition = re.split("(?<=\w)\s+(?=\w)",query) #regex to split up multiple conditions
for each in condition: #for each section of a condition
keyword = re.split("\s*?=<=|<|>|>=|=|:", each) #regex to split keyword and term/email/date
if keyword[0] in keywords[:2]: #if condition is subj or body then call term() and append to conditions
#print("SUBJ/BODY")
conditions.append(term(each))
elif keyword[0] == keywords[2]: #if condition is date then call date() and append to conditions
#print("DATE")
conditions.append(dates(each))
elif keyword[0] in keywords[3:7]: #if condition is from, to, cc, or bcc call email() and append to conditions
#print("EMAIL")
conditions.append(email(each))
elif keyword[0] == keywords[7]: #if input is output=x
#print("OUTPUT")
if output == "brief" and keyword[1] == "full": #if output is brief and x is full, change output mode to full
output = "full"
outputChange = True #outputChange to true
elif output == "full" and keyword[1] == "brief":#if output is full and x is brief, change output mode to brief
output = "brief"
outputChange = True #outputChange to true
break
else: #anything else is considered a term to search in body and subj
#print("random term")
for each2 in term(each): #for each list term() returns (return a list for body and one for subject)
conditions.append(each2) #append to conditions
if not outputChange: #if output mode has not changed in current iteration
q.query(conditions,output) #call query in query.py
main()
```
#### File: jonny21099/DataBase-Email-Search/prepDF.py
```python
import re
#This function writes to terms.txt file
def prepTerms(inFile):
termsFile = open("terms.txt", "w+") #Creates terms.txt with w+ (writing and reading) rights
with open(inFile, 'r') as file: #Opens inFile (xml file passed as argument)
for line in file: #for loop for each line
if line.startswith("<mail>"): #Only take lines starting with <mail>
if line.split("<subj>")[1].split("</subj>")[0] != "": #checks if <subj> content is non-empty
for term in re.split("[^A-Za-z0-9\-_]+", re.sub("&.*?;", " ", line.split("<subj>")[1].split("</subj>")[0])): #splits by all chars except [A-Za-z0-9_-], substitutes all instances of &xxx; with space char, splits by <subj> and </subj> to get contents
if len(term) > 2: #only write to file if the term length is greater than 2
termsFile.write("s-%s:%s\n" %(term.lower(), line.split("<row>")[1].split("</row>")[0])) #write the term and row id
if line.split("<body>")[1].split("</body>") != "": #checks if <body> content is non-empty
for term in re.split("[^A-Za-z0-9\-_]+", re.sub("&.*?;", " ", line.split("<body>")[1].split("</body>")[0])): #splits the same as above for <subj>
if len(term) > 2: #only write term length > 2
termsFile.write("b-%s:%s\n" %(term.lower(), line.split("<row>")[1].split("</row>")[0])) #write the term and row id
#This functions write to emails.txt file
def prepEmails(inFile):
emailsFile = open("emails.txt", "w+") #same as above but for emails.txt
with open(inFile, 'r') as file: #same as above
for line in file: #same as above
if line.startswith("<mail>"): #same as above
emailsFile.write("from-%s:%s\n" %(line.split("<from>")[1].split("</from>")[0],line.split("<row>")[1].split("</row>")[0])) #write <from> contents into file. No condition since will always have from email
if line.split("<to>")[1].split("</to>")[0] != "": #checks if <to> content is non-empty
for email in line.split("<to>")[1].split("</to>")[0].split(","): #for loop to print all emails in <to> split by ','
emailsFile.write("to-%s:%s\n" %(email,line.split("<row>")[1].split("</row>")[0])) #writes <to> contents and row id to file
if line.split("<cc>")[1].split("</cc>")[0] != "": #checks if <cc> content is non-empty
for email in line.split("<cc>")[1].split("</cc>")[0].split(","): #for loop to print all emails in <cc> split by ','
emailsFile.write("cc-%s:%s\n" %(email,line.split("<row>")[1].split("</row>")[0])) #writes <cc> contents and row id to file
if line.split("<bcc>")[1].split("</bcc>")[0] != "": #checks if <bcc> content is non-empty
for email in line.split("<bcc>")[1].split("</bcc>")[0].split(","): #for loop to print all emails in <bcc> split by ','
emailsFile.write("bcc-%s:%s\n" %(email,line.split("<row>")[1].split("</row>")[0])) #writes <bcc> contents and row id to file
def prepDates(inFile):
datesFile = open("dates.txt", "w+") #same as above but for dates.txt
with open(inFile, 'r') as file: #same as above
for line in file: #same as above
if line.startswith("<mail>"): #same as above
datesFile.write("%s:%s\n" %(line.split("<date>")[1].split("</date>")[0],line.split("<row>")[1].split("</row>")[0])) #writes <date> content and row id
def prepRecs(inFile):
recsFile = open("recs.txt", "w+") #same as above but for recs.txt
with open(inFile, 'r') as file: #same as above
for line in file: #same as above
if line.startswith("<mail>"): #same as above
recsFile.write("%s:%s" %(line.split("<row>")[1].split("</row>")[0], line)) #writes row id and full line
```
#### File: jonny21099/DataBase-Email-Search/query.py
```python
from bsddb3 import db
import re
def RowID(result): #returns a list with all the row IDs that matches the query.
if(result[0] == "term"):
DB_File = "te.idx"
elif(result[0] == "email"):
DB_File = "em.idx"
elif(result[0] == "date"):
DB_File = "da.idx"
elif(result[0] == "rec"):
DB_File = "re.idx"
else:
print("Somethings wrong with the first part of the elements in the list")
return
database = db.DB()
database.set_flags(db.DB_DUP) #declare duplicates allowed before you create the database
database.open(DB_File,None,db.DB_BTREE,db.DB_CREATE)
curs = database.cursor()
list = []
if (len(result)==3): #this check checks whether or not it contains an operator at the end.
if (result[2] == "<"): #If it contains < I perform my code to find all dates <
find = curs.set_range(result[1].encode("utf-8"))
find = curs.prev()
if (errorCheck(find) == 1): return
row = str(find[1].decode("utf-8"))
list.append(row)
while(find != None):
find = curs.prev()
if (find != None):
row = str(find[1].decode("utf-8"))
list.append(row)
else:
return(list)
elif (result[2] == ">"): #if it contains > I perform my code to find all dates >
find = curs.set_range(result[1].encode("utf-8"))
if (errorCheck(find) == 1): return #this is for putting a hugge number
value = str(find[0].decode("utf-8"))
if (value > result[1]):
#just do everything greater than value
row = str(find[1].decode("utf-8"))
list.append(row)
while(find != None):
find = curs.next()
if (find != None):
row = str(find[1].decode("utf-8"))
list.append(row)
else:
return(list)
elif (value == result[1]):
temp = curs.next_dup()
while (temp != None):
find = temp
temp = curs.next_dup()
find = curs.next()
row = str(find[1].decode("utf-8"))
list.append(row)
while(find != None):
find = curs.next()
if (find != None):
row = str(find[1].decode("utf-8"))
list.append(row)
else:
return(list)
#gotta go to the last duplicate item
elif (result[2] == "<="):
find = curs.set_range(result[1].encode("utf-8"))
if (errorCheck(find) == 1):
find = curs.prev()
while(find != None):
row = str(find[1].decode("utf-8"))
list.append(row)
find = curs.prev()
return(list)
value = str(find[0].decode("utf-8"))
temp = curs.prev()
if (value > result[1] and temp != None):
find = temp
elif (value > result[1] and temp == None):
return
curs.next()
temp2 = curs.next_dup()
while (temp2 != None):
if (value == result[1]):
find = temp2
temp2 = curs.next_dup()
row = str(find[1].decode("utf-8"))
list.append(row)
while(find != None):
find = curs.prev()
if (find != None):
row = str(find[1].decode("utf-8"))
list.append(row)
else:
return(list)
elif (result[2] == ">="):
find = curs.set_range(result[1].encode("utf-8"))
if (errorCheck(find) == 1): return
row = str(find[1].decode("utf-8"))
list.append(row)
while(find != None):
find = curs.next()
if (find != None):
row = str(find[1].decode("utf-8"))
list.append(row)
else:
return(list)
if (len(result) == 2 or result[2] == ":" or result[2] == "|"): #If it doesnt contains one of the <,>,<=,>= operator come here
find = curs.set(result[1].encode("utf-8"))
if (errorCheck(find) == 1): return
row = str(find[1].decode("utf-8"))
list.append(row)
while(find != None):
find = curs.next_dup()
if (find != None):
row = str(find[1].decode("utf-8"))
list.append(row)
else:
return(list)
def errorCheck(find):
if (find == None):
return 1
def query(conditions, output):
result = conditions #this is what kevin passes me
Data_index = 0 #this is the index for my database
LengthDI = len(result) #this is the length of the things inside result
check = RowID(result[Data_index])
final_list = []
final = check
if (check == None and result[0][-1] != "|" ):
print("Nothing was found.")
return
while (Data_index < LengthDI): #in this while loop I perform and or checks with rowIDs
if (result[Data_index][-1] == "|"):
temp = RowID(result[Data_index])
if (temp == None):
temp = []
Data_index += 1
temp2 = RowID(result[Data_index])
if (temp2 == None):
temp2 = []
final_list.append(set(temp)|set(temp2))
final = final_list[0]
for each in final_list:
final = set(final) & each
if not final:
print("Nothing was found")
return
Data_index += 1
else:
temp = RowID(result[Data_index])
if (temp == None):
print("Nothing was found.")
return
final = set(temp) & set(final)
if not final:
print("Nothing was found")
return
Data_index += 1
database = db.DB()
DB_File = "re.idx"
database.open(DB_File,None,db.DB_HASH,db.DB_CREATE)
curs = database.cursor()
#Here is the output
if (output == "brief"):
for each in final:
output = curs.set(each.encode("utf-8"))
print("Row ID: %s\n\tSubject: %s" %(str(output[0].decode("utf-8")), output[1].decode("utf-8").split("<subj>")[1].split("</subj>")[0]))
elif (output == "full"):
for each in final:
output = curs.set(each.encode("utf-8"))
record = str(output[1].decode("utf-8")).split("><")
print("Row ID: %s" %(str(output[0].decode("utf-8"))))
for i in range(len(record)):
print("\t%s" %(str(record[i])))
``` |
{
"source": "jonny21099/path-find",
"score": 3
} |
#### File: src/GUI/path_find_GUI.py
```python
import kivy
kivy.require('1.11.1')
import sqlite3
from kivy.config import Config
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
#connects to the sqlite3 database stored as users.db in the local storage
conn = sqlite3.connect("users.db")
c = conn.cursor()
#window is not sizable, everything is fixed size
Config.set("graphics", "resizable", False)
#this will be the screen that deals with path finding interactions
class MainActivity(Screen):
pass
#window manager deals with the transitino between the two screens
class WindowManager(ScreenManager):
pass
#using two different screens, the login screen and the mainactivity
class LoginScreen(Screen):
username = ObjectProperty(None)
password = ObjectProperty(None)
#register button, handles all checks for database error
def RegisterBtn(self):
c.execute("SELECT * FROM users WHERE username = ?",(self.username.text,))
regcheck = c.fetchall()
if (len(regcheck) == 0):
c.execute("INSERT INTO users VALUES (?, ?)",(self.username.text, self.password.text))
conn.commit()
prompt = "Success"
message = "Successfully registered!"
else:
prompt = "Failed"
message = "Username already exists!"
#create content for the popup
registerErrorPopup = BoxLayout(orientation="vertical")
label = Label(text = message)
registerErrorPopup.add_widget(label)
popupWindow = Popup(title = prompt, content = registerErrorPopup, size_hint = (None, None), size = (400, 150), auto_dismiss = False)
registerErrorPopup.add_widget(Button(text="ok", on_press = popupWindow.dismiss, size_hint = (0.2, 0.4), pos_hint = {"center_x": 0.5,"y": 0.1}))
popupWindow.open()
#login button, handles all chekcs for database error
def LoginBtn(self):
c.execute("SELECT * FROM users WHERE username = ?", (self.username.text,))
logincheck = c.fetchall()
#check if username exists
if(len(logincheck) == 0):
prompt = "Error"
loginErrorPopup = BoxLayout(orientation = "vertical")
label = Label(text = "This account is not registered!")
loginErrorPopup.add_widget(label)
popupWindow = Popup(title = prompt, content = loginErrorPopup, size_hint = (None, None), size = (400, 150), auto_dismiss = False)
loginErrorPopup.add_widget(Button(text="ok", on_press = popupWindow.dismiss, size_hint = (0.2, 0.4), pos_hint = {"center_x": 0.5,"y": 0.1}))
popupWindow.open()
#check if password is correct
elif(len(logincheck) == 1 and logincheck[0][1] != self.password.text):
prompt = "Error"
loginErrorPopup = BoxLayout(orientation = "vertical")
label = Label(text = "The username or password is incorrect!")
popupWindow = Popup(title = prompt, content = loginErrorPopup, size_hint = (None, None), size = (400, 150), auto_dismiss = False)
loginErrorPopup.add_widget(Button(text="ok", on_press = popupWindow.dismiss, size_hint = (0.2, 0.4), pos_hint = {"center_x": 0.5,"y": 0.1}))
popupWindow.open()
#if all checks are satisfied switch into the mainactivity
else:
self.manager.current = "path_finding_interaction"
#loading in the pathfind.kv file
interface = Builder.load_file("pathfind.kv")
class PathFinder(App):
def build(self):
return interface
if __name__ == '__main__':
PathFinder().run()
```
#### File: path-find/src/process_input.py
```python
from src.utilities.algorithms.bfs import run_bfs
from src.utilities.algorithms.a_star import run_a_star
def driver(array):
# TODO: Check errors
grid = Grid(array)
arr = run_a_star(grid)
print(arr)
class Grid():
def __init__(self, array):
self.grid = array
self.height = len(array) - 1
self.width = len(array[0]) - 1
self.start = ()
self.end = ()
self.walls = []
self.path = []
self.analyze_grid()
def analyze_grid(self):
for i, row in enumerate(self.grid):
for j, column in enumerate(row):
if column == 1:
self.start = (i, j)
elif column == 2:
self.end = (i, j)
self.path.append((i,j))
elif column == 0:
self.path.append((i,j))
elif column == 3:
self.walls.append((i,j))
```
#### File: utilities/algorithms/a_star.py
```python
import time
class Cell():
def __init__(self, parent, coords):
self.parent = parent
self.location = coords
self.g = 0
self.h = 0
self.f = 0
def __str__(self):
return "%s" % (self.location,)
def __repr__(self):
return "%s" % (self.location,)
def __eq__(self, other):
return self.location == other.location
def run_a_star(grid):
open_list = []
closed_list = []
solution = []
start_cell = Cell(None, grid.start)
open_list.append(start_cell)
while len(open_list) > 0:
current_cell = open_list[0]
for cell in open_list:
if cell.f < current_cell.f:
current_cell = cell
# print(len(open_list))
open_list.remove(current_cell)
# print(len(open_list))
closed_list.append(current_cell)
if current_cell.location == grid.end:
current = current_cell
while current is not None:
solution.append(current.location)
current = current.parent
return solution[::-1]
children = []
for adjacent_cell in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]:
cell_location = (current_cell.location[0] + adjacent_cell[0],
current_cell.location[1] + adjacent_cell[1])
if cell_location[0] > grid.height or cell_location[0] < 0 or cell_location[1] > grid.width or cell_location[1] < 0 or cell_location in grid.walls:
continue
new_cell = Cell(current_cell, cell_location)
children.append(new_cell)
for child in children:
for closed in closed_list:
if child == closed:
continue
child.g = current_cell.g + 1
# Using Manhattan distance as our Heuristic
child.h = ((child.location[0] - grid.end[0])) ** 2 + ((child.location[1] - grid.end[1])) ** 2
child.f = child.g + child.h
for open_cell in open_list:
if child == open_cell and child.g > open_cell.g:
continue
# if not any(x.location == child.location for x in ):
open_list.append(child)
# time.sleep(.7)
# print(open_list)
```
#### File: src/utilities/error_definitions.py
```python
class Error(Exception):
# Base class for other exceptions
pass
class Size_Error(Error):
# Raised when the size of the array is too large or small
def __init__(self, size):
print("Error: %s is an incompatible size" % size)
``` |
{
"source": "jonny21099/PianoStudioManager",
"score": 3
} |
#### File: jonny21099/PianoStudioManager/main.py
```python
from PianoProgram.Login import Login
from PianoProgram.Calendar import Calendar
from PianoProgram.Update import Update_information
import os
import time
import sqlite3
#Main Interface
def main():
print("Welcome to PianoProgram")
Login()
conn = sqlite3.connect("teaching.db")
c = conn.cursor()
Update_information(c, conn)
time.sleep(1)
os.system("clear")
Calendar(c, conn)
if __name__ == '__main__':
main()
```
#### File: PianoStudioManager/PianoProgram/Calendar.py
```python
import os
import sys
import time
from PianoProgram.Add_student import Add_student
from PianoProgram.View_unpaid import View_unpaid
from PianoProgram.Update import Update_information
def Calendar(c, conn):
user_option = input("What would you like to do?\n1.View all unpaid lessons\n2.Add new student\n3.Quit\n")
#View all unpaid lessons
if user_option == "1":
time.sleep(0.4)
os.system("clear")
result = View_unpaid(c, conn)
if result == "1":
#Make a payment
student = input("\nWhich student would you like to update payment information for?\n")
c.execute("SELECT total_lessons FROM calendar WHERE student_name = ?", (student,))
database_result = c.fetchall()
if len(database_result) == 0:
print("This student doesn't exist.\n")
elif len(database_result) == 1:
amount = input("\nHow many lessons have been paid?\n")
c.execute("UPDATE calendar set total_lessons = total_lessons - ?, total_price = total_price - (lesson_price * ?) WHERE student_name = ?", (amount, amount, student))
conn.commit()
elif result == "2":
#go back
pass
elif result == "3":
#quit
sys.exit(0)
time.sleep(0.4)
os.system("clear")
#Add new students
elif user_option == "2":
time.sleep(0.4)
os.system("clear")
Add_student(c, conn)
time.sleep(0.4)
os.system("clear")
#quit
elif user_option == "3":
sys.exit(0)
#Invalid entry
else:
print("\nPlease enter a valid input")
time.sleep(0.4)
os.system("clear")
Calendar(c, conn)
``` |
{
"source": "jonny21099/TwitterBot",
"score": 3
} |
#### File: src/TwitterBot/markov_tweet.py
```python
import numpy as np
import tweepy #update_status
import random
def generateWordDict(api):
#Created a nested dictionary with the 1st Key = a word second key = possible words that come after and value = counter
#Create a dictionary for every word encountered with the number of times that word occurs as its value
with open("../../docs/markovChain.txt", 'r', encoding="utf-8") as f:
#words_dic contains a dictionary with the following format
#{word:{nextword:appearances, anotherwordthatcomesafter:appearances}}
words_dic = {}
words_occurences = {}
words_list = []
for line in f:
line = line.replace("\n"," \n")
words = line.split(" ")
words_list.append(words)
for index, word in enumerate(words):
#Check if new word or not and add to occurences accordingly
if (word in words_occurences):
words_occurences[word] += 1
else:
words_occurences[word] = 1
temp_kv_dic = {}
#if we encounter a new line, move on to next line
if word == "\n":
break
#check if a word exists in the dictionary, if not intialize with the {currentword: {the next word:1}}
elif word not in words_dic:
temp_kv_dic.update({words[index+1]:1})
words_dic.update({word:temp_kv_dic})
#if word is in dictionary, check if the following word is a key, if not intialize it, if it is update value
elif word in words_dic:
if words[index+1] in words_dic[word]:
words_dic[word][words[index+1]] += 1
else:
temp_kv_dic.update({words[index+1]:1})
words_dic[word].update(temp_kv_dic)
#Normalize all potential next words so we can use the values as probabilities
#The number of times we see a word is equal to the sum of all ooccurences of its next words
#EG. "the fox is doing the dance" -> {the: {fox:1,dance:1},fox:{is:1},is:...}
#We see "the" twice which is equal to [fox] + [dance] = 2
for word in words_dic:
for next_word in words_dic[word]:
words_dic[word][next_word] = words_dic[word][next_word]/words_occurences[word]
api.update_status(generateSentence(words_dic,words_list))
def generateSentence(words_dic, words_list):
line = []
while (len(line) <= 2):
#Choose random line
line = random.choice(words_list)
#Take first word of that line
start = line[0]
#Get next word possibilities of word
next_words = words_dic[start]
sentence = start
next_word = ""
#End the line after \n is encountered
while (next_word != '\n'):
next_word = random.choice(list(next_words))
if (next_word == '\n'):
break
next_words = words_dic[next_word]
sentence = sentence + " " + next_word
return sentence
``` |
{
"source": "jonny5532/wagtail-liveedit",
"score": 2
} |
#### File: liveedit/templatetags/liveedit.py
```python
from django import template
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.templatetags.static import static
from django.urls import reverse
from django.utils.html import format_html
from django.utils.module_loading import import_string
from wagtail.admin.views.pages.preview import PreviewOnEdit
from wagtail.core.models import Page, PageRevision
import json
# monkey-patch PageRevision.as_page_object to store revision id on pages
original_as_page_object = PageRevision.as_page_object
def as_page_object(self, *args, **kwargs):
page = original_as_page_object(self, *args, **kwargs)
page._live_edit_revision_id = self.id
return page
PageRevision.as_page_object = as_page_object
# monkey-patch PreviewOnEdit.get_page so we can tell if we're looking at a unsaved preview
original_get_page = PreviewOnEdit.get_page
def get_page(self, *args, **kwargs):
page = original_get_page(self, *args, **kwargs)
page._live_edit_is_preview = True
return page
PreviewOnEdit.get_page = get_page
register = template.Library()
is_enabled = import_string(getattr(settings, 'LIVEEDIT_ENABLED_CHECK', 'liveedit.utils.is_enabled'))
def is_authenticated(request):
if request and request.user and request.user.is_authenticated:
return True
return False
@register.simple_tag(takes_context=True)
def liveedit_css(context):
request = context.get('request')
if not is_enabled(request) or not is_authenticated(request):
return ''
return format_html(
'<link rel="stylesheet" type="text/css" href="{}">',
static('css/liveedit.css')
)
@register.simple_tag(takes_context=True)
def liveedit_js(context):
request = context.get('request')
if not is_enabled(request) or not is_authenticated(request):
return ''
return format_html(
'<script type="text/javascript" src="{}"></script>',
static('js/liveedit.js')
)
@register.simple_tag(takes_context=True)
def liveedit_attributes(context):
if 'liveedit_data' not in context:
return ''
return format_html('data-liveedit="{}"',
json.dumps(context['liveedit_data'])
)
@register.simple_tag(takes_context=True)
def liveedit_include_block(context, block, object=None, field=None):
context = context.flatten()
request = context.get('request')
def finish():
return block.render_as_block(context)
if not is_enabled(request) or not is_authenticated(request):
return finish()
if object and isinstance(object, Page):
perms = object.permissions_for_user(request.user)
if not perms.can_edit():
return finish()
data = {
**(context.get('liveedit_data') or {}),
'id':block.id,
'block_type': block.block_type
}
if object and field:
if isinstance(object, Page):
if object.has_unpublished_changes:
# There is a new unpublished version of this page, are we looking at it?
cur_rev_id = getattr(object, '_live_edit_revision_id', None)
latest_rev_id = object.get_latest_revision().id
if cur_rev_id!=latest_rev_id:
# We're not, so don't allow live editing, but send a link to the latest revision.
return finish() + format_html("<script>window._live_edit_draft_url='{}';</script>",
reverse('wagtailadmin_pages:revisions_view', args=(object.id, latest_rev_id))
)
if getattr(object, '_live_edit_is_preview', False):
# We're viewing an unsaved preview, don't allow editing
return finish()
elif getattr(request, 'is_dummy', False):
# We are in preview mode, without a unpublished revision, don't allow editing
return finish()
data.update({
'content_type_id': ContentType.objects.get_for_model(object).id,
'object_id': object.id,
'object_field': field
})
context['liveedit_data'] = data
return finish()
``` |
{
"source": "jonny5532/wsgo",
"score": 2
} |
#### File: wsgo/tests/wsgi_app.py
```python
import hashlib
import time
import threading
thread_local = threading.local()
def application(environ, start_response):
h = hashlib.md5()
if environ['REQUEST_METHOD']=='POST':
n = 0
while True:
to_read = 4096
data = environ['wsgi.input'].read(to_read)
h.update(data)
n += len(data)
if len(data)<to_read:
break
assert n>0
if environ['PATH_INFO']=='/wait/':
time.sleep(1)
print("calling start_response")
start_response('200 OK', [
('Content-Type','text/html'),
('Set-Cookie','cookie1=cookievalue1'),
('Set-Cookie','cookie2=cookievalue2'),
('Set-Cookie','cookie3=cookievalue3'),
])
if environ['PATH_INFO']=='/output/':
def ret():
thread_local.name = threading.current_thread().name
for i in range(100):
yield b'hello'*1000000
#print('checking name', thread_local.name, threading.current_thread().name)
assert thread_local.name == threading.current_thread().name
return ret()
return [h.hexdigest().encode('utf-8')]
``` |
{
"source": "jonny9066/MP-SPDZ",
"score": 3
} |
#### File: MP-SPDZ/Compiler/comparison.py
```python
const_rounds = False
# Set use_inv to use preprocessed inverse tuples for more efficient
# online phase comparisons.
use_inv = True
# If do_precomp is not set, use_inv uses standard inverse tuples, otherwise if
# both are set, use a list of "special" tuples of the form
# (r[i], r[i]^-1, r[i] * r[i-1]^-1)
do_precomp = True
from . import instructions_base
from . import util
def set_variant(options):
""" Set flags based on the command-line option provided """
global const_rounds, do_precomp, use_inv
variant = options.comparison
if variant == 'log':
const_rounds = False
elif variant == 'plain':
const_rounds = True
use_inv = False
elif variant == 'inv':
const_rounds = True
use_inv = True
do_precomp = True
elif variant == 'sinv':
const_rounds = True
use_inv = True
do_precomp = False
elif variant is not None:
raise CompilerError('Unknown comparison variant: %s' % variant)
def ld2i(c, n):
""" Load immediate 2^n into clear GF(p) register c """
t1 = program.curr_block.new_reg('c')
ldi(t1, 2 ** (n % 30))
for i in range(n // 30):
t2 = program.curr_block.new_reg('c')
mulci(t2, t1, 2 ** 30)
t1 = t2
movc(c, t1)
inverse_of_two = {}
def divide_by_two(res, x, m=1):
""" Faster clear division by two using a cached value of 2^-1 mod p """
tmp = program.curr_block.new_reg('c')
inv2m(tmp, m)
mulc(res, x, tmp)
def require_ring_size(k, op):
if int(program.options.ring) < k:
raise CompilerError('ring size too small for %s, compile '
'with \'-R %d\' or more' % (op, k))
@instructions_base.cisc
def LTZ(s, a, k, kappa):
"""
s = (a ?< 0)
k: bit length of a
"""
from .types import sint, _bitint
from .GC.types import sbitvec
if program.use_split():
summands = a.split_to_two_summands(k)
carry = CarryOutRawLE(*reversed(list(x[:-1] for x in summands)))
msb = carry ^ summands[0][-1] ^ summands[1][-1]
movs(s, sint.conv(msb))
return
elif program.options.ring:
from . import floatingpoint
require_ring_size(k, 'comparison')
m = k - 1
shift = int(program.options.ring) - k
r_prime, r_bin = MaskingBitsInRing(k)
tmp = a - r_prime
c_prime = (tmp << shift).reveal() >> shift
a = r_bin[0].bit_decompose_clear(c_prime, m)
b = r_bin[:m]
u = CarryOutRaw(a[::-1], b[::-1])
movs(s, sint.conv(r_bin[m].bit_xor(c_prime >> m).bit_xor(u)))
return
t = sint()
Trunc(t, a, k, k - 1, kappa, True)
subsfi(s, t, 0)
def LessThanZero(a, k, kappa):
from . import types
res = types.sint()
LTZ(res, a, k, kappa)
return res
@instructions_base.cisc
def Trunc(d, a, k, m, kappa, signed):
"""
d = a >> m
k: bit length of a
m: compile-time integer
signed: True/False, describes a
"""
t = program.curr_block.new_reg('s')
c = [program.curr_block.new_reg('c') for i in range(3)]
c2m = program.curr_block.new_reg('c')
if m == 0:
movs(d, a)
return
elif program.options.ring:
return TruncRing(d, a, k, m, signed)
else:
a_prime = program.non_linear.mod2m(a, k, m, signed)
subs(t, a, a_prime)
ldi(c[1], 1)
divide_by_two(c[2], c[1], m)
mulm(d, t, c[2])
def TruncRing(d, a, k, m, signed):
program.curr_tape.require_bit_length(1)
if program.use_split() in (2, 3):
if signed:
a += (1 << (k - 1))
from Compiler.types import sint
from .GC.types import sbitint
length = int(program.options.ring)
summands = a.split_to_n_summands(length, program.use_split())
x = sbitint.wallace_tree_without_finish(summands, True)
if program.use_split() == 2:
carries = sbitint.get_carries(*x)
low = carries[m]
high = sint.conv(carries[length])
else:
if m == 1:
low = x[1][1]
high = sint.conv(CarryOutLE(x[1][:-1], x[0][:-1])) + \
sint.conv(x[0][-1])
else:
mid_carry = CarryOutRawLE(x[1][:m], x[0][:m])
low = sint.conv(mid_carry) + sint.conv(x[0][m])
tmp = util.tree_reduce(carry, (sbitint.half_adder(xx, yy)
for xx, yy in zip(x[1][m:-1],
x[0][m:-1])))
top_carry = sint.conv(carry([None, mid_carry], tmp, False)[1])
high = top_carry + sint.conv(x[0][-1])
shifted = sint()
shrsi(shifted, a, m)
res = shifted + sint.conv(low) - (high << (length - m))
if signed:
res -= (1 << (k - m - 1))
else:
a_prime = Mod2mRing(None, a, k, m, signed)
a -= a_prime
res = TruncLeakyInRing(a, k, m, signed)
if d is not None:
movs(d, res)
return res
def TruncZeros(a, k, m, signed):
if program.options.ring:
return TruncLeakyInRing(a, k, m, signed)
else:
from . import types
tmp = types.cint()
inv2m(tmp, m)
return a * tmp
def TruncLeakyInRing(a, k, m, signed):
"""
Returns a >> m.
Requires a < 2^k and leaks a % 2^m (needs to be constant or random).
"""
assert k > m
assert int(program.options.ring) >= k
from .types import sint, intbitint, cint, cgf2n
n_bits = k - m
n_shift = int(program.options.ring) - n_bits
if n_bits > 1:
r, r_bits = MaskingBitsInRing(n_bits, True)
else:
r_bits = [sint.get_random_bit() for i in range(n_bits)]
r = sint.bit_compose(r_bits)
if signed:
a += (1 << (k - 1))
shifted = ((a << (n_shift - m)) + (r << n_shift)).reveal()
masked = shifted >> n_shift
u = sint()
BitLTL(u, masked, r_bits[:n_bits], 0)
res = (u << n_bits) + masked - r
if signed:
res -= (1 << (n_bits - 1))
return res
def TruncRoundNearest(a, k, m, kappa, signed=False):
"""
Returns a / 2^m, rounded to the nearest integer.
k: bit length of a
m: compile-time integer
"""
if m == 0:
return a
nl = program.non_linear
nl.check_security(kappa)
return program.non_linear.trunc_round_nearest(a, k, m, signed)
@instructions_base.cisc
def Mod2m(a_prime, a, k, m, kappa, signed):
"""
a_prime = a % 2^m
k: bit length of a
m: compile-time integer
signed: True/False, describes a
"""
nl = program.non_linear
nl.check_security(kappa)
movs(a_prime, program.non_linear.mod2m(a, k, m, signed))
def Mod2mRing(a_prime, a, k, m, signed):
assert(int(program.options.ring) >= k)
from Compiler.types import sint, intbitint, cint
shift = int(program.options.ring) - m
r_prime, r_bin = MaskingBitsInRing(m, True)
tmp = a + r_prime
c_prime = (tmp << shift).reveal() >> shift
u = sint()
BitLTL(u, c_prime, r_bin[:m], 0)
res = (u << m) + c_prime - r_prime
if a_prime is not None:
movs(a_prime, res)
return res
def Mod2mField(a_prime, a, k, m, kappa, signed):
from .types import sint
r_dprime = program.curr_block.new_reg('s')
r_prime = program.curr_block.new_reg('s')
r = [sint() for i in range(m)]
c = program.curr_block.new_reg('c')
c_prime = program.curr_block.new_reg('c')
v = program.curr_block.new_reg('s')
u = program.curr_block.new_reg('s')
t = [program.curr_block.new_reg('s') for i in range(6)]
c2m = program.curr_block.new_reg('c')
c2k1 = program.curr_block.new_reg('c')
PRandM(r_dprime, r_prime, r, k, m, kappa)
ld2i(c2m, m)
mulm(t[0], r_dprime, c2m)
if signed:
ld2i(c2k1, k - 1)
addm(t[1], a, c2k1)
else:
t[1] = a
adds(t[2], t[0], t[1])
adds(t[3], t[2], r_prime)
asm_open(c, t[3])
modc(c_prime, c, c2m)
if const_rounds:
BitLTC1(u, c_prime, r, kappa)
else:
BitLTL(u, c_prime, r, kappa)
mulm(t[4], u, c2m)
submr(t[5], c_prime, r_prime)
adds(a_prime, t[5], t[4])
return r_dprime, r_prime, c, c_prime, u, t, c2k1
def MaskingBitsInRing(m, strict=False):
program.curr_tape.require_bit_length(1)
from Compiler.types import sint
if program.use_edabit():
return sint.get_edabit(m, strict)
elif program.use_dabit:
r, r_bin = zip(*(sint.get_dabit() for i in range(m)))
else:
r = [sint.get_random_bit() for i in range(m)]
r_bin = r
return sint.bit_compose(r), r_bin
def PRandM(r_dprime, r_prime, b, k, m, kappa, use_dabit=True):
"""
r_dprime = random secret integer in range [0, 2^(k + kappa - m) - 1]
r_prime = random secret integer in range [0, 2^m - 1]
b = array containing bits of r_prime
"""
program.curr_tape.require_bit_length(k + kappa)
from .types import sint
if program.use_edabit() and m > 1 and not const_rounds:
movs(r_dprime, sint.get_edabit(k + kappa - m, True)[0])
tmp, b[:] = sint.get_edabit(m, True)
movs(r_prime, tmp)
return
t = [[program.curr_block.new_reg('s') for j in range(2)] for i in range(m)]
t[0][1] = b[-1]
PRandInt(r_dprime, k + kappa - m)
# r_dprime is always multiplied by 2^m
if use_dabit and program.use_dabit and m > 1 and not const_rounds:
r, b[:] = zip(*(sint.get_dabit() for i in range(m)))
r = sint.bit_compose(r)
movs(r_prime, r)
return
bit(b[-1])
for i in range(1,m):
adds(t[i][0], t[i-1][1], t[i-1][1])
bit(b[-i-1])
adds(t[i][1], t[i][0], b[-i-1])
movs(r_prime, t[m-1][1])
def PRandInt(r, k):
"""
r = random secret integer in range [0, 2^k - 1]
"""
t = [[program.curr_block.new_reg('s') for i in range(k)] for j in range(3)]
t[2][k-1] = r
bit(t[2][0])
for i in range(1,k):
adds(t[0][i], t[2][i-1], t[2][i-1])
bit(t[1][i])
adds(t[2][i], t[0][i], t[1][i])
def BitLTC1(u, a, b, kappa):
"""
u = a <? b
a: array of clear bits
b: array of secret bits (same length as a)
"""
k = len(b)
p = [program.curr_block.new_reg('s') for i in range(k)]
from . import floatingpoint
a_bits = floatingpoint.bits(a, k)
if instructions_base.get_global_vector_size() == 1:
a_ = a_bits
a_bits = program.curr_block.new_reg('c', size=k)
b_vec = program.curr_block.new_reg('s', size=k)
for i in range(k):
movc(a_bits[i], a_[i])
movs(b_vec[i], b[i])
d = program.curr_block.new_reg('s', size=k)
s = program.curr_block.new_reg('s', size=k)
t = [program.curr_block.new_reg('s', size=k) for j in range(5)]
c = [program.curr_block.new_reg('c', size=k) for j in range(4)]
else:
d = [program.curr_block.new_reg('s') for i in range(k)]
s = [program.curr_block.new_reg('s') for i in range(k)]
t = [[program.curr_block.new_reg('s') for i in range(k)] for j in range(5)]
c = [[program.curr_block.new_reg('c') for i in range(k)] for j in range(4)]
if instructions_base.get_global_vector_size() == 1:
vmulci(k, c[2], a_bits, 2)
vmulm(k, t[0], b_vec, c[2])
vaddm(k, t[1], b_vec, a_bits)
vsubs(k, d, t[1], t[0])
vaddsi(k, t[2], d, 1)
t[2].create_vector_elements()
pre_input = t[2].vector[:]
else:
for i in range(k):
mulci(c[2][i], a_bits[i], 2)
mulm(t[0][i], b[i], c[2][i])
addm(t[1][i], b[i], a_bits[i])
subs(d[i], t[1][i], t[0][i])
addsi(t[2][i], d[i], 1)
pre_input = t[2][:]
pre_input.reverse()
if use_inv:
if instructions_base.get_global_vector_size() == 1:
PreMulC_with_inverses_and_vectors(p, pre_input)
else:
if do_precomp:
PreMulC_with_inverses(p, pre_input)
else:
raise NotImplementedError('Vectors not compatible with -c sinv')
else:
PreMulC_without_inverses(p, pre_input)
p.reverse()
for i in range(k-1):
subs(s[i], p[i], p[i+1])
subsi(s[k-1], p[k-1], 1)
subcfi(c[3][0], a_bits[0], 1)
mulm(t[4][0], s[0], c[3][0])
from .types import sint
t[3] = [sint() for i in range(k)]
for i in range(1,k):
subcfi(c[3][i], a_bits[i], 1)
mulm(t[3][i], s[i], c[3][i])
adds(t[4][i], t[4][i-1], t[3][i])
Mod2(u, t[4][k-1], k, kappa, False)
return p, a_bits, d, s, t, c, b, pre_input
def carry(b, a, compute_p=True):
""" Carry propogation:
return (p,g) = (p_2, g_2)o(p_1, g_1) -> (p_1 & p_2, g_2 | (p_2 & g_1))
"""
if a is None:
return b
if b is None:
return a
t = [program.curr_block.new_reg('s') for i in range(3)]
if compute_p:
t[0] = a[0].bit_and(b[0])
t[2] = a[0].bit_and(b[1]) + a[1]
return t[0], t[2]
# from WP9 report
# length of a is even
def CarryOutAux(a, kappa):
k = len(a)
if k > 1 and k % 2 == 1:
a.append(None)
k += 1
u = [None]*(k//2)
a = a[::-1]
if k > 1:
for i in range(k//2):
u[i] = carry(a[2*i+1], a[2*i], i != k//2-1)
return CarryOutAux(u[:k//2][::-1], kappa)
else:
return a[0][1]
# carry out with carry-in bit c
def CarryOut(res, a, b, c=0, kappa=None):
"""
res = last carry bit in addition of a and b
a: array of clear bits
b: array of secret bits (same length as a)
c: initial carry-in bit
"""
from .types import sint
movs(res, sint.conv(CarryOutRaw(a, b, c)))
def CarryOutRaw(a, b, c=0):
assert len(a) == len(b)
k = len(a)
from . import types
if program.linear_rounds():
carry = 0
for (ai, bi) in zip(a, b):
carry = bi.carry_out(ai, carry)
return carry
d = [program.curr_block.new_reg('s') for i in range(k)]
s = [program.curr_block.new_reg('s') for i in range(3)]
for i in range(k):
d[i] = list(b[i].half_adder(a[i]))
s[0] = d[-1][0].bit_and(c)
s[1] = d[-1][1] + s[0]
d[-1][1] = s[1]
return CarryOutAux(d[::-1], None)
def CarryOutRawLE(a, b, c=0):
""" Little-endian version """
return CarryOutRaw(a[::-1], b[::-1], c)
def CarryOutLE(a, b, c=0):
""" Little-endian version """
from . import types
res = types.sint()
CarryOut(res, a[::-1], b[::-1], c)
return res
def BitLTL(res, a, b, kappa):
"""
res = a <? b (logarithmic rounds version)
a: clear integer register
b: array of secret bits (same length as a)
"""
k = len(b)
a_bits = b[0].bit_decompose_clear(a, k)
s = [[program.curr_block.new_reg('s') for i in range(k)] for j in range(2)]
t = [program.curr_block.new_reg('s') for i in range(1)]
for i in range(len(b)):
s[0][i] = b[0].long_one() - b[i]
CarryOut(t[0], a_bits[::-1], s[0][::-1], b[0].long_one(), kappa)
subsfi(res, t[0], 1)
return a_bits, s[0]
def PreMulC_with_inverses_and_vectors(p, a):
"""
p[i] = prod_{j=0}^{i-1} a[i]
Variant for vector registers using preprocessed inverses.
"""
k = len(p)
a_vec = program.curr_block.new_reg('s', size=k)
r = program.curr_block.new_reg('s', size=k)
w = program.curr_block.new_reg('s', size=k)
w_tmp = program.curr_block.new_reg('s', size=k)
z = program.curr_block.new_reg('s', size=k)
m = program.curr_block.new_reg('c', size=k)
t = [program.curr_block.new_reg('s', size=k) for i in range(1)]
c = [program.curr_block.new_reg('c') for i in range(k)]
# warning: computer scientists count from 0
if do_precomp:
vinverse(k, r, z)
else:
vprep(k, 'PreMulC', r, z, w_tmp)
for i in range(1,k):
if do_precomp:
muls(w[i], r[i], z[i-1])
else:
movs(w[i], w_tmp[i])
movs(a_vec[i], a[i])
movs(w[0], r[0])
movs(a_vec[0], a[0])
vmuls(k, t[0], w, a_vec)
vasm_open(k, m, t[0])
PreMulC_end(p, a, c, m, z)
def PreMulC_with_inverses(p, a):
"""
Variant using preprocessed inverses or special inverses.
The latter are triples of the form (a_i, a_i^{-1}, a_i * a_{i-1}^{-1}).
See also make_PreMulC() in Fake-Offline.cpp.
"""
k = len(a)
r = [[program.curr_block.new_reg('s') for i in range(k)] for j in range(3)]
w = [[program.curr_block.new_reg('s') for i in range(k)] for j in range(2)]
z = [program.curr_block.new_reg('s') for i in range(k)]
m = [program.curr_block.new_reg('c') for i in range(k)]
t = [[program.curr_block.new_reg('s') for i in range(k)] for i in range(1)]
c = [program.curr_block.new_reg('c') for i in range(k)]
# warning: computer scientists count from 0
for i in range(k):
if do_precomp:
inverse(r[0][i], z[i])
else:
prep('PreMulC', r[0][i], z[i], w[1][i])
if do_precomp:
for i in range(1,k):
muls(w[1][i], r[0][i], z[i-1])
w[1][0] = r[0][0]
for i in range(k):
muls(t[0][i], w[1][i], a[i])
asm_open(m[i], t[0][i])
PreMulC_end(p, a, c, m, z)
def PreMulC_without_inverses(p, a):
"""
Plain variant with no extra preprocessing.
"""
k = len(a)
r = [program.curr_block.new_reg('s') for i in range(k)]
s = [program.curr_block.new_reg('s') for i in range(k)]
u = [program.curr_block.new_reg('c') for i in range(k)]
v = [program.curr_block.new_reg('s') for i in range(k)]
w = [program.curr_block.new_reg('s') for i in range(k)]
z = [program.curr_block.new_reg('s') for i in range(k)]
m = [program.curr_block.new_reg('c') for i in range(k)]
t = [[program.curr_block.new_reg('s') for i in range(k)] for i in range(2)]
#tt = [[program.curr_block.new_reg('s') for i in range(k)] for i in range(4)]
u_inv = [program.curr_block.new_reg('c') for i in range(k)]
c = [program.curr_block.new_reg('c') for i in range(k)]
# warning: computer scientists count from 0
for i in range(k):
triple(s[i], r[i], t[0][i])
#adds(tt[0][i], t[0][i], a[i])
#subs(tt[1][i], tt[0][i], a[i])
#startopen(tt[1][i])
asm_open(u[i], t[0][i])
for i in range(k-1):
muls(v[i], r[i+1], s[i])
w[0] = r[0]
one = program.curr_block.new_reg('c')
ldi(one, 1)
for i in range(k):
divc(u_inv[i], one, u[i])
# avoid division by zero, just for benchmarking
#divc(u_inv[i], u[i], one)
for i in range(1,k):
mulm(w[i], v[i-1], u_inv[i-1])
for i in range(1,k):
mulm(z[i], s[i], u_inv[i])
for i in range(k):
muls(t[1][i], w[i], a[i])
asm_open(m[i], t[1][i])
PreMulC_end(p, a, c, m, z)
def PreMulC_end(p, a, c, m, z):
"""
Helper function for all PreMulC variants. Local operation.
"""
k = len(a)
c[0] = m[0]
for j in range(1,k):
mulc(c[j], c[j-1], m[j])
if isinstance(p, list):
mulm(p[j], z[j], c[j])
if isinstance(p, list):
p[0] = a[0]
else:
mulm(p, z[-1], c[-1])
def PreMulC(a):
p = [type(a[0])() for i in range(len(a))]
instructions_base.set_global_instruction_type(a[0].instruction_type)
if use_inv:
PreMulC_with_inverses(p, a)
else:
PreMulC_without_inverses(p, a)
instructions_base.reset_global_instruction_type()
return p
def KMulC(a):
"""
Return just the product of all items in a
"""
from .types import sint, cint
p = sint()
if use_inv:
PreMulC_with_inverses(p, a)
else:
PreMulC_without_inverses(p, a)
return p
def Mod2(a_0, a, k, kappa, signed):
"""
a_0 = a % 2
k: bit length of a
"""
if k <= 1:
movs(a_0, a)
return
r_dprime = program.curr_block.new_reg('s')
r_prime = program.curr_block.new_reg('s')
r_0 = program.curr_block.new_reg('s')
c = program.curr_block.new_reg('c')
c_0 = program.curr_block.new_reg('c')
tc = program.curr_block.new_reg('c')
t = [program.curr_block.new_reg('s') for i in range(6)]
c2k1 = program.curr_block.new_reg('c')
PRandM(r_dprime, r_prime, [r_0], k, 1, kappa)
mulsi(t[0], r_dprime, 2)
if signed:
ld2i(c2k1, k - 1)
addm(t[1], a, c2k1)
else:
t[1] = a
adds(t[2], t[0], t[1])
adds(t[3], t[2], r_prime)
asm_open(c, t[3])
from . import floatingpoint
c_0 = floatingpoint.bits(c, 1)[0]
mulci(tc, c_0, 2)
mulm(t[4], r_0, tc)
addm(t[5], r_0, c_0)
subs(a_0, t[5], t[4])
# hack for circular dependency
from .instructions import *
``` |
{
"source": "jonnybazookatone/gut-service",
"score": 2
} |
#### File: gut-service/biblib/app.py
```python
from flask import Flask
from views import UserView, LibraryView
from flask.ext.restful import Api
from flask.ext.discoverer import Discoverer
from models import db
from utils import setup_logging_handler
__author__ = '<NAME>'
__maintainer__ = '<NAME>'
__copyright__ = 'ADS Copyright 2015'
__version__ = '1.0'
__email__ = '<EMAIL>'
__status__ = 'Production'
__credit__ = ['<NAME>']
__license__ = 'MIT'
def create_app(config_type='PRODUCTION'):
"""
Create the application and return it to the user
:param config_type: specifies which configuration file to load. Options are
TEST, LOCAL, and PRODUCTION.
:return: application
"""
app = Flask(__name__, static_folder=None)
app.url_map.strict_slashes = False
config_dictionary = dict(
TEST='test_config.py',
LOCAL='local_config.py',
PRODUCTION='config.py'
)
app.config.from_pyfile(config_dictionary['PRODUCTION'])
if config_type in config_dictionary.keys():
try:
app.config.from_pyfile(config_dictionary[config_type])
except IOError:
app.logger.warning('Could not find specified config file: {0}'
.format(config_dictionary[config_type]))
raise
# Initiate the blueprint
api = Api(app)
# Add the end resource end points
api.add_resource(UserView,
'/users/<int:user>/libraries/',
methods=['GET', 'POST'])
api.add_resource(LibraryView,
'/users/<int:user>/libraries/<int:library>',
methods=['GET', 'POST', 'DELETE'])
# Initiate the database from the SQL Alchemy model
db.init_app(app)
# Add logging
handler = setup_logging_handler(level='DEBUG')
app.logger.addHandler(handler)
discoverer = Discoverer(app)
return app
if __name__ == '__main__':
app_ = create_app()
app_.run(debug=True, use_reloader=False)
```
#### File: gut-service/biblib/models.py
```python
__author__ = '<NAME>'
__maintainer__ = '<NAME>'
__copyright__ = 'ADS Copyright 2015'
__version__ = '1.0'
__email__ = '<EMAIL>'
__status__ = 'Production'
__license__ = 'MIT'
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.mutable import Mutable
db = SQLAlchemy()
class MutableList(Mutable, list):
"""
The PostgreSQL type ARRAY cannot be mutated once it is set. This hack is
written by the author of SQLAlchemy as a solution. For further reading,
see:
https://groups.google.com/forum/#!topic/sqlalchemy/ZiDlGJkVTM0
and
http://kirang.in/2014/08/09/creating-a-mutable-array-data-type-in-sqlalchemy
"""
def append(self, value):
"""
Define an append action
:param value: value to be appended
:return: no return
"""
list.append(self, value)
self.changed()
def remove(self, value):
"""
Define a remove action
:param value: value to be removed
:return: no return
"""
list.remove(self, value)
self.changed()
@classmethod
def coerce(cls, key, value):
"""
Re-define the coerce. Ensures that a class deriving from Mutable is
always returned
:param key:
:param value:
:return:
"""
if not isinstance(value, MutableList):
if isinstance(value, list):
return MutableList(value)
return Mutable.coerce(key, value)
else:
return value
class User(db.Model):
"""
User table
Foreign-key absolute_uid is the primary key of the user in the user
database microservice.
"""
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
absolute_uid = db.Column(db.Integer, unique=True)
permissions = db.relationship('Permissions', backref='user')
def __repr__(self):
return '<User {0}, {1}>'\
.format(self.id, self.absolute_uid)
class Library(db.Model):
"""
Library table
This represents a collection of bibcodes, a biblist, and can be thought of
much like a bibtex file.
"""
__tablename__ = 'library'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
description = db.Column(db.String(50))
public = db.Column(db.Boolean)
bibcode = db.Column(MutableList.as_mutable(ARRAY(db.String(50))))
permissions = db.relationship('Permissions', backref='library')
def __repr__(self):
return '<Library, library_id: {0:d} name: {1}, ' \
'description: {2}, public: {3},' \
'bibcode: {4}>'\
.format(self.id,
self.name,
self.description,
self.public,
self.bibcode)
class Permissions(db.Model):
"""
Permissions table
Logically connects the library and user table. Whereby, a Library belongs
to a user, and the user can give permissions to other users to view their
libraries.
User (1) to Permissions (Many)
Library (1) to Permissions (Many)
"""
__tablename__ = 'permissions'
id = db.Column(db.Integer, primary_key=True)
read = db.Column(db.Boolean)
write = db.Column(db.Boolean)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
library_id = db.Column(db.Integer, db.ForeignKey('library.id'))
def __repr__(self):
return '<Permissions, user_id: {0}, library_id: {1}, read: {2}, '\
'write: {3}'\
.format(self.user_id, self.library_id, self.read, self.write)
```
#### File: gut-service/biblib/utils.py
```python
__author__ = '<NAME>'
__maintainer__ = '<NAME>'
__copyright__ = 'Copyright 2015'
__version__ = '1.0'
__email__ = '<EMAIL>'
__status__ = 'Production'
__credit__ = ['<NAME>']
__license__ = 'GPLv3'
import os
PROJECT_HOME = os.path.abspath(
os.path.join(os.path.dirname(__file__), '../')
)
import logging
from cloghandler import ConcurrentRotatingFileHandler
def setup_logging_handler(level='DEBUG'):
"""
Sets up generic logging to file with rotating files on disk
:param level: the level of the logging DEBUG, INFO, WARN
:return: logging instance
"""
# Get the log level based on the user input
level = getattr(logging, level)
# Define the format of the output
logfmt = '%(levelname)s\t%(process)d [%(asctime)s]:\t%(message)s'
datefmt = '%m/%d/%Y %H:%M:%S'
formatter = logging.Formatter(fmt=logfmt, datefmt=datefmt)
file_name_path = os.path.join(
os.path.dirname(__file__), PROJECT_HOME, 'logs'
)
# Make the logging directory if it does not exist
if not os.path.exists(file_name_path):
os.makedirs(file_name_path)
# Construct the output path for the logs
file_name = os.path.join(file_name_path, 'app.log')
# Instantiate the file handler for logging
# Rotate every 2MB
rotating_file_handler = ConcurrentRotatingFileHandler(
filename=file_name,
maxBytes=2097152,
backupCount=5,
mode='a',
encoding='UTF-8'
)
# Add the format and log level
rotating_file_handler.setFormatter(formatter)
rotating_file_handler.setLevel(level)
return rotating_file_handler
def get_post_data(request):
"""
Attempt to coerce POST json data from the request, falling
back to the raw data if json could not be coerced.
:type request: flask.request
"""
try:
return request.get_json(force=True)
except:
return request.values
```
#### File: gut-service/biblib/views.py
```python
__author__ = '<NAME>'
__maintainer__ = '<NAME>'
__copyright__ = 'ADS Copyright 2015'
__version__ = '1.0'
__email__ = '<EMAIL>'
__status__ = 'Production'
__credit__ = ['<NAME>']
__license__ = 'MIT'
from flask import request, current_app
from flask.ext.restful import Resource
from flask.ext.discoverer import advertise
from models import db, User, Library, Permissions
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import NoResultFound
from utils import get_post_data
DUPLICATE_LIBRARY_NAME_ERROR = {'body': 'Library name given already '
'exists and must be unique.',
'number': 409}
MISSING_LIBRARY_ERROR = {'body': 'Library specified does not exist.',
'number': 410}
MISSING_DOCUMENT_ERROR = {'body': 'Document specified does not exist.',
'number': 410}
class UserView(Resource):
"""
End point to create a library for a given user
XXX: need to ignore the anon user, they should not be able to create libs
XXX: public/private
XXX: name of the library already exists
XXX: must give the library name/missing input function saves time
"""
decorators = [advertise('scopes', 'rate_limit')]
scopes = ['scope1', 'scope2']
rate_limit = [1000, 60*60*24]
def create_user(self, absolute_uid):
"""
Creates a user in the database with a UID from the API
:param absolute_uid: UID from the API
:return: no return
"""
try:
user = User(absolute_uid=absolute_uid)
db.session.add(user)
db.session.commit()
except IntegrityError as error:
current_app.logger.error('IntegritError. User: {0:d} was not'
'added. Full traceback: {1}'
.format(absolute_uid, error))
raise
def user_exists(self, absolute_uid):
"""
Checks if a use exists before it would attempt to create one
:param absolute_uid: UID from the API
:return: boolean for if the user exists
"""
user_count = User.query.filter(User.absolute_uid == absolute_uid).all()
user_count = len(user_count)
if user_count == 1:
return True
elif user_count == 0:
return False
def create_library(self, service_uid, library_data):
_name = library_data['name']
_description = library_data['description']
_read = library_data['read']
_write = library_data['write']
_public = library_data['public']
current_app.logger.info('Creating library for user_service: {0:d}'
.format(service_uid))
try:
# Make the library in the library table
library = Library(name=_name,
description=_description,
public=_public)
user = User.query.filter(User.id == service_uid).one()
# Make the permissions
permission = Permissions(
read=_read,
write=_write
)
# Use the ORM to link the permissions to the library and user,
# so that no commit is required until the complete action is
# finished. This means any rollback will not leave a single
# library without permissions
library.permissions.append(permission)
user.permissions.append(permission)
db.session.add_all([library, permission, user])
db.session.commit()
current_app.logger.info('Library: "{0}" made, user_service: {1:d}'
.format(library.name, user.id))
return library
except IntegrityError as error:
# Roll back the changes
db.session.rollback()
current_app.logger.error('IntegitryError, database has been rolled'
'back. Caused by user_service: {0:d}.'
'Full error: {1}'
.format(user.id, error))
# Log here
raise
except Exception:
db.session.rollback()
raise
def absolute_uid_to_service_uid(self, absolute_uid):
"""
Convert the API UID to the BibLib service ID
:param absolute_uid: API UID
:return: BibLib service ID
"""
user = User.query.filter(User.absolute_uid == absolute_uid).one()
return user.id
def get_libraries(self, absolute_uid):
"""
Get all the libraries a user has
:param absolute_uid: api UID of the user
:return: list of libraries in json format
"""
user_libraries = \
Library.query.filter(User.absolute_uid == absolute_uid).all()
output_libraries = []
for library in user_libraries:
payload = {
'name': library.name,
'id': library.id,
'description': library.description,
}
output_libraries.append(payload)
return output_libraries
# Methods
def get(self, user):
"""
HTTP GET request that returns all the libraries that belong to a given
user
:param user: user ID as given by the API
:return: list of the users libraries with the relevant information
"""
# XXX: Check that user is not anon
user_libraries = self.get_libraries(absolute_uid=user)
return {'libraries': user_libraries}, 200
def post(self, user):
"""
HTTP POST request that creates a library for a given user
:param user: user ID as given by the API
:return: the response for if the library was successfully created
"""
# Check if the user exists, if not, generate a user in the database
current_app.logger.info('Checking if the user exists')
if not self.user_exists(absolute_uid=user):
current_app.logger.info('User: {0:d}, does not exist.'
.format(user))
self.create_user(absolute_uid=user)
current_app.logger.info('User: {0:d}, created.'.format(user))
else:
current_app.logger.info('User already exists.')
# Switch to the service UID and not the API UID
service_uid = self.absolute_uid_to_service_uid(absolute_uid=user)
current_app.logger.info('user_API: {0:d} is now user_service: {1:d}'
.format(user, service_uid))
# Create the library
data = get_post_data(request)
try:
library = \
self.create_library(service_uid=service_uid, library_data=data)
except IntegrityError as error:
return {'error': DUPLICATE_LIBRARY_NAME_ERROR['body']}, \
DUPLICATE_LIBRARY_NAME_ERROR['number']
return {'name': library.name,
'id': library.id,
'description': library.description}, 200
class LibraryView(Resource):
"""
End point to interact with a specific library, by adding content and
removing content
XXX: need to ignore the anon user, they should not be able to do anything
XXX: document already exists
XXX: adding tags using PUT for RESTful endpoint?
"""
def add_document_to_library(self, library_id, document_data):
"""
Adds a document to a user's library
:param library_id: the library id to update
:param document_data: the meta data of the document
:return: no return
"""
current_app.logger.info('Adding a document: {0} to library_id: {1:d}'
.format(document_data, library_id))
# Find the specified library
library = Library.query.filter(Library.id == library_id).one()
if not library.bibcode:
current_app.logger.debug('Zero length array: {0}'
.format(library.bibcode))
library.bibcode = [document_data['bibcode']]
else:
current_app.logger.debug('Non-Zero length array: {0}'
.format(library.bibcode))
library.bibcode.append(document_data['bibcode'])
db.session.commit()
current_app.logger.info(library.bibcode)
def remove_documents_from_library(self, library_id, document_data):
"""
Remove a given document from a specific library
:param library_id: the unique ID of the library
:param document_data: the meta data of the document
:return: no return
"""
current_app.logger.info('Removing a document: {0} from library_id: '
'{1:d}'.format(document_data, library_id))
library = Library.query.filter(Library.id == library_id).one()
library.bibcode.remove(document_data['bibcode'])
db.session.commit()
current_app.logger.info('Removed document successfully: {0}'
.format(library.bibcode))
def get_documents_from_library(self, library_id):
"""
Retrieve all the documents that are within the library specified
:param library_id: the unique ID of the library
:return: bibcodes
"""
library = Library.query.filter(Library.id == library_id).one()
return library.bibcode
def delete_library(self, library_id):
"""
Delete the entire library from the database
:param library_id: the unique ID of the library
:return: no return
"""
library = Library.query.filter(Library.id == library_id).one()
db.session.delete(library)
db.session.commit()
def get(self, user, library):
"""
HTTP GET request that returns all the documents inside a given
user's library
:param user: user ID as given by the API
:param library: library ID
:return: list of the users libraries with the relevant information
"""
try:
documents = self.get_documents_from_library(library_id=library)
return {'documents': documents}, 200
except:
return {'error': MISSING_LIBRARY_ERROR['body']}, \
MISSING_LIBRARY_ERROR['number']
def post(self, user, library):
"""
HTTP POST request that adds a document to a library for a given user
:param user: user ID as given by the API
:param library: library ID
:return: the response for if the library was successfully created
"""
data = get_post_data(request)
if data['action'] == 'add':
current_app.logger.info('User requested to add a document')
self.add_document_to_library(library_id=library,
document_data=data)
return {}, 200
elif data['action'] == 'remove':
current_app.logger.info('User requested to remove a document')
self.remove_documents_from_library(
library_id=library,
document_data=data
)
return {}, 200
else:
current_app.logger.info('User requested a non-standard action')
return {}, 400
def delete(self, user, library):
"""
HTTP DELETE request that deletes a library defined by the number passed
:param user: user ID as given by the API
:param library: library ID
:return: the response for it the library was deleted
"""
try:
current_app.logger.info('user_API: {0:d} '
'requesting to delete library: {0:d}'
.format(library))
self.delete_library(library_id=library)
current_app.logger.info('Deleted library.')
except NoResultFound as error:
current_app.logger.info('Failed to delete: {0}'.format(error))
return {'error': MISSING_LIBRARY_ERROR['body']}, \
MISSING_LIBRARY_ERROR['number']
return {}, 200
``` |
{
"source": "jonnybazookatone/slackback",
"score": 3
} |
#### File: slackback/slackback/views.py
```python
import json
import requests
from flask import current_app, request
from flask.ext.restful import Resource
from utils import get_post_data, err
from werkzeug.exceptions import BadRequestKeyError
CHECK_CAPTCHA = False
ERROR_UNVERIFIED_CAPTCHA = dict(
body='captcha was not verified',
number=403
)
ERROR_MISSING_KEYWORDS = dict(
body='Incorrect POST data, see the readme',
number=404
)
def verify_recaptcha(request, ep=None):
"""
Verify a google recaptcha based on the data contained in the request
:param request: flask.request
:param ep: google recaptcha endpoint
:type ep: basestring|None
:return:True|False
"""
if ep is None:
ep = current_app.config['GOOGLE_RECAPTCHA_ENDPOINT']
data = get_post_data(request)
payload = {
'secret': current_app.config['GOOGLE_RECAPTCHA_PRIVATE_KEY'],
'remoteip': request.remote_addr,
'response': data['g-recaptcha-response']
}
r = requests.post(ep, data=payload)
r.raise_for_status()
return True if (r.json()['success'] == True) else False
class SlackFeedback(Resource):
"""
Forwards a user's feedback to slack chat using a web end
"""
@staticmethod
def prettify_post(post_data):
"""
Converts the given input into a prettified version
:param post_data: the post data to prettify, dictionary expected
:return: prettified_post data, dictionary
"""
channel = current_app.config['SLACKBACK_CHANNEL']
icon_emoji = current_app.config['SLACKBACK_EMOJI']
username = current_app.config['SLACKBACK_USERNAME']
try:
name = post_data['name']
reply_to = post_data['_replyto']
comments = post_data['comments']
subject = post_data['_subject']
feedback_type = post_data['feedback-type']
except BadRequestKeyError:
raise
prettified_data = {
'text': '```Incoming Feedback```\n'
'*Commenter*: {commenter}\n'
'*e-mail*: {email}\n'
'*Type*: {feedback_type}\n'
'*Subject*: {subject}\n'
'*Feedback*: {feedback}'.format(
commenter=name,
email=reply_to,
feedback_type=feedback_type,
feedback=comments,
subject=subject
),
'username': username,
'channel': channel,
'icon_emoji': icon_emoji
}
return prettified_data
def post(self):
"""
HTTP POST request
:return: status code from the slack end point
"""
post_data = get_post_data(request)
current_app.logger.info('Received feedback: {0}'.format(post_data))
if not post_data.get('g-recaptcha-response', False) or \
not verify_recaptcha(request):
current_app.logger.info('The captcha was not verified!')
return err(ERROR_UNVERIFIED_CAPTCHA)
else:
current_app.logger.info('Skipped captcha!')
try:
current_app.logger.info('Prettifiying post data: {0}'
.format(post_data))
formatted_post_data = json.dumps(self.prettify_post(post_data))
current_app.logger.info('Data prettified: {0}'
.format(formatted_post_data))
except BadRequestKeyError as error:
current_app.logger.error('Missing keywords: {0}, {1}'
.format(error, post_data))
return err(ERROR_MISSING_KEYWORDS)
slack_response = requests.post(
url=current_app.config['FEEDBACK_SLACK_END_POINT'],
data=formatted_post_data
)
return slack_response.json(), slack_response.status_code
``` |
{
"source": "Jonnyblacklabel/gsc_sa_downloader",
"score": 2
} |
#### File: gsc_sa_downloader/gsc_sa_downloader/gsc_sa_downloader.py
```python
from searchanalytics import Client, QueryThreaded
from datetime import datetime
from loguru import logger
from typing import List
from tqdm import tqdm
import config
import json
import time
import sys
import db
import os
def generate_queries(client: Client, account_name: str,
gsc_property: str, p_key: int, j_keys: List[int]):
db.init_query_queue()
length = 0
for j_key in tqdm(j_keys, desc='jobs'):
data = []
job = db.get_gsc_property_job(j_key)
dates = client.get_date_list(gsc_property, searchtype=job['searchtype'])
dates = [datetime.strptime(date, '%Y-%m-%d').date() for date in dates]
dates_from_db = [row['date'] for row in
db.get_query_queue_items(p_key, j_key)]
if len(dates_from_db) > 0:
dates = [x for x in dates if x not in dates_from_db]
for date in dates:
data.append(dict(gsc_property_id = p_key,
gsc_property_job_id = j_key,
date = date))
db.con['query_queue'].insert_many(data)
length += len(data)
logger.info(f'inserted {length} items in query_queue')
def create_account_and_property(account_name, gsc_property, reset=False):
"""add or reset account with property
(new) account with (new) property is inserted into database.
if reset → data database will be deleted, jobs will be reset
Args:
account_name: name of account (credentials filename)
gsc_property: gsc property (with trailing slash)
reset: delete data sqlite and delete row in root db (default: {False})
"""
client = Client(account_name = account_name)
client.set_webproperty(gsc_property)
# löschen der daten sqlite des accounts
if reset:
try:
sqlite_data = os.path.join(os.environ['SQLITE_PATH'], account_name+'.db')
logger.info(f'deleting database {sqlite_data}.')
os.remove(sqlite_data)
except FileNotFoundError:
logger.info('no sqlite db found.')
try:
gsc_property_id = db.get_gsc_property(account_name=account_name,
gsc_property=gsc_property)['id']
logger.info(f'removing queue items for {gsc_property}')
db.delete_query_queue_items(gsc_property_id)
logger.info(f'removing jobs for {gsc_property}')
db.delete_gsc_property_jobs(gsc_property_id)
logger.info(f'removing {account_name} with {gsc_property} from database')
db.delete_gsc_property(account_name, gsc_property)
except TypeError:
logger.info('cannot delete')
# erstellen neuer einträge
# gsc property
try:
gsc_property_id = db.get_gsc_property(account_name, gsc_property)['id']
except TypeError:
logger.info(f'create {account_name} with {gsc_property} in database.')
gsc_property_id = db.create_gsc_property(account_name, gsc_property)
# property jobs
job_keys = [row['id'] for row in db.get_gsc_property_jobs(gsc_property_id)]
if len(job_keys) == 0:
logger.info(f'create job definitions for {gsc_property} without iterators')
combinations = config.get_combinations_without_iterators()
job_keys = []
for combination in tqdm(combinations, desc='jobs'):
id_ = db.create_gsc_property_job(gsc_property_id = gsc_property_id,
searchtype = combination[0],
dimensions = json.dumps(combination[1]))
job_keys.append(id_)
logger.info(f'create job definitions for {gsc_property} with iterators')
iterators = config.get_filter_iterators()
combinations_iterators = []
for iterator in tqdm(iterators, desc='creating iterations'):
combinations_iterators.extend(config.get_combinations_with_iterators(client, iterator))
# job_keys = []
for combination in tqdm(combinations_iterators, desc='inserting iterators'):
id_ = db.create_gsc_property_job(gsc_property_id = gsc_property_id,
searchtype = combination[0],
dimensions = json.dumps(combination[1]),
filter = json.dumps(combination[2]))
job_keys.append(id_)
logger.info('genereating daily queries in database.')
# query jobs
generate_queries(client, account_name, gsc_property,
gsc_property_id, job_keys)
def download(account_name, gsc_property, generate=False, reset=False, max_workers=5):
"""download gsc searchanalytics data
download gsc searchanalytics data for gsc property.
will create new jobs for property.
Args:
account_name: name of account (credentials filename)
gsc_property: gsc property (with trailing slash)
generate: if True, generate new queue items
reset: delete data sqlite and delete row in root db (default: {False})
"""
if generate or reset:
create_account_and_property(account_name=account_name,
gsc_property=gsc_property,
reset=reset)
logger.info(f'starting download for {account_name} with {gsc_property}.')
properties = db.get_gsc_properties(account_name = account_name,
gsc_property = gsc_property,
active = True)
for property_ in tqdm(list(properties), desc='properties'):
jobs = db.get_gsc_property_jobs(property_['id'], active=True)
for job in tqdm(list(jobs), desc='jobs', leave=False):
queue = db.get_query_queue_items(property_['id'],
job['id'],
finished = False,
attempts = {'<=': 5})
thread_queue_items = []
for item in queue:
try:
table_name = job['searchtype'] + '_' + '_'.join(json.loads(job['dimensions']))
if job['filter'] is not None:
filter_ = json.loads(job['filter'])
table_name = '_'.join([table_name, filter_[1].lower()])
thread_queue_items.append(dict(tbl_name=table_name,
query=item,
job=job))
except Exception as e:
logger.error(f'error: {e}')
logger.info(f'starting threaded fetching - [max_workers {max_workers}]')
query_threaded = QueryThreaded(account_name = property_['account_name'],
gsc_property = property_['gsc_property'],
items = thread_queue_items,
max_workers = max_workers)
query_threaded.run()
logger.info('finished threaded fetching')
logger.info(f'finsihed download for {account_name} with {gsc_property}.')
def download_all(generate=False, reset=False, max_workers=5):
"""download gsc searchanalytics data for all properties
!!! ALL Databases are deleted and cleard if reset=True
Args:
reset: delete data sqlite and delete row in root db (default: {False})
"""
logger.info('starting download for all properties')
for row in db.con['gsc_properties'].all():
download(row['account_name'], row['gsc_property'], reset=reset)
logger.info('finished download for all properties')
def main():
logger.add('logs/{time:YYYY-MM-DD}.log', level='DEBUG', backtrace=True,
format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}")
from argparse import ArgumentParser
parser = ArgumentParser(description='run searchanalytics data downloader')
parser.add_argument('--reset', '-r', action='store_true',
help='clear controle tables & delete account database')
subparsers = parser.add_subparsers(title='commands')
dl_all = subparsers.add_parser('download_all',
help='generate queries & download')
dl_all.set_defaults(func=download_all)
dl = subparsers.add_parser('download',
help='create/generate queries & download for property of account')
dl.set_defaults(func=download)
for sp in [dl_all, dl]:
sp.add_argument('--generate', '-g', action='store_true',
help='generate queue items for new dates')
sp.add_argument('--max_workers', '-w', type=int, default=10,
help='number of max_workers')
ga = subparsers.add_parser('create-account',
help='create/generate queries for property of account')
ga.set_defaults(func=create_account_and_property)
for sp in [dl,ga]:
sp.add_argument('account_name', help='name of account')
sp.add_argument('gsc_property', help='name of gsc property')
args = parser.parse_args()
args.func(**{k: v for k,v in vars(args).items() if k is not 'func'})
if __name__ == '__main__':
main()
``` |
{
"source": "Jonnyblacklabel/metrics_tools",
"score": 3
} |
#### File: metrics_tools/metrics_tools/url.py
```python
from .endpoint_base import BaseEndpoint
from .method_base import BaseMethod, MethodParams, AcceptsOrderColumn, AcceptsDateFilter, Paginatable
class Url(BaseEndpoint):
"""Url Endpoint
metrics.tools url endpoint.
Call url('https://www.example.com/') to set url.
Methods:
- rankings
Attributes
----------
endpoint : {str}
Last part of API url
"""
endpoint = 'url'
def __init__(self, client, *args, **kwargs):
self.rankings = Rankings(client, self.endpoint)
def __call__(self, url):
if len(url) > 0:
self.rankings.params.url = url
else:
raise ValueError('Input can not be empty.')
return self
class Rankings(AcceptsOrderColumn, AcceptsDateFilter, Paginatable, BaseEndpoint):
"""Rankings method
metrics.tools method for url.rankings.
Returns rankings for given url.
Attributes
----------
params : {MethodParams}
Definition for fixed and needed parameters
"""
params = MethodParams(fixed={'query':'rankings'},needed=['url'],optional=['limit','offset','order_column','order_direction'])
def __init__(self, client, endpoint):
super().__init__(client, endpoint)
if __name__ == '__main__':
pass
``` |
{
"source": "jonnybluesman/emomucs",
"score": 2
} |
#### File: emomucs/models/config.py
```python
import configparser
from nets import DeezerConv1d, VGGishEmoNet, VGGishExplainable
from nets import get_vggish_poolings_from_features, cnn_weights_init, torch_weights_init
# TODO: default parameters go here ...
NAMES_TO_MODELS = {
"deezeremo": DeezerConv1d,
"vggemonet": VGGishEmoNet,
"vggexp": VGGishExplainable
}
def hparams_from_config(config_path):
"""
Read a config file with the hparameters configuration,
and return them, after parsing, as a dictionary.
TODO:
- Sanity checks on types and values.
"""
config = configparser.ConfigParser()
config.read(config_path)
hparams_cfg = config['HPARAMS']
hparams_dict = {
'mse_reduction': hparams_cfg.get('mse_reduction', 'sum'),
'num_epochs': hparams_cfg.getint('num_epochs', 10000),
'patience': hparams_cfg.getint('patience', 20),
'lr': hparams_cfg.getfloat('lr', 10000),
'batch_sizes': [int(b_size) for b_size in hparams_cfg.get(
'batch_sizes', '32, 32, 32').split(',')]
}
return hparams_dict
def get_model_from_selection(model_name, input_shape):
"""
Returns the model instantiated from the specification,
together with the function to reinitialise the weights.
We only support 3 models at the moment:
i.e. DeezerConv1d, VGGishEmoNet, VGGishExplainable
Args:
model_name (str): one of 'deezeremo', 'vggemonet', 'vggexp';
input_shape (tuple): shape of the input tensors.
"""
reinit_fn = torch_weights_init
if model_name == 'deezeremo':
sel_model = DeezerConv1d(input_shape)
elif model_name == 'vggemonet':
sel_model = VGGishEmoNet(input_shape)
elif model_name == 'vggexp':
sel_model = VGGishExplainable(input_shape)
else:
raise ValueError("deezeremo, vggemonet, vggexp are supported!")
return sel_model, reinit_fn
```
#### File: emomucs/models/experiment.py
```python
import os
import re
import glob
import math
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Subset, DataLoader
# from torch.utils.tensorboard import SummaryWriter
from training import train_network, RegressionModelEvaluator
from data import load_nested_cv_fold, create_data_loaders
from nets import cnn_weights_init, torch_weights_init
from utils import create_dir
def nn_train_evaluate_model(
model, tr_loader, va_loader, hparameters, dtype, device, loggers=None, logdir=None):
"""
The given model is then trained and evaluated on the validation set after each
epoch, so as to implement the early stropping strategy.
Args:
model (torch.nn.Module): the model to train and evaluate;
tr_loader (DataLoader): data loader for the training set;
va_loader (DataLoader): data loader for the validation set;
hparameters (dict): a dictionary with the training hyper-parameters.
...
***TODO: Run the models multiple times with different weight initialisation.***
Returns the trained model and the history of the training/validation loss.
"""
# setting loggers verbosity for the training/evaluation step
loggers = [False] * 3 if loggers is None else [False, True, True]
(net_trained, min_loss), hist = train_network(
model, tr_loader, va_loader, hparameters=hparameters,
dtype=dtype, device=device, loggers=loggers, log_dir=logdir
)
return net_trained, min_loss, hist
class NestedCrossValidation(object):
"""
Nested cross-validation experiment for the evaluation of a regression model.
Args:
model (nn.Module): the model to evaluate in the nested CV loop;
dataset (data.Dataset): the full dataset that will be splitted in folds;
fold_path (str): path to the file with the nested cv splits;
hparams (dict): hyper-parameters as a mapping from hparam name to value;
dtype (torch dtype): the type of tensors to use for data and parameters;
model_name (str): name of the model (for checkpointing purposes);
checkpoint_dir (str): where to save fold checkpoints. None if not needed.
TODO:
- create fold dict file if null is specified.
"""
def __init__(self, model, dataset, fold_path, hparams, dtype,
checkpointing=False, model_name=None, checkpoint_dir=None):
self.model = model
self.dtype = dtype
self.hparams = hparams
self.dataset = dataset
self.checkpointing = checkpointing
self.model_name = model.__class__.__name__ \
if model_name is None else model_name
self.checkpoint_dir = create_dir(checkpoint_dir)
self.ncv_dict = load_nested_cv_fold(fold_path)
self.test_losses = dict() # {out_fold: test losses}
self.best_models = dict() # {out_fold: best model}
self.targets, self.predictions = [], []
def get_outer_fold_test_scores(self):
"""
Simple getter for the results of the Nested CV experiment.
TODO:
- Warning in case not all the outer fold were run.
"""
assert len(self.test_losses) > 0, "Nested CV not started yet!"
return self.test_losses
def get_targets_and_predictions(self):
"""
Simple getter for the results of the Nested CV experiment.
TODO:
- Warning in case not all the outer fold were run.
"""
assert len(self.targets) > 0, "Nested CV not started yet!"
all_targets = torch.cat(self.targets, 0).numpy()
all_predics = torch.cat(self.predictions, 0).numpy()
out_names = self.dataset.annotation_df.columns
return dict(
**{"out_" + out_names[i] : all_predics[:, i]
for i in range(len(out_names))},
**{"target_" + out_names[i] : all_targets[:, i]
for i in range(len(out_names))})
def get_outer_fold_best_models(self, sel_folds=None):
"""
Simple getter for the results of the Nested CV experiment.
TODO:
- Warning in case not all the outer fold were run.
- This should not work, as it is not a deep copy.
"""
assert len(self.best_models)> 0, "Nested CV not started yet!"
sel_folds = self.best_models if sel_folds is None else sel_folds
assert all([fold in self.best_models.keys() for fold in sel_folds])
return {fold: model for fold, model in self.best_models.items() if fold in sel_folds}
def run_nested_cv_evaluation(
self, sel_folds, device, warmup_fn=None, reinit_fn=torch_weights_init):
"""
Perform Nested CV on the selected outer folds using the provided device.
Designed to be adapted for parallelisation.
Args:
sel_folds (list): list of outer fold identifiers to run;
device (torch device): which device to use for experimentation;
warmup_fn (fucntion): optional preprocessing function for the model;
reinit_fn (function): how to reinit the net, `torch_weights_init` as default.
TODO:
- Run on all outer folds if sel_folds is None;
- Split function in process_outer_fold and process_inner_fold;
"""
warmup_fn = warmup_fn if warmup_fn is not None \
else lambda model, model_name, logdir, dev, fold : model
sel_folds = list(self.ncv_dict.keys()) if sel_folds is None else sel_folds
assert all([fold not in self.test_losses.keys() for fold in sel_folds]), \
"One or more of the specified folds has/have already been run!"
batch_sizes = self.hparams.get("batch_sizes")
ncv_dict_sel = {outer_fold : outer_fold_data for outer_fold, outer_fold_data
in self.ncv_dict.items() if outer_fold in sel_folds}
for outer_fold, outer_fold_data in ncv_dict_sel.items():
test_ids = outer_fold_data.pop('test_ids')
te_loader = DataLoader(
Subset(self.dataset, test_ids), shuffle=False,
batch_size=len(test_ids) if batch_sizes[-1] is None else batch_sizes[-1])
print("Outer fold {} starting | {} test samples".format(outer_fold, len(test_ids)))
innerfold_models = dict() # dictionary {validation loss: network}
for inner_fold, inner_fold_data in outer_fold_data.items():
warmup_fn(self.model, self.model_name, self.checkpoint_dir, device, (outer_fold, inner_fold))
tr_ids, va_ids = inner_fold_data['training_ids'], inner_fold_data['validation_ids']
tr_loader, va_loader = create_data_loaders(self.dataset, tr_ids, va_ids)
print('... processing fold {}-{} --- training samples: {}, validation samples: {}'
.format(outer_fold, inner_fold, len(tr_ids), len(va_ids)))
tr_loader, va_loader = create_data_loaders(
self.dataset, tr_ids, va_ids, batch_sizes=batch_sizes[:2], num_workers=0
)
infold_model, infold_validloss, _ = nn_train_evaluate_model(
self.model, tr_loader, va_loader, self.hparams,
dtype=self.dtype, device=device, loggers=[False, True, True]
)
innerfold_models[infold_validloss] = infold_model
if self.checkpointing:
torch.save(infold_model.state_dict(), os.path.join(
self.checkpoint_dir, f"{self.model_name}_{outer_fold}_{inner_fold}.pt"))
self.model.apply(reinit_fn) # reset model params for next fold
infold_best = innerfold_models[min(innerfold_models.keys())]
self.best_models[outer_fold] = infold_best # or just save the state dict
te_evaluator = RegressionModelEvaluator(infold_best, device, self.dtype)
rmse, r2score, targets, predictions = te_evaluator.evaluate_net_raw(te_loader)
out_names = self.dataset.annotation_df.columns
self.targets.append(targets)
self.predictions.append(predictions)
self.test_losses[outer_fold] = {
**dict(zip(['rmse_' + col for col in out_names], rmse)),
**dict(zip(['r2score_' + col for col in out_names], r2score))
}
```
#### File: emomucs/models/nets.py
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
activations = nn.ModuleDict([
['sigmoid', nn.Sigmoid()],
['tanh', nn.Tanh()],
['lrelu', nn.LeakyReLU()],
['relu', nn.ReLU()],
['selu', nn.SELU()],
['elu', nn.ELU()]
])
def compute_flattened_maps(cnn_layers, input_shape):
"""
Utility function to compute the size of the flattened feature maps
after the convolutional layers, which should be passed as input
together with the shape of the input tensors.
"""
x = torch.randn(1, 1, *input_shape)
with torch.no_grad():
x = cnn_layers(x)
return np.prod(x.shape[1:])
def cnn_weights_init(m):
"""
Reinitialise the parameters of a network with custom init functions.
Xavier initialisation is used for Linear layers, whereas convolutional
layers are initialised with the Hu Kaiming method for more stability.
This method only supports, for the moment, conv and linear layers. The idea
of this method is "reset and refine", which ensures that all layer are reinit.
"""
if ("reset_parameters" in dir(m)):
m.reset_parameters() # first of all reset the layer
if isinstance(m, (nn.Conv1d, nn.Conv2d)):
nn.init.kaiming_uniform_(m.weight)
elif isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight)
def torch_weights_init(m):
"""
Reinitialise the parameters of a layer as the good torch would do.
This method is not very useful as it is right now.
"""
if ("reset_parameters" in dir(m)):
m.reset_parameters() # first reset the layer
# TODO: do something more from the specs
def create_dense_block(
in_feats, out_feats, architecture=['fc', 'act', 'drop'],
activation='relu', dropout_prob=0, wrapping=True):
"""
Factory method for fully connected layers, with the possibility
to choose the activation function and the regularisation technique.
TODO:
- add the support for batch normalisation;
"""
assert all(name in ['fc', 'act', 'drop'] for name in architecture)
dense_block = {
'fc': nn.Linear(in_feats, out_feats),
'act' : activations[activation],
'drop': nn.Dropout(p=dropout_prob),
}
dense_block = [dense_block[name] for name in architecture]
return nn.Sequential(*dense_block) if wrapping else dense_block
def create_2d_convolutional_block(
in_feats, num_filters, filter_size, architecture=['bn', 'act', 'pool', 'drop'],
pool_size=(2,2), padding=0, stride=1, activation='relu', dropout_prob=0):
"""
Factory method for convolutional layers, with the possibility.
Args:
in_features (int): number of input features;
num_filters (int): number of kernels;
filter_size (tuple): size of the 2D filters/kernels;
architecture (list): list of strings describing the cnn items;
pool_size (tuple): size of the pooling operation (same of stride);
padding (int or tuple): the amount of padding for each dimension;
stride (int or tuple): stride of the convolutional kernel;
activation (str): namne of the activation function;
dropout_prob (float): probability of dropping out;
"""
assert all(name in ['bn', 'act', 'pool', 'drop'] for name in architecture)
cnn_block = {
'bn' : nn.BatchNorm2d(num_filters),
'act' : activations[activation],
'pool': nn.MaxPool2d(pool_size),
'drop': nn.Dropout(p=dropout_prob),
}
return nn.Sequential(
nn.Conv2d(in_feats, num_filters, filter_size,
padding=padding, stride=stride),
*[cnn_block[name] for name in architecture])
class DeezerConv1d(nn.Module):
"""
Simple implementation of the AudioCNN presented in
"Music Mood Detection Based On Audio And Lyrics With Deep Neural Net".
Code adapted from https://github.com/Dohppak/Music_Emotion_Recognition
"""
def __init__(self, input_shape, n_kernels=[32, 16], kernel_sizes=[8, 8],
mpool_stride=[4, 4], fc_units=[64, 2]):
"""
Class constructor for the creation of a static 1DCNN.
Args:
input_shape (2-tuple): (number of mel bands, frames).
n_kernels (2-tuple): number of 1D filters per conv layer;
kernel_sizes (2-tuple): size of kernels as number of frames;
mpool_stride (2-tuple): strides of 1D max pooling (same as size);
fc_units (2-tuple): number of units in the last fully-connected layers.
TODO:
- Class constructor from sample input instead of specifying nmel;
- The parameterisation of the net can be more beautiful;
- It is still not clear which activation function is used in the first FCL.
"""
super(DeezerConv1d, self).__init__()
self.flattened_size = int(np.floor(
((np.floor((input_shape[1] - kernel_sizes[0] + 1) / mpool_stride[0]))
- kernel_sizes[1] + 1) / mpool_stride[1]) * n_kernels[-1])
self.conv_blocks = nn.Sequential(
nn.Sequential(
nn.Conv1d(input_shape[0], n_kernels[0], kernel_size=kernel_sizes[0]),
nn.MaxPool1d(mpool_stride[0], stride=mpool_stride[0]),
nn.BatchNorm1d(n_kernels[0])),
nn.Sequential(
nn.Conv1d(n_kernels[0], n_kernels[1], kernel_size=kernel_sizes[1]),
nn.MaxPool1d(mpool_stride[1], stride=mpool_stride[1]),
nn.BatchNorm1d(n_kernels[1]))
)
self._fcl = nn.Sequential(
nn.Dropout(),
nn.Linear(in_features=self.flattened_size, out_features=fc_units[0]),
#nn.Tanh(), # we use a relu instead
nn.ReLU(),
nn.Dropout(),
nn.Linear(in_features=fc_units[0], out_features=fc_units[1]),
)
self.apply(self._init_weights)
def convolutional_features(self, x):
x = self.conv_blocks(x)
return x.view(x.size(0), -1)
def forward(self, x):
x_cnn_flat = self.convolutional_features(x)
pred = self._fcl(x_cnn_flat)
return pred
def _init_weights(self, layer) -> None:
if isinstance(layer, nn.Conv1d):
nn.init.kaiming_uniform_(layer.weight)
elif isinstance(layer, nn.Linear):
nn.init.xavier_uniform_(layer.weight)
class VGGishEmoNet(nn.Module):
"""
A VGG-based 2dCNN typically used for music tagging and transfer learning as in:
"Transfer learning for music classification and regression tasks"
Architecture inspired from https://github.com/keunwoochoi/transfer_learning_music/
"""
def __init__(
self, input_shape, n_kernels=[32]*5, kernel_sizes=[(3,3)]*5,
pooling_sizes=None, dropout=0., cnn_activation='elu', fc_units=2):
"""
Class constructor for the creation of a static 2DCNN.
Args:
input_shape (2-tuple): (number of mel bands, frames).
n_kernels (list): number of 2D filters per conv layer;
kernel_sizes (list): size of kernels for each conc layer;
pooling_sizes (list): size of each 2D maxpooling operation;
dropout (float): probability of dropping out conv activations;
cnn_activation (str): name of the activation function for conv layers;
fc_units (int): number of units in the last fully-connected layer.
TODO:
- The parameterisation of the net can be more beautiful;
"""
super(VGGishEmoNet, self).__init__()
if pooling_sizes is None:
pooling_sizes = get_vggish_poolings_from_features(*input_shape)
assert len(n_kernels) == len(kernel_sizes) == len(pooling_sizes)
conv_input_shapes = [1] + n_kernels[:-1]
cnn_arch = ['bn', 'act', 'pool', 'drop']
conv_blocks = [create_2d_convolutional_block(
conv_input_shape, n_kernel, kernel_size, cnn_arch,
pooling_size, 1, 1, cnn_activation, dropout) \
for conv_input_shape, n_kernel, kernel_size, pooling_size \
in zip(conv_input_shapes, n_kernels, kernel_sizes, pooling_sizes)]
self.conv_blocks = nn.Sequential(
*conv_blocks, nn.AdaptiveAvgPool2d((1, 1)))
# the following operation is not needed as we already have the adaptive pooling
# self.flattened_size = compute_flattened_maps(self.conv_blocks, input_shape)
self.flattened_size = n_kernels[-1]
self._fcl = nn.Sequential(
nn.Linear(in_features=self.flattened_size, out_features=fc_units),
)
def convolutional_features(self, x):
x = x.unsqueeze(1) # to ensure n_channels is 1
x = self.conv_blocks(x)
return x.view(x.size(0), -1)
def forward(self, x):
x_cnn_flat = self.convolutional_features(x)
pred = self._fcl(x_cnn_flat)
return pred
class VGGishExplainable(nn.Module):
"""
A VGG-based 2dCNN designed for explainable MER, presented in:
"Towards explainable MER, by using mid-level features".
This is the model that is denoted as A2E in the paper.
"""
def __init__(
self, input_shape, n_kernels=[64, 64, 128, 128, 256, 256, 384, 512, 256],
kernel_sizes=[(5,5)]+[(3,3)]*8, pooling_sizes=[(2, 2), (2, 2)],
strides=[2]+[1]*8, paddings=[2]+[1]*7+[0], dropout=[.3, .3],
cnn_activation='relu', fc_units=2):
"""
Class constructor for the creation of a static 2DCNN.
Args:
input_shape (2-tuple): (number of mel bands, frames).
n_kernels (list): number of 2D filters per conv layer;
kernel_sizes (list): size of kernels for each conc layer;
pooling_sizes (list): size of each 2D maxpooling operation;
dropout (float): probability of dropping out conv activations;
cnn_activation (str): name of the activation function for conv layers;
fc_units (int): number of units in the last fully-connected layer.
TODO:
- The parameterisation of the net can be more beautiful;
"""
super(VGGishExplainable, self).__init__()
assert len(n_kernels) == len(kernel_sizes) == len(strides) == len(paddings)
conv_input_shapes = [1] + n_kernels[:-1]
conv_blocks = [create_2d_convolutional_block(
conv_input_shape, n_kernel, kernel_size, ['bn', 'act'],
None, padding, stride, cnn_activation) \
for conv_input_shape, n_kernel, kernel_size, padding, stride \
in zip(conv_input_shapes, n_kernels, kernel_sizes, paddings, strides)]
self.conv_blocks = nn.Sequential(
*conv_blocks[:2],
nn.MaxPool2d(pooling_sizes[0]),
nn.Dropout(p=dropout[0]),
*conv_blocks[2:4],
nn.MaxPool2d(pooling_sizes[1]),
nn.Dropout(p=dropout[1]),
*conv_blocks[4:],
nn.AdaptiveAvgPool2d((1, 1)),
)
# the following operation is not needed as we already have the adaptive pooling
# flattened_size = compute_flattened_maps(self.conv_blocks, input_shape)
self.flattened_size = n_kernels[-1]
self._fcl = nn.Sequential(
nn.Linear(in_features=self.flattened_size, out_features=fc_units),
)
def convolutional_features(self, x):
x = x.unsqueeze(1) # to ensure n_channels is 1
x = self.conv_blocks(x)
return x.view(x.size(0), -1)
def forward(self, x):
x_cnn_flat = self.convolutional_features(x)
pred = self._fcl(x_cnn_flat)
return pred
def get_vggish_poolings_from_features(n_mels=96, n_frames=1360):
"""
Get the pooling sizes for the standard VGG-based model for audio tagging.
Code from: https://github.com/keunwoochoi/transfer_learning_music/blob/master/models_transfer.py
Todo:
- This code is ugly, reorganise in a config file;
- This method is assuming (at the moment) a certain number of frames (1360 covering 30s);
"""
if n_mels >= 256:
poolings = [(2, 4), (4, 4), (4, 5), (2, 4), (4, 4)]
elif n_mels >= 128:
poolings = [(2, 4), (4, 4), (2, 5), (2, 4), (4, 4)]
elif n_mels >= 96:
poolings = [(2, 4), (3, 4), (2, 5), (2, 4), (4, 4)]
elif n_mels >= 72:
poolings = [(2, 4), (3, 4), (2, 5), (2, 4), (3, 4)]
elif n_mels >= 64:
poolings = [(2, 4), (2, 4), (2, 5), (2, 4), (4, 4)]
elif n_mels >= 48:
poolings = [(2, 4), (2, 4), (2, 5), (2, 4), (3, 4)]
elif n_mels >= 32:
poolings = [(2, 4), (2, 4), (2, 5), (2, 4), (2, 4)]
elif n_mels >= 24:
poolings = [(2, 4), (2, 4), (2, 5), (3, 4), (1, 4)]
elif n_mels >= 18:
poolings = [(2, 4), (1, 4), (3, 5), (1, 4), (3, 4)]
elif n_mels >= 18:
poolings = [(2, 4), (1, 4), (3, 5), (1, 4), (3, 4)]
elif n_mels >= 16:
poolings = [(2, 4), (2, 4), (2, 5), (2, 4), (1, 4)]
elif n_mels >= 12:
poolings = [(2, 4), (1, 4), (2, 5), (3, 4), (1, 4)]
elif n_mels >= 8:
poolings = [(2, 4), (1, 4), (2, 5), (2, 4), (1, 4)]
elif n_mels >= 6:
poolings = [(2, 4), (1, 4), (3, 5), (1, 4), (1, 4)]
elif n_mels >= 4:
poolings = [(2, 4), (1, 4), (2, 5), (1, 4), (1, 4)]
elif n_mels >= 2:
poolings = [(2, 4), (1, 4), (1, 5), (1, 4), (1, 4)]
else: # n_mels == 1
poolings = [(1, 4), (1, 4), (1, 5), (1, 4), (1, 4)]
ratio = n_frames / 1360 # as these measures are referred to this unit
# print([(poo_w, pool_l * ratio) for poo_w, pool_l in poolings])
return [(poo_w, round(pool_l * ratio)) for poo_w, pool_l in poolings]
def simple_param_count(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def tensor_shape_flows_through(conv_blocks, feat_shape):
"""
Currently works just for a CNN...
TODO:
- Make it general for any network
"""
print('Generating random batch of 2 x {} data'.format(feat_shape))
x = torch.rand((2, *feat_shape))
conv_blocks.eval()
conv_blocks.to(device=torch.device('cpu'), dtype=torch.float)
x.to(device=torch.device('cpu'), dtype=torch.float)
print("Initial shape: {}".format(x.shape))
for i, layer in enumerate(conv_blocks):
if isinstance(layer, nn.Sequential):
for j, sub_layer in enumerate(layer):
x = sub_layer(x)
if isinstance(sub_layer, nn.Conv2d) or isinstance(sub_layer, nn.MaxPool2d):
print("Layer {} ({}) | Shape after {}: {} "
.format(i, j, sub_layer.__class__.__name__, x.shape))
else:
x = layer(x)
# only print if the level is expected to afffect the shape
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.MaxPool2d) or isinstance(layer, nn.AdaptiveAvgPool2d):
print("Layer {} | Shape after {}: {} "
.format(i, layer.__class__.__name__, x.shape))
```
#### File: emomucs/models/utils.py
```python
import matplotlib.pyplot as plt
import pandas as pd
import os
import joblib
def plot_training_history(training_history):
pd.DataFrame(training_history).plot()
plt.xlabel('epoch')
plt.ylabel('MSE')
plt.title('Loss history during training')
plt.show()
def is_file(parser, f_arg):
if not os.path.exists(f_arg):
return parser.error("File %s does not exist!" % f_arg)
return f_arg
def create_dir(path):
"""Create dir if it does not exist."""
if (path is not None) and (not os.path.exists(path)):
os.mkdir(path)
return path
def save_data(dicted_data, save_path, compression=0):
"""
Simple utility to save dicted data in joblib.
"""
assert os.path.exists(os.path.dirname(save_path))
with open(save_path, "wb") as f:
joblib.dump(dicted_data, f, compress=compression)
def str_list(a_list, keep_decimal=False, separator="-"):
"""
Convert a list to a single string.
"""
s_list = [str(item) for item in a_list]
s_list = [fitem.split(".")[1] for fitem in s_list] \
if keep_decimal else s_list
return '-'.join(s_list)
```
#### File: emomucs/preprocessing/feature_extraction.py
```python
import os
import glob
import joblib
import pandas as pd
import numpy as np
import librosa
from joblib import Parallel, delayed
from tqdm import tqdm
def post_process_separated_track(stereo_track, target_sr=22050, target_duration=30, padding=True):
"""
Post-processing audio sequences obtained from the separation of tracks with demucs.
"""
mono_track = librosa.to_mono(stereo_track) # from stereo to mono
monores_track = librosa.resample(mono_track, 44100, target_sr) # resampling
if padding and len(monores_track) < target_sr*target_duration:
monores_track = librosa.util.fix_length(
monores_track, target_sr*target_duration)
return monores_track
def extract_audio_ts(audio_file, offset_df, clip_duration=30, sr=22050, padding=True):
"""
We assume that the base name of the audio file path corresponds to the
integer id that is associated to an entry in the offset_df dataframe.
TODO:
- The offset parameter should be either a dict or a dataframe;
- Provide different types of padding (right, center, left);
"""
track_id = int(os.path.basename(audio_file).split('.')[0])
y, _ = librosa.load(
audio_file, offset=offset_df.loc[track_id]["offset"],
duration=clip_duration, sr=sr)
if padding and offset_df.loc[track_id]["duration"] < clip_duration:
y = librosa.util.fix_length(y, sr*clip_duration)
return track_id, y
def extract_audio_ts_from_dataset(audio_dir, offset_df, clip_duration=30, sr=22050, njobs=1, save=None):
"""
Extracting audio time series from a collection of audio files.
TODO:
- same considerations of the atomic function used here;
- implement a blacklist filtering mechanism;
"""
audio_paths = glob.glob(audio_dir + "/*.mp3")
audio_ts = Parallel(n_jobs=njobs)(delayed(extract_audio_ts)(audio, offset_df, clip_duration, sr)
for _, audio in zip(tqdm(range(len(audio_paths))), audio_paths))
audio_ts = {track_id: track_audio_ts for track_id, track_audio_ts in audio_ts}
if save is not None:
with open(save, "wb") as f:
joblib.dump(audio_ts, f, compress=3)
return audio_ts
def extract_melspectogram(track_id, audio_ts, sr=22050, num_mels=40, fft_size=1024, win_size=1024, hop_size=512):
"""
... TODO
Requiring the track_id is just a temporary workaround to a joblib's bug (does not
always keep the order of elements processed in parallel).
"""
ms = librosa.feature.melspectrogram(
y=audio_ts, sr=sr, n_mels=num_mels,
n_fft=fft_size, win_length=win_size, hop_length=hop_size)
ms_db = librosa.power_to_db(ms, ref=np.max)
return track_id, ms, ms_db
def extract_multisource_melspectogram(track_id, multi_audio_ts, sr=22050, num_mels=40, fft_size=1024, win_size=1024, hop_size=512):
"""
... TODO
Same of the method before but for multi-sourced audio.
"""
multi_source_mel = {}
multi_source_lmel = {}
for source_name, source_audio_ts in multi_audio_ts.items():
_, ms, ms_db = extract_melspectogram(
None, source_audio_ts, sr=sr, num_mels=num_mels,
fft_size=fft_size, win_size=win_size, hop_size=hop_size)
multi_source_mel[source_name] = ms
multi_source_lmel[source_name] = ms_db
return track_id, multi_source_mel, multi_source_lmel
def extract_melspectograms_from_dataset(
audio_ts_map, sr=22050, num_mels=40, fft_size=1024, win_size=1024, hop_size=512, njobs=1, save=None, compression=3):
"""
Given a mapping {track_id : audio_ts} as a dict, compute the mel and the log-mel spectograms
for each track and return the resulting features as two separate items (indexed by track_id).
"""
extract_fn = extract_melspectogram
if isinstance(audio_ts_map[list(audio_ts_map.keys())[0]], dict):
extract_fn = extract_multisource_melspectogram
all_mels = Parallel(n_jobs=njobs)(delayed(extract_fn)(
track_id, audio_ts, sr, num_mels, fft_size, win_size, hop_size) \
for _, (track_id, audio_ts) in zip(tqdm(range(len(audio_ts_map))), audio_ts_map.items()))
result_mel = {track_id: mel for track_id, mel , _ in all_mels}
result_lmel = {track_id: logmel for track_id, _ , logmel in all_mels}
if save is not None:
with open(save, "wb") as f:
joblib.dump({'mel': result_mel, 'lmel': result_lmel}, f)
return result_mel, result_lmel
```
#### File: emomucs/preprocessing/pre_extraction.py
```python
import os
import glob
import librosa
import librosa.display
import pandas as pd
import numpy as np
# ensuring the reprod. of the exp setup
from numpy.random import seed
from numpy.random import randint
# seed(1992)
from joblib import Parallel, delayed
from tqdm import tqdm
def get_offset_from_track(audio_file, clip_duration=30):
"""
"""
dict_item = {
'track_id': os.path.basename(audio_file).split(".")[0],
'duration': librosa.get_duration(filename=audio_file)}
dict_item['offset'] = \
randint(0, np.ceil(dict_item['duration'] - clip_duration)) \
if dict_item['duration'] > clip_duration else 0.0
return dict_item
def get_offsets_from_dataset(audio_dir, clip_duration=30, njobs=1):
"""
Returns a list with dict entries, each associated to a specific
track. An inner dict contains the track id, the full duration
of the corresponding track, and an offset (in seconds) chosen
randomly to extract a clip of fixed "clip_duration".
TODO:
- Logging info and warnings...
"""
audio_paths = glob.glob(audio_dir + "/*.mp3")
audio_ofs = Parallel(n_jobs=njobs)\
(delayed(get_offset_from_track)(audio_file, clip_duration) \
for _, audio_file in zip(tqdm(range(len(audio_paths))), audio_paths))
return audio_ofs
def save_track_metadata(track_mapping, save_path, track_id="track_id"):
"""
Convert a list of dictionaries into a pandas dataframe, where the track id
is the index of the dataframe, and save it as a csv file.
"""
meta_df = pd.DataFrame(track_mapping)
meta_df[track_id] = pd.to_numeric(meta_df[track_id])
meta_df.set_index(track_id, inplace=True)
meta_df.to_csv(save_path)
return meta_df
def min_max_scaling(values, min_values=np.array([1., 1.]), max_values=np.array([9., 9.])):
"""
Min-max scaling for ensuring that the annotations are in the [-1, 1] VA range.
Minimum and maximum values for each column can be specified individually.
"""
return 2 * ((values - min_values) / (max_values - min_values)) - 1
def get_duration_from_file(audio_file):
"""
Simple wrapping function of ...
"""
track_id = int(os.path.basename(audio_file).split('.')[0])
return track_id, librosa.get_duration(filename=audio_file)
def compute_duration_per_track(audio_dir, njobs=1, save=None):
audio_paths = glob.glob(audio_dir + "/*.mp3")
print("Processing {} audio files.".format(len(audio_paths)))
audio_dur = Parallel(n_jobs=njobs)\
(delayed(get_duration_from_file)(audio_file) \
for _, audio_file in zip(tqdm(range(len(audio_paths))), audio_paths))
audio_dur = {track_id: duration for track_id, duration in audio_dur}
if save is not None:
with open(save, "wb") as f:
joblib.dump(audio_dur, f)
return audio_dur
``` |
{
"source": "JonnyBoy2000/Kira-Public",
"score": 3
} |
#### File: Kira-Public/modules/logs.py
```python
import discord
from discord.ext import commands
import datetime
class GuildLogs(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_guild_join(self, guild):
msg = f"<:check:534931851660230666> Joined guild {guild.name} with {guild.member_count} users. Now in {len(self.bot.guilds)} guilds."
print(msg)
self.bot.logger.info(f"[GUILD JOIN] Joined guild {guild.name} with {guild.member_count} users. Now in {len(self.bot.guilds)} guilds.")
@commands.Cog.listener()
async def on_guild_remove(self, guild):
msg = f"<:tickred:539495579793883176> Left guild {guild.name} with {guild.member_count} users. Now in {len(self.bot.guilds)} guilds."
print(msg)
self.bot.logger.info(f"[GUILD LEAVE] Left guild {guild.name} with {guild.member_count} users. Now in {len(self.bot.guilds)} guilds.")
def setup(bot):
bot.add_cog(GuildLogs(bot))
```
#### File: Kira-Public/modules/mod.py
```python
import discord
import random
import asyncio
import datetime
from datetime import timedelta
from discord.ext import commands
from utils import checks
from utils.mod import mass_purge, slow_deletion
class Mod(commands.Cog):
def __init__(self, bot):
self.bot = bot
def format_mod_embed(self, ctx, user, success, method):
'''Helper function to format an embed to prevent extra code'''
em = discord.Embed()
em.colour = 0x36393E
em.set_author(name=method.title(), icon_url=user.avatar_url)
em.set_footer(text='User ID: {}'.format(user.id))
if success:
if method == 'ban' or method == 'unban':
em.description = '{} was just {}ned.'.format(user, method)
else:
em.description = '{} was just {}d.'.format(user, method)
else:
em.description = 'You do not have the permissions to {} users.'.format(method)
return em
def _role_from_string(self, guild, rolename, roles=None):
if roles is None:
roles = guild.roles
role = discord.utils.find(lambda r: r.name.lower() == rolename.lower(),
roles)
return role
@commands.command()
@commands.guild_only()
async def clean(self, ctx):
"""Clean bot messages and command messages."""
logs = await self.bot.db.settings.find_one({"guild_id": ctx.guild.id})
can_mass_purge = ctx.channel.permissions_for(ctx.guild.me).manage_messages
await ctx.channel.purge(limit=100, check=lambda m: m.author == ctx.bot.user, before=ctx.message, after=datetime.datetime.now() - timedelta(days=14), bulk=can_mass_purge)
try:
await ctx.channel.purge(limit=100, check=lambda m: (m.content.startswith("k.") or m.content.startswith("k!") or m.content.startswith(str(logs['prefix']))), before=ctx.message, after=datetime.datetime.now() - timedelta(days=14), bulk=can_mass_purge)
except:
pass
await ctx.message.add_reaction('\u2705')
@commands.command()
@commands.guild_only()
@commands.check(checks.guild)
@commands.check(checks.kick)
async def voicekick(self, ctx, member: discord.Member):
"""Kick a member from voice chat"""
if member.voice is not None:
kick_channel = await ctx.guild.create_voice_channel(name=self.bot.user.name)
await member.move_to(kick_channel)
await kick_channel.delete()
await ctx.send("{0.name} has been kicked from voice".format(member))
else:
await ctx.send("{0.name} is not in a voice channel".format(member))
@commands.command()
@commands.guild_only()
@commands.check(checks.role)
async def addrole(self, ctx, role: discord.Role, user : discord.Member=None):
"""Adds a role to a user."""
if user is None:
user = ctx.author
try:
await user.add_roles(role)
await ctx.send('<:check:534931851660230666> Added role {} to {}'.format(role.name, user.name))
except discord.errors.Forbidden:
await ctx.send("<:notdone:334852376034803714> I don't have `manage_roles` permissions!")
@commands.command(aliases=['bc'])
@commands.check(checks.delete)
@commands.guild_only()
async def botclean(self, ctx, amount: int=100):
"""Deletes messages from bots in a channel"""
def is_bot(m):
return m.author.bot
try:
await ctx.channel.purge(limit=amount, check=is_bot)
except discord.HTTPException:
await ctx.send("The bot is missing permissions to delete messages.")
@commands.command()
@commands.guild_only()
@commands.check(checks.kick)
async def kick(self, ctx, member : discord.Member, *, reason : str = "[No reason specified]"):
"""Kick a user from your guild."""
reason = "[{}] {}".format(str(ctx.author), reason)
if member.top_role.position >= ctx.author.top_role.position:
await ctx.send("I can't do this.")
return
if member == ctx.guild.owner:
await ctx.send("I can't do this.")
return
if member == ctx.me:
await ctx.send("I can't do this.")
return
confcode = "{}".format(random.randint(1000,9999))
msg = "Please type in the confirmation code to confirm and kick this user, or wait 30 seconds to cancel."
e = discord.Embed()
e.colour = 0x36393E
e.description = msg
e.title = f"Kicking user {str(member)}:"
e.add_field(name="Reason:", value=reason)
e.add_field(name="Confirmation Code:", value=confcode)
m = await ctx.send(embed=e)
def a(m):
return m.content == confcode and m.channel == ctx.channel and m.author == ctx.author
try:
msg = await self.bot.wait_for("message", check=a, timeout=30)
except asyncio.TimeoutError:
await m.delete()
await ctx.send("Operation cancelled.")
return
await m.delete()
try:
await ctx.guild.kick(member, reason=reason)
await ctx.send("User {} was successfully kicked.".format(str(member)))
except (discord.HTTPException, discord.Forbidden) as e:
await ctx.send("I couldn't kick the user. Have you checked I have the proper permissions and that my role is higher than the user you want to kick?")
@commands.command()
@commands.guild_only()
@commands.check(checks.ban)
async def ban(self, ctx, member : discord.Member, *, reason : str = "[No reason specified]"):
"""Ban a user from your guild."""
reason = "[{}] {}".format(str(ctx.author), reason)
if member.top_role.position >= ctx.author.top_role.position:
await ctx.send("I can't do this.")
return
if member == ctx.guild.owner:
await ctx.send("I can't do this.")
return
if member == ctx.me:
await ctx.send("I can't do this.")
return
confcode = "{}".format(random.randint(1000,9999))
msg = "Please type in the confirmation code to confirm and ban this user, or wait 30 seconds to cancel."
e = discord.Embed()
e.colour = 0x36393E
e.description = msg
e.title = f"Banning user {str(member)}:"
e.add_field(name="Reason:", value=reason)
e.add_field(name="Confirmation Code:", value=confcode)
m = await ctx.send(embed=e)
def a(m):
return m.content == confcode and m.channel == ctx.channel and m.author == ctx.author
try:
msg = await self.bot.wait_for("message", check=a, timeout=30)
except asyncio.TimeoutError:
await m.delete()
await ctx.send("Operation cancelled.")
return
await m.delete()
try:
await ctx.guild.ban(member, reason=reason, delete_message_days=7)
await ctx.send("User {} was successfully banned.".format(str(member)))
except (discord.HTTPException, discord.Forbidden) as e:
await ctx.send("I couldn't ban the user. Have you checked I have the proper permissions and that my role is higher than the user you want to ban?")
@commands.command()
@commands.guild_only()
@commands.check(checks.ban)
async def hackban(self, ctx, userid, *, reason : str = "[No reason specified]"):
"""Hackban a user from your guild."""
reason = "[{}] {}".format(str(ctx.author), reason)
user = discord.Object(id=userid)
try:
name = await self.bot.http.get_user_info(userid)
except:
await ctx.send("User not found.")
return
confcode = "{}".format(random.randint(1000,9999))
msg = "Please type in the confirmation code to confirm and ban this user, or wait 30 seconds to cancel."
e = discord.Embed()
e.colour = 0x36393E
e.description = msg
e.title = f"Banning user {str(user)}:"
e.add_field(name="Reason:", value=reason)
e.add_field(name="Confirmation Code:", value=confcode)
m = await ctx.send(embed=e)
def a(m):
return m.content == confcode and m.channel == ctx.channel and m.author == ctx.author
try:
msg = await self.bot.wait_for("message", check=a, timeout=30)
except asyncio.TimeoutError:
await m.delete()
await ctx.send("Operation cancelled.")
return
await m.delete()
try:
await ctx.guild.ban(user)
await ctx.send(f"User {name['username']} was successfully banned.")
except (discord.HTTPException, discord.Forbidden) as e:
await ctx.send("I couldn't ban the user. Have you checked I have the proper permissions and that my role is higher than the user you want to ban?")
@commands.command()
@commands.guild_only()
@commands.check(checks.ban)
async def softban(self, ctx, member : discord.Member, *, reason : str = "[No reason specified]"):
"""Softban a user from your guild."""
reason = "[{}] {}".format(str(ctx.author), reason)
if member.top_role.position >= ctx.author.top_role.position:
await ctx.send("I can't do this.")
return
if member == ctx.guild.owner:
await ctx.send("I can't do this.")
return
if member == ctx.me:
await ctx.send("I can't do this.")
return
confcode = "{}".format(random.randint(1000,9999))
msg = "Please type in the confirmation code to confirm and softban this user, or wait 30 seconds to cancel."
e = discord.Embed()
e.colour = 0x36393E
e.description = msg
e.title = f"Soft Banning user {str(member)}:"
e.add_field(name="Reason:", value=reason)
e.add_field(name="Confirmation Code:", value=confcode)
m = await ctx.send(embed=e)
def a(m):
return m.content == confcode and m.channel == ctx.channel and m.author == ctx.author
try:
msg = await self.bot.wait_for("message", check=a, timeout=30)
except asyncio.TimeoutError:
await m.delete()
await ctx.send("Operation cancelled.")
return
await m.delete()
try:
await ctx.guild.ban(member, reason=reason, delete_message_days=7)
await ctx.guild.unban(member, reason=reason)
await ctx.send("User {} was successfully softbanned.".format(str(member)))
except (discord.HTTPException, discord.Forbidden) as e:
await ctx.send("I couldn't softban the user. Have you checked I have the proper permissions and that my role is higher than the user you want to softban?")
@commands.command()
@commands.guild_only()
@commands.check(checks.guild)
async def mute(self, ctx, user: discord.Member):
"""Mute someone from the channel"""
try:
await ctx.channel.set_permissions(user, send_messages=False)
except:
success=False
else:
success=True
em=self.format_mod_embed(ctx, user, success, 'mute')
await ctx.send(embed=em)
@commands.command()
@commands.guild_only()
@commands.check(checks.delete)
async def prune(self, ctx: commands.Context, number: int):
"""Prunes messages from the channel."""
channel = ctx.channel
author = ctx.author
is_bot = self.bot.user.bot
to_delete = []
tmp = ctx.message
done = False
while len(to_delete) - 1 < number and not done:
async for message in channel.history(limit=1000, before=tmp):
if len(to_delete) - 1 < number and \
(ctx.message.created_at - message.created_at).days < 14:
to_delete.append(message)
elif (ctx.message.created_at - message.created_at).days >= 14:
done = True
break
tmp = message
if is_bot:
await mass_purge(to_delete, channel)
else:
await slow_deletion(to_delete)
@commands.command()
@commands.guild_only()
@commands.check(checks.guild)
async def unmute(self, ctx, user: discord.Member):
"""Unmute someone from the channel"""
try:
await ctx.channel.set_permissions(user, send_messages=True)
except:
success=False
else:
success=True
em= self.format_mod_embed(ctx, user, success, 'unmute')
await ctx.send(embed=em)
def setup(bot):
bot.add_cog(Mod(bot))
```
#### File: Kira-Public/modules/sounds.py
```python
import discord
from utils import checks
from discord.ext import commands
class Sounds(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.music = self.bot.get_cog('Music')
@commands.group()
@commands.guild_only()
@commands.check(checks.can_embed)
async def sounds(self, ctx):
"""Soundboard sounds."""
if ctx.invoked_subcommand is None:
e = discord.Embed()
e.colour = 0x36393E
e.set_author(name="Help for Wakk's command group sounds.", icon_url=ctx.guild.me.avatar_url)
e.description = "**add - ** Add a sound to your soundboard sounds..\n"
e.description += "**delete -** Delete a sound from your soundboard sounds.\n"
e.description += "**start -** Start a sound from your soundboard sounds.\n"
e.description += "**show -** Show your soundboard sounds.\n"
e.set_thumbnail(url=ctx.guild.me.avatar_url)
await ctx.send(embed=e)
@sounds.command(name="show")
async def _show(self, ctx):
"""Show your soundboard sounds."""
logs = await self.bot.db.sounds.find_one({"user_id": ctx.author.id})
settings = {
"user_id": ctx.author.id,
}
if not logs:
await ctx.send("Database not found for you, create one by adding a sound.")
return
if logs:
if logs == settings:
await ctx.send("You have a database, but you don't have any sounds, use the command `..sounds` to add some, use this as an example `..sounds add <sound_name>`")
return
number = 0
data = discord.Embed()
data.set_author(name="Here are those lit soundboard sounds.", icon_url=ctx.author.avatar_url)
data.colour = 0x36393E
description = "\n**Available Sounds:**\n"
for key, val in logs.items():
if "_id" in key:
continue
number += 1
description += f"`{number})` {key}\n"
if description == "\n**Available Sounds:**\n":
description += "Oh you don't have any sounds? Here is how to add some."
data.description = description.replace('\n**Available Sounds:**\n', '')
data.set_image(url="http://the-best.thicc-ho.es/34e04ecb36.gif")
data.description = description
await ctx.send(embed=data)
@sounds.command(name="add")
async def _add(self, ctx, sound_name: str):
"""Add a sound to your soundboard sounds."""
logs = await self.bot.db.sounds.find_one({"user_id": ctx.author.id})
msg = ctx.message
if not msg.attachments:
await ctx.send("Please attach a sound file to the command message.")
return
if ("png" or "jpg" or "gif" or "webp") in msg.attachments[0].url:
await ctx.send("Please only use audio files.")
return
if msg.attachments[0].size > 1000000:
await ctx.send("I'm sorry but you can only add sounds that are 1mb.")
return
if not logs:
settings = {
"user_id": ctx.author.id,
}
await self.bot.db.sounds.insert_one(settings)
try:
await self.bot.db.sounds.update_one({"user_id": ctx.author.id}, {'$set': {sound_name: msg.attachments[0].url}})
await ctx.send("Done, I have added your file to your database. DO NOT DELETE THE FILE FROM DISCORD IT WILL BREAK. Unless you don't want to be able to play this sound anymore.")
except Exception as e:
await ctx.send(e)
@sounds.command(name="delete")
async def _delete(self, ctx, sound_name: str):
"""Delete a sound from your soundboard sounds."""
logs = await self.bot.db.sounds.find_one({"user_id": ctx.author.id})
if logs:
if logs[sound_name]:
await self.bot.db.sounds.update_one({"user_id": ctx.author.id}, {'$unset': {sound_name: logs[sound_name]}})
await ctx.send("Done, deleted.")
return
else:
await ctx.send("Sorry, but I couldn't find that sound in your databse.")
return
else:
await ctx.send("Why are you trying to delete something when you don't have a databse?")
@sounds.command(name="start")
@commands.check(checks.in_voice)
async def _start(self, ctx, sound_name: str):
"""Start a sound from your soundboard sounds."""
logs = await self.bot.db.sounds.find_one({"user_id": ctx.author.id})
if logs:
try:
if logs[sound_name]:
msg = await ctx.send("Playing...")
await self.music.play(ctx, ctx.guild, ctx.message, ctx.author, ctx.channel, msg, False, True, logs[sound_name])
else:
await ctx.send("Sorry, but I couldn't find that sound in your databse.")
return
except:
await ctx.send("Sorry, but I couldn't find that sound in your databse.")
else:
await ctx.send("Why are you trying to play something when you don't have a databse?")
def setup(bot):
n = Sounds(bot)
bot.add_cog(n)
```
#### File: Kira-Public/utils/checks.py
```python
async def is_owner(ctx):
if ctx.author.id == ctx.bot.config['ownerid']:
return True
else:
await ctx.send("<:tickred:539495579793883176> Command is locked to developers, sorry.", delete_after=10)
return False
async def is_nsfw(ctx):
try:
if ctx.channel.is_nsfw() == True:
return True
else:
await ctx.send("<:tickred:539495579793883176> Nice try you perv. This isn't a NSFW channel.", delete_after=10)
return False
except:
return True
async def can_embed(ctx):
try:
if (ctx.guild.me.permissions_in(ctx.channel).attach_files and ctx.guild.me.permissions_in(ctx.channel).embed_links) is True:
return True
else:
await ctx.send("<:tickred:539495579793883176> I can't embed links or send files. Please fix permissions and try again.", delete_after=10)
return False
except:
return True
async def kick(ctx):
try:
if (ctx.author.permissions_in(ctx.channel).kick_members and ctx.guild.me.permissions_in(ctx.channel).kick_members) is True:
return True
else:
await ctx.send("<:tickred:539495579793883176> Either you or me do not have the `kick_members` permission. Please fix permissions and try again.", delete_after=10)
return False
except:
return True
async def ban(ctx):
try:
if (ctx.author.permissions_in(ctx.channel).ban_members and ctx.guild.me.permissions_in(ctx.channel).ban_members) is True:
return True
else:
await ctx.send("<:tickred:539495579793883176> Either you or me do not have the `ban_members` permission. Please fix permissions and try again.", delete_after=10)
return False
except:
return True
async def delete(ctx):
try:
if (ctx.author.permissions_in(ctx.channel).manage_messages and ctx.guild.me.permissions_in(ctx.channel).manage_messages) is True:
return True
else:
await ctx.send("<:tickred:539495579793883176> Either you or me do not have the `manage_messages` permission. Please fix permissions and try again.", delete_after=10)
return False
except:
return True
async def guild(ctx):
try:
if (ctx.author.permissions_in(ctx.channel).manage_guild and ctx.guild.me.permissions_in(ctx.channel).manage_guild) is True:
return True
else:
await ctx.send("<:tickred:539495579793883176> Either you or me do not have the `manage_guild` permission. Please fix permissions and try again.", delete_after=10)
return False
except:
return True
async def role(ctx):
try:
if (ctx.author.permissions_in(ctx.channel).manage_roles and ctx.guild.me.permissions_in(ctx.channel).manage_roles) is True:
return True
else:
await ctx.send("<:tickred:539495579793883176> Either you or me do not have the `manage_roles` permission. Please fix permissions and try again.", delete_after=10)
return False
except:
return True
async def in_voice(ctx):
if ctx.author.voice:
if ctx.guild.me.voice:
if ctx.author.voice.channel != ctx.guild.me.voice.channel:
await ctx.send("<:tickred:539495579793883176> You must be in **my** voice channel to use the command.", delete_after=10)
return False
else:
return True
else:
return True
else:
await ctx.send("<:tickred:539495579793883176> You must be in a voice channel to use the command.", delete_after=10)
return False
```
#### File: Kira-Public/utils/mod.py
```python
from typing import List, Iterable, Union
import discord
import asyncio
async def mass_purge(messages: List[discord.Message],
channel: discord.TextChannel):
while messages:
if len(messages) > 1:
await channel.delete_messages(messages[:100])
messages = messages[100:]
else:
await messages[0].delete()
messages = []
await asyncio.sleep(1.5)
async def slow_deletion(messages: Iterable[discord.Message]):
for message in messages:
try:
await message.delete()
except discord.HTTPException:
pass
``` |
{
"source": "JonnyBoy2000/Lavalink.py",
"score": 2
} |
#### File: Lavalink.py/examples/music-v3.py
```python
import logging
import math
import re
import discord
import lavalink
from discord.ext import commands
time_rx = re.compile('[0-9]+')
url_rx = re.compile('https?:\/\/(?:www\.)?.+')
class Music:
def __init__(self, bot):
self.bot = bot
if not hasattr(bot, 'lavalink'):
lavalink.Client(bot=bot, password='<PASSWORD>',
loop=bot.loop, log_level=logging.DEBUG)
self.bot.lavalink.register_hook(self._track_hook)
def __unload(self):
for guild_id, player in self.bot.lavalink.players:
self.bot.loop.create_task(player.disconnect())
player.cleanup()
# Clear the players from Lavalink's internal cache
self.bot.lavalink.players.clear()
self.bot.lavalink.unregister_hook(self._track_hook)
async def _track_hook(self, event):
if isinstance(event, lavalink.Events.StatsUpdateEvent):
return
channel = self.bot.get_channel(event.player.fetch('channel'))
if not channel:
return
if isinstance(event, lavalink.Events.TrackStartEvent):
await channel.send(embed=discord.Embed(title='Now playing:',
description=event.track.title,
color=discord.Color.blurple()))
elif isinstance(event, lavalink.Events.QueueEndEvent):
await channel.send('Queue ended! Why not queue more songs?')
@commands.command(name='play', aliases=['p'])
@commands.guild_only()
async def _play(self, ctx, *, query: str):
""" Searches and plays a song from a given query. """
player = self.bot.lavalink.players.get(ctx.guild.id)
query = query.strip('<>')
if not url_rx.match(query):
query = f'ytsearch:{query}'
results = await self.bot.lavalink.get_tracks(query)
if not results or not results['tracks']:
return await ctx.send('Nothing found!')
embed = discord.Embed(color=discord.Color.blurple())
if results['loadType'] == 'PLAYLIST_LOADED':
tracks = results['tracks']
for track in tracks:
player.add(requester=ctx.author.id, track=track)
embed.title = 'Playlist Enqueued!'
embed.description = f'{results["playlistInfo"]["name"]} - {len(tracks)} tracks'
await ctx.send(embed=embed)
else:
track = results['tracks'][0]
embed.title = 'Track Enqueued'
embed.description = f'[{track["info"]["title"]}]({track["info"]["uri"]})'
await ctx.send(embed=embed)
player.add(requester=ctx.author.id, track=track)
if not player.is_playing:
await player.play()
@commands.command(name='previous', aliases=['pv'])
@commands.guild_only()
async def _previous(self, ctx):
""" Plays the previous song. """
player = self.bot.lavalink.players.get(ctx.guild.id)
try:
await player.play_previous()
except lavalink.NoPreviousTrack:
await ctx.send('There is no previous song to play.')
@commands.command(name='playnow', aliases=['pn'])
@commands.guild_only()
async def _playnow(self, ctx, *, query: str):
""" Plays immediately a song. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue and not player.is_playing:
return await ctx.invoke(self._play, query=query)
query = query.strip('<>')
if not url_rx.match(query):
query = f'ytsearch:{query}'
results = await self.bot.lavalink.get_tracks(query)
if not results or not results['tracks']:
return await ctx.send('Nothing found!')
tracks = results['tracks']
track = tracks.pop(0)
if results['loadType'] == 'PLAYLIST_LOADED':
for _track in tracks:
player.add(requester=ctx.author.id, track=_track)
await player.play_now(requester=ctx.author.id, track=track)
@commands.command(name='playat', aliases=['pa'])
@commands.guild_only()
async def _playat(self, ctx, index: int):
""" Plays the queue from a specific point. Disregards tracks before the index. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if index < 1:
return await ctx.send('Invalid specified index.')
if len(player.queue) < index:
return await ctx.send('This index exceeds the queue\'s length.')
await player.play_at(index-1)
@commands.command(name='seek')
@commands.guild_only()
async def _seek(self, ctx, *, time: str):
""" Seeks to a given position in a track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
seconds = time_rx.search(time)
if not seconds:
return await ctx.send('You need to specify the amount of seconds to skip!')
seconds = int(seconds.group()) * 1000
if time.startswith('-'):
seconds *= -1
track_time = player.position + seconds
await player.seek(track_time)
await ctx.send(f'Moved track to **{lavalink.Utils.format_time(track_time)}**')
@commands.command(name='skip', aliases=['forceskip', 'fs'])
@commands.guild_only()
async def _skip(self, ctx):
""" Skips the current track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
await player.skip()
await ctx.send('⏭ | Skipped.')
@commands.command(name='stop')
@commands.guild_only()
async def _stop(self, ctx):
""" Stops the player and clears its queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
player.queue.clear()
await player.stop()
await ctx.send('⏹ | Stopped.')
@commands.command(name='now', aliases=['np', 'n', 'playing'])
@commands.guild_only()
async def _now(self, ctx):
""" Shows some stats about the currently playing song. """
player = self.bot.lavalink.players.get(ctx.guild.id)
song = 'Nothing'
if player.current:
position = lavalink.Utils.format_time(player.position)
if player.current.stream:
duration = '🔴 LIVE'
else:
duration = lavalink.Utils.format_time(player.current.duration)
song = f'**[{player.current.title}]({player.current.uri})**\n({position}/{duration})'
embed = discord.Embed(color=discord.Color.blurple(),
title='Now Playing', description=song)
await ctx.send(embed=embed)
@commands.command(name='queue', aliases=['q'])
@commands.guild_only()
async def _queue(self, ctx, page: int = 1):
""" Shows the player's queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue:
return await ctx.send('There\'s nothing in the queue! Why not queue something?')
items_per_page = 10
pages = math.ceil(len(player.queue) / items_per_page)
start = (page - 1) * items_per_page
end = start + items_per_page
queue_list = ''
for index, track in enumerate(player.queue[start:end], start=start):
queue_list += f'`{index + 1}.` [**{track.title}**]({track.uri})\n'
embed = discord.Embed(colour=discord.Color.blurple(),
description=f'**{len(player.queue)} tracks**\n\n{queue_list}')
embed.set_footer(text=f'Viewing page {page}/{pages}')
await ctx.send(embed=embed)
@commands.command(name='pause', aliases=['resume'])
@commands.guild_only()
async def _pause(self, ctx):
""" Pauses/Resumes the current track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
if player.paused:
await player.set_pause(False)
await ctx.send('⏯ | Resumed')
else:
await player.set_pause(True)
await ctx.send('⏯ | Paused')
@commands.command(name='volume', aliases=['vol'])
@commands.guild_only()
async def _volume(self, ctx, volume: int = None):
""" Changes the player's volume. Must be between 0 and 1000. Error Handling for that is done by Lavalink. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not volume:
return await ctx.send(f'🔈 | {player.volume}%')
await player.set_volume(volume)
await ctx.send(f'🔈 | Set to {player.volume}%')
@commands.command(name='shuffle')
@commands.guild_only()
async def _shuffle(self, ctx):
""" Shuffles the player's queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Nothing playing.')
player.shuffle = not player.shuffle
await ctx.send('🔀 | Shuffle ' + ('enabled' if player.shuffle else 'disabled'))
@commands.command(name='repeat', aliases=['loop'])
@commands.guild_only()
async def _repeat(self, ctx):
""" Repeats the current song until the command is invoked again. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Nothing playing.')
player.repeat = not player.repeat
await ctx.send('🔁 | Repeat ' + ('enabled' if player.repeat else 'disabled'))
@commands.command(name='remove')
@commands.guild_only()
async def _remove(self, ctx, index: int):
""" Removes an item from the player's queue with the given index. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue:
return await ctx.send('Nothing queued.')
if index > len(player.queue) or index < 1:
return await ctx.send(f'Index has to be **between** 1 and {len(player.queue)}')
index -= 1
removed = player.queue.pop(index)
await ctx.send(f'Removed **{removed.title}** from the queue.')
@commands.command(name='find')
@commands.guild_only()
async def _find(self, ctx, *, query):
""" Lists the first 10 search results from a given query. """
if not query.startswith('ytsearch:') and not query.startswith('scsearch:'):
query = 'ytsearch:' + query
results = await self.bot.lavalink.get_tracks(query)
if not results or not results['tracks']:
return await ctx.send('Nothing found')
tracks = results['tracks'][:10] # First 10 results
o = ''
for index, track in enumerate(tracks, start=1):
track_title = track["info"]["title"]
track_uri = track["info"]["uri"]
o += f'`{index}.` [{track_title}]({track_uri})\n'
embed = discord.Embed(color=discord.Color.blurple(), description=o)
await ctx.send(embed=embed)
@commands.command(name='disconnect', aliases=['dc'])
@commands.guild_only()
async def _disconnect(self, ctx):
""" Disconnects the player from the voice channel and clears its queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_connected:
return await ctx.send('Not connected.')
if not ctx.author.voice or (player.is_connected and ctx.author.voice.channel.id != int(player.channel_id)):
return await ctx.send('You\'re not in my voicechannel!')
player.queue.clear()
await player.disconnect()
await ctx.send('*⃣ | Disconnected.')
@_playnow.before_invoke
@_previous.before_invoke
@_play.before_invoke
async def ensure_voice(self, ctx):
""" A few checks to make sure the bot can join a voice channel. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_connected:
if not ctx.author.voice or not ctx.author.voice.channel:
await ctx.send('You aren\'t connected to any voice channel.')
raise commands.CommandInvokeError(
'Author not connected to voice channel.')
permissions = ctx.author.voice.channel.permissions_for(ctx.me)
if not permissions.connect or not permissions.speak:
await ctx.send('Missing permissions `CONNECT` and/or `SPEAK`.')
raise commands.CommandInvokeError(
'Bot has no permissions CONNECT and/or SPEAK')
player.store('channel', ctx.channel.id)
await player.connect(ctx.author.voice.channel.id)
else:
if player.connected_channel.id != ctx.author.voice.channel.id:
return await ctx.send('Join my voice channel!')
def setup(bot):
bot.add_cog(Music(bot))
```
#### File: Lavalink.py/lavalink/Client.py
```python
import asyncio
import logging
from urllib.parse import quote
import aiohttp
from .Events import TrackEndEvent, TrackExceptionEvent, TrackStuckEvent
from .PlayerManager import DefaultPlayer, PlayerManager
from .Stats import Stats
from .WebSocket import WebSocket
log = logging.getLogger(__name__)
def set_log_level(log_level):
root_log = logging.getLogger(__name__.split('.')[0])
root_log.setLevel(log_level)
class Client:
def __init__(self, bot, log_level=logging.INFO, loop=asyncio.get_event_loop(), host='localhost',
rest_port=2333, password='', ws_retry=3, ws_port=80, shard_count=1, player=DefaultPlayer):
"""
Creates a new Lavalink client.
-----------------
:param bot:
The bot to attach the Client to.
:param log_level:
The log_level to set the client to. Defaults to ``INFO``
:param loop:
The event loop for the client.
:param host:
Your Lavalink server's host address.
:param rest_port:
The port over which the HTTP requests should be made.
:param password:
The password for your Lavalink server. The default password is ``<PASSWORD>``.
:param ws_retry:
How often the client should attempt to reconnect to the Lavalink server.
:param ws_port:
The port on which a WebSocket connection to the Lavalink server should be established.
:param shard_count:
The bot's shard count. Defaults to ``1``.
:param player:
The class that should be used for the player. Defaults to ``DefaultPlayer``.
Do not change this unless you know what you are doing!
"""
bot.lavalink = self
self.http = aiohttp.ClientSession(loop=loop)
self.voice_state = {}
self.hooks = []
set_log_level(log_level)
self.bot = bot
self.bot.add_listener(self.on_socket_response)
self.loop = loop
self.rest_uri = 'http://{}:{}/loadtracks?identifier='.format(host, rest_port)
self.password = password
self.ws = WebSocket(
self, host, password, ws_port, ws_retry, shard_count
)
self._server_version = 2
self.stats = Stats()
self.players = PlayerManager(self, player)
def register_hook(self, func):
"""
Registers a hook. Since this probably is a bit difficult, I'll explain it in detail.
A hook basically is an object of a function you pass. This will append that object to a list and whenever
an event from the Lavalink server is dispatched, the function will be called internally. For declaring the
function that should become a hook, pass ``event` as its sole parameter.
Can be a function but also a coroutine.
Example for a method declaration inside a class:
---------------
self.bot.lavalink.register_hook(my_hook)
async def my_hook(self, event):
channel = self.bot.get_channel(event.player.fetch('channel'))
if not channel:
return
if isinstance(event, lavalink.Events.TrackStartEvent):
await channel.send(embed=discord.Embed(title='Now playing:',
description=event.track.title,
color=discord.Color.blurple()))
---------------
:param func:
The function that should be registered as a hook.
"""
if func not in self.hooks:
self.hooks.append(func)
def unregister_hook(self, func):
""" Unregisters a hook. For further explanation, please have a look at ``register_hook``. """
if func in self.hooks:
self.hooks.remove(func)
async def dispatch_event(self, event):
""" Dispatches an event to all registered hooks. """
log.debug('Dispatching event of type {} to {} hooks'.format(event.__class__.__name__, len(self.hooks)))
for hook in self.hooks:
try:
if asyncio.iscoroutinefunction(hook):
await hook(event)
else:
hook(event)
except Exception as e: # pylint: disable=broad-except
# Catch generic exception thrown by user hooks
log.warning(
'Encountered exception while dispatching an event to hook `{}` ({})'.format(hook.__name__, str(e)))
if isinstance(event, (TrackEndEvent, TrackExceptionEvent, TrackStuckEvent)) and event.player:
await event.player.handle_event(event)
async def update_state(self, data):
""" Updates a player's state when a payload with opcode ``playerUpdate`` is received. """
guild_id = int(data['guildId'])
if guild_id in self.players:
player = self.players.get(guild_id)
player.position = data['state'].get('position', 0)
player.position_timestamp = data['state']['time']
async def get_tracks(self, query):
""" Returns a Dictionary containing search results for a given query. """
log.debug('Requesting tracks for query {}'.format(query))
async with self.http.get(self.rest_uri + quote(query), headers={'Authorization': self.password}) as res:
return await res.json(content_type=None)
# Bot Events
async def on_socket_response(self, data):
"""
This coroutine will be called every time an event from Discord is received.
It is used to update a player's voice state through forwarding a payload via the WebSocket connection to Lavalink.
-------------
:param data:
The payload received from Discord.
"""
# INTERCEPT VOICE UPDATES
if not data or data.get('t', '') not in ['VOICE_STATE_UPDATE', 'VOICE_SERVER_UPDATE']:
return
if data['t'] == 'VOICE_SERVER_UPDATE':
self.voice_state.update({
'op': 'voiceUpdate',
'guildId': data['d']['guild_id'],
'event': data['d']
})
else:
if int(data['d']['user_id']) != self.bot.user.id:
return
self.voice_state.update({'sessionId': data['d']['session_id']})
guild_id = int(data['d']['guild_id'])
if self.players[guild_id]:
self.players[guild_id].channel_id = data['d']['channel_id']
if {'op', 'guildId', 'sessionId', 'event'} == self.voice_state.keys():
await self.ws.send(**self.voice_state)
self.voice_state.clear()
def destroy(self):
""" Destroys the Lavalink client. """
self.ws.destroy()
self.bot.remove_listener(self.on_socket_response)
self.hooks.clear()
```
#### File: Lavalink.py/lavalink/Events.py
```python
class QueueEndEvent:
""" This event will be dispatched when there are no more songs in the queue. """
def __init__(self, player):
self.player = player
class TrackStuckEvent:
""" This event will be dispatched when the currently playing song is stuck. """
def __init__(self, player, track, threshold):
self.player = player
self.track = track
self.threshold = threshold
class TrackExceptionEvent:
""" This event will be dispatched when an exception occurs while playing a track. """
def __init__(self, player, track, exception):
self.exception = exception
self.player = player
self.track = track
class TrackEndEvent:
""" This event will be dispatched when the player finished playing a track. """
def __init__(self, player, track, reason):
self.reason = reason
self.player = player
self.track = track
class TrackStartEvent:
""" This event will be dispatched when the player starts to play a track. """
def __init__(self, player, track):
self.player = player
self.track = track
class StatsUpdateEvent:
""" This event will be dispatched when the websocket receives a statistics update. """
def __init__(self, data):
self.stats = data
```
#### File: Lavalink.py/lavalink/Stats.py
```python
class Memory:
def __init__(self):
self.reservable = 0
self.free = 0
self.used = 0
self.allocated = 0
class CPU:
def __init__(self):
self.cores = 0
self.system_load = 0.0
self.lavalink_load = 0.0
class Stats:
def __init__(self):
self.playing_players = 0
self.memory = Memory()
self.cpu = CPU()
self.uptime = 0
def _update(self, data: dict):
self.playing_players = data.get("playingPlayers", 0)
self.memory.reservable = data.get("memory", {}).get("reservable", 0)
self.memory.free = data.get("memory", {}).get("free", 0)
self.memory.used = data.get("memory", {}).get("used", 0)
self.memory.allocated = data.get("memory", {}).get("allocated", 0)
self.cpu.cores = data.get("cpu", {}).get("cores", 0)
self.cpu.system_load = data.get("cpu", {}).get("systemLoad", 0)
self.cpu.lavalink_load = data.get("cpu", {}).get("lavalinkLoad", 0)
self.uptime = data.get("uptime", 0)
```
#### File: Lavalink.py/lavalink/Utils.py
```python
def format_time(time):
""" Formats the given time into HH:MM:SS. """
hours, remainder = divmod(time / 1000, 3600)
minutes, seconds = divmod(remainder, 60)
if hours:
return '%02dh %02dm %02ds' % (hours, minutes, seconds)
if minutes:
return '%02dm %02ds' % (minutes, seconds)
if seconds:
return '%02ds' % (seconds)
``` |
{
"source": "Jonnybuoy/AppRepo",
"score": 2
} |
#### File: Jonnybuoy/AppRepo/fabfile.py
```python
from fabric.api import local
def prepare_deploy():
local("coverage run --source='.' manage.py test")
local("coverage report")
local("cd /home/johnson/Johnproject && git status && git add django-practice/app_portfolio && git commit && git push origin learningbranch")
local("pwd")
```
#### File: AppRepo/shoppinglist/views.py
```python
from django.shortcuts import render
from shoppinglist.models import Shoppinglist
# from django.utils import timezone
# from .forms import NameForm
# from django.contrib import messages
def list_index(request):
shoplist = Shoppinglist.objects.all()
context = {
'shoplist': shoplist
}
return render(request, 'list_index.html', context)
# def list_details(request, pk):
# shoplists = Shoppinglist.objects.get(pk=pk)
# context = {
# 'shoplists': shoplists
# }
#
# return render(request, 'list_detail.html', context)
#
#
# def list_add(request):
# if request.method == "POST":
# # create form instance, populate with data from request
# form = NameForm(request.POST)
# # check if it's valid
# if form.is_valid():
# post = form.save(commit=False)
# post.created_at = timezone.now()
# post.save()
# # process and redirect
# return redirect('list_index')
#
# else:
# form = NameForm()
# return render(request, 'add.html', {'form': form})
# def list_delete(request, pk):
# shoplist = Shoppinglist.objects.get(pk=pk)
# form = DeleteForm(request.POST)
# try:
# if request.method == "POST":
# shoplist.delete()
# messages.success(request, 'Item successfully deleted!')
# else:
# form = DeleteForm(instance=shoplist)
# except Exception as e:
# messages.warning(request, "Could not delete item: Error {}".format(e))
# context = {
# 'form': form,
# 'shoplist': shoplist
# }
# return render(request, 'list_delete.html', context)
``` |
{
"source": "JonnyCBB/themepy",
"score": 3
} |
#### File: themepy/themepy/theme.py
```python
import matplotlib as mpl
from .set_theme import set_params, list_themes
class Theme:
def __init__(self, theme_name=None):
self.theme_list = list_themes()
if theme_name is None:
mpl.rcParams.update(mpl.rcParamsDefault)
self.theme_name = "Matplotlib"
self.background = mpl.rcParams['figure.facecolor']
self.primary_color = '#1f77b4'
self.secondary_color = '#ff7f0e'
self.tertiary_color = '#2ca02c'
self.markings = "k"
self.fontfamily = mpl.rcParams['font.family']
self.title_font = {"fontfamily": mpl.rcParams['font.family']}
self.body_font = {"fontfamily": mpl.rcParams['font.family']}
self.dpi = 100
else:
set_params(self, theme_name)
def __repr__(self):
return self.theme_name + " is the active theme"
def __str__(self):
return self.theme_name + " is the active theme"
def set_theme(self, theme_name=None):
"""
Passes values from our selected theme (or defaults)
Input
=====
theme_name: str - name of theme to use
Returns
=======
changed properties of instantiated class
"""
set_params(self, theme_name)
return self
def set_font(self, fontfamily=None):
"""
Sets the font that will be used for plotting.
Input
=====
font_name: str - name of font that is
currently availble in matplotlib
Returns
=======
updated self.fontfamily
self.title_font
self.body_font
"""
if fontfamily is None:
self.fontfamily = mpl.rcParams['font.family']
else:
self.fontfamily = fontfamily
mpl.rcParams['font.family'] = fontfamily
self.title_font = {"fontfamily": fontfamily}
self.body_font = {"fontfamily": fontfamily}
return self
def set_title_font(self, title_font=None):
"""
Allows us to use a different font with **kwarg.
This does not automatically change the title font.
e.g:
theme = themepy.Theme()
theme.set_title_font("Arial")
fig, ax = plt.subplots(figsize=(8,8))
ax.set_title("This is a title", **theme.title_font)
plt.show()
Input
=====
title_font: str - name of font that is
currently availble in matplotlib
Returns
=======
updated self.title_font
"""
if title_font is None:
self.title_font = {"fontfamily": mpl.rcParams['font.family']}
else:
self.title_font = {"fontfamily": title_font}
return self
def set_body_font(self, body_font=None):
"""
Allows us to use a different font with **kwarg.
This does not automatically change the body font.
e.g:
theme = themepy.Theme()
theme.set_title_font("Arial")
fig, ax = plt.subplots(figsize=(8,8))
ax.text(0.5, 0.5,
"This is a some text", **theme.body_font)
plt.show()
Input
=====
body_font: str - name of font that is
currently availble in matplotlib
Returns
=======
updated self.body_font
"""
if body_font is None:
self.body_font = {"fontfamily": mpl.rcParams['font.family']}
else:
self.body_font = {"fontfamily": body_font}
return self
def set_pips(self, state=True):
"""
Show or hide tick lines on plots.
Input
=====
state: bool - True of False
Returns
=======
updated mpl.rcParams with ticks toggled on or off
"""
if state in ["on", True]:
mpl.rcParams['xtick.bottom'] = True
mpl.rcParams['ytick.left'] = True
elif state in ["off", False]:
mpl.rcParams['xtick.bottom'] = False
mpl.rcParams['ytick.left'] = False
else:
raise NameError("unrecognised state. Must be one of True/False or 'on'/'off")
return self
def set_spines(self, state="on", which=["top", "right", "bottom", "left"]):
"""
Sets the spines on or off. A method in matplotlib
to turn spines off might be:
Input
=====
state: str - "on" or "off"
which: list - spines to be turned on or off.
Returns
=======
updated mpl.rcParams for spine visibility
"""
if state == "on":
switch = True
else:
switch = False
for spine in which:
mpl.rcParams['axes.spines.'+spine] = switch
return self
def set_ticklabel_size(self, size="medium", which="both"):
"""
Sets the size of x, y, or both ticklabels.
Input
=====
size: str or int
which: str - 'both', 'x', or 'y'
Returns
=======
updated mpl.rcParams for x and/or y tick labelsize
"""
if (type(size) is str) & (size not in ["small", "medium", "large"]):
raise ValueError("""{} is not a value size arguement. Size must either be a value or one of xx-small, x-small, small, medium, large, x-large, xx-large, smaller, larger""".format(size))
if which == "both":
mpl.rcParams['xtick.labelsize'] = size
mpl.rcParams['ytick.labelsize'] = size
elif which == "x":
mpl.rcParams['xtick.labelsize'] = size
elif which == "y":
mpl.rcParams['ytick.labelsize'] = size
else:
raise KeyError("{} is not a valid arg. Must be 'both' or one of 'x' or 'y'".format(which))
return self
``` |
{
"source": "JonnyD1117/RGB-D-Plant-Segmentation",
"score": 2
} |
#### File: data/Carvana_Dataset/ValDS.py
```python
import os
import cv2
from pathlib import Path
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset, DataLoader, random_split
from torchvision import transforms, datasets
import torchvision.transforms.functional as tf
from albumentations import (Compose, RandomCrop, Resize, HorizontalFlip, ShiftScaleRotate, RandomResizedCrop, RandomBrightnessContrast, ElasticTransform, IAAAffine, IAAPerspective, OneOf)
class ValidationData(Dataset):
def __init__(self, root_dir=os.path.join(Path(__file__).parents[0], "data\\val"), transform=None, image_size=(512, 512)):
# Initialize Directory Tree from current working directory if no directory is provided
self.root_dir = root_dir
# Get Image/Mask Path
self.img_dir = os.path.join(self.root_dir, 'images')
self.mask_dir = os.path.join(self.root_dir, 'masks')
# Get List of Images/Masks in Carvana Directory
self.img_list = os.listdir(self.img_dir)
self.mask_list = os.listdir(self.mask_dir)
# Get Number of Images/Masks
self.num_img = len(self.img_list)
self.num_mask = len(self.mask_list)
# Define Transform Image Dimensions
self.image_height = image_size[1]
self.image_width = image_size[0]
# Define Custom Augmentation Transform
self.transform = transform
# Define Default Aug Transformation
self.album_transform = Compose([
HorizontalFlip(),
ShiftScaleRotate(
shift_limit=0.0625,
scale_limit=0.2,
rotate_limit=45,
p=0.2),
OneOf([
ElasticTransform(p=.2),
IAAPerspective(p=.35),
], p=.35)
])
def __len__(self):
"""
Define the length of the dataset.
"""
# Check if number of image/masks are equal
if self.num_img == self.num_mask:
return self.num_img
else:
raise Exception("Number of Images & GT Masks is NOT equal")
def __getitem__(self, item):
"""
Get the image/mask at index "item"
:return:
"""
# Define full image/mask path for extracting data
img_path = os.path.join(self.img_dir, self.img_list[item])
mask_path = os.path.join(self.mask_dir, self.mask_list[item])
# Use OpenCV to read Image/Masks from given paths
img = cv2.imread(img_path)
msk = cv2.imread(mask_path, 0)
if self.transform is not None:
# augment = self.album_transform(image=image, mask=mask)
augment = self.transform(image=img, mask=msk)
img, msk = augment['image'], augment['mask']
# Convert & Resize Image & Mask
img, msk = Image.fromarray(img), Image.fromarray(msk)
image_resized = tf.resize(img=img, size=[self.image_height, self.image_width])
mask_resized = tf.resize(img=msk, size=[self.image_height, self.image_width])
# Normalize Image but NOT mask (implicit in applied transforms)
image_ten = tf.to_tensor(image_resized).float()
mask_ten = tf.pil_to_tensor(mask_resized).float()
return image_ten, mask_ten
if __name__ == '__main__':
c_ds = ValidationData()
dl = DataLoader(c_ds, batch_size=1, shuffle=True)
for image, mask in dl:
print(f"Image Shape = {image.shape}, type = {type(image)}, min = {torch.min(image)} max = {torch.max(image)}")
print(f"Mask Shape = {mask.shape}, type = {type(mask)}, min = {torch.min(mask)} max = {torch.max(mask)}")
break
```
#### File: models/unets/unet.py
```python
import torch
import torch.nn as nn
class UNet(nn.Module):
def __init__(self):
super(UNet, self).__init__()
self.c1 = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
)
self.p1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.c2 = nn.Sequential(
nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
)
self.p2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.c3 = nn.Sequential(
nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
)
self.p3 = nn.MaxPool2d(kernel_size=2, stride=2)
self.c4 = nn.Sequential(
nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
)
self.p4 = nn.MaxPool2d(kernel_size=2, stride=2)
self.c4 = nn.Sequential(
nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
)
self.p4 = nn.MaxPool2d(kernel_size=2, stride=2)
self.c5 = nn.Sequential(
nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
)
self.u6 = nn.ConvTranspose2d(256, 128, 2, stride=2)
self.c6 = nn.Sequential(
nn.Conv2d(in_channels=256, out_channels=128, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
)
self.u7 = nn.ConvTranspose2d(128, 64, 2, stride=2)
self.c7 = nn.Sequential(
nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
)
self.u8 = nn.ConvTranspose2d(64, 32, 2, stride=2)
self.c8 = nn.Sequential(
nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
)
self.u9 = nn.ConvTranspose2d(32, 16, 2, stride=2)
self.c9 = nn.Sequential(
nn.Conv2d(in_channels=32, out_channels=16, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, padding=(3 - 1) // 2),
nn.ReLU(),
nn.Dropout2d(),
)
# self.final_out = nn.Conv2d(16, 1, 1)
self.final_out = nn.Conv2d(in_channels=16, out_channels=2, kernel_size=3, padding=(3 - 1) // 2)
def forward(self, x):
# Encoder
x1 = self.p1(self.c1(x))
x2 = self.p2(self.c2(x1))
x3 = self.p3(self.c3(x2))
x4 = self.p4(self.c4(x3))
x5 = self.c5(x4)
# Decoder
x6 = self.u6(x5)
x7 = torch.cat([x6, self.c4(x3)], 1)
x8 = self.u7(self.c6(x7))
x9 = torch.cat([x8, self.c3(x2)], 1)
x10 = self.u8(self.c7(x9))
x11 = torch.cat([x10, self.c2(x1)], 1)
x12 = self.u9(self.c8(x11))
x13 = torch.cat([x12, self.c1(x)], 1)
x14 = self.c9(x13)
x_final = self.final_out(x14)
# x_final = F.softmax(x_final, 1)
return x_final
```
#### File: RGB_Segmentation/tests/test_pytorch_trainer.py
```python
import os
import cv2
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import unittest
from pathlib import Path
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms.functional as tf
from RGB_Segmentation.data.Carvana_Dataset.CarvanaDS import CarvanaData
from albumentations import (Compose, RandomCrop, Resize, HorizontalFlip, ShiftScaleRotate, RandomResizedCrop, RandomBrightnessContrast, ElasticTransform, IAAAffine, IAAPerspective, OneOf)
class TestPytorchTrainer(unittest.TestCase):
def test_image_mask_processing(self):
"""
This test checks if the dataloader images & masks
are being handled correctly.
"""
# Image & Mask Paths
test_data_path = os.getcwd() + r"\data\test_image_mask_processing"
img_path = os.path.join(test_data_path, r'0cdf5b5d0ce1_01.jpg')
mask_path = os.path.join(test_data_path, r'0cdf5b5d0ce1_01_mask.jpg')
# Image Dimensions
image_size = [512, 512]
# Use OpenCV to read Image/Masks from given paths
image = cv2.imread(img_path)
mask = cv2.imread(mask_path, 0)
image, mask = Image.fromarray(image), Image.fromarray(mask)
# Resize the Img & Mask
r_img, r_msk = tf.resize(image, image_size), tf.resize(mask, image_size)
# Convert to tensor
image, mask = tf.to_tensor(r_img), tf.to_tensor(r_msk)
# Instantiate Carvana DataSet & DataLoader
carv_ds = CarvanaData()
carvana_dl = DataLoader(carv_ds)
car_iter = iter(carvana_dl)
# DataLoader Img & Mask
dl_img, dl_msk = next(car_iter)
# Account for Batch Dimension
dl_img = torch.squeeze(dl_img, dim=0)
dl_msk = torch.squeeze(dl_msk, dim=0)
# Test Shape & Type are Consistent
self.assertEqual(type(image), type(dl_img))
self.assertEqual(type(mask), type(dl_msk))
self.assertEqual(image.shape, dl_img.shape)
self.assertEqual(mask.shape, dl_msk.shape)
def test_resize_n_recrop(self):
# Image & Mask Paths
test_data_path = os.getcwd() + r"\data\test_image_mask_processing"
img_path = os.path.join(test_data_path, r'0cdf5b5d0ce1_01.jpg')
mask_path = os.path.join(test_data_path, r'0cdf5b5d0ce1_01_mask.jpg')
# Image Dimensions
image_size = [512, 512]
# Use OpenCV to read Image/Masks from given paths
image = cv2.imread(img_path)
mask = cv2.imread(mask_path, 0)
image, mask = Image.fromarray(image), Image.fromarray(mask)
# Resize the Img & Mask
r_img, r_msk = tf.resize(image, image_size), tf.resize(mask, image_size)
# Convert to tensor
image, mask = tf.to_tensor(r_img), tf.to_tensor(r_msk)
# Instantiate Carvana DataSet & DataLoader
carv_ds = CarvanaData()
carvana_dl = DataLoader(carv_ds)
car_iter = iter(carvana_dl)
# DataLoader Img & Mask
dl_img, dl_msk = next(car_iter)
# Account for Batch Dimension
dl_img = torch.squeeze(dl_img, dim=0)
dl_msk = torch.squeeze(dl_msk, dim=0)
# Test Shape & Type are Consistent
self.assertEqual(type(image), type(dl_img))
self.assertEqual(type(mask), type(dl_msk))
self.assertEqual(image.shape, dl_img.shape)
self.assertEqual(mask.shape, dl_msk.shape)
def test_image_normalization(self):
pass
def test_albumentations_transformation(self):
pass
def test_dice_metric(self):
pass
def test_loss_function(self):
pass
def test_dataset(self):
pass
def test_dataloader(self):
pass
def test_nn_model(self):
pass
if __name__ == '__main__':
unittest.main()
```
#### File: RGB_Segmentation/trainers/optuna_trainer.py
```python
from tqdm import tqdm
from RGB_Segmentation.data.Carvana_Dataset.CarvanaDS import CarvanaData
from RGB_Segmentation.data.Carvana_Dataset.ValDS import ValidationData
import torch
from torch import optim
import torch.nn as nn
from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau
from torch.utils.data import DataLoader
import optuna
from optuna.trial import TrialState
from RGB_Segmentation.models.unets.off_the_shelf_unet_w_sigmoid import UNet
from RGB_Segmentation.models.losses.bce_dice_loss import DiceBCELoss
from RGB_Segmentation.models.losses.dice_loss import DiceLoss
def objective(trial):
# Define Training Parameters
EPOCHS = trial.suggest_int('epochs', 30, 100)
lr = trial.suggest_uniform('lr', 1e-5, 1e-1)
batch_size = trial.suggest_int('batch_size', 5, 15)
val_batch_size = trial.suggest_int('val_batch_size', 5, 10)
img_height = 517
img_width = 517
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Define Model
model = UNet().to(device)
# Define Optimizer
optimizer = optim.Adam(model.parameters(), lr=lr)
scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=5)
# Define Loss Function
# loss_criterion = [DiceBCELoss().to(device), DiceLoss().to(device), nn.BCEWithLogitsLoss.to(device)][0]
loss_criterion = DiceBCELoss().to(device)
# Create DataLoader
carvana_dl = DataLoader(CarvanaData(test=False), batch_size, shuffle=True, num_workers=4, drop_last=True)
validation_dl = DataLoader(ValidationData(), val_batch_size, shuffle=False, num_workers=4, drop_last=True)
# Loop Through All Epochs
for epoch in range(EPOCHS):
model = model.train()
for image, mask in tqdm(carvana_dl):
image = image.to(device)
mask = mask.to(device)
pred = model(image)
loss = loss_criterion(pred, mask)
optimizer.zero_grad()
loss.backward()
optimizer.step()
with torch.no_grad():
mean_val_loss = 0
val_ctr = 1.0
# Compute Validation Loss
for val_img, val_mask in tqdm(validation_dl):
model = model.eval()
val_img = val_img.to(device)
val_mask = val_mask.to(device)
val_pred = model(val_img)
val_loss = loss_criterion(val_pred, val_mask)
mean_val_loss = mean_val_loss + (val_loss - mean_val_loss)/val_ctr
val_ctr += 1
scheduler.step(loss)
if __name__ == '__main__':
study = optuna.create_study(direction='minimize')
study.optimize(objective, n_trials=75)
complete_trials = study.get_trials(deepcopy=False, states=[TrialState.COMPLETE])
print("Best trial:")
trial = study.best_trial
print(" Value: ", trial.value)
print(" Params: ")
for key, value in trial.params.items():
print(" {}: {}".format(key, value))
``` |
{
"source": "jonnydc4/CS1400Winter2021",
"score": 4
} |
#### File: CS1400Winter2021/Assignments/6.1.py
```python
import math
# Receive the input number from the user
def newton(x):
# Initialize the tolerance and estimate
tolerance = 0.000001
estimate = 1.0
# Perform the successive approximations
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= tolerance:
break
# Output the result
print("The program's estimate is", estimate)
print("Python's estimate is", math.sqrt(x))
def main():
while True:
x = input("Enter a positive number: ")
if x != "":
newton(float(x))
else:
exit()
main()
```
#### File: CS1400Winter2021/Assignments/7.8.py
```python
def sepia(image):
"""Converts an image to sepia."""
grayscale(image)
for y in range(image.getHeight()):
for x in range(image.getWidth()):
(r, g, b) = image.getPixel(x, y)
if r < 63:
r = int(r * 1.1)
b = int(b * 0.9)
elif r < 192:
r = int(r * 1.15)
b = int(b * 0.85)
else:
r = min(int(r * 1.08), 255)
b = int(b * 0.93)
image.setPixel(x, y, (r, g, b))
pass
def grayscale(image):
"""Converts an image to grayscale."""
for y in range(image.getHeight()):
for x in range(image.getWidth()):
(r, g, b) = image.getPixel(x, y)
r = int(r * 0.299)
g = int(g * 0.587)
b = int(b * 0.114)
lum = r + g + b
image.setPixel(x, y, (lum, lum, lum))
def main():
filename = input("Enter the image file name: ")
image = Image(filename)
sepia(image)
image.draw()
if __name__ == "__main__":
main()
```
#### File: Projects/P2 Turtle Patterns 1/main.py
```python
import turtle
import sys
import time
def draw_retangle():
turtle.pendown()
turtle.pencolor("grey")
turtle.fillcolor("brown")
turtle.begin_fill()
for i in range(2):
turtle.forward(200)
turtle.left(90)
turtle.forward(20)
turtle.left(90)
turtle.forward(200)
turtle.end_fill()
turtle.penup()
def draw_circle(radius):
turtle.pendown()
turtle.pencolor("light grey")
turtle.fillcolor("gold")
turtle.begin_fill()
turtle.circle(radius)
turtle.end_fill()
turtle.penup()
def draw_triangle():
turtle.pendown()
turtle.pencolor("black")
turtle.fillcolor("dark grey")
turtle.begin_fill()
for i in range(3):
turtle.forward(100)
turtle.left(120)
turtle.end_fill()
turtle.penup()
def main():
try:
width = int(input("Enter the width: "))
if width < 0:
raise ValueError("Enter positive integer for width.")
height = int(input("Enter the height: "))
if height < 0:
raise ValueError("Enter positive integer for height.")
except ValueError as err:
print(err)
sys.exit()
turtle.screensize(width, height)
turtle.speed(10)
turtle.pensize(5)
turtle.backward(50)
draw_triangle()
turtle.goto(0, 85)
turtle.right(10)
draw_retangle()
turtle.goto(-150, 130)
draw_circle(30)
turtle.goto(150, 80)
draw_circle(45)
time.sleep(5)
if __name__ == "__main__":
main()
```
#### File: Projects/P6 Random Walk/main.py
```python
from turtle import Turtle
from scipy.stats import variation
from numpy import random, mean, max, min
from math import hypot
'''
<NAME>
CS1400-007
12/5/20
P6 Random walks
My program will be able to track the random walks of Pa, Mi-Ma, and Reg. It will return the maximum and minimum
distance of each walk as well as the mean and the coefficient of variance.
Instructions:
When asked to enter steps, you can enter integer numbers only. Multiple can be entered if they are separated by a comma.
Negative numbers will not work nor anything under 3.
When asked to enter trials, you can only enter one integer value. Negative numbers will not work nor anything under 3.
When asked to enter subject, the options will only be "Pa", "Mi-ma", "Reg", or "all".
'''
# configure turtle
screen = Turtle()
screen.speed(0)
'''
get_one_walk determines which walk will be done and for how many times. It also performs the walks and
plots the points.
'''
def get_one_walk(subject, numSteps):
# print(f"{subject} is taking a walk of {numSteps} steps")
x = 0
y = 0
color = ""
# take all your steps
if subject == 'Pa':
color = "blue"
for stepDirection in random.randint(4, size=(int(numSteps))):
if stepDirection == 0:
x = x + 1
if stepDirection == 1:
y = y + 1
if stepDirection == 2:
x = x - 1
if stepDirection == 3:
y = y - 1
if subject == 'Mi-ma':
color = "red"
for stepDirection in random.randint(6, size=(int(numSteps))):
if stepDirection == 0:
x = x + 1
if stepDirection == 1:
y = y + 1
if stepDirection == 2:
x = x - 1
if stepDirection >= 3:
y = y - 1
if subject == 'Reg':
color = "green"
for stepDirection in random.randint(2, size=(int(numSteps))):
if stepDirection == 0:
x = x + 1
if stepDirection == 1:
x = x - 1
# calculate distance from ending position to 0,0
walk_distance = hypot(x, y)
# plot x and y
screen.penup()
screen.goto(x, y)
screen.pendown()
screen.dot(5, color)
# return the distance between where you ended up and 0,0
return walk_distance
'''
get_walks_array makes an array with all of the walk distances. It also prints which walk is being done and
how many times.
'''
def get_walks_array(subject, numWalks, numSteps):
print(f"{subject} random walk of {numSteps} steps {numWalks} times")
walk_array = []
for trials in range(1, numWalks):
walk_distance = get_one_walk(subject, numSteps)
walk_array.append(walk_distance)
# return an array of distances where you ended up distance to 0,0
return walk_array
'''
do_many_trials takes the array made from get_many_walks and uses it to get the max, min, mean, and CV of the walks
performed. It then prints that information.
'''
def get_outputs(subject, walkList, numWalks):
for numSteps in walkList.split(','):
all_walks = get_walks_array(subject, numWalks, numSteps)
# calculate stats
walks_mean = mean(all_walks)
walks_max = max(all_walks)
walks_min = min(all_walks)
walks_variance = variation(all_walks)
# print stats
print(f'Mean = {walks_mean} CV = {walks_variance} \nMax = {walks_max} Min = {walks_min}')
'''
random_walks hold parameters for the command-line inputs
'''
def random_walks(walkList, numWalks, subject):
# walkList of "10,100" is a comma-delimited list of walks to take and each number is the number of steps
# numWalks is the number of walks to do in order to calculate max, min, mean, variance
# subject is “Pa”, “Mi-Ma” or “Reg” or "all"
walks = walkList.split(",")
if subject in ["Pa", 'all']:
get_outputs("Pa", walkList, numWalks)
if subject in ["Mi-ma", 'all']:
get_outputs("Mi-ma", walkList, numWalks)
if subject in ["Reg", 'all']:
get_outputs("Reg", walkList, numWalks)
return
'''
The main function takes the command line inputs and runs the program.
'''
def main():
steps = input("Enter steps: ")
trials = int(input("Enter trials: "))
subject = input("Enter Subject: ")
if trials < 3:
print("Enter something larger or equal to 3 for trials")
exit()
elif int(steps) < 3:
print("Enter something larger or equal to 3 for steps")
exit()
elif subject in ["Pa", "Mi-ma", "Reg", 'all']:
pass
else:
print("Please enter a valid subject")
exit()
random_walks(steps, trials, subject)
main()
```
#### File: Projects/P7 Clinton/main.py
```python
import sys
'''
The get_jobs function creates and returns a dictionary filled with the job statistics given in the bls_private.csv file.
This dictionary is used as an input for the calculate_presidents function.
'''
def get_jobs(filename):
# open bls_private.csv
file1 = open(filename, "r")
line_count = 0
jobs = {}
# make an array of bls_private.csv contents
for line in file1:
line_count += 1
if line_count > 13:
job_array = line.split(",")
# specified file conditions to make sure the file has all 12 months plus year of job data
if len(job_array) == 13:
# add array to dictionary
jobs[job_array[0]] = job_array
else:
print("Invalid File input.")
print(f"Error in {filename}.")
print("Data missing or incorrect data added.")
exit()
file1.close()
return jobs
'''
The calculate_presidents function make an array out of presidents.txt and uses it to print the name of each president,
their political party, how many jobs existed at the beginning and end of their administration, and how many jobs they
produced.
This function also tallies the total jobs produced and the partisan totals.
'''
def calculate_presidents(filename, jobs_dict):
# open presidents.txt
file2 = open(filename, "r")
democrat = 0
republican = 0
# make an array with the file contents
count = 0
for line in file2:
count += 1
# make an array and use the elements to make variables
president = line.split("\t")
if count > 1:
starting_year = president[2]
starting_month = int(president[3])
ending_year = president[4]
ending_month = int(president[5])
starting_jobs = int(jobs_dict[starting_year][starting_month])
ending_jobs = int(jobs_dict[ending_year][ending_month])
jobs_gained = ending_jobs - starting_jobs
# print stats for each presidency
print(f"Name: {president[1]} \nParty: {president[0]}")
print(f" Staring Jobs: {starting_jobs}")
print(f" Ending Jobs: {ending_jobs}")
print(f" Jobs Gained: {jobs_gained}")
# calculate partisan job totals
if president[0] == "Republican":
republican += jobs_gained
else:
democrat += jobs_gained
total_jobs = republican + democrat
# final print statements
print(f"Total Jobs Gained: {total_jobs}")
print(f"Republican jobs gained: {republican}")
print(f"Democrat jobs gained: {democrat}")
if republican > democrat:
print("CONCLUSION: The numbers have proven that Bill Clinton's statement was false.")
else:
print("CONCLUSION: The numbers have proven that Bill Clinton's statement was true based on the given information.")
pass
print("Just because the numbers add up as Clinton said doesn't mean that democratic administrations\ncan take all"
" the credit for creating those jobs. Although the numbers were correct they give\nlittle insight into what a"
" democratic administration actually does to create jobs.")
# print(f"Percent Republican: {int(100 * (republican/ total_jobs))}%")
# print(f"Percent Democrat: {int(100 * (democrat/ total_jobs))}%")
file2.close()
'''
This function will run the program and take the command line parameters.
'''
def main(argv):
# print(argv[0])
# print(argv[1])
# print(argv[2])
# exit()
if argv[1] != "BLS_private.csv":
print("Enter BLS_private.csv file as first argument.")
exit()
else:
pass
if argv[2] != "presidents.txt":
print("Enter presidents.txt as second argument.")
exit()
else:
pass
# make the get_jobs dictionary a variable
jobs = get_jobs(argv[1])
# use the jobs dictionary as input for calculate_president
calculate_presidents(argv[2], jobs)
if __name__ == "__main__":
main(sys.argv)
``` |
{
"source": "jonnydford/gimme",
"score": 2
} |
#### File: gimme/tests/test_ui.py
```python
from __future__ import absolute_import, print_function, unicode_literals
import responses
from gimme.helpers import CLOUD_RM
def test_not_logged_in(app):
"""Test what happens when we're not logged in.
Ensure we trigger the OAuth flow if we don't have a valid
session.
"""
res = app.test_client().get('/')
assert ('You should be redirected automatically to target URL: <a href'
'="/login/google">/login/google</a>').lower() in \
res.get_data(as_text=True).lower()
assert res.status_code == 302
def test_invalid_logged_in(invalid_loggedin_app):
"""Test what happens when someone comes from a non-whitelisted domain.
Ensure that we deny them access.
"""
res = invalid_loggedin_app.get('/')
assert res.status_code == 403
assert 'does not match the configured whitelist' in \
res.get_data(as_text=True).lower()
@responses.activate
def test_incomplete_loggedin(incomplete_loggedin_app):
"""Test what happens when there's a valid session but no profile info.
Ensure that we call out to the userinfo OAuth endpoint, fetch and
store the domain and then grant access.
"""
responses.add(responses.GET,
'https://www.googleapis.com/userinfo/v2/me',
status=200, json={
'hd': 'example.<EMAIL>',
'email': '<EMAIL>',
})
res = incomplete_loggedin_app.get('/')
assert len(responses.calls) == 1
assert res.content_type == 'text/html; charset=utf-8'
assert res.status_code == 200
@responses.activate
def test_incomplete_loggedin_profile_failed(incomplete_loggedin_app):
"""Test what happens when we have a valid session but can't get profile info.
Ensures we deny access if the profile endpoint returns anything
other than a 200 OK.
"""
responses.add(responses.GET,
'https://www.googleapis.com/userinfo/v2/me',
status=404)
res = incomplete_loggedin_app.get('/')
assert len(responses.calls) == 1
assert res.content_type == 'text/html; charset=utf-8'
assert res.status_code == 403
assert 'could not get your profile information' in \
res.get_data(as_text=True).lower()
@responses.activate
def test_incomplete_loggedin_domain_missing(incomplete_loggedin_app):
"""Test what happens when the profile response is incomplete.
Ensure we deny access if the profile endpoint doesn't return all the
information we need in order to decide if we should let someone in or
not.
"""
responses.add(responses.GET,
'https://www.googleapis.com/userinfo/v2/me',
status=200, json={})
res = incomplete_loggedin_app.get('/')
assert len(responses.calls) == 1
assert res.content_type == 'text/html; charset=utf-8'
assert res.status_code == 403
assert 'incomplete profile information' in \
res.get_data(as_text=True).lower()
def test_simple_get(loggedin_app):
"""Test what happens when we satisfy all the prerequisites.
Ensures we render the index page.
"""
res = loggedin_app.get('/')
assert res.content_type == 'text/html; charset=utf-8'
assert res.status_code == 200
assert '<div class="mui-row messages">' not in \
res.get_data(as_text=True).lower()
@responses.activate
def test_valid_post(loggedin_app):
"""Test what happens when a form is submitted with correct data.
Ensures we set the new IAM policy on the target project.
"""
form = {
'project': 'test',
'access': 'roles/compute.instanceAdmin',
'period': '15',
'target': 'test4',
'domain': 'example.com',
'csrf_token': '<PASSWORD>',
}
url = '{}/{}:getIamPolicy'.format(CLOUD_RM, 'test')
responses.add(
responses.POST, url, status=200,
json={
'bindings': [
{
'role': 'roles/owner',
'members': [
'user:<EMAIL>',
'user:<EMAIL>',
],
},
{
'role': 'roles/storage.admin',
'condition': {
'expression': 'request.time < timestamp(\'2018-05-04T00:00:00.00+00:00\')', # noqa: E501
'title': 'testing',
},
'members': [
'user:<EMAIL>',
],
},
],
'version': 1,
'etag': 'test',
})
url = '{}/{}:setIamPolicy'.format(CLOUD_RM, 'test')
responses.add(responses.POST, url, status=200)
res = loggedin_app.post('/', data=form, follow_redirects=True)
assert res.status_code == 200
assert res.content_type == 'text/html; charset=utf-8'
assert len(responses.calls) == 2
assert responses.calls[0].request.method == 'POST'
assert responses.calls[0].request.url == '{}/{}:getIamPolicy'.format(
CLOUD_RM, 'test')
assert responses.calls[1].request.method == 'POST'
assert responses.calls[1].request.url == '{}/{}:setIamPolicy'.format(
CLOUD_RM, 'test')
assert 'policy' in responses.calls[1].request.body.decode('utf-8').lower()
assert 'granted by <EMAIL>' in \
responses.calls[1].request.body.decode('utf-8').lower()
assert 'this is a temporary grant' in \
responses.calls[1].request.body.decode('utf-8').lower()
assert 'great success' in res.get_data(as_text=True).lower()
@responses.activate
def test_valid_post_group(loggedin_app):
"""Test what happens when a form is submitted with correct data.
Ensures we set the new IAM policy on the target project.
"""
form = {
'project': 'test',
'access': 'roles/compute.instanceAdmin',
'period': '15',
'target': 'test4',
'domain': 'example.com',
'csrf_token': 'not validated in tests',
}
url = '{}/{}:getIamPolicy'.format(CLOUD_RM, 'test')
responses.add(
responses.POST, url, status=200,
json={
'bindings': [
{
'role': 'roles/owner',
'members': [
'user:<EMAIL>',
'user:<EMAIL>',
],
},
{
'role': 'roles/storage.admin',
'condition': {
'expression': 'request.time < timestamp(\'2018-05-04T00:00:00.00+00:00\')', # noqa: E501
'title': 'testing',
},
'members': [
'user:<EMAIL>',
],
},
],
'version': 1,
'etag': 'test',
})
url = '{}/{}:setIamPolicy'.format(CLOUD_RM, 'test')
responses.add(
responses.POST, url, status=400,
json={
'error': {'message': 'is of type "group"'},
})
url = '{}/{}:getIamPolicy'.format(CLOUD_RM, 'test')
responses.add(
responses.POST, url, status=200,
json={
'bindings': [
{
'role': 'roles/owner',
'members': [
'user:<EMAIL>',
'user:<EMAIL>',
],
},
{
'role': 'roles/storage.admin',
'condition': {
'expression': 'request.time < timestamp(\'2018-05-04T00:00:00.00+00:00\')', # noqa: E501
'title': 'testing',
},
'members': [
'user:<EMAIL>',
],
},
],
'version': 1,
'etag': 'test',
})
url = '{}/{}:setIamPolicy'.format(CLOUD_RM, 'test')
responses.add(responses.POST, url, status=200)
res = loggedin_app.post('/', data=form, follow_redirects=True)
assert res.status_code == 200
assert res.content_type == 'text/html; charset=utf-8'
assert len(responses.calls) == 4
assert responses.calls[0].request.method == 'POST'
assert responses.calls[0].request.url == '{}/{}:getIamPolicy'.format(
CLOUD_RM, 'test')
assert responses.calls[1].request.method == 'POST'
assert responses.calls[1].request.url == '{}/{}:setIamPolicy'.format(
CLOUD_RM, 'test')
assert 'policy' in responses.calls[1].request.body.decode('utf-8').lower()
assert 'granted by <EMAIL>' in \
responses.calls[1].request.body.decode('utf-8').lower()
assert 'this is a temporary grant' in \
responses.calls[1].request.body.decode('utf-8').lower()
assert 'user:<EMAIL>' in \
responses.calls[1].request.body.decode('utf-8').lower()
assert 'group:<EMAIL>' in \
responses.calls[3].request.body.decode('utf-8').lower()
@responses.activate
def test_valid_post_token_expired(loggedin_app, freezer):
"""Test what happens when we try to set a policy but our token has expiredy.
Ensures the error handler catches the token expiry and retriggers the OAuth
flow to get a new token.
"""
freezer.move_to('2018-05-05')
form = {
'project': 'test',
'access': 'roles/compute.instanceAdmin',
'period': '15',
'target': 'test4',
'domain': 'example.com',
'csrf_token': '<PASSWORD>',
}
responses.add(
responses.POST, 'https://accounts.google.com/o/oauth2/token',
status=400,
json={
'error_description': 'Missing required parameter: refresh_token',
'error': 'invalid_request'})
res = loggedin_app.post('/', data=form)
assert res.status_code == 302
assert ('you should be redirected automatically to target url: '
'<a href="/">/</a>.') in res.get_data(as_text=True).lower()
@responses.activate
def test_post_invalid_project_url(loggedin_app):
"""Test what happens when we submit an invalid project URL.
Ensures that we inform the user the information they provided is
incorrect. This should never call the Cloud Resource Manager.
"""
form = {
'project': 'https://console.cloud.google.com/?test=test',
'access': 'roles/compute.instanceAdmin',
'period': '15',
'target': 'test4',
'domain': 'example.com',
'csrf_token': '<PASSWORD>',
}
res = loggedin_app.post('/', data=form, follow_redirects=True)
assert res.status_code == 200
assert res.content_type == 'text/html; charset=utf-8'
assert len(responses.calls) == 0
assert 'could not find project ID in'.lower() in \
res.get_data(as_text=True).lower()
@responses.activate
def test_valid_post_failed_get_policy(loggedin_app):
"""Test what happens when we can't fetch the IAM Policy.
Ensures we inform the user when the policy could not be fetched.
This usually means the poject name was incorrect or that they
don't have access to said project.
This must never trigger a call to setIamPolicy.
"""
form = {
'project': 'test',
'access': 'roles/compute.instanceAdmin',
'period': '15',
'target': 'test4',
'domain': 'example.com',
'csrf_token': '<PASSWORD>',
}
url = '{}/{}:getIamPolicy'.format(CLOUD_RM, 'test')
responses.add(
responses.POST, url, status=404,
json={'error': {'message': 'resource not found'}})
res = loggedin_app.post('/', data=form, follow_redirects=True)
assert res.status_code == 200
assert res.content_type == 'text/html; charset=utf-8'
assert len(responses.calls) == 1
assert responses.calls[0].request.method == 'POST'
assert responses.calls[0].request.url == '{}/{}:getIamPolicy'.format(
CLOUD_RM, 'test')
assert 'could not fetch IAM policy'.lower() in \
res.get_data(as_text=True).lower()
@responses.activate
def test_valid_post_failed_set_policy(loggedin_app):
"""Test what happens when we fail to set the policy.
Ensures that we inform the user when we fail to set the new IAM policy,
i.e the permissions aren't granted. This can happen if the user has
viewer rights for example, and therefore can view the IAM policy, but
lacks the permissions to update it.
"""
form = {
'project': 'test',
'access': 'roles/compute.instanceAdmin',
'period': '15',
'target': 'test4',
'domain': 'example.com',
'csrf_token': 'not validated in tests',
}
url = '{}/{}:getIamPolicy'.format(CLOUD_RM, 'test')
responses.add(
responses.POST, url, status=200,
json={
'bindings': [
{
'role': 'roles/owner',
'members': [
'user:<EMAIL>',
'user:<EMAIL>',
],
},
{
'role': 'roles/storage.admin',
'condition': {
'expression': 'request.time < timestamp(\'2018-05-04T00:00:00.00+00:00\')', # noqa: E501
'title': 'testing',
},
'members': [
'user:<EMAIL>',
],
},
],
'version': 1,
'etag': 'test',
})
url = '{}/{}:setIamPolicy'.format(CLOUD_RM, 'test')
responses.add(
responses.POST, url, status=400,
json={
'error': {
'code': 400,
'detail': [{
'@type': 'type.googleapis.com/google.rpc.BadRequest',
'fieldViolations': [
{'description': 'Invalid JSON payload'}],
}],
'status': 'INVALID_ARGUMENT',
'message': 'Invalid JSON payload received.',
}})
res = loggedin_app.post('/', data=form, follow_redirects=True)
assert res.status_code == 200
assert res.content_type == 'text/html; charset=utf-8'
assert len(responses.calls) == 2
assert 'could not apply new policy'.lower() in \
res.get_data(as_text=True).lower()
@responses.activate
def test_logout(loggedin_app):
"""Test what happens when we logout the user.
Ensures we revoke the token and clear the session, which will trigger the
OAuth flow again.
"""
responses.add(responses.GET, 'https://accounts.google.com/o/oauth2/revoke',
status=200)
res = loggedin_app.get('/logout')
assert len(responses.calls) == 1
assert ('You should be redirected automatically to target URL: <a href'
'="/">/</a>').lower() in res.get_data(as_text=True).lower()
assert res.status_code == 302
@responses.activate
def test_logout_expired_token(loggedin_app, freezer):
"""Test what happens when we logout the user but token has expired.
Ensures we clear the session as we're no longer able to revoke the
token.
"""
freezer.move_to('2018-05-05')
responses.add(
responses.POST, 'https://accounts.google.com/o/oauth2/token',
status=400,
json={
'error_description': 'Missing required parameter: refresh_token',
'error': 'invalid_request'})
res = loggedin_app.get('/logout')
assert len(responses.calls) == 1
assert ('You should be redirected automatically to target URL: <a href'
'="/">/</a>').lower() in res.get_data(as_text=True).lower()
assert res.status_code == 302
@responses.activate
def test_logout_invalid_login(invalid_loggedin_app):
"""Test what happens when an invalid user tries to log out.
Ensures we revoke the token and clear the session.
"""
responses.add(responses.GET, 'https://accounts.google.com/o/oauth2/revoke',
status=200)
res = invalid_loggedin_app.get('/logout')
assert len(responses.calls) == 1
assert ('You should be redirected automatically to target URL: <a href'
'="/">/</a>').lower() in res.get_data(as_text=True).lower()
assert res.status_code == 302
@responses.activate
def test_logout_not_logged_in(app):
"""Test what happens when we try to logout if we're not logged in.
Ensures that we clear the session and redirect.
"""
res = app.test_client().get('/logout')
assert ('You should be redirected automatically to target URL: <a href'
'="/">/</a>').lower() in res.get_data(as_text=True).lower()
assert res.status_code == 302
``` |
{
"source": "jonnydubowsky/indy-node",
"score": 2
} |
#### File: indy_node/server/config_req_handler.py
```python
from typing import List
from indy_common.authorize.auth_actions import AuthActionEdit, AuthActionAdd
from indy_common.authorize.auth_map import auth_map, anyone_can_write_map
from indy_common.authorize.auth_request_validator import WriteRequestValidator
from indy_common.config_util import getConfig
from plenum.common.exceptions import InvalidClientRequest, \
UnauthorizedClientRequest
from plenum.common.txn_util import reqToTxn, is_forced, get_payload_data, append_txn_metadata
from plenum.server.ledger_req_handler import LedgerRequestHandler
from plenum.common.constants import TXN_TYPE, NAME, VERSION, FORCE
from indy_common.constants import POOL_UPGRADE, START, CANCEL, SCHEDULE, ACTION, POOL_CONFIG, NODE_UPGRADE, PACKAGE, \
APP_NAME, REINSTALL
from indy_common.types import Request
from indy_node.persistence.idr_cache import IdrCache
from indy_node.server.upgrader import Upgrader
from indy_node.server.pool_config import PoolConfig
from indy_node.utils.node_control_utils import NodeControlUtil
class ConfigReqHandler(LedgerRequestHandler):
write_types = {POOL_UPGRADE, NODE_UPGRADE, POOL_CONFIG}
def __init__(self, ledger, state, idrCache: IdrCache,
upgrader: Upgrader, poolManager, poolCfg: PoolConfig):
super().__init__(ledger, state)
self.idrCache = idrCache
self.upgrader = upgrader
self.poolManager = poolManager
self.poolCfg = poolCfg
self.write_req_validator = WriteRequestValidator(config=getConfig(),
auth_map=auth_map,
cache=self.idrCache,
anyone_can_write_map=anyone_can_write_map)
def doStaticValidation(self, request: Request):
identifier, req_id, operation = request.identifier, request.reqId, request.operation
if operation[TXN_TYPE] == POOL_UPGRADE:
self._doStaticValidationPoolUpgrade(identifier, req_id, operation)
elif operation[TXN_TYPE] == POOL_CONFIG:
self._doStaticValidationPoolConfig(identifier, req_id, operation)
def _doStaticValidationPoolConfig(self, identifier, reqId, operation):
pass
def _doStaticValidationPoolUpgrade(self, identifier, reqId, operation):
action = operation.get(ACTION)
if action not in (START, CANCEL):
raise InvalidClientRequest(identifier, reqId,
"{} not a valid action".
format(action))
if action == START:
schedule = operation.get(SCHEDULE, {})
force = operation.get(FORCE)
force = str(force) == 'True'
isValid, msg = self.upgrader.isScheduleValid(
schedule, self.poolManager.getNodesServices(), force)
if not isValid:
raise InvalidClientRequest(identifier, reqId,
"{} not a valid schedule since {}".
format(schedule, msg))
# TODO: Check if cancel is submitted before start
def curr_pkt_info(self, pkg_name):
if pkg_name == APP_NAME:
return Upgrader.getVersion(), [APP_NAME]
return NodeControlUtil.curr_pkt_info(pkg_name)
def validate(self, req: Request):
status = '*'
operation = req.operation
typ = operation.get(TXN_TYPE)
if typ not in [POOL_UPGRADE, POOL_CONFIG]:
return
if typ == POOL_UPGRADE:
pkt_to_upgrade = req.operation.get(PACKAGE, getConfig().UPGRADE_ENTRY)
if pkt_to_upgrade:
currentVersion, cur_deps = self.curr_pkt_info(pkt_to_upgrade)
if not currentVersion:
raise InvalidClientRequest(req.identifier, req.reqId,
"Packet {} is not installed and cannot be upgraded".
format(pkt_to_upgrade))
if all([APP_NAME not in d for d in cur_deps]):
raise InvalidClientRequest(req.identifier, req.reqId,
"Packet {} doesn't belong to pool".format(pkt_to_upgrade))
else:
raise InvalidClientRequest(req.identifier, req.reqId, "Upgrade packet name is empty")
targetVersion = req.operation[VERSION]
reinstall = req.operation.get(REINSTALL, False)
if not Upgrader.is_version_upgradable(currentVersion, targetVersion, reinstall):
# currentVersion > targetVersion
raise InvalidClientRequest(req.identifier, req.reqId, "Version is not upgradable")
action = operation.get(ACTION)
# TODO: Some validation needed for making sure name and version
# present
txn = self.upgrader.get_upgrade_txn(
lambda txn: get_payload_data(txn).get(
NAME,
None) == req.operation.get(
NAME,
None) and get_payload_data(txn).get(VERSION) == req.operation.get(VERSION),
reverse=True)
if txn:
status = get_payload_data(txn).get(ACTION, '*')
if status == START and action == START:
raise InvalidClientRequest(
req.identifier,
req.reqId,
"Upgrade '{}' is already scheduled".format(
req.operation.get(NAME)))
if status == '*':
auth_action = AuthActionAdd(txn_type=POOL_UPGRADE,
field=ACTION,
value=action)
else:
auth_action = AuthActionEdit(txn_type=POOL_UPGRADE,
field=ACTION,
old_value=status,
new_value=action)
self.write_req_validator.validate(req,
[auth_action])
elif typ == POOL_CONFIG:
action = '*'
status = '*'
self.write_req_validator.validate(req,
[AuthActionEdit(txn_type=typ,
field=ACTION,
old_value=status,
new_value=action)])
def apply(self, req: Request, cons_time):
txn = append_txn_metadata(reqToTxn(req),
txn_time=cons_time)
self.ledger.append_txns_metadata([txn])
(start, _), _ = self.ledger.appendTxns([txn])
return start, txn
def commit(self, txnCount, stateRoot, txnRoot, ppTime) -> List:
committedTxns = super().commit(txnCount, stateRoot, txnRoot, ppTime)
for txn in committedTxns:
# Handle POOL_UPGRADE or POOL_CONFIG transaction here
# only in case it is not forced.
# If it is forced then it was handled earlier
# in applyForced method.
if not is_forced(txn):
self.upgrader.handleUpgradeTxn(txn)
self.poolCfg.handleConfigTxn(txn)
return committedTxns
def applyForced(self, req: Request):
super().applyForced(req)
txn = reqToTxn(req)
self.upgrader.handleUpgradeTxn(txn)
self.poolCfg.handleConfigTxn(txn)
``` |
{
"source": "jonnydubowsky/lod-cloud-draw",
"score": 3
} |
#### File: lod-cloud-draw/scripts/get-data.py
```python
import json
from urllib.request import urlopen
from urllib.parse import urlencode
from bs4 import BeautifulSoup
import requests
import sys, traceback
from itertools import islice
import codecs
def check_url(url, entry):
try:
soup = BeautifulSoup(
urlopen(
"http://lodlaundromat.org/sparql/?"
+ urlencode({
"query": "PREFIX llo: <http://lodlaundromat.org/ontology/> SELECT DISTINCT ?dataset WHERE {?dataset llo:url <" +
url + ">}" })), features="xml")
uris = soup.find_all("uri")
except:
traceback.print_exc()
uris = []
if len(uris) > 0:
print("%s => %s" % (url, uris[0].text))
entry.update({
"mirror":[
"http://download.lodlaundromat.org/" + uris[0].text[34:]
],
"status": "OK"
})
else:
try:
r = requests.head(url,
allow_redirects=True,
timeout=30)
if r.status_code == 200:
print("%s OK" % url)
entry.update({
"status": "OK",
"media_type": str(r.headers["content-type"])
})
else:
print("%s %d" % (url, r.status_code))
entry.update({
"status": "FAIL (%d)" % r.status_code
})
except Exception as e:
#traceback.print_exc(file=sys.stdout)
print("%s FAIL: (%s)" % (url, str(e)))
entry.update({
"status": "FAIL (%s)" % str(e)
})
def check_example(url, entry):
try:
r = requests.get(url,
allow_redirects=True,
timeout=30,
headers={"Accept":"application/rdf+xml,text/turtle,application/n-triples,application/ld+json,*/*q=0.9"})
if r.status_code == 200:
print("%s OK" % url)
entry.update({
"status": "OK",
"media_type": str(r.headers["content-type"])
})
else:
print("%s %d" % (url, r.status_code))
entry.update({
"status": "FAIL (%d)" % r.status_code
})
except Exception as e:
#traceback.print_exc(file=sys.stdout)
print("%s FAIL: (%s)" % (url, str(e)))
entry.update({
"status": "FAIL (%s)" % str(e)
})
def check_sparql(url, entry):
try:
r = requests.head(url,
allow_redirects=True,
timeout=30)
if r.status_code == 200:
print("%s OK" % url)
entry.update({
"status": "OK"
})
else:
print("%s %d" % (url, r.status_code))
entry.update({
"status": "FAIL (%d)" % r.status_code
})
except Exception as e:
#traceback.print_exc(file=sys.stdout)
print("%s FAIL: (%s)" % (url, str(e)))
entry.update({
"status": "FAIL (%s)" % str(e)
})
if __name__ == "__main__":
reader = codecs.getreader("utf-8")
data = json.load(reader(urlopen("https://lod-cloud.net/extract/datasets")))
print("# Report for LOD Cloud availability")
print()
#data = list(islice(data.items(),2))
data = data.items()
for (identifier, dataset) in data:
print("## Dataset name: " + dataset["identifier"])
print()
print("### Full Downloads (%d)" % len(dataset["full_download"]))
print()
for full_download in dataset["full_download"]:
check_url(full_download["download_url"], full_download)
print()
print()
print("### Other downloads (%d)" % len(dataset["other_download"]))
if "other_download" in dataset:
for other_download in dataset["other_download"]:
if "access_url" in other_download:
check_url(other_download["access_url"], other_download)
print()
if "example" in dataset:
print("### Examples (%d)" % len(dataset["example"]))
for example in dataset["example"]:
if "access_url" in example:
check_example(example["access_url"], example)
print()
if "sparql" in dataset:
print("### SPARQL Endpoints (%d)" % len(dataset["sparql"]))
for sparql in dataset["sparql"]:
if "access_url" in sparql:
check_sparql(sparql["access_url"], sparql)
print()
print()
data = dict(data)
with open("lod-data.json","w") as out:
out.write(json.dumps(data, indent=2))
resources = 0
resources_available = 0
links = {"full_download":0,"other_download":0,"example":0,"sparql":0}
links_available = {"full_download":0,"other_download":0,"example":0,"sparql":0}
for (_, res) in data.items():
resources += 1
success = False
for (clazz,link_list) in res.items():
if clazz in ["full_download","other_download","example","sparql"]:
for link in link_list:
links[clazz] += 1
if link["status"] == "OK":
links_available[clazz] += 1
if not success:
success = True
resources_available += 1
print("| | Status |")
print("|----------------|-----------|")
print("| Resources | %4d/%4d |" % (resources_available, resources))
print("| Full Download | %4d/%4d |" % (links_available["full_download"], links["full_download"]))
print("| Other Download | %4d/%4d |" % (links_available["other_download"], links["other_download"]))
print("| Examples | %4d/%4d |" % (links_available["example"], links["example"]))
print("| SPARQL | %4d/%4d |" % (links_available["sparql"], links["sparql"]))
``` |
{
"source": "Jonny-exe/binary-fractions",
"score": 3
} |
#### File: binary-fractions/binary_fractions/binary.py
```python
from __future__ import annotations # to allow type hinting in class methods
import math
import re
import unittest
from fractions import Fraction
from typing import Any, Union
_BINARY_WARNED_ABOUT_FLOAT = False # type: bool
_BINARY_RELATIVE_TOLERANCE = 1e-10 # type: float
# number of binary digits to the right of decimal point
_BINARY_PRECISION = 128 # type: int
_PREFIX = "0b" # type: str
_EXP = "e" # type: str
_NAN = "NaN" # type: str
_INF = "Inf" # type: str
_NINF = "-Inf" # type: str
# _BINARY_VERSION will be set automatically with git hook upon commit
_BINARY_VERSION = "20210721-160328" # type: str # format: date +%Y%m%d-%H%M%S
# _BINARY_TOTAL_TESTS will be set automatically with git hook upon commit
_BINARY_TOTAL_TESTS = 1646 # type: int # number of asserts in .py file
# see implementation of class Decimal:
# https://github.com/python/cpython/blob/3.9/Lib/_pydecimal.py
# https://docs.python.org/3/library/decimal.html
# see implementation of class Fraction:
# https://github.com/python/cpython/blob/3.9/Lib/fractions.py
# https://docs.python.org/3/library/fractions.html
# https://github.com/bradley101/fraction/blob/master/fraction/Fraction.py
##########################################################################
# CLASS TWOSCOMPLEMENT
##########################################################################
class TwosComplement(str):
"""Floating point class for representing twos-complement (2's complement).
If you are curious about Two's complement, read the following:
- https://en.wikipedia.org/wiki/Two%27s_complement
- https://janmr.com/blog/2010/07/bitwise-operators-and-negative-numbers/
The twos-complement format is as follows.
- there is no sign (-, +)
- there is no extra sign bit per se
- positive numbers must have a leading 0 to be recognized as positive
- hence positive numbers by definition always start with a 0
- negative numbers always start with a 1
- negative numbers can have an arbitrary number of additional leading 1s
- positive numbers can have an arbitrary number of additional leading 0s
- there must be one or more decimal bits
- there is an optional decimal point
- there are 0 or more fractional bits
- there is an optional exponent in decimal (e.g. e-34), the exponent is not binary
```
Syntax:
In 'regex' the syntax is
r"\s*((?=[01])(?P<int>[01]+)(\.(?P<frac>[01]*))?(E(?P<exp>[-+]?\d+))?)\s*\Z".
In simpler terms, the syntax is as follows:
[0,1]+[.][0,1]*[e[-,+][0-9]+]
integer bits (at least 1 bit required, leading bit indicates if pos. or neg.)
decimal point (optional, one or none)
fractional bits (optional, zero or more)
exponent (optional, possible with sign - or +, in decimal)
decimal | binary fraction | twos-complement
---------------------------------------------
-2.5e89 | -10.1e89 | 101.1e89
-6 | -110 | 1010
-5 | -101 | 1011
-0.5e3 | -0.1e3 | 1.1e3
-4 | -100 | 100
-3 | -11 | 101
-2.5 | -10.1 | 101.1
-0.25e3 | -0.01e3 | 1.11e3
-2 | -10 | 10
-1.5 | -1.1 | 10.1
-1 | -1 | 1
-0.5 | -0.1 | 1.1
-0.25 | -0.01 | 1.11
-0.125 | -0.001 | 1.111
0 | 0 | 0
1.5e-4 | 1.1e-4 | 01.1e-4
2.75e-4 | 10.11e-4 | 010.11e-4
0.25 | 0.01 | 0.01
0.5 | 0.1 | 0.1
1 | 1 | 01
1.5 | 1.1 | 01.1
2 | 10 | 010
2.75 | 10.11 | 010.11
3 | 11 | 011
4 | 100 | 0100
5 | 101 | 0101
6 | 110 | 0110
```
Valid TwosComplement strings are: 0, 1, 01, 10, 0.0, 1.1, 1., 0.1e+34,
11101.e-56, 0101.01e78. 000011.1000e0 is valid and is the same as 011.1.
Along the same line, 111101.0100000e-0 is valid and is the same as 101.01.
Invalid TwosComplement strings are: -1 (minus), +1 (plus),
.0 (no leading decimal digit),
12 (2 is not a binary digit),
1.2.3 (2 decimal points),
1e (missing exponent number),
1e-1.1 (decimal point in exponent).
"""
def __new__(
cls,
value: Union[int, float, Fraction, str] = 0,
length: int = -1,
rel_tol: float = _BINARY_RELATIVE_TOLERANCE,
ndigits: int = _BINARY_PRECISION,
simplify: bool = True,
warn_on_float: bool = False,
) -> TwosComplement:
"""Constructor.
Use __new__ and not __init__ because TwosComplement is immutable.
Allows string, float, integer, and Fraction as input for constructor.
If instance is contructed from a string, by default the string will
be simplified. With 'simplify' being False, attention is paid to
*not* modify the string or to modify it as little as possible.
With simplify being False, if given '1e1' it will remain as '1e1',
it will not change it to '1'. Same with '1000', which will not change
to '1e4'. In short, without simplification, attempts are made to keep
the string representation as close to the original as possible.
Examples:
* TwosComplement(4) returns '0100'
* TwosComplement(-2) returns '10'
* TwosComplement(-1.5) returns '10.1'
* TwosComplement(Fraction(-1.5)) returns '10.1'
* TwosComplement('110.101') returns '110.101'
* TwosComplement('110.101e-34') returns '110.101e-34'
Parameters:
value (int, float, Fraction, str): value of number
length (int): desired length of resulting string. If default -1, string
will be presented its normal (shortest) representation. If
larger, string will be prefixed with leading bits to achieve
desired length. If length is too short to fit number, an
exception will be raised.
Example of length 4 is '01.1'.
ndigits (int): desired digits after decimal point. 'ndigits' is only
relevant for Fractions.
rel_tol (float): relative tolerance that influences precision further.
A bigger tolerance leads to a possibly less precise result.
A smaller tolerance leads to a possibly more precise result.
'rel_tol' is only relevant for floats.
simplify (bool): If True, try to simplify string representation.
If False, try to leave the string representation as much as is.
'simplify' is only relevant for strings.
warn_on_float (bool): If True print a warning statement to stdout to
warn about possible loss in precision in case of conversion from
float to TwosComplement.
If False, print no warning to stdout.
'warn_on_float' is only relevant for floats.
Returns:
TwosComplement: created immutable instance representing twos-complement
number as a string of class TwosComplement.
Testcases:
model: self.assertIsInstance(TwosComplement(X1), TwosComplement)
cases: some test cases for return class
- 1
- -2
- -2.5
- '10'
- '010'
- Fraction(3,4)
model: self.assertEqual(TwosComplement(X1), X2)
cases: some test cases for equal
- -2 ==> '10'
- 2 ==> '010'
- -1.5 ==> '10.1'
- 3.5 ==> '011.5'
- '10.101' ==> '10.101'
- '0001.00' ==> '01'
- Fraction(-3,2) ==> '10.1'
- Fraction(7,2) ==> '011.5'
model: with self.assertRaises(ValueError):
TwosComplement(X1)
cases: some test cases for raising ValueError
- "102"
- "nan"
"""
if isinstance(value, int):
return str.__new__(cls, TwosComplement._int2twoscomp(value, length))
if isinstance(value, float):
return str.__new__(
cls,
TwosComplement._float2twoscomp(value, length, rel_tol, warn_on_float),
)
if isinstance(value, Fraction):
return str.__new__(cls, TwosComplement._fraction2twoscomp(value, length))
if isinstance(value, str):
return str.__new__(
cls, TwosComplement._str2twoscomp(value, length, simplify=simplify)
)
# any other types
raise TypeError(
f"Cannot convert {value} of type {type(value)} to TwosComplement"
)
@staticmethod
def _int2twoscomp(value: int, length: int = -1) -> str:
"""Computes the two's complement of int value.
This is a utility function.
Users should use the constructor TwosComplement(value) instead.
Parameters:
value (int): integer to convert into twos-complement string.
length (int): desired length of string. If default -1, string
will be presented its normal (shortest) representation. If
larger, string will be prefixed with leading bits to achieve
desired length. If length is too short to fit number, an
exception will be raised.
Example of length 4 is '01.1'.
Returns:
str: string containing twos-complement of value
"""
if value == 0:
digits = 1 # type: int
elif value > 0:
# add 1 for leading '0' in positive numbers
# less precise: digits = math.ceil(math.log(abs(value + 1), 2)) + 1
digits = len(bin(value).replace(_PREFIX, "")) + 1
else: # negative
# less precise: digits = math.ceil(math.log(abs(value), 2)) + 1
digits = len(bin(value + 1).replace(_PREFIX, ""))
# digits = number of bits required to represent this
# negative number in twos-complement
if length == -1:
length = digits
if length < digits:
raise OverflowError(f"Argument {value} does not fit into {length} digits.")
if value == 0:
result = "0" * length
elif value < 0: # negative
value = value - (1 << length) # compute negative value
result = bin(value & ((2 ** length) - 1)).replace(_PREFIX, "")
result = "1" * (len(result) - length) + result
else: # positive
result = "0" + bin(value).replace(_PREFIX, "")
result = "0" * (length - len(result)) + result
if length != -1:
le = len(result)
if le > length:
raise OverflowError
result = result[0] * (length - le) + result
return result
@staticmethod
def _frac2twoscomp(
value: float, length: int = -1, rel_tol: float = _BINARY_RELATIVE_TOLERANCE
) -> str:
"""Computes the two's complement of the fractional part (mantissa) of a float.
This is a utility function.
Users should use the constructor TwosComplement(f-int(f)) instead.
The returned string always has one integer digit, followed by a decimal point.
The integer digit indicates the sign.
The decimal part consists of at least 1 bit.
Hence, the shortest values are 0.0, 0.1, 1.0, and 1.1.
This function has rounding errors as it deals with floats.
_frac2twoscomp(+1.0000000000000000000000000000000001) returns '0.0'.
_frac2twoscomp(-0.9999999999999999999999999999999999) returns '1.0'
because it is rounded to -1.
Use the method _fraction2twoscomp() using Fractions to avoid rounding
errors.
Examples:
* For -3.5 it computes the twos-complement of -0.5.
So, _frac2twoscomp(-3.5) returns '1.1'.
* _frac2twoscomp(+3.5) returns '0.1'.
* _frac2twoscomp(-3.375) returns '1.101'.
* _frac2twoscomp(+3.375) returns '1.11'.
Parameters:
value (float): number whose mantissa will be converted to twos-complement.
length (int): desired length of resulting string. If -1, result is neither
prefixed nor truncated. A shorter length will truncate the mantissa,
losing precision. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
lenght.
Example of length 4 is '01.1'.
rel_tol (float): relative tolerance that influences precision further.
A bigger tolerance leads to a possibly less precise result.
A smaller tolerance leads to a possibly more precise result.
Returns:
str: twos-complement string of the mantissa
"""
if length < 1 and length != -1:
raise ValueError(f"Argument {length} has be greater than 0, or default -1.")
fp, ip = math.modf(value)
afp = abs(fp)
result = ""
i = 1
if value == 0:
result = "0.0"
elif fp == 0:
result = "0.0" if ip >= 0 else "1.0"
elif fp >= 0: # Positive
rest = 0.0
while not (math.isclose(rest, fp, rel_tol=rel_tol)):
b = 2 ** -i
if b + rest <= fp:
result += "1"
rest += b
else:
result += "0"
i += 1
result = "0." + result
else: # Negative
rest = 1.0
while not (math.isclose(rest, afp, rel_tol=rel_tol)):
b = 2 ** -i
if rest - b < afp:
result += "0"
else:
rest -= b
result += "1"
i += 1
result = "0" if result == "" else result
result = "1." + result
if length == -1:
result = result
elif length > len(result): # fill
sign = result[0]
result = sign * (length - len(result)) + result
elif length < len(result): # truncate
result = result[0:length]
return result
@staticmethod
def _float2twoscomp(
value: float,
length: int = -1,
rel_tol: float = _BINARY_RELATIVE_TOLERANCE,
warn_on_float: bool = False,
) -> str:
"""Converts float to two's-complement.
This is a utility function.
Users should use the constructor TwosComplement(value) instead.
If maximum precision is desired, use Fractions instead of floats.
Parameters:
value (float): number to be converted to twos-complement.
length (int): desired length of resulting string. If -1, result is neither
prefixed nor truncated. If length is too short to fit value, an
exception is raised. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
lenght.
Example of length 4 is '01.1'.
rel_tol (float): relative tolerance that influences precision further.
A bigger tolerance leads to a possibly less precise result.
A smaller tolerance leads to a possibly more precise result.
Returns:
str: twos-complement string of value
"""
if math.isnan(value) or math.isinf(value):
raise ArithmeticError(
f"ArithmeticError: argument {value} is NaN or infinity."
)
global _BINARY_WARNED_ABOUT_FLOAT
if value != int(value): # not an integer
if not _BINARY_WARNED_ABOUT_FLOAT:
_BINARY_WARNED_ABOUT_FLOAT = True
if warn_on_float:
print(
"Warning: possible loss of precision "
"due to mixing floats and TwosComplement. "
"Consider using Fraction instead of float."
)
# more precise to use Fraction than float
return TwosComplement._fraction2twoscomp(Fraction(value), length)
@staticmethod
def _float2twoscomp_implementation_with_less_precision(
value: float, length: int = -1, rel_tol: float = _BINARY_RELATIVE_TOLERANCE
) -> str:
"""Converts float to two's-complement.
This is a utility function.
Users should use the constructor TwosComplement(value) instead.
Does the same as _float2twoscomp() but with possibly less precision.
"""
if math.isnan(value) or math.isinf(value):
raise ArithmeticError(
f"ArithmeticError: argument {value} is NaN or infinity."
)
fp, ip = math.modf(value)
if fp == 0:
return TwosComplement._int2twoscomp(int(ip), length)
if fp < 0: # negative
intresult = TwosComplement._int2twoscomp(math.floor(value), -1)
else:
intresult = TwosComplement._int2twoscomp(int(ip), -1)
if intresult == "0" and fp < 0: # -0.x
intresult = "1"
fracresult = TwosComplement._frac2twoscomp(fp, -1)
result = intresult + "." + fracresult[2:]
if length < len(result) and length != -1:
raise OverflowError(f"Argument {value} does not fit into {length} digits.")
if length != -1:
sign = result[0]
result = sign * (length - len(result)) + result
return result
@staticmethod
def _fraction2twoscomp(
value: Fraction, length: int = -1, ndigits: int = _BINARY_PRECISION
) -> str:
"""Converts fraction to two's-complement.
This is a utility function.
Users should use the constructor TwosComplement(value) instead.
First parameter 'ndigits', then secundarily parameter 'length' will
be applied to result. 'ndigits' influences digits after decimal point,
'length' influences digits (sign bits) before the decimal point.
Parameters:
value (Fraction): number to be converted to twos-complement.
length (int): desired length of resulting string. If -1, result is neither
prefixed nor truncated. If length is too short to fit value, an
exception is raised. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
lenght.
Example of length 4 is '01.1'.
ndigits (int): desired digits after decimal point.
Returns:
str: twos-complement string of value
"""
if value.denominator == 1:
result = TwosComplement._int2twoscomp(value.numerator, length=length)
return result
# uses Fractions for computation for more precision
if value.numerator >= 0: # positive
# alternative implementation: just call function in Binary:
# result = Binary.fraction_to_string(value, ndigits, simplify=True)
# But to keep TwosComplement independent of Binary it was redone
# here.
result = bin(int(value)).replace(_PREFIX, "")
fraction_number = value - int(value)
if fraction_number > 0:
result += "."
rest = Fraction(0)
ii = 1
while ii < ndigits + 1:
b = Fraction(1, 2 ** ii)
if rest + b < fraction_number:
result += "1"
rest += b
elif rest + b > fraction_number:
result += "0"
elif rest + b == fraction_number:
result += "1"
break
ii += 1
if result[0] != "0":
result = "0" + result
else: # negative
absvalue = -value
digits = len(bin(int(absvalue)).replace(_PREFIX, "")) + 1
resultintpart = 2 ** digits - math.ceil(absvalue)
result = bin(resultintpart).replace(_PREFIX, "")
# remove duplicate 1s on left
result = "1" + result.lstrip("1")
fraction_number = absvalue - int(absvalue)
if fraction_number > 0:
result += "."
rest = Fraction(1)
ii = 1
while ii < ndigits + 1:
b = Fraction(1, 2 ** ii)
if rest - b < fraction_number:
result += "0"
elif rest - b > fraction_number:
rest -= b
result += "1"
elif rest - b == fraction_number:
result += "1"
break
ii += 1
# remove 0s on right
if "." in result:
result = result.rstrip("0")
if length != -1:
le = len(result)
if le > length:
raise OverflowError
result = result[0] * (length - le) + result
return result
@staticmethod
def _str2twoscomp(value: str, length: int = -1, simplify: bool = True) -> str:
"""Converts two's-complement string to possibly refined two's-complement
string.
This is a utility function.
Users should use the constructor TwosComplement(value) instead.
A possible simplification will be done before a possible length
extension.
Parameters:
value (str): twos-complement string to be converted to twos-complement.
length (int): desired length of resulting string. If -1, result is
not prefixed. If length is too short to fit value, an
exception is raised. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
length.
Example of length 4 is '01.1'.
simplify (bool): If True, result will be simplified. If False, result
will be left unchanged as much as possible.
Returns:
str: twos-complement string of value
"""
if TwosComplement.istwoscomplement(value):
if length < len(value) and length != -1:
raise OverflowError(
f"Argument {value} does not fit into {length} digits."
)
if simplify:
value = TwosComplement.simplify(value)
if length != -1:
sign = value[0]
value = sign * (length - len(value)) + value
return value
else:
raise ValueError(f"Argument {value} not a valid twos-complement.")
def istwoscomplement(value: str) -> bool:
"""Determine if string content has a valid two's-complement syntax.
Parameters:
value (str): string to check
Returns:
bool: True if value is a valid twos-complement. False otherwise.
"""
try:
TwosComplement.components(value)
# don't catch TypeError
except ValueError:
return False
return True
def components(
self_value: Union[str, TwosComplement], simplify: bool = True
) -> tuple[int, str, str, int]:
"""Returns sign, integer part (indicates sign in first bit), fractional
part, and exponent as a tuple of int, str, str, and int.
This is both a function and a method.
Examples:
Here are some examples for `simplify` being False.
* For 3.25*4, input '11.01e2' returns (1, '11', '01', 2).
* For 0, input '0' returns (0, '0', '', 0).
* For -1, input '1' returns (1, '1', '', 0).
* For 1, input '01' returns (0, '01', '', 0).
* For -0.5, input 1.1 returns (1, '1', '1', 0).
* For neg. number, input 101.010e-4 returns (1, '101', '010', -4).
* For pos. number, input 0101.010e-4 returns (0, '0101', '010', -4).
* For input 111101.010000e-4 returns (1, '111101', '010000', -4).
Here are some examples for `simplify` being True.
* For -3.25*4, input '1111101.11e2' returns (1, '101', '11', 2).
* For input '11111111.0111e4' returns (1, '1', '0111', 4).
* For 0, input '0' returns (0, '0', '', 0).
* For -1, input '1' returns (1, '1', '', 0).
* For 1, input '01' returns (0, '01', '', 0).
* For -0.5, input 1.1 returns (1, '1', '1', 0).
* For neg. number, input 111101.0100e-4 returns (1, '101', '01', -4).
* For pos. number, input 0000101.0100e-4 returns (0, '0101', '01', -4).
Parameters:
self_value (str, TwosComplement): twos-complement from which to
derive the components.
simplify (bool): If True simplify output by performing cleanup and
removing unnecessary digits.
If False, then produce exact as-is twos-complement components
without any cleanup or simplifications.
Returns:
tuple: tuple of sign (int), integer part (str) including a sign bit,
fractional part (str), exponent (int). Sign is int 1 for negative (-).
Sign is int 0 for positive (+).
"""
if not isinstance(self_value, str) and not isinstance(
self_value, TwosComplement
):
raise TypeError(
f"Argument {self_value} must be of type str or TwosComplement."
)
# crud for parsing strings
#
# Regular expression used for parsing twos-complement strings. Additional
# comments:
#
# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
# whitespace. But note that the specification disallows whitespace in
# a numeric string.
#
# 2. For finite numbers the body of the
# number before the optional exponent must have
# at least one binary digit. The
# lookahead expression '(?=[01])' checks this.
_parser = re.compile(
r""" # A twoscomplement string consists of:
\s*
(
(?=[01]) # lookahead: a number (with at least one digit)
(?P<int>[01]+) # non-empty integer part with at least 1 digit
(\.(?P<frac>[01]*))? # followed by an optional fractional part
(E(?P<exp>[-+]?\d+))? # followed by an optional exponent
)
\s*
\Z
""",
re.VERBOSE | re.IGNORECASE,
).match
m = _parser(self_value)
if m is None:
raise ValueError(
f"Invalid literal: {self_value}. "
+ "Not a valid twos-complement string."
)
intpart = m.group("int")
fracpart = m.group("frac") or ""
exp = int(m.group("exp") or "0")
# according to parser int cannot be empty
if intpart[0] == "0":
sign = 0 # "+"
else:
sign = 1 # "-"
if simplify:
fracpart = fracpart.rstrip("0")
if sign: # neg
intpart = "1" + intpart.lstrip("1")
else: # pos
intpart = "0" + intpart.lstrip("0")
return (sign, intpart, fracpart, exp)
def simplify(self_value: Union[str, TwosComplement]) -> Union[str, TwosComplement]:
"""Simplifies two's-complement strings.
This is a utility function as well as a method.
Removes leading duplicate 0s or 1s to the left of decimal point.
Removes trailing duplicate 0s after decimal point.
Removes unnecessary exponent 0.
Parameters:
self_value (str, TwosComplement): twos-complement string to be simplified
Returns:
Union[str, TwosComplement]: returns simplied twos-complement. Return type is
str if input was of class str, return type is
TwosComplement if input was of class TwosComplement.
"""
if not isinstance(self_value, str) and not isinstance(
self_value, TwosComplement
):
raise TypeError(
f"Argument {self_value} must be of type str or TwosComplement."
)
value = str(self_value)
sign, intpart, fracpart, exp = TwosComplement.components(value)
if len(intpart) and intpart[0] == "1":
# remove duplicate 1s on left
intpart = "1" + intpart.lstrip("1")
elif len(intpart) and intpart[0] == "0":
# remove duplicate 0s on left
intpart = "0" + intpart.lstrip("0")
# remove duplicate 0s to right of decimal point
fracpart = fracpart.rstrip("0")
if fracpart != "":
fracpart = "." + fracpart
exppart = "" if exp == 0 else _EXP + str(exp)
result = intpart + fracpart + exppart
if isinstance(self_value, TwosComplement):
result = TwosComplement(result)
return result
def to_fraction(self_value: Union[str, TwosComplement]) -> Fraction:
"""Converts two's-complement to Fraction.
This is a utility function as well as a method.
Do *NOT* use it on binary fractions strings!
Parameters:
self_value (str, TwosComplement): twos-complement string to be
converted to Fraction
Returns:
Fraction: returned value as a Fraction
"""
if not isinstance(self_value, str) and not isinstance(
self_value, TwosComplement
):
raise TypeError(
f"Argument {self_value} must be of type str or TwosComplement."
)
value = str(self_value)
noman = TwosComplement.to_no_mantissa(value)
sign, intpart, fracpart, exp = TwosComplement.components(noman)
intpartlen = len(intpart)
if value[0] == "0": # positive twos-complement
num = int(intpart, 2)
else:
num = -(2 ** intpartlen - int(intpart, 2))
if exp < 0:
denom = 2 ** (-exp)
else:
num = num * 2 ** exp
denom = 1
result = Fraction(num, denom)
return result
def to_float(self_value: Union[str, TwosComplement]) -> float:
"""Converts two's-complement to float.
This is a utility function as well as a method.
Do *NOT* use it on binary fractions strings!
Parameters:
self_value (str, TwosComplement): twos-complement string to be
converted to float
Returns:
float: returned value as a float
"""
return float(TwosComplement.to_fraction(self_value))
def to_no_mantissa(
self_value: Union[str, TwosComplement], length: int = -1
) -> Union[str, TwosComplement]:
"""Adjusts exponent such that there is no fractional part, i.e. no mantissa.
This is a utility function as well as a method.
Do *NOT* use it on binary fractions strings!
The value does not change. The precision does not change.
Only the integer part and the exponent change such that the
same value is represented but without mantissa.
Examples:
* converts 1.1 to 11e-1
* converts 01.11 to 0111e-2
Parameters:
self_value (str, TwosComplement): twos-complement string to be
converted to representation without mantissa
length (int): desired length of resulting string. If -1, result is
not prefixed. If length is too short to fit value, an
exception is raised. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
length.
Example of length 4 is '01.1'.
Returns:
Union[str, TwosComplement]: returns twos-complement without mantissa.
Return type is
str if input was of class str, return type is
TwosComplement if input was of class TwosComplement.
"""
if not isinstance(self_value, str) and not isinstance(
self_value, TwosComplement
):
raise TypeError(
f"Argument {self_value} must be of type str or TwosComplement."
)
value = str(self_value)
sign, intpart, fracpart, exp = TwosComplement.components(value)
fracpartlen = len(fracpart)
exp -= fracpartlen
intpart += fracpart
result = intpart + _EXP + str(exp) if exp else intpart
if isinstance(self_value, TwosComplement):
result = TwosComplement(result)
if length != -1:
le = len(result)
# NOTE: this function does not implement shortening or truncating
if le > length:
raise OverflowError
result = result[0] * (length - le) + result
return result
def to_no_exponent(
self_value: Union[str, TwosComplement], length: int = -1, simplify: bool = True
) -> Union[str, TwosComplement]:
"""Remove exponent part from twos-complement string.
This is a utility function as well as a method.
Do *NOT* use it on binary fractions strings!
The value does not change. The precision does not change.
Only the integer part and the mantissa change such that the
same value is represented but without exponent.
Any possible simplification will be done before any possible length adjustment.
It removes the exponent, and returns a fully "decimal" twos-complement string.
Examples:
* converts '011.01e-2' to '0.1101'.
* converts 0.25, '0.1e-1' to '0.01'.
* converts -0.125, '1.111e0' to '1.111'.
* converts -0.25, '1.11e0' to '1.11'.
* converts -0.5, '1.1e0' to '1.1'.
* converts -1.0, '1.e0' to '1'.
* converts -2.0, '1.e1' to '10'.
* converts -3.0, '1.01e2' to '101'.
* converts -1.5, '1.01e1' to '10.1'.
* converts -2.5, '1.011e2' to '101.1'.
Parameters:
self_value (str, TwosComplement): twos-complement string to be
converted to representation without exponent
length (int): desired length of resulting string. If -1, result is
not prefixed. If length is too short to fit value, an
exception is raised. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
length.
Example of length 4 is '01.1'.
simplify (bool): If True simplify output by performing cleanup and
removing unnecessary digits.
If False, then produce exact as-is twos-complement components
without any cleanup or simplifications.
Returns:
Union[str, TwosComplement]: returns twos-complement without exponent.
Return type is
str if input was of class str, return type is
TwosComplement if input was of class TwosComplement.
"""
if not isinstance(self_value, str) and not isinstance(
self_value, TwosComplement
):
raise TypeError(
f"Argument {self_value} must be of type str or TwosComplement."
)
if length <= 0 and length != -1:
raise ValueError(f"Argumet {length} must be bigger than 0 or -1")
value = str(self_value)
if _NAN.lower() in value.lower() or _INF.lower() in value.lower():
raise ArithmeticError(
f"ArithmeticError: argument {self_value} is NaN or infinity."
)
if len(value) == 0 or _PREFIX in value or value[0] == "-":
raise ValueError(
f"Argument {value} must not contain prefix 0b or negative sign -. "
"It should be two's complement string such as 10.1e-23."
)
sign, intpart, fracpart, exp = TwosComplement.components(value, simplify)
if exp == 0:
result = intpart + "." + fracpart
elif exp > 0:
le = len(fracpart[:exp])
result = intpart + (
fracpart[:exp] if le > exp else fracpart[:exp] + "0" * (exp - le)
)
result += "." + fracpart[exp:]
elif exp < 0:
le = len(intpart)
aexp = abs(exp)
signdigit = "1" if sign else "0"
if le > aexp:
result = (
intpart[: (le - aexp)] + "." + intpart[(le - aexp) :] + fracpart
)
else: # le <= aexp
result = (
intpart[0]
+ "."
+ signdigit * (aexp - le + 1)
+ intpart[1:]
+ fracpart
)
if "." not in value:
result = result.rstrip(".")
if _EXP in value:
result = result.rstrip(".")
if simplify:
# result = "1" + result.lstrip("1")
# result = result.rstrip("0")
# result = result.rstrip(".")
result = TwosComplement.simplify(result)
if length != -1:
le = len(result)
if le > length:
raise OverflowError
ii = length - le
result = result[: le - ii] if ii < 0 else result[0] * ii + result
if isinstance(self_value, TwosComplement):
result = TwosComplement(result)
return result
def invert(
self_value: Union[str, TwosComplement], simplify: bool = True
) -> Union[str, TwosComplement]:
"""Inverts (bitwise negates) string that is in two's-complement format.
This is a utility function as well as a method.
Do *NOT* use this function on binary fractions strings.
It negates (flips) every bit in the given twos-complement string.
Using 'simplify' can lead to a representation that drops
leading and/or trailing bits for simplification. If no bits
should be dropped by `invert`, set `simplify` to False.
`invert` will try to maintain the representation of the input.
If the input has an exponent, the output will have an exponent.
If the input has no exponent, the output will have no exponent.
Examples:
* invert('01') returns '10' (like decimal: ~1==-2)
* invert('0') returns 1 (like decimal: ~0==-1)
* invert('1') returns 0 (like decimal: ~-1==0)
* invert('10') returns '01' (like decimal: ~-2==1)
* invert('101010') returns '010101'
* invert('0101010') returns '1010101'
* invert('0101010e-34') returns '1010101e-34'
* invert('1010101e-34') returns '0101010e-34'
* invert(invert('0101010e-34')) returns '0101010e-34'
* invert('010101e34') returns '101010.1111111111111111111111111111111111e34'
* invert('101010e34') returns '010101.1111111111111111111111111111111111e34'
* invert(invert('101010e34')) returns '101010e34'
* invert(invert(n)) == n for all valid n
* invert('1..1') raises exception, 2 decimal points
* invert('34') raises exception, not binary
* invert('1ee2') raises exception, two exponential signs
* invert('1e') raises exception, missing exponent digit
Parameters:
self_value (str, TwosComplement): twos-complement string to be
inverted
simplify (bool): If False, try to change the string as little as
possible in format.
If True, returned string will also be simplified
by removing unnecessary digits.
Returns:
Union[str, TwosComplement]: returns the bitwise negated string,
a twos-complement formated string. The
return type is
str if input was of class str, return type is
TwosComplement if input was of class TwosComplement.
"""
if not isinstance(self_value, str) and not isinstance(
self_value, TwosComplement
):
raise TypeError(
f"Argument {self_value} must be of type str or TwosComplement."
)
value = str(self_value)
if _NAN.lower() in value.lower() or _INF.lower() in value.lower():
raise ArithmeticError(
f"ArithmeticError: argument {value} is NaN or infinity."
)
if not TwosComplement.istwoscomplement(value):
raise ValueError(f"Argument {value} not a valid twos-complement literal.")
if _EXP in value:
sign, intpart, fracpart, exp = TwosComplement.components(value, simplify)
if exp > 0:
# # Alternative implementation A: using TwosComplement.to_no_exponent()
# # simplify = False to not miss any bits on the right
# value = TwosComplement.to_no_exponent(value, simplify=False)
# Alternative implementation B:
# just adding sufficient 0s after decimal point
fl = len(fracpart)
# if negative, no 0s will be added
fracpart += "0" * (exp - fl)
value = intpart + "." + fracpart + _EXP + str(exp)
# assert len(fracpart) >= exp
result = ""
for i in value:
if i == "0":
result += "1"
elif i == "1":
result += "0"
elif i == ".":
result += "."
elif i.lower() == _EXP:
result += _EXP + str(exp)
break
else:
raise ValueError(f"Unexpected literal {i} in {value}.")
if simplify:
result = TwosComplement.simplify(result)
if isinstance(self_value, TwosComplement):
result = TwosComplement(result)
return result
##########################################################################
# CLASS BINARY
##########################################################################
class Binary(object):
"""Floating point class for binary fractions and arithmetic.
The class Binary implements a basic representation and basic operations
of binary fractions and binary floats:
A binary fraction is a subset of binary floats. Basically, a binary fraction
is a binary float without an exponent (e.g. '-0b101.0101').
Let's have a look at an example binary float value to see how it is represented.
```
prefix '0b' to indicate "binary" or "base 2"
||
|| decimal point
|| |
|| | exponent separator
|| | |
|| | | exponent in base 10 (not in base 2!)
|| | | ||
-0b101.0101e-34 <-- example floating-point binary fraction
| ||| |||| |
sign ||| |||| exponent sign
||| ||||
||| fraction bits in base 2
|||
integer bits in base 2
```
Valid binary fraction of class 'Binary' are:
0, 1, 10, 0.0, 1.1, 1., 0.1e+34, -1, -10, -0.0, -1.1, -1., -0.1e+34,
11101.e-56, 101.01e78. 000011.1000e0 is valid and is the same as 11.1.
Along the same line, 111101.0100000e-000 is valid and is the same as 111101.01.
Invalid binary fraction of class 'Binary' are: --1 (multiple minus),
*1 (asterisk),
12 (2 is not a binary digit),
1.2.3 (2 decimal points),
1e (missing exponent number),
1e-1.1 (decimal point in exponent).
If you are curious about floating point binary fractions, have a look at:
- https://en.wikipedia.org/wiki/Computer_number_format#Representing_fractions_in_binary
- https://www.electronics-tutorials.ws/binary/binary-fractions.html
- https://ryanstutorials.net/binary-tutorial/binary-floating-point.php
- https://planetcalc.com/862/
"""
__slots__ = [
"_fraction",
"_string",
"_sign",
"_is_special",
"_warn_on_float",
"_is_lossless",
]
def __new__(
cls,
value: Union[int, float, str, Fraction, TwosComplement, Binary] = "0",
simplify: bool = True,
warn_on_float: bool = False,
) -> Binary:
"""Constructor.
Use __new__ and not __init__ because Binary objects are immutable.
Allows string, float, integer, Fraction and TwosComplement
as input for constructor.
With 'simplify' being False, if an instance is contructed from a
string, attention is paid to *not*
modify the string or to modify it as little as possible.
For example, if given '1e1' it will remain as '1e1', it will not change it
to '1'. Same with '1000', it will not change it to '1e4'. We try to keep then
string representation as close to the original as possible.
With 'simplify' set to True, simplifications will be performed, e.g.
'+01e0' will be turned into '1'.
Examples:
* Binary(123)
* Binary(123.456)
* Binary(Fraction(179, 1024))
* Binary('-101.0101e-45')
* Binary(TwosComplement(Fraction(179, 1024)))
Parameters:
value (int, float, str): value of number
simplify (bool): If True try to simplify string representation.
If False, try to leave the string representation as much as is.
warn_on_float (bool): if True print a warning statement to stdout to
warn about possible loss in precision in case of conversion from
float to Binary.
If False, print no warning to stdout.
Returns:
Binary: created immutable instance
"""
# crud for parsing strings
#
# Regular expression used for parsing numeric strings. Additional
# comments:
#
# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
# whitespace. But note that the specification disallows whitespace in
# a numeric string.
#
# 2. For finite numbers (not infinities and NaNs) the body of the
# number between the optional sign and the optional exponent must have
# at least one Binary digit, possibly after the Binary point. The
# lookahead expression '(?=\d|\.\d)' checks this.
_parser = re.compile(
r""" # A numeric string consists of:
\s*
(?P<sign>[-+])? # an optional sign, followed by either...
(
(?=\d|\.[01]) # ...a number (with at least one digit)
(?P<int>[01]*) # having a (possibly empty) integer part
(\.(?P<frac>[01]*))? # followed by an optional fractional part
(E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
|
Inf(inity)? # ...an infinity, or...
|
(?P<signal>s)? # ...an (optionally signaling)
NaN # NaN
(?P<diag>\d*) # with (possibly empty) diagnostic info.
)
\s*
\Z
""",
re.VERBOSE | re.IGNORECASE,
).match
global _BINARY_WARNED_ABOUT_FLOAT
self = super(Binary, cls).__new__(cls)
self._fraction = Fraction()
self._string = ""
self._sign = 0 # 0 indicates positive, 1 indicates negative sign
self._is_special = False
self._warn_on_float = warn_on_float
# indicate if operations were lossless
# if True it was lossless,
# if False it might be lossy (but it could also be lossless)
self._is_lossless = True
# From a TwosComplement string
# important that this isinstance check is BEFORE isinstance(str) check!
if isinstance(value, TwosComplement):
resultbin = Binary(TwosComplement.to_fraction(value))
if simplify:
return resultbin
else: # not simplify
sign, fracpart, intpart, exp = TwosComplement.components(
value, simplify
)
resultbin = resultbin.to_exponent(exp)
if _EXP in value and exp == 0:
resultstr: str = resultbin.string
if _EXP not in resultstr: # check just in case
resultstr += _EXP + "0" # keep it as alike as possible
return Binary(resultstr, simplify=False)
else:
return resultbin
# From a string
# REs insist on real strings, so we can too.
if isinstance(value, str):
value = value.strip().replace("_", "")
if len(value) >= 3:
if value[0:3] == ("-" + _PREFIX):
value = "-" + value[3:]
elif value[0:2] == _PREFIX:
value = value[2:]
m = _parser(value)
if m is None:
raise ValueError(f"Invalid literal for Binary: {value}.")
if m.group("sign") == "-":
signstr = "-"
self._sign = 1
else:
signstr = ""
self._sign = 0
intpart = m.group("int")
if intpart is not None:
# finite number
if not simplify:
self._string = value # leave as is
else:
fracpart = m.group("frac") or ""
fracpart = fracpart.rstrip("0")
exp = int(m.group("exp") or "0")
if exp != 0:
# # version A: this normalizes to remove decimal point
# intpart = str(int(intpart + fracpart))
# exppart = str(exp - len(fracpart))
# self._string = signstr + intpart + _EXP + exppart
# version B: this leaves string as much as is
if fracpart == "":
self._string = signstr + intpart + _EXP + str(exp)
else:
self._string = (
signstr + intpart + "." + fracpart + _EXP + str(exp)
)
else:
if fracpart == "":
self._string = signstr + intpart
else:
self._string = signstr + intpart + "." + fracpart
else:
self._is_special = True
diag = m.group("diag")
if diag is not None:
# NaN
if m.group("signal"):
self._string = _NAN # "NaN", N, ignore signal
else:
self._string = _NAN # "NaN", n, ignore signal
else:
# infinity
self._string = signstr + "Infinity" # F
if not self._is_special:
self._fraction = Binary.to_fraction(self._string)
return self
# From a tuple/list conversion (possibly from as_tuple())
if isinstance(value, (list, tuple)):
if len(value) != 3:
raise ValueError(
"Invalid tuple size in creation of Decimal "
"from list or tuple. The list or tuple "
"should have exactly three elements."
)
# process sign. The isinstance test rejects floats
if not (isinstance(value[0], int) and value[0] in (0, 1)):
raise ValueError(
"Invalid sign. The first value in the tuple "
"should be an integer; either 0 for a "
"positive number or 1 for a negative number."
)
if value[0]:
self._sign = 1
sign = "-"
else:
self._sign = 0
sign = ""
if value[2] == "F":
# infinity: value[1] is ignored
self._string = "Infinity"
self._is_special = True
else:
# process and validate the digits in value[1]
digits = []
for digit in value[1]:
if isinstance(digit, int) and 0 <= digit <= 1:
# skip leading zeros
if digits or digit != 0:
digits.append(digit)
else:
raise ValueError(
"The second value in the tuple must "
"be composed of integers in the range "
"0 through 1."
)
if value[2] in ("n", "N"):
# NaN: digits form the diagnostic
self._string = _NAN # "NaN"
self._is_special = True
elif isinstance(value[2], int):
# finite number: digits give the coefficient
integer = "".join(map(str, digits or [0]))
self._string = sign + integer + _EXP + str(value[2])
else:
raise ValueError(
"The third value in the tuple must "
"be an integer, or one of the "
"strings 'F', 'n', 'N'."
)
if not self._is_special:
self._fraction = Binary.to_fraction(self._string)
return self
# From another Binary
if isinstance(value, Binary):
self._sign = value.sign
self._string = value.string
self._fraction = value.fraction
self._is_lossless = value.islossless
self._is_special = value.isspecial
self._warn_on_float = value.warnonfloat
return self
if isinstance(value, Fraction):
self._fraction = value
self._string = Binary.fraction_to_string(value)
self._sign = 1 if value < 0 else 0
return self
# From an integer
if isinstance(value, int):
self._fraction = Fraction(value)
# self._string = Binary.fraction_to_string(self._string)
self._string = bin(value).replace(_PREFIX, "")
self._sign = 1 if value < 0 else 0
return self
# from a float
if isinstance(value, float):
if math.isnan(value):
return Binary(_NAN)
if value == float("inf"):
return Binary(_INF)
if value == float("-inf"):
return Binary(_NINF)
if value != int(value): # not an integer
if not _BINARY_WARNED_ABOUT_FLOAT:
_BINARY_WARNED_ABOUT_FLOAT = True
if self._warn_on_float:
print(
"Warning: possible loss of precision "
"due to mixing floats and Binary. "
"Consider using Fraction instead of float."
)
if value != int(value):
self._is_lossless = False
self._fraction = Fraction(value)
self._string = Binary.fraction_to_string(value)
self._sign = 1 if value < 0 else 0
return self
# any other types
raise TypeError(f"Cannot convert {value} to Binary")
@staticmethod
def to_float(value: str) -> Union[float, int]:
"""Convert from Binary string to float or integer.
This is a utility function that converts
a Binary string to a float or integer.
This might lead to loss of precision due to possible float conversion.
If you need maximum precision consider working with `Fractions.`
Parameters:
value (str): binary string representation of number
Returns:
Union[float, int]: number as float or integer
"""
if not isinstance(value, str):
raise TypeError(f"Argument {value} must be of type str.")
# Alternative implementation:
# could also use inverse of method float.hex()
if value.lower() == "inf" or value.lower() == "infinity":
return float("inf")
elif value.lower() == "-inf" or value.lower() == "-infinity":
return float("-inf")
elif value.lower() == "nan" or value.lower() == "-nan":
return float("nan")
value = Binary.to_no_exponent(
value
) # type: ignore # pypi complains, but this is ok
li = value.split(".")
intpart = li[0]
result = int(intpart, 2)
if result < 0:
sign = -1
else:
sign = 1
if len(li) == 1:
fracpart = ""
return result # an integer
else:
fracpart = li[1]
le = len(fracpart)
for i in range(le):
if fracpart[i] == "1":
result += (2 ** -(i + 1)) * sign
return result # float
@staticmethod
def from_float(value: float, rel_tol: float = _BINARY_RELATIVE_TOLERANCE) -> str:
"""Convert from float to Binary string of type string.
This is a utility function. It converts from
float to Binary.
This might lead to loss of precision due to possible float conversion.
If you need maximum precision consider working with `Fractions.`
Parameters:
value (float): value of number
rel_tol (float): relative tolerance to know when to stop converting.
A smaller rel_tol leads to more precision.
Returns:
str: string representation of Binary string
"""
# alternative implementation: could also use method float.hex()
if not isinstance(value, float):
raise TypeError(f"Argument {value} must be of type float.")
if value == float("inf"):
return "inf" # lowercase like in float class
elif value == float("-inf"):
return "-inf" # lowercase like in float class
elif math.isnan(value): # NOT CORRECT: value == float("-nan"):
return "nan" # lowercase like in float class
if value >= 0:
sign = ""
else:
sign = "-"
value = abs(value)
integer = int(value)
intpart = bin(integer).replace(_PREFIX, "")
fracpart = ""
rest = 0.0
i = 1
fraction = value - integer
while not (math.isclose(rest, fraction, rel_tol=rel_tol)):
b = 2 ** -i
if b + rest <= fraction:
fracpart += "1"
rest += b
else:
fracpart += "0"
i += 1
result = sign + _PREFIX + intpart + "." + fracpart
return Binary.simplify(result, add_prefix=True)
def to_no_exponent(
self_value: Union[Binary, str],
length: int = -1,
simplify: bool = True,
add_prefix: bool = False,
) -> Union[Binary, str]:
"""Normalizes string representation. Removes exponent part.
This is both a method as well as a utility function.
Do *NOT* use it on Twos-complement strings!
It removes the exponent, and returns a fully "decimal" binary string.
Any possible simplification will be done before any possible length adjustment.
Examples:
* converts '11.01e-2' to '0.1101'
Parameters:
self_value (Binary, str): a Binary instance or
a binary string representation of number
length (int): desired length of resulting string. If -1, result is
not prefixed. If length is too short to fit value, an
exception is raised. A larger length will prefix the decimal digits
with additional sign bits to produce a resulting string of specified
length.
Example of length 4 is '01.1'.
simplify (bool): If True try to simplify string representation.
If False, try to leave the string representation as much as is.
add_prefix (bool):
if self_value is a string:
if True add 0b prefix to returned output,
if False then do not add prefix to returned output
if self_value is a Binary instance:
always forces to True, will always show prefix 0b
Returns:
Union[Binary, str]: binary string representation of number
If self_value was of class Binary, it returns a Binary instance.
If self_value was of class str, it returns a str instance.
"""
if not (isinstance(self_value, str) or isinstance(self_value, Binary)):
raise TypeError(f"Argument {self_value} must be of type Binary or str.")
if isinstance(self_value, Binary):
return Binary(
Binary.to_no_exponent(
self_value.string, length=length, simplify=simplify
)
)
if self_value == "":
raise ValueError(f"Argument {self_value} must not be empty string.")
value: str = self_value # it is a string
# print(f"before normalize {value}")
if _NAN.lower() in value.lower() or _INF.lower() in value.lower():
return value
value = value.replace(_PREFIX, "") # just in case: remove 0b prefix
if _EXP not in value:
result = value
else:
li = value.split(_EXP)
intfracpart = li[0]
exp = int(li[1])
li = intfracpart.split(".")
intpart = li[0]
intpart = "0" if intpart == "" else intpart
if len(li) == 1:
fracpart = ""
else:
fracpart = li[1]
lenintpart = len(intpart)
lenfracpart = len(fracpart)
if exp >= 0:
if lenfracpart <= exp:
fracpart += "0" * (exp - lenfracpart)
result = intpart + fracpart
else:
intpart += fracpart[:exp]
fracpart = fracpart[exp:]
result = intpart + "." + fracpart
else: # exp < 0
if lenintpart <= abs(exp):
if intpart[0] == "-":
intpart = "0" * (abs(exp) - lenintpart + 1) + intpart[1:]
result = "-0." + intpart + fracpart
else:
intpart = "0" * (abs(exp) - lenintpart) + intpart
result = "0." + intpart + fracpart
else:
fracpart = intpart[exp:] + fracpart
if intpart[:exp] == "":
intpart = "0"
elif intpart[:exp] == "-":
intpart = "-0"
else:
intpart = intpart[:exp]
result = intpart + "." + fracpart
if simplify:
result = Binary.simplify(result, add_prefix)
if length != -1:
le = len(result)
if le > length:
raise OverflowError
result = "0" * (length - le) + result
# print(f"after normalize {value} {result}")
return result # str
def to_no_mantissa(self: Binary) -> Binary:
"""Convert to exponential representation without fraction,
i.e. without mantissa.
A method that changes the string representation of a number
so that the resulting string has no decimal point.
The value does not change. The precision does not change.
Examples:
* converts '1.1' to '11e-1'
* converts '-0.01e-2' to '-1e-4'
Parameters:
none
Returns:
Binary: binary string representation of number
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isspecial:
raise OverflowError(
f"Argument 'self' ({self}): cannot convert NaN and infinities."
)
value = self.string
if _EXP not in value:
exp = 0
intfracpart = Binary.simplify(value)
else:
li = value.split(_EXP)
intfracpart = Binary.simplify(li[0])
exp = int(li[1])
li = intfracpart.split(".")
intpart = li[0]
if len(li) == 1:
fracpart = ""
else:
fracpart = li[1]
# lenintpart = len(intpart)
lenfracpart = len(fracpart)
exp -= lenfracpart
intpart += fracpart
if self.sign:
intpart = "-" + intpart[1:].lstrip("0") if len(intpart) > 1 else intpart
else:
intpart = intpart.lstrip("0") if len(intpart) > 1 else intpart
result = intpart + _EXP + str(exp)
# do not remove possible e0 by simplifying it
return Binary(result, simplify=False)
def to_exponent(self: Binary, exp: int = 0) -> Binary:
"""Convert to exponential representation with specified exponent.
This is a method that changes string representation of number.
It does not change the value. It does not change the precision.
If `exp` is not set, it defaults to 0, producing a respresentation
without an exponent, same as `to_no_exponent()`.
Examples:
* converts '1.1' with exp=0 ==> '1.1'
* converts '1.1' with exp=3 ==> '0.0011e3'
* converts '1.1' with exp=-3 ==> '1100e-3'
* converts '-0.01e-2' with exp=2 ==> '-0.000001e2'
Parameters:
exp (int): the desired exponent, 0 is the default
Returns:
Binary: binary string representation of number
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isspecial:
raise OverflowError(
f"Argument 'self' ({self}): cannot convert NaN and infinities."
)
sign, intpart, fracpart, _ = self.to_no_exponent().components() # type: ignore
result = "-" if sign else ""
if exp >= 0:
new_intpart = intpart[: len(intpart) - exp]
new_fracpart = (
"0" * (-len(intpart) + exp) + intpart[len(intpart) - exp :] + fracpart
)
else:
new_intpart = (
intpart + fracpart[: abs(exp)] + (-len(fracpart) + abs(exp)) * "0"
)
new_fracpart = fracpart[abs(exp) :]
result += new_intpart + "." + new_fracpart + _EXP + str(exp)
return Binary(Binary.simplify(result))
def to_sci_exponent(self: Binary) -> Binary:
"""Convert to exponential representation in scientific notation.
This is a method that changes string representation of number.
It does not change the value. It does not change the precision.
Scientific notation is an exponent representation with a single
binary digit before decimal point.
The decimal part is always 1 or -1 except for the number 0.
Examples:
* converts '1.1' ==> '1.1e0'
* converts '-0.01e-2' ==> '-1e-4'
Parameters:
none
Returns:
Binary: binary string representation of number
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isspecial:
raise OverflowError(
f"Argument 'self' ({self}): cannot convert NaN and infinities."
)
value = self.string
if _EXP not in value:
exp = 0
intfracpart = Binary.simplify(value)
else:
li = value.split(_EXP)
intfracpart = Binary.simplify(li[0])
exp = int(li[1])
li = intfracpart.split(".")
intpart = li[0]
if len(li) == 1:
fracpart = ""
else:
fracpart = li[1]
if self.sign:
intpart = intpart[1:]
sign = "-"
else:
sign = ""
lenintpart = len(intpart)
intfracpart = intfracpart.replace(".", "").replace("-", "")
middle = 1
start = 0
exp += lenintpart - 1
while True:
if middle > len(intfracpart):
break
if intfracpart[start : start + 1] != "0":
fracpart = intfracpart[middle:]
intpart = intfracpart[start:middle]
break
start += 1
middle += 1
exp -= 1
if fracpart == "" or fracpart == "0":
result = sign + intpart + _EXP + str(exp)
else:
result = sign + intpart + "." + fracpart + _EXP + str(exp)
# do not remove possible e0 by simplifying it
return Binary(result, simplify=False)
def to_eng_exponent(self: Binary) -> Binary:
"""Convert to exponential representation in engineering notation.
- See https://www.purplemath.com/modules/exponent4.htm.
- See https://www.thinkcalculator.com/numbers/decimal-to-engineering.php
- See https://en.wikipedia.org/wiki/Engineering_notation.
- See https://en.wikipedia.org/wiki/Engineering_notation#Binary_engineering_notation
Engineering notation is an exponent representation with the exponent
modulo 10 being 0, and where there are 1 through 9 digit before the
decimal point.
The integer part must not be 0 unless the number is 0.
The integer part is from 1 to 1023, or written in binary fraction
from 0b1 to 0b111111111.
Method that changes string representation of number. It does not change
value. It does not change precision.
Examples:
* converts '1.1' ==> '1.1'
* converts '1.1111' ==> '1.1111'
* converts '100.1111' ==> '100.1111'
* converts '1.1111' ==> '1.1111'
* converts '10.1111' ==> '10.1111'
* converts '100.1111' ==> '100.1111'
* converts '1000.1111' ==> '1000.1111'
* converts 1023 ==> '1111111111' => '1111111111'
* converts 1024 ==> '10000000000' => '1e10'
* converts 1025 ==> '10000000001' => '1.0000000001e10'
* converts 3072 ==> '110000000000' ==> 1.1e10
* converts 1024 ** 2 ==> '1000000000000000000000000000000' => '1e20'
* converts '0.1' => '100000000e-10'
* converts '0.11' => '110000000e-10'
* converts '0.01' => '10000000e-10'
* converts '0.0000000001' => '1e-10'
* converts '0.000000001' => '10e-10'
* converts '0.00000000111' => '11.1e-10'
* converts '.11111e1' ==> '1.1111'
* converts '.011111e2' ==> '1.1111'
* converts '.0011111e3' ==> '1.1111'
* converts '-0.01e-2' ==> '-1e-3' => '-1000000e-10'
* converts '-0.0001e-4' == -0.00000001 ==> '-100e-10',
* converts '-0.0001111e-4' == -0.00000001111 ==> '-111.1e-10',
Parameters:
none
Returns:
Binary: binary string representation of number
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isspecial:
raise OverflowError(
f"Argument 'self' ({self}): cannot convert NaN and infinities."
)
if self.string == Binary.simplify("0"):
return Binary("0")
if _EXP in self.string:
value = self.to_no_exponent().string # type: ignore
else:
value = self.string
sign, intpart, fracpart, exp = Binary.get_components(value)
assert exp == 0
result = "-" if sign else ""
i = math.floor((len(intpart) - 1) / 10) * 10
new_intpart = intpart[: len(intpart) - i]
new_intpart = "0" if new_intpart == "" else new_intpart
while new_intpart == "0":
i -= 10
new_intpart = intpart[: len(intpart) + i]
if i > 0:
new_fracpart = intpart[len(intpart) - i :] + fracpart
else:
new_intpart += fracpart[: abs(i)] + "0" * (abs(i) - len(fracpart[: abs(i)]))
new_fracpart = fracpart[abs(i) :]
result += new_intpart + "." + new_fracpart
result = result.rstrip("0")
result = result.rstrip(".")
result += _EXP + str(i)
return Binary(Binary.simplify(result))
def to_fraction(self_value: Union[str, Binary]) -> Fraction:
"""Convert string representation of Binary to Fraction.
This is a utility function. If operating on `Binary` use
method `fraction()` instead.
Parameters:
self_value (str, Binary): binary number as string
Returns:
Fraction: self_value as fraction
"""
if not isinstance(self_value, str) and not isinstance(self_value, Binary):
raise TypeError(f"Argument {self_value} must be of type str or Binary.")
if isinstance(self_value, Binary):
# this is just an alternative way to get the fraction part of a Binary
return self_value.fraction
sign, intpart, fracpart, exp = Binary.get_components(self_value)
exp -= len(fracpart)
if exp > 0:
result = Fraction((-1) ** sign * int(intpart + fracpart, 2) * (2 ** exp), 1)
else:
result = Fraction((-1) ** sign * int(intpart + fracpart, 2), 2 ** -exp)
return result
@staticmethod
def to_fraction_alternative_implementation(value: str) -> Fraction:
"""Convert string representation of Binary to Fraction.
This is a utility function.
This is an alternative implementation with possibly less precision.
Use function `to_fraction()` or method `fraction()` instead.
Parameters:
value (str): binary number as string
Returns:
Fraction: value as fraction
"""
if not isinstance(value, str):
raise TypeError(f"Argument {value} must be of type str.")
if _EXP in value:
value = Binary.to_no_exponent(value) # type: ignore
sign, intpart, fracpart, exp = Binary.get_components(value)
result = Fraction(int(intpart, 2))
le = len(fracpart)
for i in range(le):
c = fracpart[i]
if c == "1":
result += Fraction(1, 2 ** (i + 1))
return result if sign == 0 else -result
def to_twoscomplement(self: Binary, length: int = -1) -> TwosComplement:
"""Computes the representation as a string in twos-complement.
This is a method returning a string of class `TwosComplement`.
See `TwosComplement` class for more details on twos-complement format.
Examples:
* converts '-11.1e-2' to '101.1e-2' (-3/4)
* converts '-11', 3 to '101' (3)
* converts '-0.1' to '11.1' (-0.5)
* converts '-1' to '1' (-1)
* converts '-10' to '10' (-2)
* converts '-11' to '101' (-3)
* converts '-100' to '100' (-4)
* converts '-1.5' to '10.1'
* converts '-2.5' to '101.1'
* converts '-2.5e89' to '101.1e89'
Parameters:
length (int): this increases the length of the returned string
to a lenght of "length" by prefilling it with leading
0s for positive numbers, and 1s for negative numbers.
length == -1 means that the string will be returned as short
as possible without prefilling. If the desired "length"
is shorter than needed to represent the number, the exception
OverflowError will be raised. The length is counted in a
non-exponential representation with the decimal point counting
as 1. So, for example, '11.01' has a length of 5. The same
value in length 8 would be '11111.01'. Or, the decimal 2 in
length 8 would be '00000010'.
Returns:
TwosComplement: binary string representation in twos-complement
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(length, int):
raise TypeError(f"Argument {length} must be of type int.")
if length <= 0 and length != -1:
raise ValueError(f"Argument {length} must be bigger than 0 or -1")
if self.isspecial:
raise ArithmeticError(
f"ArithmeticError: argument {self} is NaN or infinity."
)
return TwosComplement(self.fraction, length=length)
@staticmethod
def from_twoscomplement(value: TwosComplement, simplify: bool = True) -> str:
"""The opposite of `to_twoscomplement()` function.
This is a utility function that converts from twos-complement format
to binary fraction format.
The user, programmer should use the constructor instead, e.g.
`Binary(TwosComplement(-123))`, to directly convert an instance of
class `TwosComplement` into an instance of class `Binary`.
See `TwosComplement` class for more details on twos-complement format.
Examples:
* converts '1101' to '-11' (-3)
* converts '1101.1e-2' to '-11.1e-2' (-3.5/4)
Parameters:
value (TwosComplement): string in twos-complement format
simplify (bool): If simplify is False, it leaves fractional binary strings
as much unchanged as possible.
If simplify is True it simplifies returned fractional
binary string representation.
Returns:
str: string in binary fraction format
"""
if not isinstance(value, TwosComplement):
raise TypeError(f"Argument {value} must be of type TwosComplement.")
if _NAN.lower() in value.lower() or _INF.lower() in value.lower():
raise ArithmeticError(
f"ArithmeticError: argument {value} is NaN or infinity."
)
if not TwosComplement.istwoscomplement(value):
raise ValueError(f"Argument {value} not a valid twos-complement literal.")
result = str(value)
if value[0] == "0":
# positive twoscomplement is like binary fraction but with leading 0
if simplify:
# result = value[1:] if value != "0" else value
result = Binary.simplify(result)
return result
return Binary(value, simplify=simplify).string
def __float__(self: Binary) -> Union[float, int]:
"""Convert from Binary to float.
This is a method that convert Binary to float (or if possible to
integer).
Returns:
float or integer: number as float or integer
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isinfinity():
result = float("Inf")
elif self.isnan():
result = float("NaN")
else:
result = float(self.fraction)
# alternative implementation of float
# result = Binary.to_float(self.string)
return result # float or integer
def __int__(self: Binary) -> int:
"""Convert from Binary to int.
This method converts a Binary to an integer.
Returns:
int: number as integer
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isinfinity():
raise ValueError(
f"Argument {self} is infinity. Infinity cannot be converted to integer."
)
else:
result = int(self.fraction)
return result # int
def __str__(self: Binary) -> str:
"""Returns string of the binary fraction.
Method that implements the string conversion `str()`.
Return format includes the prefix of '0b'.
As alternative one can use attribute method `obj.string` which returns
the same property, but without prefix '0b'.
Examples:
* 0b1
* 0b0
* 0b101.101e23
* -0b101.101e-23
Parameters:
None
Returns:
str: string representation with prefix '0b'
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isnan():
return _NAN
if self.ispositiveinfinity():
return _INF
if self.isnegativeinfinity():
return _NINF
if self.sign:
return "-" + _PREFIX + self.string[1:]
else:
return _PREFIX + self.string
def compare_representation(self: Binary, other: Union[str, Binary]) -> bool:
"""Compare representation of self to representation of other string.
Does *NOT* compare values! '1.1' does *NOT* equal to '11e-1' in
`compare_representation()` even though the values are equal.
Only string '11e-1' equals '11e-1' !
Returns integer.
Parameters:
other (str, Binary): object to compare to
Returns:
bool: returns True if both strings match, False otherwise
"""
if not isinstance(self, Binary) or not (
isinstance(other, Binary) or isinstance(other, str)
):
raise TypeError(f"Argument {self} must be of type Binary.")
# compare representation to another Binary
if isinstance(other, Binary):
return str(self.string) == str(other.string)
if isinstance(other, str):
return str(self.string) == other
else:
return str(self.string) == str(other)
def __repr__(self: Binary) -> str:
"""Represents self. Shows details of the given object.
Parameters:
None
Returns:
str: returns details of the object
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return (
f"{self.__class__.__name__}"
+ f"({self.string}, {self.sign}, {self.isspecial})"
)
def no_prefix(self_value: Union[str, Binary]) -> str:
"""Remove prefix '0b' from string representation.
A method as well as a utility function.
Return format is without prefix '0b'.
Examples:
* 0
* 1
* 10.1e45
* -101.101e-23.
Parameters:
value (str, Binary): string from where to remove prefix
Returns:
str: string without prefix '0b'
"""
if not isinstance(self_value, str) and not isinstance(self_value, Binary):
raise TypeError(f"Argument {self_value} must be of type str or Binary.")
if isinstance(self_value, str):
return self_value.replace(_PREFIX, "")
else:
return str(self_value.string)
def np(self_value: Union[str, Binary]) -> str: # no prefix
"""Remove prefix '0b' from string representation.
Same as `no_prefix()`.
Parameters:
value (str, Binary): string from where to remove prefix
Returns:
str: string without prefix '0b'
"""
return Binary.no_prefix(self_value)
@staticmethod
def version() -> str:
"""Gives version number.
This is a utility function giving version of this program.
Examples:
* "20210622-103815"
Returns:
str: version number as date in format "YYMMDD-HHMMSS".
"""
return _BINARY_VERSION
@staticmethod
def simplify(value: str, add_prefix: bool = False) -> str:
"""Simplifies string representation.
This is a utility function.
Do *NOT* use it on Twos-complement strings!
Examples:
* converts '11.0' to '11'
* converts '0011.0e-0' to '11'
Parameters:
value (str): binary string representation of number
add_prefix (bool): if True add '0b' prefix to returned output;
if False then do not add prefix to returned output.
Returns:
str: simplified binary string representation of number
"""
if not isinstance(value, str):
raise TypeError(f"Argument {value} must be of type str.")
if not isinstance(add_prefix, bool):
raise TypeError(f"Argument {value} must be of type bool.")
if _NAN.lower() in value.lower() or _INF.lower() in value.lower():
return value
value = value.replace(_PREFIX, "") # just in case: remove 0b prefix
sign, intpart, fracpart, exp = Binary.get_components(value)
fracpart = fracpart.rstrip("0")
intpart = intpart.lstrip("0")
pre = _PREFIX if add_prefix else ""
if intpart == "" and fracpart == "":
# it does not matter what sign is
# it does not matter what exp is, for any exp, result is 0
return pre + "0"
signstr = "-" if sign else ""
intpart = "0" if intpart == "" else intpart
if exp == 0:
if fracpart == "":
return signstr + pre + intpart
else:
return signstr + pre + intpart + "." + fracpart
else:
if fracpart == "":
return signstr + pre + intpart + _EXP + str(exp)
else:
return signstr + pre + intpart + "." + fracpart + _EXP + str(exp)
def __round__(self: Binary, ndigits: int = 0) -> Binary:
"""Normalize and round number to `ndigits` digits after decimal point.
This is a method. It implements the function `round()`.
Same as method `round()`.
See utility function `round_to()` for details and examples.
Parameters:
ndigits (int): number of digits after decimal point, precision
Returns:
Binary: binary string representation of number
Other classes like Fractions have the simplicity of returning class int.
The return class here must be Binary and it cannot be int because round()
needs to be able to support ndigits (precision).
"""
return self.round(ndigits)
def round(self: Binary, ndigits: int = 0, simplify: bool = True) -> Binary:
"""Normalize and round number to `ndigits` digits after decimal point.
This is a method. Same as function `__round__()`.
See utility function `round_to()` for details and examples.
Parameters:
ndigits (int): number of digits after decimal point, precision
simplify (bool): If simplify is False, it leaves fractional binary strings
as much unchanged as possible.
If simplify is True it simplifies returned fractional
binary string representation.
Returns:
Binary: binary string representation of number
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(ndigits, int):
raise TypeError(f"Argument {self} must be of type int.")
value = self.string
result = Binary.round_to(value, ndigits, simplify)
return Binary(result, simplify)
@staticmethod
def round_to(value: str, ndigits: int = 0, simplify: bool = True) -> str:
"""Normalize and round number to `ndigits` digits after decimal point.
This is a utility function.
First it normalizes the number, i.e. it changes the representation intro
a representation without exponent. Then it rounds to the right of the
decimal point. The optional simplification is done as the last step.
Examples:
* converts '11.01e-2' to '0.11' with ndigits==2.
* converts '0.1' to '0' with ndigits==0.
* converts '0.10000001' to '1' with ndigits==0.
Parameters:
value (str): binary string representation of number
ndigits (int): number of digits after decimal point, precision
simplify (bool): If simplify is False, it leaves fractional binary strings
as much unchanged as possible.
If simplify is True it simplifies returned fractional
binary string representation.
Returns:
str: binary string representation of number
"""
if not isinstance(value, str):
raise TypeError(f"Argument {value} must be of type str.")
if not isinstance(ndigits, int):
raise TypeError(f"Argument {ndigits} must be of type int.")
if ndigits < 0:
raise ValueError(
f"Argument 'ndigits' ({ndigits}) must be a positive integer."
)
if _NAN.lower() in value.lower():
raise ValueError(
f"Argument 'value' ({value}): cannot convert NaN to integer."
)
if _INF.lower() in value.lower():
raise OverflowError(
f"Argument 'value' ({value}): cannot convert infinities to integer."
)
if _EXP in value:
value = Binary.to_no_exponent(value, simplify=simplify) # type: ignore
value = value.replace(_PREFIX, "")
li = value.split(".")
intpart = li[0]
if len(li) == 1:
fracpart = ""
else:
fracpart = li[1]
if len(fracpart) <= ndigits:
if simplify:
value = Binary.simplify(value)
return value
nplusonedigit = fracpart[ndigits]
nplusonedigits = fracpart[ndigits:]
if (len(nplusonedigits.rstrip("0")) <= 1) or (nplusonedigit == "0"):
# '' or '1'
result = intpart + "." + fracpart[0:ndigits]
# round down from 0.10xxx1 to 0.11000 ==> 0.1
else:
# round up from 0.1xxxx1 to 0.111111 ==> 1.0
digits = intpart + fracpart[0:ndigits]
if digits[0] == "-":
signstr = "-"
digits = digits[1:] # remove - sign
else:
signstr = ""
digits = bin(int(digits, 2) + 1)[2:] # rounded up
# print(f'digits is {digits}')
le = len(digits)
result = signstr + digits[: le - ndigits] + "." + digits[le - ndigits :]
if simplify:
result = Binary.simplify(result)
return result
def lfill(self: Binary, ndigits: int = 0, strict: bool = False):
"""Normalize and left-fill number to `ndigits` digits after decimal point.
This is a method. See also function `lfill_to()` for more details.
See also function `rfill()` to perform a right-fill.
Parameters:
ndigits (int): desired number of leading integer digits
strict (bool): If True, truncate result by cutting off leading integer digits
if input is
too long to fit into `ndigits` before the decimal point. This would
change the value significantly as the largest-value bits are removed.
If True, result will have strictly
(i.e. exactly) `ndigits` digits before the (possible) decimal point.
If False, never truncate. If False, result can have more than
`ndigits` integer
digits before the decimal point. In this case the value will not change.
Returns:
Binary: binary string representation of number
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(ndigits, int):
raise TypeError(f"Argument {self} must be of type int.")
if not isinstance(strict, bool):
raise TypeError(f"Argument {self} must be of type bool.")
value = self.string
return Binary(Binary.lfill_to(value, ndigits, strict), simplify=False)
@staticmethod
def lfill_to(value: str, ndigits: int = 0, strict: bool = False) -> str:
"""Normalize and left-fill number to n digits after decimal point.
This is a utility function.
See also function `rfill_to()` to perform a right-fill.
Normalizes the input, i.e. it converts it into a representation
without an exponent. Then it appends leading '0's to the left,
to assure at least `ndigits` digits before the
decimal point.
This function is a bit similar to the `str.zfill()` method.
If strict is True and if value does not fit into `ndigit`
integer digits before the decimal point,
then the integer part is shortened to strictly (exactly) `ndigits` digits.
In this case the value changes as the leading digits are cut off.
If strict is False, the function never shortens, never truncates the result.
In this case, the return value could have more than `ndigits`
digits before the decimal point.
Parameters:
ndigits (int): desired number of leading integer digits
strict (bool): If True, truncate result by cutting off leading integer digits
if input is
too long to fit into `ndigits` before the decimal point. This would
change the value significantly as the largest-value bits are removed.
If True, result will have strictly
(i.e. exactly) `ndigits` digits before the (possible) decimal point.
If False, never truncate. If False, result can have more than
`ndigits` integer
digits before the decimal point. In this case the value will not change.
Returns:
str: binary string representation of number
"""
if not isinstance(value, str):
raise TypeError(f"Argument {value} must be of type str.")
if _NAN.lower() in value.lower():
raise ValueError(f"Argument 'value' ({value}): cannot fill NaN.")
if _INF.lower() in value.lower():
raise OverflowError(f"Argument 'value' ({value}): cannot fill infinities.")
if ndigits < 0:
raise ValueError(
f"Argument 'ndigits' ({ndigits}) must be a positive integer."
)
if _EXP in value:
value = Binary.to_no_exponent(value, simplify=False) # type: ignore
sign, intpart, fracpart, exp = Binary.get_components(value, simplify=False)
if ndigits > len(intpart):
result = (ndigits - len(intpart)) * "0" + intpart
else:
if strict:
result = intpart[len(intpart) - ndigits :]
else:
result = intpart
if len(result) == 0:
result = "0"
if len(fracpart) > 0:
result += "." + fracpart
result = "-" + result if sign and result != "0" else result
return result
def rfill(self: Binary, ndigits: int = 0, strict: bool = False):
"""Normalize and right-fill number to `ndigits` digits after decimal point.
This is a method. See also function `rfill_to()` for more details.
See also function `lfill()` to perform a left-fill.
Parameters:
ndigits (int): desired number of digits after decimal point, precision
strict (bool): If True, truncate result by rounding if input is
too long to fit into ndigits after decimal point. This would
remove precision. If True, result will have strictly
(i.e. exactly) `ndigits` digits after decimal point.
If False, never truncate. If False, result can have more than
`ndigits`
digits after decimal point.
Returns:
Binary: binary string representation of number
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(ndigits, int):
raise TypeError(f"Argument {self} must be of type int.")
if not isinstance(strict, bool):
raise TypeError(f"Argument {self} must be of type bool.")
value = self.string
return Binary(Binary.rfill_to(value, ndigits, strict), simplify=False)
@staticmethod
def rfill_to(value: str, ndigits: int = 0, strict: bool = False) -> str:
"""Normalize and right-fill number to n digits after decimal point.
This is a utility function.
See also function `lfill_to()` to perform a left-fill.
Normalizes the input, i.e. it converts it into a representation
without an exponent. Then it appends '0's to the right, after the
decimal point, to assure at least `ndigits` digits after the
decimal point.
If strict is True and if value does not fit into ndigit digits
after the decimal point,
then shorten fractional part to strictly (exactly) ndigits.
In this case precision is lost.
If strict is False, never shorten, never truncate the result.
In this case, the return value could have more than `ndigits`
digits after the decimal point.
Parameters:
ndigits (int): desired number of digits after decimal point, precision
strict (bool): If True, truncate result by rounding if input is
too long to fit into ndigits after decimal point. This would
remove precision. If True, result will have strictly
(i.e. exactly) `ndigits` digits after decimal point.
If False, never truncate. If False, result can have more than
`ndigits`
digits after decimal point.
Returns:
str: binary string representation of number
"""
if not isinstance(value, str):
raise TypeError(f"Argument {value} must be of type str.")
if _NAN.lower() in value.lower():
raise ValueError(f"Argument 'value' ({value}): cannot fill NaN.")
if _INF.lower() in value.lower():
raise OverflowError(f"Argument 'value' ({value}): cannot fill infinities.")
if ndigits < 0:
raise ValueError(
f"Argument 'ndigits' ({ndigits}) must be a positive integer."
)
if _EXP in value:
value = Binary.to_no_exponent(value, simplify=False) # type: ignore
li = value.split(".")
if len(li) == 1:
fracpart = ""
else:
fracpart = li[1]
if len(fracpart) == ndigits:
return value
elif len(fracpart) < ndigits:
if fracpart == "":
value += "."
return value + "0" * (ndigits - len(fracpart))
elif not strict: # len(fracpart) > ndigits:
return value
else: # strict
result = Binary.round_to(value, ndigits)
# rounding can shorten it drastically, 0.1111 => 1
return Binary.rfill_to(result, ndigits, strict)
@staticmethod
def get_components(value: str, simplify: bool = True) -> tuple[int, str, str, int]:
"""Returns sign, integer part (without sign), fractional part, and
exponent.
A `sign` of integer 1 represents a negative (-) value. A `sign` of integer 0
represents a positive (+) value.
Examples:
* converts 11 ==> (0, '11', '', 0)
* converts 11.01e3 ==> (0, '11', '01', 3)
* converts -11.01e2 ==> (1, '11', '01', 2)
Parameters:
value (str): respresentation of a binary
simplify (bool): If simplify is False, it leaves fractional binary strings
as much unchanged as possible.
If simplify is True it simplifies returned fractional
binary string representation.
Returns:
tuple: tuple of 4 elements: sign (int), integer part (without sign) (str),
fractional part (str), exponent (int)
"""
if not isinstance(value, str):
raise TypeError(f"Argument {value} must be of type str.")
if _NAN.lower() in value.lower() or _INF.lower() in value.lower():
raise ValueError(f"Argument {value} must not be Inf, -Inf or NaN.")
value = value.replace(_PREFIX, "") # just in case: remove 0b prefix
sign = 1 if value[0] == "-" else 0
if sign:
value = value[1:] # remove sign from intpart
if _EXP not in value:
exp = 0
intfracpart = value
else:
li = value.split(_EXP)
intfracpart = li[0]
exp = int(li[1])
li = intfracpart.split(".")
intpart = li[0]
if len(li) == 1:
fracpart = ""
else:
fracpart = li[1]
if simplify:
# simplify intpart uand fracpart
fracpart = fracpart.rstrip("0")
intpart = intpart.lstrip("+")
intpart = intpart.lstrip("0")
intpart = "0" if intpart == "" else intpart
sign = 0 if intpart == "0" and fracpart == "" else sign
return (sign, intpart, fracpart, exp)
def components(self: Binary, simplify: bool = True) -> tuple[int, str, str, int]:
"""Returns sign, integer part (without sign), fractional part, and
exponent.
A `sign` of integer 1 represents a negative (-) value. A `sign` of integer 0
represents a positive (+) value.
Examples:
* converts 11 ==> (0, '11', '', 0)
* converts 11.01e3 ==> (0, '11', '01', 3)
* converts -11.01e2 ==> (1, '11', '01', 2)
Parameters:
value (str): respresentation of a binary
simplify (bool): If simplify is False, it leaves fractional binary strings
as much unchanged as possible.
If simplify is True it simplifies returned fractional
binary string representation.
Returns:
tuple: tuple of 4 elements: sign (int), integer part (without sign) (str),
fractional part (str), exponent (int)
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return Binary.get_components(self.string, simplify=simplify)
def isinfinity(self: Binary) -> bool:
"""Determines if object is positive or negative Infinity.
Parameters:
none
Returns:
bool: is or is not any kind of infinity or negative infinity
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return _INF in self.string
def isnegativeinfinity(self: Binary) -> bool:
"""Determines if object is Negative Infinity.
Parameters:
none
Returns:
bool: is or is not negative infinity
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return _NINF in self.string
def ispositiveinfinity(self: Binary) -> bool:
"""Determines if object is Positive Infinity.
Parameters:
none
Returns:
bool: is or is not positive infinity
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return _INF in self.string and _NINF not in self.string
def isnan(self: Binary) -> bool:
"""Determines if object is not-a-number (NaN).
Parameters:
none
Returns:
bool: is or is not a NaN
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return _NAN in self.string # "NaN"
def isint(self: Binary) -> bool:
"""Determines if binary fraction is an integer.
This is a utility function.
Returns:
bool: True if int, False otherwise (i.e. has a non-zero fraction).
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isspecial:
return False
return self.fraction == int(self.fraction)
def _adjusted(self: Binary) -> int:
"""Return the adjusted exponent of self.
Parameters:
none
Returns:
int: adjusted exponent
"""
if self.isspecial:
return 0
se = Binary.to_no_mantissa(self)
sign, intpart, fracpart, exp = Binary.components(se)
if fracpart != "":
raise ValueError(
f"Invalid literal: {se.string}. Internal error. "
"Fraction part should be empty."
)
return exp + len(intpart) - 1
@property
def fraction(self: Binary) -> Fraction:
"""Extracts Fractional representation from Binary instance.
A method to get the Binary as a `Fraction`.
Since this is a Python `property`, one must call it via `obj.fraction`
instead of `obj.fraction()`, i.e. drop the parenthesis.
Furthermore, since it is a property, it *cannot* be called as a method,
i.e. `Binary.fraction(obj)` will *not* work.
Parameters:
None
Returns:
Fraction: binary number in Fraction representation
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return self._fraction # type: ignore
@property
def string(self: Binary) -> str:
"""Extracts string representation from Binary instance.
A method to get the Binary as a string.
It does not have a '0b' prefix.
Since this is a Python `property`, one must call it via `obj.string`
instead of `obj.string()`, i.e. drop the parenthesis.
Furthermore, since it is a property, it *cannot* be called as a method,
i.e. `Binary.string(obj)` will *not* work.
See also function `__str__()` which implements the `str()` conversion function
which returns the string representation, but with a '0b' prefix.
Parameters:
None
Returns:
str: binary number in string representation without prefix '0b'
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return self._string # type: ignore
@property
def sign(self: Binary) -> int:
"""Gets sign from Binary instance.
It returns int 1 for negative (-) or int 0 for positive (+) numbers.
Since this is a Python `property`, one must call it via `obj.sign`
instead of `obj.sign()`, i.e. drop the parenthesis.
Furthermore, since it is a property, it *cannot* be called as a method,
i.e. `Binary.sign(obj)` will *not* work.
Parameters:
None
Returns:
int: int 1 for negative (-) or int 0 for positive (+) numbers
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return self._sign # type: ignore
@property
def isspecial(self: Binary) -> bool:
"""Gets is_special property from Binary instance.
It returns bool True for negative infinity, positive infinity and NaN.
It returns bool False for anything else, i.e. for regular numbers.
Since this is a Python `property`, one must call it via `obj.isspecial`
instead of `obj.isspecial()`, i.e. drop the parenthesis.
Furthermore, since it is a property, it *cannot* be called as a method,
i.e. `Binary.isspecial(obj)` will *not* work.
Parameters:
None
Returns:
bool: True for special numbers like infinities and NaN,
False for regular numbers
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return self._is_special # type: ignore
@property
def warnonfloat(self: Binary) -> bool:
"""Gets warn_on_float property from Binary instance.
It returns bool True if flag warn_on_float was set to True.
It returns bool False if flag warn_on_float was set to False.
Since this is a Python `property`, one must call it via `obj.warnonfloat`
instead of `obj.warnonfloat()`, i.e. drop the parenthesis.
Furthermore, since it is a property, it *cannot* be called as a method,
i.e. `Binary.warnonfloat(obj)` will *not* work.
Parameters:
None
Returns:
bool: boolean value of warn_on_float flag
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return self._warn_on_float # type: ignore
@property
def islossless(self: Binary) -> bool:
"""Gets is_lossless property from Binary instance.
It returns bool True if Binary instance has lost no precision.
It returns bool False if Binary instance possibly has lost precision.
Since this is a Python `property`, one must call it via `obj.islossless`
instead of `obj.islossless()`, i.e. drop the parenthesis.
Furthermore, since it is a property, it *cannot* be called as a method,
i.e. `Binary.islossless(obj)` will *not* work.
Parameters:
None
Returns:
bool: boolean value indicating if there was possible loss of precision
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
return self._is_lossless # type: ignore
@staticmethod
def fraction_to_string(
number: Union[int, float, Fraction],
ndigits: int = _BINARY_PRECISION,
simplify: bool = True,
) -> str:
"""Converts number representation (int, float, or Fraction) to string.
This is a utility function.
Parameters:
number (int,float,Fraction): binary number in number representation
ndigits (int): desired digits after decimal point.
simplify (bool): If True simplify output by performing cleanup and
removing unnecessary digits.
If False, then produce exact as-is twos-complement components
without any cleanup or simplifications.
Returns:
str: binary number in string representation
"""
number = Fraction(number) if not isinstance(number, Fraction) else number
sign = "-" if number < 0 else ""
number = abs(number)
int_number = math.floor(number)
if int_number == 0:
result = [sign, "0"]
else:
result = [sign] + bin(int_number)[2:].split()
rest = Fraction(0)
i = 1
fraction_number = number - int_number
if fraction_number > 0:
result.append(".")
while i < ndigits + 1:
b = Fraction(1, 2 ** i)
if b + rest < fraction_number:
result.append("1")
rest += b
elif b + rest > fraction_number:
result.append("0")
elif b + rest == fraction_number:
result.append("1")
break
i += 1
return Binary.simplify("".join(result)) if simplify else "".join(result)
def isclose(
self: Binary, other: Any, rel_tol: float = _BINARY_RELATIVE_TOLERANCE
) -> bool:
"""Compare two objects to see if they are mathematically close.
This is a utility function. Useful for floats that have been converted
to binary fractions. A substitute for the `==` operand for binary fractions
created from floats with precision errors.
Parameters:
other (Any, int, float, Fraction, Binary): value of number
rel_tol (float): relative tolerance as epsilon-value
to decide if two numbers are close relative to each other
Returns:
bool: True if two numbers are close, False otherwise
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isspecial or other._is_special:
return False
return math.isclose(self.fraction, other._fraction, rel_tol=rel_tol)
def _cmp(self: Binary, other: Any) -> int:
"""Compare two objects.
Compare the two non-NaN decimal instances self and other.
Returns -1 if self < other, 0 if self == other and 1
if self > other. This routine is for internal use only.
Returns integer.
Note: The Decimal standard doesn't cover rich comparisons for
Decimals. In particular, the specification is silent on the
subject of what should happen for a comparison involving a NaN.
In Decimal they take the following approach:
```
== comparisons involving a quiet NaN always return False
!= comparisons involving a quiet NaN always return True
== or != comparisons involving a signaling NaN signal
InvalidOperation, and return False or True as above if the
InvalidOperation is not trapped.
<, >, <= and >= comparisons involving a (quiet or signaling)
NaN signal InvalidOperation, and return False if the
InvalidOperation is not trapped.
```
That Decimal behavior is designed to conform as closely as possible to
that specified by IEEE 754.
Here in Binary we take a similar approach and try to follow Decimal.
Parameters:
other (Any, str, Binary, int, float, Fraction): object to compare to
Returns:
int: returns -1 if s<o, 0 if equal, 1 if s>o
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isspecial or other._is_special:
if self.isnan() or other.isnan():
# Compare(NaN, NaN) => exception
# Equal(NaN, NaN) => False
# Compare(NaN, 1) => False
# Compare(NaN, Inf) => False
raise ArithmeticError("Arithmetic Error: Cannot compare two NaNs.")
if self.isnegativeinfinity() and other.ispositiveinfinity():
return -1
elif self.ispositiveinfinity() and other.isnegativeinfinity():
return 1
elif self.isnegativeinfinity() and other.isnegativeinfinity():
return 0
elif self.ispositiveinfinity() and other.ispositiveinfinity():
return 0
elif self.isnegativeinfinity():
return -1
elif self.ispositiveinfinity():
return 1
elif other.isnegativeinfinity():
return -1
else: # other.ispostiveinfinity():
return 1
if self.fraction == other._fraction:
result = 0
elif self.fraction < other._fraction:
result = -1
else:
result = 1
return result
def compare(self: Binary, other: Any) -> Binary:
"""Compares `self` to `other`. Returns a Binary value.
```
s or o is a NaN ==> Binary('NaN')
s < o ==> Binary('-1')
s == o ==> Binary('0')
s > o ==> Binary('1')
```
Parameters:
other (str, Binary): object to compare to
Returns:
Binary: returns Binary -1 if s<o, Binary 0 if equal,
Binary 1 if s>o
"""
return Binary(self._cmp(other))
def __eq__(self: Binary, other: Any) -> bool:
"""Implements equal, implements operand `==`.
Method that implements `==` operand.
See `_cmp()` for details.
Parameters:
self (Binary): binary fraction number
other (Any): number
Returns:
bool: result
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return False # see comments in _cmp()
return self._cmp(other) == 0
def __lt__(self: Binary, other: Any) -> bool:
"""Less than operation.
Method that implements `<` operand.
Parameters:
self (Binary): binary fraction number
other (Any): number
Returns:
bool: result
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return False # see comments in _cmp()
return self._cmp(other) == -1
def __gt__(self: Binary, other: Any) -> bool:
"""Greater than operation.
Method that implements `>` operand.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
bool: result
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return False # see comments in _cmp()
return self._cmp(other) == 1
def __le__(self: Binary, other: Any) -> bool:
"""Less or equal operation.
Method that implements `<=` operand.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
bool: result
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return False # see comments in _cmp()
compare = self._cmp(other)
return not compare == 1 or compare == 0
def __ge__(self: Binary, other: Any) -> bool:
"""Greater or equal operation.
Method that implements `>=` operand.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
bool: result
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return False # see comments in _cmp()
compare = self._cmp(other)
return not compare == -1 or compare == 0
def __add__(self: Binary, other: Any) -> Binary:
"""Add operation.
Method that implements the `+` operand.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
Binary: addition of the two numbers
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return Binary(_NAN)
if self.ispositiveinfinity() and other.ispositiveinfinity():
return Binary(_INF)
if self.isnegativeinfinity() and other.isnegativeinfinity():
return Binary(_NINF)
if self.isnegativeinfinity() and other.ispositiveinfinity():
return Binary(_NAN)
if self.ispositiveinfinity() and other.isnegativeinfinity():
return Binary(_NAN)
if self.ispositiveinfinity() or other.ispositiveinfinity():
return Binary(_INF)
if self.isnegativeinfinity() or other.isnegativeinfinity():
return Binary(_NINF)
return Binary(self.fraction + other._fraction)
def __sub__(self: Binary, other: Any) -> Binary:
"""Subtraction operation.
Method that implements the `-` operand.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
Binary: substraction of the two numbers
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return Binary(_NAN)
if self.ispositiveinfinity() and other.ispositiveinfinity():
return Binary(_NAN)
if self.isnegativeinfinity() and other.isnegativeinfinity():
return Binary(_NAN)
if self.isnegativeinfinity() and other.ispositiveinfinity():
return Binary(_NINF)
if self.ispositiveinfinity() and other.isnegativeinfinity():
return Binary(_INF)
if self.ispositiveinfinity():
return Binary(_INF)
if self.isnegativeinfinity():
return Binary(_NINF)
if other.isnegativeinfinity():
return Binary(_INF)
if other.ispositiveinfinity():
return Binary(_NINF)
return Binary(self.fraction - other._fraction)
def __mul__(self: Binary, other: Any) -> Binary:
"""Multiply operation.
Method that implements the `*` operand.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
Binary: multiplication, i.e. product, of the two numbers
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return Binary(_NAN)
if self.ispositiveinfinity() and other.ispositiveinfinity():
return Binary(_INF)
if self.isnegativeinfinity() and other.isnegativeinfinity():
return Binary(_INF)
if self.isnegativeinfinity() and other.ispositiveinfinity():
return Binary(_NINF)
if self.ispositiveinfinity() and other.isnegativeinfinity():
return Binary(_NINF)
if self.ispositiveinfinity():
return Binary(_INF)
if self.isnegativeinfinity():
return Binary(_NINF)
if other.isnegativeinfinity():
return Binary(_NINF)
if other.ispositiveinfinity():
return Binary(_INF)
return Binary(self.fraction * other._fraction)
def __truediv__(self: Binary, other: Any) -> Binary:
"""True division operation.
Method that implements the `/` operand.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
Binary: true division of the two numbers
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return Binary(_NAN)
if self.ispositiveinfinity() and other.ispositiveinfinity():
return Binary(_NAN)
if self.isnegativeinfinity() and other.isnegativeinfinity():
return Binary(_NAN)
if self.isnegativeinfinity() and other.ispositiveinfinity():
return Binary(_NAN)
if self.ispositiveinfinity() and other.isnegativeinfinity():
return Binary(_NAN)
if self.ispositiveinfinity():
return Binary(_INF)
if self.isnegativeinfinity():
return Binary(_NINF)
if other.isnegativeinfinity():
return Binary(0)
if other.ispositiveinfinity():
return Binary(-0)
if other.fraction == 0:
raise ZeroDivisionError(
f"ZeroDivisionError: Binary division by zero ({other})."
)
return Binary(self.fraction / other._fraction)
def __floordiv__(self: Binary, other: Any) -> Binary:
"""Floor division operation.
Method that implements the `//` operand.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
Binary: floor division of the two numbers
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return Binary(_NAN)
if self.ispositiveinfinity() and other.ispositiveinfinity():
return Binary(_NAN)
if self.isnegativeinfinity() and other.isnegativeinfinity():
return Binary(_NAN)
if self.isnegativeinfinity() and other.ispositiveinfinity():
return Binary(_NAN)
if self.ispositiveinfinity() and other.isnegativeinfinity():
return Binary(_NAN)
if self.ispositiveinfinity():
return Binary(_NAN)
if self.isnegativeinfinity():
return Binary(_NAN)
if other.isnegativeinfinity():
return Binary(0) if self.sign else Binary(-1)
if other.ispositiveinfinity():
return Binary(-1) if self.sign else Binary(0)
if other._fraction == 0:
raise ZeroDivisionError(
f"ZeroDivisionError: Binary division by zero ({other})."
)
return Binary(self.fraction // other._fraction)
def __mod__(self: Binary, other: Any) -> Binary:
"""Modulo operation.
Method that implements modulo, i.e. returns the integer remainder.
Method that implements the `%` operand.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
Binary: modulo of the two numbers
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return Binary(_NAN)
if self.ispositiveinfinity() and other.ispositiveinfinity():
return Binary(_NAN)
if self.isnegativeinfinity() and other.isnegativeinfinity():
return Binary(_NAN)
if self.isnegativeinfinity() and other.ispositiveinfinity():
return Binary(_NAN)
if self.ispositiveinfinity() and other.isnegativeinfinity():
return Binary(_NAN)
if self.ispositiveinfinity():
return Binary(_NAN)
if self.isnegativeinfinity():
return Binary(_NAN)
if other.isnegativeinfinity():
return self if self.sign else Binary(_NINF)
if other.ispositiveinfinity():
return Binary(_INF) if self.sign else self
if other._fraction == 0:
raise ZeroDivisionError(f"ZeroDivisionError: Binary modulo ({other}).")
return Binary(self.fraction % other._fraction)
def __pow__(self: Binary, other: Any) -> Binary:
"""Power of operation.
Method that implements the `**` operand.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
Binary: power of the two numbers
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isnan() or other.isnan():
return Binary(_NAN)
if self.ispositiveinfinity() and other.ispositiveinfinity():
return Binary(_INF)
if self.isnegativeinfinity() and other.isnegativeinfinity():
return Binary(0)
if self.isnegativeinfinity() and other.ispositiveinfinity():
return Binary(_INF)
if self.ispositiveinfinity() and other.isnegativeinfinity():
return Binary(0)
if self.ispositiveinfinity():
return Binary(0) if other._sign else Binary(_INF)
if self.isnegativeinfinity():
return Binary(-0) if other._sign else Binary(_NINF)
if other.isnegativeinfinity():
return Binary(0)
if other.ispositiveinfinity():
return Binary(_INF)
if other._fraction == 0:
return Binary(1)
po = self.fraction ** other._fraction
# (-3.4)**(-3.4) ==> (-0.00481896804140973+0.014831258607220378j)
# type((-3.4)**(-3.4)) ==> <class 'complex'>
if isinstance(po, complex):
raise ArithmeticError(
f"Argument {self} to the power of {other} is a "
"complex number which cannot be represented as a Binary."
)
return Binary(po)
def __abs__(self: Binary) -> Binary:
"""Computes absolute value.
Method that implements absolute value, i.e. the positive value.
Parameters:
self (Binary): binary number
Returns:
Binary: Absolute of the number
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isnan():
return Binary(_NAN)
if self.isinfinity():
return Binary(_INF)
return Binary(abs(self.fraction))
def __ceil__(self: Binary) -> int:
"""Performs math ceiling operation returning an int.
Method that implements `ceil`. This method is invoked by calling
`math.ceil()`. Note, that `math.ceil()` will return an int (and NOT
a Binary). See method `ceil()` for a function that returns a `Binary` instance.
Examples:
* input '1.11' will return 1.
Parameters:
self (Binary): binary number.
Returns:
int: ceiling of the number expressed as an int.
Other classes like Fractions return class int to be consistent
with math.ceil().
Following their lead, Binary does the same and returns class int
instead of class Binary. Use method Binary.ceil() to get result
in Binary.
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isnan():
raise ValueError("ValueError: cannot convert Binary NaN to integer.")
if self.isinfinity():
raise OverflowError(
"OverflowError: cannot convert Binary infinity to integer."
)
return math.ceil(self.fraction)
def ceil(self: Binary) -> Binary:
"""Perform math ceiling operation returning a Binary.
Method that implements `ceil`. This method returns a Binary.
See method '__ceil__()' for getting an `int` return.
Examples:
* input '1.11' will return '0b1' as Binary.
Parameters:
self (Binary): binary number.
Returns:
Binary: ceiling of the number as Binary.
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isnan():
raise ValueError("ValueError: cannot convert Binary NaN to integer.")
if self.isinfinity():
raise OverflowError(
"OverflowError: cannot convert Binary infinity to integer."
)
return Binary(math.ceil(self.fraction))
def __floor__(self: Binary) -> int:
"""Perform math floor operation returning an int.
Method that implements `floor`. This method is invoked by calling
`math.floor()`. Note, that `math.floor()` will return an int (and NOT
a Binary). See method `floor()` for a function that returns a `Binary` instance.
Examples:
* input '1.11' will return int 1.
Parameters:
self (Binary): binary number.
Returns:
int: floor of the number expressed as an int.
Other classes like Fractions return class int to be consistent
with math.floor().
Following their lead, Binary does the same and returns class int
instead of class Binary. Use method Binary.floor() to get result
in Binary.
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isnan():
raise ValueError("ValueError: cannot convert Binary NaN to integer.")
if self.isinfinity():
raise OverflowError(
"OverflowError: cannot convert Binary infinity to integer."
)
return math.floor(self.fraction)
def floor(self: Binary) -> Binary:
"""Perform math floor operation returning a Binary.
Method that implements `floor`. This method returns a Binary.
See method '__floor__()' for getting an int return.
Examples:
* input '1.11' will return '0b1' as Binary.
Parameters:
self (Binary): binary number.
Returns:
Binary: floor of the number as Binary.
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isnan():
raise ValueError("ValueError: cannot convert Binary NaN to integer.")
if self.isinfinity():
raise OverflowError(
"OverflowError: cannot convert Binary infinity to integer."
)
return Binary(math.floor(self.fraction))
def __rshift__(self: Binary, ndigits: int) -> Binary:
"""Shifts number `ndigits` digits (bits) to the right.
Method that implementes `>>` operand.
As example, shifting right by 1, divides the number by 2.
The string representation will be changed as little as possible.
If the string representation is in exponential form it will remain in
exponential form. If the string representation is in non-exponential form,
it will remain in non-exponential form, i.e. only the decimal point will be
moved to the left.
Parameters:
self (Binary): number to be shifted
ndigits (int): number of digits to be shifted right
Returns:
Binary: right shifted number
"""
if not isinstance(self, Binary) or not isinstance(ndigits, int):
raise TypeError(
f"Arguments {self} {ndigits} must be of type Binary and int."
)
if ndigits < 0:
raise ValueError(f"ValueError: negative shift count ({ndigits})")
if self.isnan():
return Binary(_NAN)
if self.isnegativeinfinity():
return Binary(_NINF)
if self.ispositiveinfinity():
return Binary(_INF)
if ndigits == 0:
return self
if _EXP in self.string:
sign, intpart, fracpart, exp = Binary.get_components(self.string)
shifted = (
sign * "-"
+ intpart
+ "."
+ (fracpart if len(fracpart) > 0 else "0")
+ _EXP
+ str(exp - ndigits)
)
else:
sign, intpart, fracpart, exp = Binary.get_components(self.string)
if ndigits >= len(intpart):
intpart = (ndigits - len(intpart) + 1) * "0" + intpart
shifted_intpart = sign * "-" + intpart[: len(intpart) - ndigits] + "."
shifted_fracpart = intpart[len(intpart) - ndigits :] + fracpart
shifted = Binary.simplify(shifted_intpart + shifted_fracpart)
return Binary(shifted)
def __lshift__(self: Binary, ndigits: int) -> Binary:
"""Shifts number `ndigits` digits (bits) to the left.
Method that implementes `<<` operand.
As example, shifting left by 1, multiplies the number by 2.
The string representation will be changed as little as possible.
If the string representation is in exponential form it will remain in
exponential form. If the string representation is in non-exponential form,
it will remain in non-exponential form, i.e. only the decimal point will be
moved to the right.
Parameters:
self (Binary): number to be shifted
ndigits (int): number of digits to be shifted left
Returns:
Binary: left shifted number
"""
if not isinstance(self, Binary) or not isinstance(ndigits, int):
raise TypeError(
f"Arguments {self} {ndigits} must be of type Binary and int."
)
if ndigits < 0:
raise ValueError(f"ValueError: negative shift count ({ndigits})")
if self.isnan():
return Binary(_NAN)
if self.isnegativeinfinity():
return Binary(_NINF)
if self.ispositiveinfinity():
return Binary(_INF)
if ndigits == 0:
return self
if _EXP in self.string:
sign, intpart, fracpart, exp = Binary.get_components(self.string)
shifted = (
sign * "-"
+ intpart
+ "."
+ (fracpart if len(fracpart) > 0 else "0")
+ _EXP
+ str(exp + ndigits)
)
else:
sign, intpart, fracpart, exp = Binary.get_components(self.string)
if ndigits >= len(fracpart):
fracpart += (ndigits - len(fracpart) + 1) * "0"
shifted_intpart = (
sign * "-" + (intpart + fracpart[:ndigits]).lstrip("0") + "."
)
shifted_intpart = "0." if len(shifted_intpart) <= 1 else shifted_intpart
shifted_fracpart = fracpart[ndigits:]
shifted = Binary.simplify(shifted_intpart + shifted_fracpart)
return Binary(shifted)
def __bool__(self: Binary) -> bool:
"""Boolean transformation. Used for `bool()` and `not` operand.
Method that implements transformation to boolean `bool`. This
boolean transformation is then used by operations like `not`.
Number 0 returns `False`. All other numbers return `True`.
Parameters:
self (Binary): binary number
Returns:
bool: boolean transformation of the number
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if self.isnan() or self.isinfinity():
return True
return bool(self.fraction)
def __not__(self: Binary) -> bool:
"""Return the 'boolean not' of self.
Method that implements the `not` operand.
Do not confuse it with the 'bitwise not' operand `~`.
If self is 0, then method returns True.
For all other values it returns False.
Examples:
* operation not Binary(0) returns True.
* operation not Binary(3.5) returns False.
Parameters:
self (Binary): number
Returns:
Binary: 'boolean not' of number
"""
return not self.fraction
def __and__(self: Binary, other: Any) -> Binary:
"""Return the bitwise 'and' of self and other.
Method that implements the `&` operand.
Any negative number will be converted into twos-complement
representation, than bitwise-and will be done, then the resulting
number will be converted back from twos-complement to
binary string format.
Examples:
* operation '11.1' & '10.1' will return '10.1'
* operation '-0.1' & '+1' will return '-1'
because twos-complement of '-0.1' is 1.1.
Further, 1.1 & 01.0 results in twos-complement 1.0,
and 1.0 in twos-complement is '-1' in binary fraction. Leading to the
final result '-1' (or '-0b1').
Parameters:
self (Binary): binary number
other (Any): number
Returns:
Binary: bitwise 'and' of the two numbers in binary fraction format
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isspecial or other._is_special:
raise ArithmeticError(
f"ArithmeticError: one of the arguments {self}, {other} "
"is NaN or infinity."
)
return Binary._and_or_xor(self, other, "and")
def __or__(self: Binary, other: Any) -> Binary:
"""Return the bitwise 'or' of self and other.
Method that implements the `|` operand.
Any negative number will be converted into twos-complement
representation, than bitwise-or will be done, then the resulting
number will be converted back from twos-complement to
binary string format.
Examples:
* operation '11.1' | '10.1' will return '11.1'
* operation '-0.1' | '+1' will return '-0.1'
because twos-complement of
'-0.1' is 1.1; and 1.1 | 01.0 results in twos-complement 1.1;
and 1.1 in twos-complement is '-0.1' in binary fraction. Hence, the
final result of '-0.1'.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
Binary: bitwise 'or' of the two numbers in binary fraction format
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isspecial or other._is_special:
raise ArithmeticError(
f"ArithmeticError: one of the arguments {self}, {other} "
"is NaN or infinity."
)
return Binary._and_or_xor(self, other, "or")
def __xor__(self: Binary, other: Any) -> Binary:
"""Return the bitwise 'xor' of self and other.
Method that implements the `^` operand.
Any negative number will be converted into twos-complement
representation, than bitwise-xor will be done, then the resulting
number will be converted back from twos-complement to
binary string format.
Examples:
* operation '11.1' ^ '10.1' will return '1'.
* operation '-0.1' ^ '+1' will return '-1.1' because twos-complement of
'-0.1' is 1.1; and 1.1 ^ 01.0 results in twos-complement 10.1;
and 10.1 in twos-complement is '-1.1' in binary fraction. Hence, the final
result of '-1.1'.
Parameters:
self (Binary): binary number
other (Any): number
Returns:
Binary: bitwise 'xor' (bitwise exclusive or) of the
two numbers in binary fraction format
"""
if not isinstance(self, Binary):
raise TypeError(f"Argument {self} must be of type Binary.")
if not isinstance(other, Binary):
other = Binary(other)
if self.isspecial or other._is_special:
raise ArithmeticError(
f"ArithmeticError: one of the arguments {self}, {other} "
"is NaN or infinity."
)
return Binary._and_or_xor(self, other, "xor")
def _and_or_xor(this: Binary, other: Binary, which: str) -> Binary:
"""Performs bitwise 'and', 'or', or 'xor' on two binary fractions.
This is a function, not a method.
Parameters:
this (Binary): number, binary fraction
other (Binary): number, binary fraction
which (str): 'and' or 'or' or 'xor'
Returns:
Binary: 'and'ed, 'or'ed or 'xor'ed binary fraction
"""
if not isinstance(this, Binary) or not isinstance(other, Binary):
raise TypeError(
f"Arguments {this}, {other} must be of type Binary and Binary."
)
if not isinstance(which, str):
raise TypeError(f"Arguments {which} must be of type str.")
if this.isspecial or other.isspecial:
raise ArithmeticError(
f"ArithmeticError: one of the arguments {this}, {other} "
"is NaN or infinity."
)
which = which.lower()
if which != "and" and which != "or" and which != "xor":
raise ValueError(
f"ValueError: which ({which}) should be 'and', 'or', or 'xor'."
)
def __and(ab):
a, b = ab
return "1" if a == "1" and b == "1" else "." if a == "." else "0"
def __or(ab):
a, b = ab
return "1" if a == "1" or b == "1" else "." if a == "." else "0"
def __xor(ab):
a, b = ab
return "1" if a != b else "." if a == "." else "0"
sign1, _, _, _ = this.components()
sign2, _, _, _ = other.components()
thisstr = this.string
otherstr = other.string
if sign1:
thisstr = str(TwosComplement(this.fraction))
if sign2:
otherstr = str(TwosComplement(other.fraction))
_, intpart1, fracpart1, _ = Binary.get_components(thisstr)
_, intpart2, fracpart2, _ = Binary.get_components(otherstr)
v1, v2 = intpart1, intpart2
l1, l2 = len(v1), len(v2)
if sign1 and not sign2:
if l1 <= l2:
v1 = (l2 - l1 + 1) * "1" + v1
if not sign1 and sign2:
if l2 <= l1:
v2 = (l1 - l2 + 1) * "1" + v2
l1, l2 = len(v1), len(v2)
if l1 > l2:
v2 = (l1 - l2) * str(sign2) + v2
else:
v1 = (l2 - l1) * str(sign1) + v1
value1 = v1
value2 = v2
v1, v2 = fracpart1, fracpart2
l1, l2 = len(v1), len(v2)
if l1 > l2:
v2 = v2 + (l1 - l2) * "0"
else:
v1 = v1 + (l2 - l1) * "0"
value1 += "." + v1
value2 += "." + v2
value1 = value1.rstrip(".")
value2 = value2.rstrip(".")
func = (
__and
if which == "and"
else __or
if which == "or"
else __xor
if which == "xor"
else __and
)
def negative(number):
return Binary(TwosComplement(number))._string
result = "-"
if number[0] == "1":
result += "1" + number.lstrip("1")
else:
result += number
return result
result = "".join(map(func, zip(value1, value2)))
if which == "and":
if sign1 and sign2:
result = negative(result)
elif which == "or":
if sign1 or sign2:
result = negative(result)
elif which == "xor":
if sign1 != sign2:
result = negative(result)
return Binary(Binary.simplify(result))
def __invert__(self: Binary) -> Binary:
"""Returns the 'bitwise not' of self.
Method that implements the 'bitwise not' operand `~`.
This is also called the 'invert' operand, or the 'bitwise not' operand.
Do not confuse it with the 'boolean not' operand implemented
via the `not` operand and the `__not__()` method.
It is only defined for integers. If self is not an integer it
will raise an exception. For integers, `~` is defined as
`~n = -(n+1)`.
To perform `~` on a non-integer Binary instance, convert it to
two's complement string of class `TwosComplement`, adjust that string
to the desired representation with the desired mantissa and exponent,
and then perform `TwosComplement.invert()` on that string.
In short, for non-integer binary fractions, do this:
`TwosComplement.invert(Binary.to_twoscomplement(value))`.
Forcing the user to do this, will lead to more awareness of how to represent
the number before inverting it. If arbitrary Binary or float values were
allowed to be inverted directly it would lead to unexpected results.
To avoid confusion this additional 'manual' step was introduced.
For more information, see also the `TwosComplement.invert()` function.
Examples:
* operation ~9 will return -10.
* operation ~-10 will return 9.
Parameters:
self (Binary): number
Returns:
Binary: 'bitwise not' (`~`) of integer number
"""
if not isinstance(self, Binary):
raise TypeError(f"Arguments {self} must be of type Binary.")
if self.isspecial:
raise ArithmeticError(
f"ArithmeticError: argument {self} is NaN or infinity."
)
# for integers it is defined as -(x+1). So ~9 is -10.
if Binary.isint(self):
# for integers ~ is defined as: ~n = - (n+1) formula
return Binary(-(self.fraction + 1))
else:
# For floating point numbers ~ is not defined. What would ~0.5 be?
# It could be implemented but only if the number of fractional bits is
# known and managed.
# ~ of floats would be very difficult to understand and get right as a
# user. To avoid user error and to avoid introducing ndigits for
# number of fractional bits it is better to force the user to convert
# to a twos-complement string and invert (~) this twos-complement formatted
# string. This avoids the computation of a number representation (float) of
# an inverted (~) float.
raise ValueError(
f"Invalid literal for Binary: {self.string}. "
"~ operand only allowed on integers and integer fractions. "
"To perform ~ on Binary, convert it to two's complement string"
"and then perform invert() on that string. In short, do this: "
"TwosComplement.invert(Binary.to_twoscomplement(value))."
)
##########################################################################
# CLASS TESTTWOSCOMPLEMENT
##########################################################################
class TestTwosComplement(unittest.TestCase):
"""Unit testing of class TwosComplement."""
def selftest(self) -> bool:
"""Perform self test by running various test cases.
`TwosComplement` uses module `unittest` for unit testing.
See https://docs.python.org/3/library/unittest.html for details.
Parameters:
none
Returns:
bool: True if all tests pass, False if any single test fails
"""
# default would be: unittest.main()
# This would run all testcase, print resultsm and terminates program.
# But this would not allow further inspection or tuning.
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestTwosComplement)
test_result = unittest.TextTestRunner().run(suite)
err = len(test_result.errors)
fail = len(test_result.failures)
skip = len(test_result.skipped)
run = test_result.testsRun
ttl = suite.countTestCases()
success = test_result.wasSuccessful()
print("")
print("Test results for class TwosComplement are: ")
print(f" Total number of individual tests = {_BINARY_TOTAL_TESTS}")
print(f" Total number of unit tests = {ttl}")
print(f" Unit tests executed = {run}")
print(f" Unit tests skipped = {skip}")
print(f" Unit tests failed = {fail}")
print(f" Unit tests with error = {err}")
if success:
result = f"Self-Test: 😃 All {run} out of {ttl} unit tests passed ✅"
ret = True
else:
plural = "" if run - err - fail == 1 else "s"
result = f"Self-Test: {run-err-fail} unit test{plural} passed ✅\n"
plural = "" if err + fail == 1 else "s"
result += f"Self-Test: {err+fail} unit test{plural} failed ❌"
ret = False
print(f"{result}")
return ret
def test___new__(self):
"""Testing the constructor."""
self.assertIsInstance(TwosComplement(1), TwosComplement)
self.assertIsInstance(TwosComplement(1.6), TwosComplement)
self.assertIsInstance(TwosComplement("1.1"), TwosComplement)
self.assertIsInstance(TwosComplement("1.1e+2"), TwosComplement)
self.assertTrue("TwosComplement" in str(type(TwosComplement(5))))
self.assertEqual(TwosComplement(1) + TwosComplement(1), "0101")
self.assertEqual(len(TwosComplement("1.1")), 3)
self.assertEqual(str(TwosComplement(+3.5)), "011.1")
self.assertEqual(TwosComplement(1975), "011110110111")
self.assertEqual(TwosComplement(1975, 13), "0011110110111")
self.assertEqual(TwosComplement(-1975), "100001001001")
self.assertEqual(TwosComplement(-1975, 20), "11111111100001001001")
self.assertEqual(TwosComplement(+0.375), "0.011")
self.assertEqual(TwosComplement(-0.375), "1.101")
with self.assertRaises(ValueError):
TwosComplement("102") # should fail
with self.assertRaises(TypeError):
TwosComplement(complex(1, 1)) # should fail
with self.assertRaises(OverflowError):
TwosComplement(1975, 11)
with self.assertRaises(OverflowError):
TwosComplement(-1975, 11)
with self.assertRaises(ArithmeticError):
TwosComplement(float("inf"))
with self.assertRaises(ArithmeticError):
TwosComplement(float("nan"))
with self.assertRaises(ValueError):
TwosComplement("nan")
def test__int2twoscomp(self):
"""Test function/method."""
self.assertIsInstance(TwosComplement._int2twoscomp(1), str)
self.assertEqual(TwosComplement._int2twoscomp(8), "01000")
self.assertEqual(TwosComplement._int2twoscomp(-2), "10")
self.assertEqual(TwosComplement._int2twoscomp(-0), "0")
self.assertEqual(TwosComplement._int2twoscomp(-1), "1")
self.assertEqual(TwosComplement._int2twoscomp(+1), "01")
def test__frac2twoscomp(self):
"""Test function/method."""
self.assertIsInstance(TwosComplement._frac2twoscomp(1), str)
self.assertEqual(TwosComplement._frac2twoscomp(0.5), "0.1")
self.assertEqual(TwosComplement._frac2twoscomp(-0.5), "1.1")
self.assertEqual(TwosComplement._frac2twoscomp(1.5), "0.1")
self.assertEqual(TwosComplement._frac2twoscomp(-1.5), "1.1")
def test__float2twoscomp(self):
"""Test function/method."""
self.assertIsInstance(TwosComplement._float2twoscomp(1.0), str)
self.assertEqual(TwosComplement._float2twoscomp(0.5), "0.1")
self.assertEqual(TwosComplement._float2twoscomp(-0.5), "1.1")
self.assertEqual(TwosComplement._float2twoscomp(1.5), "01.1")
self.assertEqual(TwosComplement._float2twoscomp(-1.5), "10.1")
def test__fraction2twoscomp(self):
"""Test function/method."""
self.assertIsInstance(TwosComplement._fraction2twoscomp(Fraction(1, 1)), str)
self.assertEqual(TwosComplement._fraction2twoscomp(Fraction(1, 2)), "0.1")
self.assertEqual(TwosComplement._fraction2twoscomp(Fraction(-1, 2)), "1.1")
self.assertEqual(TwosComplement._fraction2twoscomp(Fraction(3, 2)), "01.1")
self.assertEqual(TwosComplement._fraction2twoscomp(Fraction(-3, 2)), "10.1")
def test__str2twoscomp(self):
"""Test function/method."""
self.assertIsInstance(TwosComplement._str2twoscomp("1.0"), str)
self.assertEqual(TwosComplement._str2twoscomp("0.1"), "0.1")
self.assertEqual(TwosComplement._str2twoscomp("1.1"), "1.1")
self.assertEqual(TwosComplement._str2twoscomp("01.1"), "01.1")
self.assertEqual(TwosComplement._str2twoscomp("10.1"), "10.1")
def test_istwoscomplement(self):
"""Test function/method."""
self.assertIsInstance(TwosComplement.istwoscomplement("1.0"), bool)
self.assertEqual(TwosComplement.istwoscomplement("0.1"), True)
self.assertEqual(TwosComplement.istwoscomplement("0"), True)
self.assertEqual(TwosComplement.istwoscomplement("1"), True)
self.assertEqual(TwosComplement.istwoscomplement("0.1"), True)
self.assertEqual(TwosComplement.istwoscomplement("1.1e+123"), True)
self.assertEqual(TwosComplement.istwoscomplement("0b0.1"), False)
self.assertEqual(TwosComplement.istwoscomplement("-0b0.1"), False)
self.assertEqual(TwosComplement.istwoscomplement("-1"), False)
self.assertEqual(TwosComplement.istwoscomplement("+1"), False)
self.assertEqual(TwosComplement.istwoscomplement("0x1"), False)
self.assertEqual(TwosComplement.istwoscomplement("1"), True)
self.assertEqual(TwosComplement.istwoscomplement("0b1"), False)
self.assertEqual(TwosComplement.istwoscomplement("0b01"), False)
self.assertEqual(TwosComplement.istwoscomplement("0"), True)
self.assertEqual(TwosComplement.istwoscomplement("1.1"), True)
self.assertEqual(TwosComplement.istwoscomplement("0.1"), True)
self.assertEqual(TwosComplement.istwoscomplement("1.1e9"), True)
self.assertEqual(TwosComplement.istwoscomplement("0.1e8"), True)
self.assertEqual(TwosComplement.istwoscomplement("1110.1e-19"), True)
self.assertEqual(TwosComplement.istwoscomplement("00001.1e-18"), True)
self.assertEqual(TwosComplement.istwoscomplement("1.1e9"), True)
self.assertEqual(TwosComplement.istwoscomplement("00.001.1e-18"), False)
self.assertEqual(TwosComplement.istwoscomplement("00e001.1e-18"), False)
self.assertEqual(TwosComplement.istwoscomplement("8"), False)
self.assertEqual(TwosComplement.istwoscomplement("Hello"), False)
self.assertEqual(TwosComplement.istwoscomplement(""), False)
self.assertEqual(TwosComplement.istwoscomplement("-0b1"), False)
self.assertEqual(TwosComplement.istwoscomplement("-0b01"), False)
self.assertEqual(TwosComplement.istwoscomplement("-0"), False)
self.assertEqual(TwosComplement.istwoscomplement("0b1"), False)
self.assertEqual(TwosComplement.istwoscomplement("0b01"), False)
self.assertEqual(TwosComplement.istwoscomplement("inf"), False)
with self.assertRaises(TypeError):
TwosComplement.istwoscomplement(1975) # should fail
with self.assertRaises(TypeError):
TwosComplement.istwoscomplement(1.1) # should fail
def test_components(self):
"""Test function/method."""
self.assertEqual(TwosComplement.components("0"), (0, "0", "", 0))
self.assertEqual(TwosComplement.components("1"), (1, "1", "", 0))
self.assertEqual(TwosComplement.components("01"), (0, "01", "", 0))
self.assertEqual(TwosComplement.components("10"), (1, "10", "", 0))
self.assertEqual(TwosComplement.components("01."), (0, "01", "", 0))
self.assertEqual(TwosComplement.components("10."), (1, "10", "", 0))
self.assertEqual(TwosComplement.components("01.0"), (0, "01", "", 0))
self.assertEqual(TwosComplement.components("10.0"), (1, "10", "", 0))
self.assertEqual(TwosComplement.components("00001.0"), (0, "01", "", 0))
self.assertEqual(TwosComplement.components("11110.0"), (1, "10", "", 0))
self.assertEqual(TwosComplement.components("0.01e-2"), (0, "0", "01", -2))
self.assertEqual(TwosComplement.components("1.00e-2"), (1, "1", "", -2))
self.assertEqual(TwosComplement.components("1.01e+2"), (1, "1", "01", 2))
self.assertEqual(TwosComplement.components("0.01e2"), (0, "0", "01", 2))
self.assertEqual(TwosComplement.components("101010.e+2"), (1, "101010", "", 2))
with self.assertRaises(ValueError):
TwosComplement.components("inf") # should fail
with self.assertRaises(ValueError):
TwosComplement.components("-1") # should fail
with self.assertRaises(ValueError):
TwosComplement.components("+1") # should fail
with self.assertRaises(ValueError):
TwosComplement.components("0b1") # should fail
with self.assertRaises(TypeError):
TwosComplement.components(0.0) # should fail
with self.assertRaises(ValueError):
TwosComplement.components(".01e-2")
with self.assertRaises(ValueError):
TwosComplement.components("+0101010e2")
def test_simplify(self):
"""Test function/method."""
self.assertEqual(TwosComplement.simplify("0"), "0")
self.assertEqual(TwosComplement.simplify("1"), "1")
self.assertEqual(TwosComplement.simplify("01"), "01")
self.assertEqual(TwosComplement.simplify("10"), "10")
self.assertEqual(TwosComplement.simplify("001"), "01")
self.assertEqual(TwosComplement.simplify("110"), "10")
self.assertEqual(TwosComplement.simplify("01."), "01")
self.assertEqual(TwosComplement.simplify("10."), "10")
self.assertEqual(TwosComplement.simplify("01.0"), "01")
self.assertEqual(TwosComplement.simplify("10.0"), "10")
self.assertEqual(TwosComplement.simplify("001.00"), "01")
self.assertEqual(TwosComplement.simplify("110.00"), "10")
self.assertEqual(TwosComplement.simplify("001.00e0"), "01")
self.assertEqual(TwosComplement.simplify("110.00e-00"), "10")
self.assertEqual(TwosComplement.simplify("001.00e+0"), "01")
self.assertEqual(TwosComplement.simplify("110.00e+000"), "10")
self.assertEqual(TwosComplement.simplify("001.001"), "01.001")
self.assertEqual(TwosComplement.simplify("110.001"), "10.001")
def test_to_fraction(self):
"""Test function/method."""
self.assertEqual(TwosComplement.to_fraction("0"), Fraction(0, 1))
self.assertEqual(TwosComplement.to_fraction("1"), Fraction(-1, 1))
self.assertEqual(TwosComplement.to_fraction("100001001001"), Fraction(-1975, 1))
self.assertEqual(TwosComplement.to_fraction("011110110111"), Fraction(+1975, 1))
self.assertEqual(TwosComplement.to_fraction("0.1"), Fraction(1, 2))
self.assertEqual(TwosComplement.to_fraction("1.1"), Fraction(-1, 2))
self.assertEqual(TwosComplement.to_fraction("10.1"), Fraction(-3, 2))
for ii in [
-8,
-7.5,
-4.24,
-2,
-1.375,
-1.0,
-0.25,
0,
0.75,
1,
1.875,
2,
4.58757,
7,
8,
]:
self.assertEqual(TwosComplement(Fraction(ii)).to_fraction(), Fraction(ii))
def test_to_float(self):
"""Test function/method."""
self.assertEqual(TwosComplement.to_float("0"), 0.0)
self.assertEqual(TwosComplement.to_float("1"), -1.0)
self.assertEqual(TwosComplement.to_float("100001001001"), -1975.0)
self.assertEqual(TwosComplement.to_float("011110110111"), +1975.0)
self.assertEqual(TwosComplement.to_float("0.1"), 0.5)
self.assertEqual(TwosComplement.to_float("1.1"), -0.5)
self.assertEqual(TwosComplement.to_float("10.1"), -1.5)
for ii in [
-8,
-7.5,
-4.24,
-2,
-1.375,
-1.0,
-0.25,
0,
0.75,
1,
1.875,
2,
4.58757,
7,
8,
]:
self.assertEqual(TwosComplement(ii).to_float(), ii)
def test_to_no_mantissa(self):
"""Test function/method."""
self.assertEqual(TwosComplement.to_no_mantissa("0"), "0")
self.assertEqual(TwosComplement.to_no_mantissa("01e12"), "01e12")
self.assertEqual(TwosComplement.to_no_mantissa("01e-12"), "01e-12")
self.assertEqual(TwosComplement.to_no_mantissa("101e12"), "101e12")
self.assertEqual(TwosComplement.to_no_mantissa("101e-12"), "101e-12")
self.assertEqual(TwosComplement.to_no_mantissa("01.e12"), "01e12")
self.assertEqual(TwosComplement.to_no_mantissa("01.e-12"), "01e-12")
self.assertEqual(TwosComplement.to_no_mantissa("01.1e12"), "011e11")
self.assertEqual(TwosComplement.to_no_mantissa("01.1e-12"), "011e-13")
self.assertEqual(TwosComplement.to_no_mantissa("01.0e12"), "01e12")
self.assertEqual(TwosComplement.to_no_mantissa("01.0e-12"), "01e-12")
self.assertEqual(TwosComplement.to_no_mantissa("01.11e12"), "0111e10")
self.assertEqual(TwosComplement.to_no_mantissa("01.11e-12"), "0111e-14")
self.assertEqual(TwosComplement.to_no_mantissa("01.01e12"), "0101e10")
self.assertEqual(TwosComplement.to_no_mantissa("01.01e-12"), "0101e-14")
self.assertEqual(TwosComplement.to_no_mantissa("01.01e1"), "0101e-1")
self.assertEqual(TwosComplement.to_no_mantissa("01.01e2"), "0101")
def test_to_no_exponent(self):
"""Test function/method."""
self.assertEqual(TwosComplement.to_no_exponent("0"), "0")
self.assertEqual(TwosComplement.to_no_exponent("1"), "1")
self.assertEqual(TwosComplement.to_no_exponent("11.01e4"), "10100")
self.assertEqual(TwosComplement.to_no_exponent("11.01e3"), "1010")
self.assertEqual(TwosComplement.to_no_exponent("11.01e2"), "101")
self.assertEqual(TwosComplement.to_no_exponent("11.01e1"), "10.1")
self.assertEqual(TwosComplement.to_no_exponent("11.01e0"), "1.01")
self.assertEqual(
TwosComplement.to_no_exponent("11.01e4", simplify=False), "110100"
)
self.assertEqual(
TwosComplement.to_no_exponent("11.01e3", simplify=False), "11010"
)
self.assertEqual(
TwosComplement.to_no_exponent("11.01e2", simplify=False), "1101"
)
self.assertEqual(
TwosComplement.to_no_exponent("11.01e1", simplify=False), "110.1"
)
self.assertEqual(
TwosComplement.to_no_exponent("11.01e0", simplify=False), "11.01"
)
self.assertEqual(TwosComplement.to_no_exponent("11.01e-1"), "1.101")
self.assertEqual(TwosComplement.to_no_exponent("11.01e-2"), "1.1101")
self.assertEqual(TwosComplement.to_no_exponent("11.01e-3"), "1.11101")
self.assertEqual(TwosComplement.to_no_exponent("11.01e-4"), "1.111101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e4"), "0110100")
self.assertEqual(TwosComplement.to_no_exponent("011.01e3"), "011010")
self.assertEqual(TwosComplement.to_no_exponent("011.01e2"), "01101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e1"), "0110.1")
self.assertEqual(TwosComplement.to_no_exponent("011.01e0"), "011.01")
self.assertEqual(TwosComplement.to_no_exponent("011.01e-1"), "01.101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e-2"), "0.1101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e-3"), "0.01101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e-4"), "0.001101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e2"), "01101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e+2"), "01101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e4"), "0110100")
self.assertEqual(TwosComplement.to_no_exponent("011.01e-4"), "0.001101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e-2"), "0.1101")
self.assertEqual(TwosComplement.to_no_exponent("0.1e-1"), "0.01")
self.assertEqual(TwosComplement.to_no_exponent("1.111e0"), "1.111")
self.assertEqual(TwosComplement.to_no_exponent("1.11e0"), "1.11")
self.assertEqual(TwosComplement.to_no_exponent("1.1e0"), "1.1")
self.assertEqual(TwosComplement.to_no_exponent("1.e0"), "1")
self.assertEqual(TwosComplement.to_no_exponent("1.e1"), "10")
self.assertEqual(TwosComplement.to_no_exponent("1.01e2"), "101")
self.assertEqual(TwosComplement.to_no_exponent("1.01e1"), "10.1")
self.assertEqual(TwosComplement.to_no_exponent("1.011e2"), "101.1")
self.assertEqual(TwosComplement.to_no_exponent("1111000e-0"), "1000")
self.assertEqual(TwosComplement.to_no_exponent("1111000e-3"), "1")
self.assertEqual(TwosComplement.to_no_exponent("1111000000.e-3"), "1000")
self.assertEqual(TwosComplement.to_no_exponent("1111000e+3"), "1000000")
self.assertEqual(TwosComplement.to_no_exponent("1111e+3"), "1000")
self.assertEqual(TwosComplement.to_no_exponent("1111.1e+3"), "100")
self.assertEqual(TwosComplement.to_no_exponent("011.01e-02"), "0.1101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e-02", -1), "0.1101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e-02", 7), "00.1101")
self.assertEqual(TwosComplement.to_no_exponent("011.01e-02", 8), "000.1101")
self.assertEqual(TwosComplement.to_no_exponent("0.01"), "0.01")
self.assertEqual(TwosComplement.to_no_exponent("1.111"), "1.111")
self.assertEqual(TwosComplement.to_no_exponent("1.11"), "1.11")
self.assertEqual(TwosComplement.to_no_exponent("1.1"), "1.1")
self.assertEqual(TwosComplement.to_no_exponent("111"), "1")
self.assertEqual(TwosComplement.to_no_exponent("10.000"), "10")
self.assertEqual(TwosComplement.to_no_exponent("101.000e0"), "101")
self.assertEqual(TwosComplement.to_no_exponent("10.10"), "10.1")
self.assertEqual(TwosComplement.to_no_exponent("101.1e-0"), "101.1")
with self.assertRaises(ValueError):
TwosComplement.to_no_exponent("0b1") # leading 0b not allowed
with self.assertRaises(ValueError):
TwosComplement.to_no_exponent("0b01") # leading 0b not allowed
with self.assertRaises(ValueError):
TwosComplement.to_no_exponent("-0b1") # leading -0b not allowed
with self.assertRaises(ValueError):
TwosComplement.to_no_exponent("-0b01") # leading -0b not allowed
with self.assertRaises(ValueError):
TwosComplement.to_no_exponent("-1") # leading - not allowed
with self.assertRaises(ValueError):
TwosComplement.to_no_exponent("") # should fail
with self.assertRaises(ValueError):
TwosComplement.to_no_exponent("1", 0) # should fail
with self.assertRaises(OverflowError):
TwosComplement.to_no_exponent("11100", 1) # should fail
with self.assertRaises(ValueError):
TwosComplement.to_no_exponent("111", 0) # should fail
with self.assertRaises(OverflowError):
TwosComplement.to_no_exponent("0111", 2) # should fail
with self.assertRaises(OverflowError):
TwosComplement.to_no_exponent("011.01e-02", 5)
with self.assertRaises(ValueError):
TwosComplement.to_no_exponent("-0b10") # should fail
with self.assertRaises(TypeError):
TwosComplement.to_no_exponent(1) # should fail
with self.assertRaises(TypeError):
TwosComplement.to_no_exponent("1", "-1") # should fail
def test_invert(self):
"""Test function/method."""
self.assertIsInstance(TwosComplement.invert("1"), str)
self.assertIsInstance(
TwosComplement.invert(TwosComplement("1")), TwosComplement
)
self.assertIsInstance(TwosComplement("1").invert(), TwosComplement)
self.assertEqual(TwosComplement.invert("0001000", False), "1110111")
self.assertEqual(TwosComplement.invert("0001000", simplify=True), "10111")
self.assertEqual(TwosComplement.invert("1110110", simplify=True), "01001")
self.assertEqual(TwosComplement.invert("0.1101", simplify=False), "1.0010")
self.assertEqual(TwosComplement.invert("0.1101", simplify=True), "1.001")
self.assertEqual(TwosComplement.invert("11.1101", simplify=True), "0.001")
self.assertEqual(TwosComplement.invert("00.1101", simplify=True), "1.001")
self.assertEqual(TwosComplement.invert("01"), "10")
self.assertEqual(TwosComplement.invert("0"), "1")
self.assertEqual(TwosComplement.invert("1"), "0")
self.assertEqual(TwosComplement.invert("10"), "01")
self.assertEqual(TwosComplement.invert("101"), "010")
self.assertEqual(TwosComplement.invert("101010"), "010101")
self.assertEqual(TwosComplement.invert("0101010"), "1010101")
self.assertEqual(TwosComplement.invert("101.010"), "010.101")
self.assertEqual(TwosComplement.invert("010.1010"), "101.0101")
self.assertEqual(TwosComplement.invert("1e1"), "0.1e1")
self.assertEqual(
TwosComplement("1e1", simplify=False).invert().to_no_exponent(), "01"
)
self.assertEqual(
TwosComplement.invert("0101010e-3", simplify=False), "1010101e-3"
)
self.assertEqual(TwosComplement.invert("0101010e-3"), "1010101e-3")
self.assertEqual(TwosComplement.invert("1010101e0"), "0101010")
self.assertEqual(TwosComplement.invert("0101010e-0"), "1010101")
self.assertEqual(TwosComplement.invert("1010101e-34"), "0101010e-34")
self.assertEqual(TwosComplement.invert("0101010e-34"), "1010101e-34")
self.assertEqual(
TwosComplement.invert("010101e34"),
"101010.1111111111111111111111111111111111e34",
)
self.assertEqual(
TwosComplement("010101e34").invert().to_no_exponent(),
"1010101111111111111111111111111111111111",
)
self.assertEqual(
TwosComplement.invert("101010e34"),
"010101.1111111111111111111111111111111111e34",
)
self.assertEqual(
TwosComplement("101010e34").invert().to_no_exponent(),
"0101011111111111111111111111111111111111",
)
self.assertEqual(TwosComplement.invert("010.1010e-34"), "101.0101e-34")
self.assertEqual(
TwosComplement.invert("101.010e34"),
"010.1011111111111111111111111111111111e34",
)
self.assertEqual(
TwosComplement("101.010e34").invert().to_no_exponent(),
"0101011111111111111111111111111111111",
)
self.assertEqual(
TwosComplement.invert("101.010e1", simplify=False), "010.101e1"
)
self.assertEqual(
TwosComplement("101.010e1", simplify=False)
.invert(simplify=False)
.to_no_exponent(),
"0101.01",
)
self.assertEqual(
TwosComplement("101.010e1", simplify=False).invert(simplify=False),
"010.101e1",
)
self.assertEqual(
TwosComplement.invert("101.010e1", simplify=False), "010.101e1"
)
self.assertEqual(
TwosComplement("101.010e1", simplify=False)
.invert(simplify=False)
.to_no_exponent(),
"0101.01",
)
self.assertEqual(TwosComplement.invert("101.010e0"), "010.101")
self.assertEqual(
TwosComplement.invert(TwosComplement.invert("0101010e-34")), "0101010e-34"
)
self.assertEqual(
TwosComplement.invert(TwosComplement.invert("101010e34")), "101010e34"
)
self.assertEqual(
TwosComplement("101010e34").invert().invert().to_no_exponent(),
"1010100000000000000000000000000000000000",
)
with self.assertRaises(ValueError):
TwosComplement.invert("1975") # should fail
with self.assertRaises(ValueError):
TwosComplement.invert("1.1.") # should fail
with self.assertRaises(ValueError):
TwosComplement.invert("1e") # should fail
with self.assertRaises(ValueError):
TwosComplement.invert("1e2e3") # should fail
with self.assertRaises(TypeError):
TwosComplement.invert(1975) # should fail
with self.assertRaises(ArithmeticError):
TwosComplement.invert("Inf")
with self.assertRaises(ArithmeticError):
TwosComplement.invert("-inf")
with self.assertRaises(ArithmeticError):
TwosComplement.invert("nan")
##########################################################################
# CLASS TESTBINARY
##########################################################################
class TestBinary(unittest.TestCase):
"""Unit testing of class Binary."""
def selftest(self) -> bool:
"""Perform self test by running various test cases.
`Binary` uses module `unittest` for unit testing.
See https://docs.python.org/3/library/unittest.html for details.
Parameters:
none
Returns:
bool: True if all tests pass, False if any single test fails
"""
# default would be: unittest.main()
# This would run all testcase, print resultsm and terminates program.
# But this would not allow further inspection or tuning.
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestBinary)
test_result = unittest.TextTestRunner().run(suite)
err = len(test_result.errors)
fail = len(test_result.failures)
skip = len(test_result.skipped)
run = test_result.testsRun
ttl = suite.countTestCases()
success = test_result.wasSuccessful()
print("")
print("Test results for class Binary are: ")
print(f" Total number of individual tests = {_BINARY_TOTAL_TESTS}")
print(f" Total number of unit tests = {ttl}")
print(f" Unit tests executed = {run}")
print(f" Unit tests skipped = {skip}")
print(f" Unit tests failed = {fail}")
print(f" Unit tests with error = {err}")
if success:
result = f"Self-Test: 😃 All {run} out of {ttl} unit tests passed ✅"
ret = True
else:
plural = "" if run - err - fail == 1 else "s"
result = f"Self-Test: {run-err-fail} unit test{plural} passed ✅\n"
plural = "" if err + fail == 1 else "s"
result += f"Self-Test: {err+fail} unit test{plural} failed ❌"
ret = False
print(f"{result}")
return ret
def test___new__(self):
"""Testing the constructor."""
self.assertIsInstance(Binary(1), Binary)
self.assertIsInstance(Binary(1.5), Binary)
self.assertIsInstance(Binary("0110"), Binary)
self.assertIsInstance(Binary("0110.010e-23"), Binary)
self.assertIsInstance(Binary(TwosComplement(1)), Binary)
self.assertTrue("Binary" in str(type(Binary(5))))
self.assertEqual(float(Binary("0")), 0.0)
self.assertEqual(float(Binary("1.1")), 1.5)
self.assertEqual(float(Binary("-1.11")), -1.75)
self.assertEqual(Binary("0b1.1"), "1.1")
self.assertEqual(Binary("-0b1.1"), "-1.1")
self.assertEqual(Binary(-3.5), "-11.1")
self.assertEqual(Binary(-3.5), "-0b11.1")
self.assertEqual(str(Binary(-3.5)), "-0b11.1")
self.assertEqual(
Binary((1, (1, 0, 1, 0), -2)).compare_representation("-1010e-2"), True
)
self.assertEqual(Binary(TwosComplement(0)), 0)
self.assertEqual(Binary(TwosComplement(1)), 1)
self.assertEqual(Binary(TwosComplement(2)), 2)
self.assertEqual(Binary(TwosComplement(-1)), -1)
self.assertEqual(Binary(TwosComplement(-2)), -2)
self.assertEqual(Binary(TwosComplement(-1975)), -1975)
self.assertEqual(Binary(TwosComplement(1975)), 1975)
self.assertEqual(Binary(TwosComplement("01")), 1)
self.assertEqual(Binary(TwosComplement("1")), -1)
self.assertEqual(Binary(TwosComplement("10")), -2)
with self.assertRaises(ValueError):
Binary("102") # should fail
with self.assertRaises(TypeError):
Binary(complex(1, 1)) # should fail
def test_version(self):
"""Testing the version method."""
self.assertIsInstance(Binary.version(), str)
self.assertEqual(len(Binary.version()), len("20210622-103815"))
self.assertEqual(Binary.version()[8], "-")
self.assertEqual(Binary.version()[0:2], "20") # YY
def test_to_float(self):
"""Test to_float() function."""
self.assertIsInstance(Binary.to_float("1"), int)
self.assertIsInstance(Binary.to_float("1.1"), float)
self.assertEqual(Binary.to_float("inf"), float("inf"))
self.assertEqual(Binary.to_float("-inf"), float("-inf"))
self.assertEqual(math.isnan(Binary.to_float("-nan")), True)
self.assertEqual(Binary.to_float("-0b11.1"), -3.5)
self.assertEqual(Binary.to_float("0b0"), 0)
self.assertEqual(Binary.to_float("0b1000.01"), 8.25)
with self.assertRaises(ValueError):
Binary.to_float("2") # should fail
def test_from_float(self):
"""Testing from_float() function."""
self.assertIsInstance(Binary.from_float(1.0), str)
self.assertEqual(Binary.from_float(float("inf")), "inf")
self.assertEqual(Binary.from_float(float("-inf")), "-inf")
self.assertEqual(Binary.from_float(float("-nan")), "nan")
self.assertEqual(Binary.from_float(-3.5), "-0b11.1")
self.assertEqual(Binary.from_float(-0.0), "0b0")
self.assertEqual(Binary.from_float(8.25), "0b1000.01")
with self.assertRaises(TypeError):
Binary.from_float("1") # should fail
def test_to_no_exponent(self):
"""Test function/method."""
self.assertIsInstance(Binary.to_no_exponent("1"), str)
self.assertIsInstance(Binary.to_no_exponent(Binary("1")), Binary)
self.assertIsInstance(Binary("1").to_no_exponent(), Binary)
self.assertEqual(Binary.to_no_exponent("0"), "0")
self.assertEqual(Binary.to_no_exponent("1"), "1")
self.assertEqual(Binary.to_no_exponent("11.01e4"), "110100")
self.assertEqual(Binary.to_no_exponent("11.01e3"), "11010")
self.assertEqual(Binary.to_no_exponent("11.01e2"), "1101")
self.assertEqual(Binary.to_no_exponent("11.01e1"), "110.1")
self.assertEqual(Binary.to_no_exponent("11.01e0"), "11.01")
self.assertEqual(Binary.to_no_exponent("11.01e4", simplify=False), "110100")
self.assertEqual(Binary.to_no_exponent("11.01e3", simplify=False), "11010")
self.assertEqual(Binary.to_no_exponent("11.01e2", simplify=False), "1101")
self.assertEqual(Binary.to_no_exponent("11.01e1", simplify=False), "110.1")
self.assertEqual(Binary.to_no_exponent("11.01e0", simplify=False), "11.01")
self.assertEqual(Binary.to_no_exponent("11.01e-1"), "1.101")
self.assertEqual(Binary.to_no_exponent("11.01e-2"), "0.1101")
self.assertEqual(Binary.to_no_exponent("11.01e-3"), "0.01101")
self.assertEqual(Binary.to_no_exponent("11.01e-4"), "0.001101")
self.assertEqual(Binary.to_no_exponent("011.01e4"), "110100")
self.assertEqual(Binary.to_no_exponent("011.01e3"), "11010")
self.assertEqual(Binary.to_no_exponent("011.01e2"), "1101")
self.assertEqual(Binary.to_no_exponent("011.01e1"), "110.1")
self.assertEqual(Binary.to_no_exponent("011.01e0"), "11.01")
self.assertEqual(Binary.to_no_exponent("011.01e-1"), "1.101")
self.assertEqual(Binary.to_no_exponent("011.01e-2"), "0.1101")
self.assertEqual(Binary.to_no_exponent("011.01e-3"), "0.01101")
self.assertEqual(Binary.to_no_exponent("011.01e-4"), "0.001101")
self.assertEqual(Binary.to_no_exponent("011.01e2"), "1101")
self.assertEqual(Binary.to_no_exponent("011.01e+2"), "1101")
self.assertEqual(Binary.to_no_exponent("011.01e4"), "110100")
self.assertEqual(Binary.to_no_exponent("011.01e-4"), "0.001101")
self.assertEqual(Binary.to_no_exponent("011.01e-2"), "0.1101")
self.assertEqual(Binary.to_no_exponent("0.1e-1"), "0.01")
self.assertEqual(Binary.to_no_exponent("1.111e0"), "1.111")
self.assertEqual(Binary.to_no_exponent("1.11e0"), "1.11")
self.assertEqual(Binary.to_no_exponent("1.1e0"), "1.1")
self.assertEqual(Binary.to_no_exponent("1.e0"), "1")
self.assertEqual(Binary.to_no_exponent("1.e1"), "10")
self.assertEqual(Binary.to_no_exponent("1.01e2"), "101")
self.assertEqual(Binary.to_no_exponent("1.01e1"), "10.1")
self.assertEqual(Binary.to_no_exponent("1.011e2"), "101.1")
self.assertEqual(Binary.to_no_exponent("1111000e-0"), "1111000")
self.assertEqual(Binary.to_no_exponent("1111000e-3"), "1111")
self.assertEqual(Binary.to_no_exponent("1111000000.e-3"), "1111000")
self.assertEqual(Binary.to_no_exponent("1111000e+3"), "1111000000")
self.assertEqual(Binary.to_no_exponent("1111e+3"), "1111000")
self.assertEqual(Binary.to_no_exponent("1111.1e+3"), "1111100")
self.assertEqual(Binary.to_no_exponent("011.01e-02"), "0.1101")
self.assertEqual(
Binary.to_no_exponent("011.01e-02", add_prefix=True), "0b0.1101"
)
self.assertEqual(Binary.to_no_exponent("011.01e-02", length=-1), "0.1101")
self.assertEqual(Binary.to_no_exponent("011.01e-02", length=7), "00.1101")
self.assertEqual(Binary.to_no_exponent("011.01e-02", length=8), "000.1101")
self.assertEqual(Binary.to_no_exponent("0.01"), "0.01")
self.assertEqual(Binary.to_no_exponent("1.111"), "1.111")
self.assertEqual(Binary.to_no_exponent("1.11"), "1.11")
self.assertEqual(Binary.to_no_exponent("1.1"), "1.1")
self.assertEqual(Binary.to_no_exponent("111"), "111")
self.assertEqual(Binary.to_no_exponent("10.000"), "10")
self.assertEqual(Binary.to_no_exponent("101.000e0"), "101")
self.assertEqual(Binary.to_no_exponent("10.10"), "10.1")
self.assertEqual(Binary.to_no_exponent("101.1e-0"), "101.1")
self.assertEqual(Binary.to_no_exponent("-0"), "0")
self.assertEqual(Binary.to_no_exponent("11.01e-2"), "0.1101")
self.assertEqual(Binary.to_no_exponent("-11.01e-2"), "-0.1101")
self.assertEqual(Binary.to_no_exponent("-11.01e-3"), "-0.01101")
self.assertEqual(Binary.to_no_exponent("-11.01e-4"), "-0.001101")
self.assertEqual(Binary.to_no_exponent("11.01e2"), "1101")
self.assertEqual(Binary.to_no_exponent("-11.01e+2"), "-1101")
self.assertEqual(Binary.to_no_exponent("11.01e4"), "110100")
self.assertEqual(Binary.to_no_exponent("-11.01e+4"), "-110100")
self.assertEqual(Binary.to_no_exponent("11.01e4", add_prefix=True), "0b110100")
self.assertEqual(
Binary.to_no_exponent("-11.01e+4", add_prefix=True), "-0b110100"
)
self.assertEqual(Binary.to_no_exponent(Binary("Inf")), "Infinity")
self.assertEqual(Binary.to_no_exponent(Binary("-0")), "0b0")
self.assertEqual(Binary.to_no_exponent(Binary("-0"), add_prefix=True), "0b0")
self.assertEqual(Binary.to_no_exponent(Binary("11.01e-2")), "0b0.1101")
self.assertEqual(Binary.to_no_exponent(Binary("-11.01e-2")), "-0b0.1101")
self.assertEqual(Binary.to_no_exponent(Binary("-11.01e-3")), "-0b0.01101")
self.assertEqual(Binary.to_no_exponent(Binary("-11.01e-4")), "-0b0.001101")
self.assertEqual(Binary.to_no_exponent(Binary("11.01e2")), "0b1101")
self.assertEqual(Binary.to_no_exponent(Binary("-11.01e+2")), "-0b1101")
self.assertEqual(Binary.to_no_exponent(Binary("11.01e4")), "0b110100")
self.assertEqual(Binary.to_no_exponent(Binary("-11.01e+4")), "-0b110100")
with self.assertRaises(ValueError):
Binary.to_no_exponent("") # should fail
with self.assertRaises(TypeError):
Binary.to_no_exponent(1) # should fail
with self.assertRaises(OverflowError):
Binary.to_no_exponent("1", length=0) # should fail
with self.assertRaises(OverflowError):
Binary.to_no_exponent("11100", length=4) # should fail
with self.assertRaises(OverflowError):
Binary.to_no_exponent("0011", length=1) # should fail
with self.assertRaises(OverflowError):
Binary.to_no_exponent("0111", length=2) # should fail
with self.assertRaises(OverflowError):
Binary.to_no_exponent("011.01e-02", length=4)
with self.assertRaises(TypeError):
Binary.to_no_exponent("1", "-1") # should fail
def test___float__(self):
"""Test __float__() method."""
self.assertEqual(float(Binary("-1")), -1.0)
self.assertEqual(float(Binary("-1.1")), -1.5)
self.assertEqual(float(Binary("1.001")), 1.125)
self.assertEqual(float(Binary((1, (1, 0, 1, 0), -2))), -2.5)
self.assertEqual(float(Binary(-13.0 - 2 ** -10)), -13.0009765625)
self.assertEqual(float(Binary(13.0 + 2 ** -20)), 13.000000953674316)
self.assertEqual(float(Binary(13.0 + 2 ** -30)), 13.000000000931323)
self.assertEqual(float(Binary("Inf")), float("Inf"))
def test___int__(self):
"""Test __int__() method."""
self.assertEqual(int(Binary("-1")), -1)
self.assertEqual(int(Binary("-1.111")), -1)
self.assertEqual(int(Binary("1.001")), 1)
self.assertEqual(int(Binary((1, (1, 0, 1, 0), -2))), -2)
self.assertEqual(int(Binary(-13.0 - 2 ** -10)), -13)
self.assertEqual(int(Binary(13.0 + 2 ** -20)), 13)
self.assertEqual(int(Binary(13.0 + 2 ** -30)), 13)
with self.assertRaises(ValueError):
int(Binary("Inf")) # should fail
def test___str__(self):
"""Test __str__() method."""
self.assertEqual(str(Binary("-1")), "-0b1")
self.assertEqual(str(Binary("-1.111")), "-0b1.111")
self.assertEqual(str(Binary("1.001")), "0b1.001")
self.assertEqual(str(Binary((1, (1, 0, 1, 0), -2))), "-0b1010e-2")
self.assertEqual(str(Binary(-13.0 - 2 ** -10)), "-0b1101.0000000001")
self.assertEqual(str(Binary(13.0 + 2 ** -20)), "0b1101.00000000000000000001")
self.assertEqual(
str(Binary(13.0 + 2 ** -30)), "0b1101.000000000000000000000000000001"
)
self.assertEqual(str(Binary("Nan")), _NAN)
self.assertEqual(str(Binary("inf")), _INF)
self.assertEqual(str(Binary("-inf")), _NINF)
with self.assertRaises(ValueError):
str(Binary("Info")) # should fail
def test_compare_representation(self):
"""Test function/method."""
self.assertEqual(
Binary(10.10).compare_representation(
"1010.0001100110011001100110011001100110011001100110011"
),
True,
)
self.assertEqual(Binary("10.111").compare_representation("10.111"), True)
self.assertEqual(Binary(5).compare_representation("101"), True)
self.assertEqual(
Binary(8.3).compare_representation(
"1000.010011001100110011001100110011001100110011001101"
),
True,
)
self.assertEqual(Binary(0.0).compare_representation("0"), True)
self.assertEqual(Binary(1.0).compare_representation("1"), True)
self.assertEqual(Binary(3.5).compare_representation("11.1"), True)
self.assertEqual(Binary(-13.75).compare_representation("-1101.11"), True)
self.assertEqual(
Binary(13.0 + 2 ** -10).compare_representation("1101.0000000001"), True
)
self.assertEqual(
Binary(13.0 + 2 ** -20).compare_representation("1101.00000000000000000001"),
True,
)
self.assertEqual(
Binary(13.0 + 2 ** -30).compare_representation(
"1101.000000000000000000000000000001"
),
True,
)
self.assertEqual(
Binary(13.0 + 2 ** -40).compare_representation(
"1101.0000000000000000000000000000000000000001"
),
True,
)
self.assertEqual(Binary(13.0 + 2 ** -50).compare_representation("1101"), True)
self.assertEqual(Binary(13.0 + 2 ** -60).compare_representation("1101"), True)
self.assertEqual(
Binary(
13.0
+ 2 ** -10
+ 2 ** -20
+ 2 ** -30
+ 2 ** -40
+ 2 ** -50
+ 2 ** -60
+ 2 ** -70
).compare_representation("1101.0000000001000000000100000000010000000001"),
True,
)
self.assertEqual(Binary("1.1").round(1).compare_representation("1.1"), True)
self.assertEqual(Binary("1.10").round(1).compare_representation("1.1"), True)
self.assertEqual(Binary("1.101").round(1).compare_representation("1.1"), True)
self.assertEqual(Binary("1.11").round(1).compare_representation("1.1"), True)
self.assertEqual(Binary("1.110").round(1).compare_representation("1.1"), True)
self.assertEqual(Binary("1.1101").round(1).compare_representation("10"), True)
self.assertEqual(Binary("1.1111").round(1).compare_representation("10"), True)
with self.assertRaises(TypeError):
Binary.compare_representation(1, "1") # should fail
def test_no_prefix(self):
"""Test function/method."""
self.assertEqual(Binary(-3.5).no_prefix(), "-11.1")
self.assertEqual(Binary.no_prefix(Binary(-3.5)), "-11.1")
self.assertEqual(Binary.no_prefix("-11.1"), "-11.1")
self.assertEqual(Binary.no_prefix("-0b11.1"), "-11.1")
self.assertEqual(Binary.no_prefix("0b11.1"), "11.1")
self.assertEqual(Binary.no_prefix("+0b11.1"), "+11.1")
with self.assertRaises(TypeError):
Binary.no_prefix(1.5) # should fail, 1 arg too much
def test_np(self):
"""Test function/method."""
self.assertEqual(Binary(-5.5).np(), "-101.1")
self.assertEqual(Binary.np(Binary(-3.5)), "-11.1")
with self.assertRaises(TypeError):
Binary.np(1.5) # should fail, 1 arg too much
def test_simplify(self):
"""Test function simplify()."""
self.assertEqual(Binary.simplify("-0"), "0")
self.assertEqual(Binary.simplify("-000"), "0")
self.assertEqual(Binary.simplify("-000.00"), "0")
self.assertEqual(Binary.simplify("-000.00e-10"), "0")
self.assertEqual(Binary.simplify("-1e-0"), "-1")
self.assertEqual(Binary.simplify("-010"), "-10")
self.assertEqual(Binary.simplify("-0010"), "-10")
self.assertEqual(Binary.simplify("-0010.00"), "-10")
self.assertEqual(Binary.simplify("-0010.00e-10"), "-10e-10")
self.assertEqual(Binary.simplify("-101.01e-0"), "-101.01")
self.assertEqual(Binary.simplify("-1e-0", True), "-0b1")
self.assertEqual(Binary.simplify("-010", True), "-0b10")
self.assertEqual(Binary.simplify("-0010", True), "-0b10")
self.assertEqual(Binary.simplify("-0010.00", True), "-0b10")
self.assertEqual(Binary.simplify("-0010.00e-10", True), "-0b10e-10")
self.assertEqual(Binary.simplify("101.01e-0", True), "0b101.01")
with self.assertRaises(TypeError):
Binary.simplify(1) # should fail
with self.assertRaises(TypeError):
Binary.simplify(Binary("Inf")) # should fail
def test_to_fraction(self):
"""Test function/method."""
self.assertIsInstance(Binary.to_fraction("1"), Fraction)
self.assertEqual(Binary.to_fraction("1"), Fraction(1))
self.assertEqual(Binary.to_fraction("0"), Fraction(0))
self.assertEqual(Binary.to_fraction("0.1"), Fraction(0.5))
self.assertEqual(Binary.to_fraction("1.1"), Fraction(1.5))
self.assertEqual(Binary.to_fraction("1.1"), Fraction(1.5))
self.assertEqual(Binary.to_fraction("-1"), Fraction(-1))
self.assertEqual(Binary.to_fraction("-0.1"), Fraction(-0.5))
self.assertEqual(Binary.to_fraction("-1.1"), Fraction(-1.5))
self.assertEqual(Binary.to_fraction("-1.1e2"), Fraction(-6))
self.assertEqual(Binary.to_fraction("-1.1e0"), Fraction(-1.5))
self.assertEqual(Binary.to_fraction("1.1e-3"), Fraction(3, 16))
self.assertEqual(Binary.to_fraction("-1.1e-3"), Fraction(-3, 16))
self.assertEqual(Binary.to_fraction("0"), Fraction(0))
self.assertEqual(Binary.to_fraction("1"), Fraction(1))
self.assertEqual(Binary.to_fraction("-0"), Fraction(0))
self.assertEqual(Binary.to_fraction("-1"), Fraction(-1))
self.assertEqual(Binary.to_fraction("11"), Fraction(3))
self.assertEqual(Binary.to_fraction("-0.0"), Fraction(0))
self.assertEqual(Binary.to_fraction("1.0"), Fraction(1))
self.assertEqual(Binary.to_fraction("1.1"), Fraction(3, 2))
self.assertEqual(Binary.to_fraction("-1.1"), Fraction(3, -2))
self.assertEqual(Binary.to_fraction("-0.111"), Fraction(-0.875))
self.assertEqual(
Binary.to_fraction("1.1" + "0" * 2 + "1"), Fraction(3 * 2 ** 3 + 1, 2 ** 4)
)
self.assertEqual(
Binary.to_fraction("1.1" + "0" * 100 + "1"),
Fraction(3 * 2 ** 101 + 1, 2 ** 102),
)
self.assertEqual(
Binary.to_fraction("1.1" + "0" * 1000 + "1"),
Fraction(3 * 2 ** 1001 + 1, 2 ** 1002),
)
self.assertEqual(Binary.to_fraction(Binary("-0.111")), Fraction(-0.875))
with self.assertRaises(ValueError):
Binary.to_fraction("102") # should fail
with self.assertRaises(TypeError):
Binary.to_fraction(1) # should fail
def test___round__(self):
"""Test function/method for rounding."""
self.assertIsInstance(round(Binary(3.75), 1), Binary)
self.assertEqual(round(Binary(3.75), 1), "11.1")
self.assertEqual(round(Binary(3.75), 1), "11.1")
self.assertEqual(round(Binary(3.75001), 1), "100.0")
self.assertEqual(round(Binary(3.75), 2), "11.11")
self.assertEqual(round(Binary(3.75001), 2), "11.11")
self.assertEqual(round(Binary(-3.75), 1), "-11.1")
self.assertEqual(round(Binary(-3.75001), 1), "-100.0")
self.assertEqual(round(Binary(-3.75), 2), "-11.11")
self.assertEqual(round(Binary(-3.75001), 2), "-11.11")
self.assertEqual(round(Binary("0.1")), "0")
self.assertEqual(round(Binary("0.10000001"), 0), "1")
with self.assertRaises(ValueError):
round(Binary("0.1"), -1) # should fail
with self.assertRaises(TypeError):
round(Binary("0.1"), "0") # should fail
with self.assertRaises(TypeError):
round(Binary("0.1"), 1, True) # should fail
def test_round(self):
"""Test function/method for rounding."""
self.assertIsInstance(Binary(3.75).round(1), Binary)
self.assertEqual(Binary(3.75).round(1), "11.1")
self.assertEqual(Binary(3.75001).round(1), "100.0")
self.assertEqual(Binary(3.75).round(2), "11.11")
self.assertEqual(Binary(3.75001).round(2), "11.11")
self.assertEqual(Binary(-3.75).round(1), "-11.1")
self.assertEqual(Binary(-3.75001).round(1), "-100.0")
self.assertEqual(Binary(-3.75).round(2), "-11.11")
self.assertEqual(Binary(-3.75001).round(2), "-11.11")
self.assertEqual(Binary("0.1").round(), "0")
self.assertEqual(Binary("0.10000001").round(0), "1")
self.assertEqual(Binary("001.0000").round(3, simplify=False), "001.000")
self.assertEqual(Binary("000.1111").round(3, simplify=False), "000.111")
self.assertEqual(Binary("000.111111").round(3, simplify=False), "1")
with self.assertRaises(ValueError):
Binary("0.1").round(-1) # should fail
with self.assertRaises(TypeError):
Binary("0.1").round("0") # should fail
def test_round_to(self):
"""Test function/method for rounding."""
self.assertEqual(Binary.round_to("11.01e-99", 2), "0")
self.assertEqual(Binary.round_to("11.01e+9", 2), "11010000000")
self.assertEqual(Binary.round_to("11.01e-2", 2), "0.11")
self.assertEqual(Binary.round_to("0.1", 0), "0")
self.assertEqual(Binary.round_to("0.10000001", 0), "1")
self.assertEqual(Binary.round_to("001.0000", 3, simplify=False), "001.000")
self.assertEqual(Binary.round_to("000.1111", 3, simplify=False), "000.111")
with self.assertRaises(TypeError):
Binary.round_to(Binary(1), 0) # should fail
with self.assertRaises(TypeError):
Binary.round_to("1", 0.0) # should fail
with self.assertRaises(ValueError):
Binary.round_to("111", -2) # should fail
with self.assertRaises(ValueError):
Binary.round_to("nan", 2) # should fail
with self.assertRaises(OverflowError):
Binary.round_to("Inf", 2) # should fail
with self.assertRaises(OverflowError):
Binary.round_to("-Inf", 0) # should fail
def test_lfill(self):
"""Test function/method."""
self.assertIsInstance(Binary(1).lfill(1), Binary)
self.assertIsInstance(Binary.lfill_to("1", 1), str)
self.assertEqual(Binary("1.1111").lfill(0), "1.1111")
self.assertEqual(Binary("1").lfill(0, strict=True), "0")
self.assertEqual(Binary("1010").lfill(0, strict=True), "0")
self.assertEqual(Binary("1010").lfill(1, strict=True), "0")
self.assertEqual(Binary("1010").lfill(2, strict=True), "10")
self.assertEqual(Binary("1010").lfill(3, strict=True), "010")
self.assertEqual(Binary("1010").lfill(4, strict=True), "1010")
self.assertEqual(Binary("1010").lfill(5, strict=True), "01010")
self.assertEqual(Binary("1010").lfill(6, strict=True), "001010")
self.assertEqual(Binary("1010").lfill(0, strict=False), "1010")
self.assertEqual(Binary("1010").lfill(1, strict=False), "1010")
self.assertEqual(Binary("1010").lfill(2, strict=False), "1010")
self.assertEqual(Binary("1010").lfill(3, strict=False), "1010")
self.assertEqual(Binary("1010").lfill(4, strict=False), "1010")
self.assertEqual(Binary("1010").lfill(5, strict=False), "01010")
self.assertEqual(Binary("1010").lfill(6, strict=False), "001010")
self.assertEqual(Binary("10.10e2").lfill(0, strict=False), "1010")
self.assertEqual(Binary("10.10e2").lfill(1, strict=False), "1010")
self.assertEqual(Binary("10.10e2").lfill(2, strict=False), "1010")
self.assertEqual(Binary("10.10e2").lfill(3, strict=False), "1010")
self.assertEqual(Binary("10.10e2").lfill(4, strict=False), "1010")
self.assertEqual(Binary("10.10e2").lfill(5, strict=False), "01010")
self.assertEqual(Binary("10.10e2").lfill(6, strict=False), "001010")
self.assertEqual(Binary("10.10e-1").lfill(0, strict=False), "1.01")
self.assertEqual(Binary("10.10e-1").lfill(1, strict=False), "1.01")
self.assertEqual(Binary("10.10e-1").lfill(2, strict=False), "01.01")
self.assertEqual(Binary("10.10e-1").lfill(3, strict=False), "001.01")
self.assertEqual(Binary("10.10e-1").lfill(4, strict=False), "0001.01")
self.assertEqual(Binary("10.10e-1").lfill(5, strict=False), "00001.01")
self.assertEqual(Binary("10.10e-1").lfill(6, strict=False), "000001.01")
self.assertEqual(Binary("10.10e-1").lfill(0, strict=True), "0.01")
self.assertEqual(Binary("10.10e-1").lfill(1, strict=True), "1.01")
self.assertEqual(Binary("10.10e-1").lfill(2, strict=True), "01.01")
self.assertEqual(Binary("10.10e-1").lfill(3, strict=True), "001.01")
self.assertEqual(Binary("10.10e-1").lfill(4, strict=True), "0001.01")
self.assertEqual(Binary("10.10e-1").lfill(5, strict=True), "00001.01")
self.assertEqual(Binary("10.10e-1").lfill(6, strict=True), "000001.01")
self.assertEqual(Binary("1.1111").lfill(0, strict=True), "0.1111")
self.assertEqual(Binary("1.1111").lfill(1), "1.1111")
self.assertEqual(Binary("1.1111").lfill(4), "0001.1111")
self.assertEqual(Binary("1.1111").lfill(5), "00001.1111")
self.assertEqual(Binary("1.1111").lfill(6), "000001.1111")
self.assertEqual(Binary("111111.1111").lfill(0, True), "0.1111")
self.assertEqual(Binary("111111.1111").lfill(1, True), "1.1111")
self.assertEqual(Binary("111111.1111").lfill(4, True), "1111.1111")
self.assertEqual(Binary("111111.1111").lfill(5, True), "11111.1111")
self.assertEqual(Binary("111111.1111").lfill(6, True), "111111.1111")
self.assertEqual(Binary("111111.0011").lfill(1, True), "1.0011")
self.assertEqual(Binary("0.01e1").lfill(4).rfill(4).string, "0000.1000")
self.assertEqual(Binary("0.01e1").rfill(4).lfill(4).string, "0000.1000")
self.assertEqual(Binary("0.01").lfill(4).rfill(4).string, "0000.0100")
self.assertEqual(Binary("0.01").rfill(4).lfill(4).string, "0000.0100")
with self.assertRaises(TypeError):
Binary.lfill(1, "1") # should fail
with self.assertRaises(ValueError):
Binary(1).lfill(-1) # should fail
def test_lfill_to(self):
"""Test function/method."""
self.assertIsInstance(Binary.lfill_to("1", 1), str)
self.assertEqual(Binary.lfill_to("1.1111", 0), "1.1111")
self.assertEqual(Binary.lfill_to("1", 0, strict=True), "0")
self.assertEqual(Binary.lfill_to("1010", 0, strict=True), "0")
self.assertEqual(Binary.lfill_to("1010", 1, strict=True), "0")
self.assertEqual(Binary.lfill_to("1010", 2, strict=True), "10")
self.assertEqual(Binary.lfill_to("1010", 3, strict=True), "010")
self.assertEqual(Binary.lfill_to("1010", 4, strict=True), "1010")
self.assertEqual(Binary.lfill_to("1010", 5, strict=True), "01010")
self.assertEqual(Binary.lfill_to("1010", 6, strict=True), "001010")
self.assertEqual(Binary.lfill_to("1010", 0, strict=False), "1010")
self.assertEqual(Binary.lfill_to("1010", 1, strict=False), "1010")
self.assertEqual(Binary.lfill_to("1010", 2, strict=False), "1010")
self.assertEqual(Binary.lfill_to("1010", 3, strict=False), "1010")
self.assertEqual(Binary.lfill_to("1010", 4, strict=False), "1010")
self.assertEqual(Binary.lfill_to("1010", 5, strict=False), "01010")
self.assertEqual(Binary.lfill_to("1010", 6, strict=False), "001010")
self.assertEqual(Binary.lfill_to("10.10e2", 0, strict=False), "1010")
self.assertEqual(Binary.lfill_to("10.10e2", 1, strict=False), "1010")
self.assertEqual(Binary.lfill_to("10.10e2", 2, strict=False), "1010")
self.assertEqual(Binary.lfill_to("10.10e2", 3, strict=False), "1010")
self.assertEqual(Binary.lfill_to("10.10e2", 4, strict=False), "1010")
self.assertEqual(Binary.lfill_to("10.10e2", 5, strict=False), "01010")
self.assertEqual(Binary.lfill_to("10.10e2", 6, strict=False), "001010")
self.assertEqual(Binary.lfill_to("10.10e-1", 0, strict=False), "1.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 1, strict=False), "1.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 2, strict=False), "01.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 3, strict=False), "001.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 4, strict=False), "0001.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 5, strict=False), "00001.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 6, strict=False), "000001.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 0, strict=True), "0.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 1, strict=True), "1.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 2, strict=True), "01.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 3, strict=True), "001.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 4, strict=True), "0001.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 5, strict=True), "00001.010")
self.assertEqual(Binary.lfill_to("10.10e-1", 6, strict=True), "000001.010")
self.assertEqual(Binary.lfill_to("1.1111", 0, strict=True), "0.1111")
self.assertEqual(Binary.lfill_to("1.1111", 1), "1.1111")
self.assertEqual(Binary.lfill_to("1.1111", 4), "0001.1111")
self.assertEqual(Binary.lfill_to("1.1111", 5), "00001.1111")
self.assertEqual(Binary.lfill_to("1.1111", 6), "000001.1111")
self.assertEqual(Binary.lfill_to("111111.1111", 0, True), "0.1111")
self.assertEqual(Binary.lfill_to("111111.1111", 1, True), "1.1111")
self.assertEqual(Binary.lfill_to("111111.1111", 4, True), "1111.1111")
self.assertEqual(Binary.lfill_to("111111.1111", 5, True), "11111.1111")
self.assertEqual(Binary.lfill_to("111111.1111", 6, True), "111111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 0, True), "-0.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 1, True), "-1.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 4, True), "-1111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 5, True), "-11111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 6, True), "-111111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 7, True), "-0111111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 8, True), "-00111111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 0, False), "-111111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 1, False), "-111111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 4, False), "-111111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 5, False), "-111111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 6, False), "-111111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 7, False), "-0111111.1111")
self.assertEqual(Binary.lfill_to("-111111.1111", 8, False), "-00111111.1111")
self.assertEqual(Binary.lfill_to("111111.0011", 1, True), "1.0011")
with self.assertRaises(TypeError):
Binary.lfill_to(1, "1") # should fail
with self.assertRaises(ValueError):
Binary.lfill_to("1", -1) # should fail
with self.assertRaises(OverflowError):
Binary.lfill_to("-Inf") # should fail
def test_rfill(self):
"""Test function/method."""
self.assertIsInstance(Binary(1).rfill(1), Binary)
self.assertIsInstance(Binary.rfill_to("1", 1), str)
self.assertEqual(Binary("1.1111").rfill(1), "1.1111")
self.assertEqual(Binary("1.1111").rfill(4), "1.1111")
self.assertEqual(Binary("1.1111").rfill(5), "1.11110")
self.assertEqual(Binary("1.1111").rfill(6), "1.111100")
self.assertEqual(Binary("1.1111").rfill(1, True), "10.0")
self.assertEqual(Binary("1.1111").rfill(4, True), "1.1111")
self.assertEqual(Binary("1.1111").rfill(5, True), "1.11110")
self.assertEqual(Binary("1.1111").rfill(6, True), "1.111100")
self.assertEqual(Binary("1.0011").rfill(1, True), "1.0")
self.assertEqual(Binary(1.25).rfill(8), "1.01000000")
self.assertEqual(Binary(-1.25).rfill(8), "-1.01000000")
with self.assertRaises(TypeError):
Binary.rfill(1, "1") # should fail
with self.assertRaises(ValueError):
Binary(1).rfill(-1) # should fail
def test_rfill_to(self):
"""Test function/method."""
self.assertIsInstance(Binary.rfill_to("1", 1), str)
self.assertEqual(Binary.rfill_to("1.1111", 1), "1.1111")
self.assertEqual(Binary.rfill_to("1.1111", 4), "1.1111")
self.assertEqual(Binary.rfill_to("1.1111", 5), "1.11110")
self.assertEqual(Binary.rfill_to("1.1111", 6), "1.111100")
self.assertEqual(Binary.rfill_to("1.1111", 1, True), "10.0")
self.assertEqual(Binary.rfill_to("1.1111", 4, True), "1.1111")
self.assertEqual(Binary.rfill_to("1.1111", 5, True), "1.11110")
self.assertEqual(Binary.rfill_to("1.1111", 6, True), "1.111100")
self.assertEqual(Binary.rfill_to("-1.1111", 1, True), "-10.0")
self.assertEqual(Binary.rfill_to("-1.1111", 4, True), "-1.1111")
self.assertEqual(Binary.rfill_to("-1.1111", 5, True), "-1.11110")
self.assertEqual(Binary.rfill_to("-1.1111", 6, True), "-1.111100")
self.assertEqual(Binary.rfill_to("1.0011", 1, True), "1.0")
self.assertEqual(Binary.rfill_to("1.01", 8), "1.01000000")
self.assertEqual(Binary.rfill_to("-1.01", 8), "-1.01000000")
with self.assertRaises(TypeError):
Binary.rfill_to(1, "1") # should fail
with self.assertRaises(ValueError):
Binary.rfill_to("1", -1) # should fail
with self.assertRaises(OverflowError):
Binary.rfill_to("-Inf") # should fail
def test_to_no_mantissa(self):
"""Test function/method."""
self.assertEqual(
Binary("-11").to_no_mantissa().compare_representation("-11e0"), True
)
self.assertEqual(
Binary("-11e-0").to_no_mantissa().compare_representation("-11e0"), True
)
self.assertEqual(
Binary("-11e+0").to_no_mantissa().compare_representation("-11e0"), True
)
self.assertEqual(
Binary("+11").to_no_mantissa().compare_representation("11e0"), True
)
self.assertEqual(
Binary("1.1").to_no_mantissa().compare_representation("11e-1"), True
)
self.assertEqual(
Binary("-0.01e-2").to_no_mantissa().compare_representation("-1e-4"), True
)
self.assertEqual(
Binary("-1.1").to_no_mantissa().compare_representation("-11e-1"), True
)
self.assertEqual(
Binary("-1.1e-1").to_no_mantissa().compare_representation("-11e-2"), True
)
self.assertEqual(
Binary("+1.1e-1").to_no_mantissa().compare_representation("11e-2"), True
)
self.assertEqual(
Binary("+1.1000e-1").to_no_mantissa().compare_representation("11e-2"), True
)
self.assertEqual(
Binary("+0001.1000e-1").to_no_mantissa().compare_representation("11e-2"),
True,
)
self.assertEqual(
Binary("+0001.1000e+1").to_no_mantissa().compare_representation("11e0"),
True,
)
self.assertEqual(
Binary("+0001.1000e+10").to_no_mantissa().compare_representation("11e9"),
True,
)
with self.assertRaises(TypeError):
Binary(1).to_no_mantissa(1) # should fail
with self.assertRaises(OverflowError):
Binary("Nan").to_no_mantissa() # should fail
def test_to_exponent(self):
"""Test function/method."""
self.assertIsInstance(Binary("1").to_exponent(), Binary)
self.assertIsInstance(Binary("1").to_exponent(-2), Binary)
self.assertEqual(str(Binary("1.1").to_exponent(3)), "0b0.0011e3")
self.assertEqual(str(Binary("1.1").to_exponent(-3)), "0b1100e-3")
self.assertEqual(str(Binary("-0.01e-2").to_exponent(-6)), "-0b100e-6")
self.assertEqual(str(Binary("-0.01e-2").to_exponent(-5)), "-0b10e-5")
self.assertEqual(str(Binary("-0.01e-2").to_exponent(-4)), "-0b1e-4")
self.assertEqual(str(Binary("-0.01e-2").to_exponent(-3)), "-0b0.1e-3")
self.assertEqual(str(Binary("-0.01e-2").to_exponent(-2)), "-0b0.01e-2")
self.assertEqual(str(Binary("-0.01e-2").to_exponent(-1)), "-0b0.001e-1")
self.assertEqual(str(Binary("-0.01e-2").to_exponent(0)), "-0b0.0001")
self.assertEqual(str(Binary("-0.01e-2").to_exponent(1)), "-0b0.00001e1")
self.assertEqual(str(Binary("-0.01e-2").to_exponent(2)), "-0b0.000001e2")
self.assertEqual(str(Binary("-0.01e-2").to_exponent(3)), "-0b0.0000001e3")
self.assertEqual(str(Binary("0.01e-2").to_exponent(-6)), "0b100e-6")
self.assertEqual(str(Binary("0.01e-2").to_exponent(-5)), "0b10e-5")
self.assertEqual(str(Binary("0.01e-2").to_exponent(-4)), "0b1e-4")
self.assertEqual(str(Binary("0.01e-2").to_exponent(-3)), "0b0.1e-3")
self.assertEqual(str(Binary("0.01e-2").to_exponent(-2)), "0b0.01e-2")
self.assertEqual(str(Binary("0.01e-2").to_exponent(-1)), "0b0.001e-1")
self.assertEqual(str(Binary("0.01e-2").to_exponent(0)), "0b0.0001")
self.assertEqual(str(Binary("0.01e-2").to_exponent(1)), "0b0.00001e1")
self.assertEqual(str(Binary("0.01e-2").to_exponent(2)), "0b0.000001e2")
self.assertEqual(str(Binary("0.01e-2").to_exponent(3)), "0b0.0000001e3")
self.assertEqual(str(Binary("+0.01e-2").to_exponent(3)), "0b0.0000001e3")
with self.assertRaises(TypeError):
Binary(1).to_exponent("1") # should fail
with self.assertRaises(OverflowError):
Binary("Nan").to_exponent() # should fail
def test_to_sci_exponent(self):
"""Test function/method."""
self.assertIsInstance(Binary("1").to_sci_exponent(), Binary)
self.assertEqual(
Binary("101e2").to_sci_exponent().compare_representation("1.01e4"), True
)
self.assertEqual(str(Binary("1.1").to_sci_exponent()), "0b1.1e0")
self.assertEqual(
Binary("-000101e002").to_sci_exponent().compare_representation("-1.01e4"),
True,
)
self.assertEqual(
Binary("-001.100").to_sci_exponent().compare_representation("-1.1e0"), True
)
self.assertEqual(
Binary("-0.01e-2").to_sci_exponent().compare_representation("-1e-4"), True
)
self.assertEqual(
Binary("-0.00001e-2").to_sci_exponent().compare_representation("-1e-7"),
True,
)
self.assertEqual(
Binary("+0.00001e+2").to_sci_exponent().compare_representation("1e-3"), True
)
self.assertEqual(
Binary("-0.00001010e-2")
.to_sci_exponent()
.compare_representation("-1.01e-7"),
True,
)
self.assertEqual(
Binary("-0.00001010e+2")
.to_sci_exponent()
.compare_representation("-1.01e-3"),
True,
)
with self.assertRaises(TypeError):
Binary(1).to_sci_exponent(1) # should fail
with self.assertRaises(OverflowError):
Binary("Nan").to_sci_exponent() # should fail
def test_to_eng_exponent(self):
"""Test function/method."""
self.assertIsInstance(Binary("1").to_eng_exponent(), Binary)
for ii in range(-1023, 1023, 1):
if ii < 0:
self.assertEqual(Binary(ii).to_eng_exponent(), "-" + bin(ii)[3:])
else:
self.assertEqual(Binary(ii).to_eng_exponent(), bin(ii)[2:])
self.assertEqual(
Binary(1023).to_eng_exponent().compare_representation("1111111111"), True
)
self.assertEqual(
Binary(1024).to_eng_exponent().compare_representation("1e10"), True
)
self.assertEqual(
Binary(1025).to_eng_exponent().compare_representation("1.0000000001e10"),
True,
)
self.assertEqual(
Binary(3072).to_eng_exponent().compare_representation("11e10"), True
)
self.assertEqual(
Binary(1024 ** 2).to_eng_exponent().compare_representation("1e20"), True
)
self.assertEqual(str(Binary(".11111e1").to_eng_exponent()), "0b1.1111")
self.assertEqual(
Binary(".01111e2").to_eng_exponent().compare_representation("1.111"), True
)
self.assertEqual(
Binary(".0011111e3").to_eng_exponent().compare_representation("1.1111"),
True,
)
self.assertEqual(
Binary("0.1").to_eng_exponent().compare_representation("1000000000e-10"),
True,
)
self.assertEqual(
Binary("0.11").to_eng_exponent().compare_representation("1100000000e-10"),
True,
)
self.assertEqual(
Binary("0.01").to_eng_exponent().compare_representation("100000000e-10"),
True,
)
self.assertEqual(
Binary("0.0000000001").to_eng_exponent().compare_representation("1e-10"),
True,
)
self.assertEqual(
Binary("0.000000001").to_eng_exponent().compare_representation("10e-10"),
True,
)
self.assertEqual(
Binary("0.00000000111")
.to_eng_exponent()
.compare_representation("11.1e-10"),
True,
)
self.assertEqual(
Binary(".11111e1").to_eng_exponent().compare_representation("1.1111"), True
)
self.assertEqual(
Binary(".011111e2").to_eng_exponent().compare_representation("1.1111"), True
)
self.assertEqual(
Binary(".0011111e3").to_eng_exponent().compare_representation("1.1111"),
True,
)
self.assertEqual(
Binary("-0.01e-2").to_eng_exponent().compare_representation("-1000000e-10"),
True,
)
self.assertEqual(
Binary("-0.0001e-4").to_eng_exponent().compare_representation("-100e-10"),
True,
)
self.assertEqual(
Binary("-0.0001111e-4")
.to_eng_exponent()
.compare_representation("-111.1e-10"),
True,
)
self.assertEqual(
Binary("-0.01e-2").to_eng_exponent().compare_representation("-1000000e-10"),
True,
)
self.assertEqual(
Binary("-0.0001e-4").to_eng_exponent().compare_representation("-100e-10"),
True,
)
self.assertEqual(
Binary("-0.0001111e-4")
.to_eng_exponent()
.compare_representation("-111.1e-10"),
True,
)
self.assertEqual(
Binary("101e2").to_eng_exponent().compare_representation("10100"), True
)
self.assertEqual(
Binary("1.1").to_eng_exponent().compare_representation("1.1"), True
)
self.assertEqual(
Binary("100_000_000").to_eng_exponent().compare_representation("100000000"),
True,
)
self.assertEqual(
Binary("1_000_000_000")
.to_eng_exponent()
.compare_representation("1000000000"),
True,
)
self.assertEqual(
Binary("10_000_000_000").to_eng_exponent().compare_representation("1e10"),
True,
)
self.assertEqual(
Binary("-100_000_000")
.to_eng_exponent()
.compare_representation("-100000000"),
True,
)
self.assertEqual(
Binary("-1_000_000_000")
.to_eng_exponent()
.compare_representation("-1000000000"),
True,
)
self.assertEqual(
Binary("-10_000_000_000").to_eng_exponent().compare_representation("-1e10"),
True,
)
self.assertEqual(
Binary("-001.100").to_eng_exponent().compare_representation("-1.1"), True
)
self.assertEqual(
Binary("-0.01e-2").to_eng_exponent().compare_representation("-1000000e-10"),
True,
)
self.assertEqual(
Binary("-0.00001e-2").to_eng_exponent().compare_representation("-1000e-10"),
True,
)
self.assertEqual(
Binary("+0.00001e+2")
.to_eng_exponent()
.compare_representation("10000000e-10"),
True,
)
self.assertEqual(
Binary("-0.00001010e-2")
.to_eng_exponent()
.compare_representation("-1010e-10"),
True,
)
self.assertEqual(
Binary("-0.00001010e+2")
.to_eng_exponent()
.compare_representation("-10100000e-10"),
True,
)
self.assertEqual(
Binary("1.1").to_eng_exponent().compare_representation("1.1"), True
)
self.assertEqual(
Binary("1.1111").to_eng_exponent().compare_representation("1.1111"), True
)
self.assertEqual(
Binary("100.1111").to_eng_exponent().compare_representation("100.1111"),
True,
)
self.assertEqual(
Binary("1000.1111").to_eng_exponent().compare_representation("1000.1111"),
True,
)
self.assertEqual(
Binary("1").to_eng_exponent().compare_representation("1"), True
)
self.assertEqual(
Binary("10").to_eng_exponent().compare_representation("10"), True
)
self.assertEqual(
Binary("100").to_eng_exponent().compare_representation("100"), True
)
self.assertEqual(
Binary("1000").to_eng_exponent().compare_representation("1000"), True
)
self.assertEqual(
Binary("10000").to_eng_exponent().compare_representation("10000"), True
)
self.assertEqual(
Binary("100000").to_eng_exponent().compare_representation("100000"), True
)
self.assertEqual(
Binary("1000000").to_eng_exponent().compare_representation("1000000"), True
)
self.assertEqual(
Binary("1_000_000_000")
.to_eng_exponent()
.compare_representation("1000000000"),
True,
)
self.assertEqual(
Binary("10_000_000_000").to_eng_exponent().compare_representation("1e10"),
True,
)
self.assertEqual(
Binary("10_000_000_001.101")
.to_eng_exponent()
.compare_representation("1.0000000001101e10"),
True,
)
self.assertEqual(
Binary("1010_000_000_001.101")
.to_eng_exponent()
.compare_representation("101.0000000001101e10"),
True,
)
self.assertEqual(
str(Binary("1010_000_000_001.10101010101010101").to_eng_exponent()),
"0b101.000000000110101010101010101e10",
)
self.assertEqual(
str(
Binary(
"1010_000_000_001.1010101010101010110101010101010101"
).to_eng_exponent()
),
"0b101.00000000011010101010101010110101010101010101e10",
)
self.assertEqual(
str(
Binary(
"1_010_001_010_000_000_001.1010101010101010110101010101010101"
).to_eng_exponent()
),
"0b101000101.00000000011010101010101010110101010101010101e10",
)
self.assertEqual(
str(
Binary(
"11_010_001_010_000_000_001.1010101010101010110101010101010101"
).to_eng_exponent()
),
"0b1101000101.00000000011010101010101010110101010101010101e10",
)
self.assertEqual(
str(
Binary(
"111_010_001_010_000_000_001.1010101010101010110101010101010101"
).to_eng_exponent()
),
"0b1.110100010100000000011010101010101010110101010101010101e20",
)
self.assertEqual(
Binary("100000.1111")
.to_eng_exponent()
.compare_representation("100000.1111"),
True,
)
self.assertEqual(
Binary("1000000.1111")
.to_eng_exponent()
.compare_representation("1000000.1111"),
True,
)
self.assertEqual(
Binary("1.1111e0").to_eng_exponent().compare_representation("1.1111"), True
)
self.assertEqual(
Binary("11.111e-1").to_eng_exponent().compare_representation("1.1111"), True
)
self.assertEqual(
Binary("111.11e-2").to_eng_exponent().compare_representation("1.1111"), True
)
self.assertEqual(
Binary("1111.1e-3").to_eng_exponent().compare_representation("1.1111"), True
)
self.assertEqual(
Binary("11111.e-4").to_eng_exponent().compare_representation("1.1111"), True
)
self.assertEqual(
Binary(".11111e1").to_eng_exponent().compare_representation("1.1111"), True
)
self.assertEqual(
Binary(".011111e2").to_eng_exponent().compare_representation("1.1111"), True
)
self.assertEqual(
Binary(".0011111e3").to_eng_exponent().compare_representation("1.1111"),
True,
)
self.assertEqual(
Binary("-0.01e-2").to_eng_exponent().compare_representation("-1000000e-10"),
True,
)
self.assertEqual(
Binary("-0.0001e-4").to_eng_exponent().compare_representation("-100e-10"),
True,
)
self.assertEqual(
Binary("-0.0001111e-4")
.to_eng_exponent()
.compare_representation("-111.1e-10"),
True,
)
with self.assertRaises(TypeError):
Binary(1).to_eng_exponent(1) # should fail
with self.assertRaises(OverflowError):
Binary("Nan").to_eng_exponent() # should fail
def test_get_components(self):
"""Test function/method."""
self.assertEqual(Binary.get_components("-0.01e-2"), (1, "0", "01", -2))
self.assertEqual(Binary.get_components("+0.01e-2"), (0, "0", "01", -2))
self.assertEqual(Binary.get_components(".01e-2"), (0, "0", "01", -2))
self.assertEqual(Binary.get_components("1.00e-2"), (0, "1", "", -2))
self.assertEqual(Binary.get_components("-0.01e+2"), (1, "0", "01", 2))
self.assertEqual(Binary.get_components("+0.01e2"), (0, "0", "01", 2))
self.assertEqual(Binary.get_components("-101010.e+2"), (1, "101010", "", 2))
self.assertEqual(Binary.get_components("+101010e2"), (0, "101010", "", 2))
with self.assertRaises(ValueError):
Binary.get_components("inf") # should fail
with self.assertRaises(TypeError):
Binary.get_components(0.0) # should fail
with self.assertRaises(TypeError):
Binary.get_components(Binary(1)) # should fail
def test_components(self):
"""Test function/method."""
self.assertEqual(Binary("-0.01e-2").components(), (1, "0", "01", -2))
self.assertEqual(Binary("+0.01e-2").components(), (0, "0", "01", -2))
self.assertEqual(Binary(".01e-2").components(), (0, "0", "01", -2))
self.assertEqual(Binary("1.00e-2").components(), (0, "1", "", -2))
self.assertEqual(Binary("-0.01e+2").components(), (1, "0", "01", 2))
self.assertEqual(Binary("+0.01e2").components(), (0, "0", "01", 2))
self.assertEqual(Binary("-101010.e+2").components(), (1, "101010", "", 2))
self.assertEqual(Binary("+101010e2").components(), (0, "101010", "", 2))
with self.assertRaises(ValueError):
Binary("inf").components() # should fail
with self.assertRaises(TypeError):
Binary.components() # should fail
with self.assertRaises(TypeError):
Binary.components("1") # should fail
def test_isinfinity(self):
"""Test function/method."""
self.assertEqual(Binary(-3.5).isinfinity(), False)
self.assertEqual(Binary(float("nan")).isinfinity(), False)
self.assertEqual(Binary("Nan").isinfinity(), False)
self.assertEqual(Binary(float("-inf")).isinfinity(), True)
self.assertEqual(Binary("-inf").isinfinity(), True)
self.assertEqual(Binary(float("inf")).isinfinity(), True)
self.assertEqual(Binary("inf").isinfinity(), True)
self.assertEqual(Binary("10.1").isinfinity(), False)
def test_isnegativeinfinity(self):
"""Test function/method."""
self.assertEqual(Binary(-3.5).isnegativeinfinity(), False)
self.assertEqual(Binary(float("nan")).isnegativeinfinity(), False)
self.assertEqual(Binary("Nan").isnegativeinfinity(), False)
self.assertEqual(Binary(float("-inf")).isnegativeinfinity(), True)
self.assertEqual(Binary("-inf").isnegativeinfinity(), True)
self.assertEqual(Binary(float("inf")).isnegativeinfinity(), False)
self.assertEqual(Binary("inf").isnegativeinfinity(), False)
self.assertEqual(Binary("10.1").isnegativeinfinity(), False)
def test_ispositiveinfinity(self):
"""Test function/method."""
self.assertEqual(Binary(-3.5).ispositiveinfinity(), False)
self.assertEqual(Binary(float("nan")).ispositiveinfinity(), False)
self.assertEqual(Binary("Nan").ispositiveinfinity(), False)
self.assertEqual(Binary(float("-inf")).ispositiveinfinity(), False)
self.assertEqual(Binary("-inf").ispositiveinfinity(), False)
self.assertEqual(Binary(float("inf")).ispositiveinfinity(), True)
self.assertEqual(Binary("inf").ispositiveinfinity(), True)
self.assertEqual(Binary("10.1").ispositiveinfinity(), False)
def test_isnan(self):
"""Test function/method."""
self.assertEqual(Binary(-3.5).isnan(), False)
self.assertEqual(Binary(float("nan")).isnan(), True)
self.assertEqual(Binary("Nan").isnan(), True)
self.assertEqual(Binary("10.1").isnan(), False)
def test_isint(self):
"""Test function/method."""
self.assertEqual(Binary(-3).isint(), True)
self.assertEqual(Binary(-3.0).isint(), True)
self.assertEqual(Binary(+3).isint(), True)
self.assertEqual(Binary(+3.0).isint(), True)
self.assertEqual(Binary("-11").isint(), True)
self.assertEqual(Binary("11").isint(), True)
self.assertEqual(Binary("-11.0").isint(), True)
self.assertEqual(Binary("11.00").isint(), True)
self.assertEqual(Binary("-0b11").isint(), True)
self.assertEqual(Binary("0b11").isint(), True)
self.assertEqual(Binary("-11.1").isint(), False)
self.assertEqual(Binary("11.1").isint(), False)
self.assertEqual(Binary("-11.1e-2").isint(), False)
self.assertEqual(Binary("11.1e2").isint(), True)
self.assertEqual(Binary(-3.5).isint(), False)
self.assertEqual(Binary(float("inf")).isint(), False)
self.assertEqual(Binary("-inf").isint(), False)
self.assertEqual(Binary(float("nan")).isint(), False)
self.assertEqual(Binary("Nan").isint(), False)
self.assertEqual(Binary("10.1").isint(), False)
def test_fraction(self):
"""Test function/method."""
self.assertEqual(isinstance(Binary(0).fraction, Fraction), True)
self.assertEqual(isinstance(Binary("0").fraction, Fraction), True)
self.assertEqual(Binary(0).fraction, Fraction(0))
self.assertEqual(Binary(1).fraction, Fraction(1))
self.assertEqual(Binary(1.5).fraction, Fraction(1.5))
with self.assertRaises(TypeError): # property is not callable
Binary.fraction(Binary(1.5))
with self.assertRaises(AttributeError): # property is not callable
Binary(1.5).fraction = 1
def test_string(self):
"""Test function/method."""
self.assertEqual(isinstance(Binary(0).string, str), True)
self.assertEqual(isinstance(Binary("0").string, str), True)
self.assertEqual(Binary(0).string, "0")
self.assertEqual(Binary(1).string, "1")
self.assertEqual(Binary(1.5).string, "1.1")
with self.assertRaises(TypeError): # property is not callable
Binary.string(Binary(1.5))
with self.assertRaises(AttributeError): # property is not callable
Binary(1.5).string = "123"
def test_fraction_to_string(self):
"""Test function/method."""
self.assertEqual(Binary.fraction_to_string(0), "0")
self.assertEqual(Binary.fraction_to_string(1), "1")
self.assertEqual(Binary.fraction_to_string(2), "10")
self.assertEqual(Binary.fraction_to_string(13), "1101")
self.assertEqual(Binary.fraction_to_string(-0), "0")
self.assertEqual(Binary.fraction_to_string(-1), "-1")
self.assertEqual(Binary.fraction_to_string(-2), "-10")
self.assertEqual(Binary.fraction_to_string(-13), "-1101")
self.assertEqual(Binary.fraction_to_string(0.0), "0")
self.assertEqual(Binary.fraction_to_string(1.0), "1")
self.assertEqual(Binary.fraction_to_string(2.0), "10")
self.assertEqual(Binary.fraction_to_string(13.0), "1101")
self.assertEqual(Binary.fraction_to_string(-0.0), "0")
self.assertEqual(Binary.fraction_to_string(-1.0), "-1")
self.assertEqual(Binary.fraction_to_string(-2.0), "-10")
self.assertEqual(Binary.fraction_to_string(-13.0), "-1101")
self.assertEqual(Binary.fraction_to_string(Fraction(0.0)), "0")
self.assertEqual(Binary.fraction_to_string(Fraction(1.0)), "1")
self.assertEqual(Binary.fraction_to_string(Fraction(2.0)), "10")
self.assertEqual(Binary.fraction_to_string(Fraction(13.0)), "1101")
self.assertEqual(Binary.fraction_to_string(Fraction(-0.0)), "0")
self.assertEqual(Binary.fraction_to_string(Fraction(-1.0)), "-1")
self.assertEqual(Binary.fraction_to_string(Fraction(-2.0)), "-10")
self.assertEqual(Binary.fraction_to_string(Fraction(-13.0)), "-1101")
self.assertEqual(
Binary.fraction_to_string(Fraction(2 ** 100 + 2 ** 0)), "1" + "0" * 99 + "1"
)
self.assertEqual(
Binary.fraction_to_string(Fraction(-(2 ** 100) - 2 ** 0)),
"-1" + "0" * 99 + "1",
)
self.assertEqual(
Binary.fraction_to_string(Fraction(2 ** 100 + 2 ** 0, 2 ** 101)),
"0.1" + "0" * 99 + "1",
)
self.assertEqual(
Binary.fraction_to_string(Fraction(2 ** 100 + 2 ** 0, -1 * 2 ** 101)),
"-0.1" + "0" * 99 + "1",
)
self.assertEqual(
Binary.fraction_to_string(
Fraction(2 ** 1000 + 2 ** 0, -1 * 2 ** 1001), ndigits=10000
),
"-0.1" + "0" * 999 + "1",
)
self.assertEqual(
Binary.fraction_to_string(
Fraction(2 ** 1000 + 2 ** 0, -1 * 2 ** 1001), ndigits=10
),
"-0.1",
)
self.assertEqual(
Binary.fraction_to_string(
Fraction(2 ** 1000 + 2 ** 0, -1 * 2 ** 1001), ndigits=10, simplify=False
),
"-0.1" + "0" * 9,
)
with self.assertRaises(TypeError):
Binary.fraction_to_string(Binary(1)) # should fail
def test_isclose(self):
"""Test function/method."""
self.assertEqual(Binary("inf").isclose("infinity"), False)
self.assertEqual(Binary("-inf").isclose("-infinity"), False)
self.assertEqual(Binary("nan").isclose(1), False)
self.assertEqual(Binary("nan").isclose("NaN"), False)
self.assertEqual(Binary("nan").isclose("nan"), False)
self.assertEqual(Binary("nan").isclose("inf"), False)
self.assertEqual(Binary("-inf").isclose("infinity"), False)
self.assertEqual(Binary("-0.01e-2").isclose("-1e-4"), True)
self.assertEqual(Binary("-0.01e-2").isclose(Fraction(-1, 16)), True)
self.assertEqual(Binary("+1.1").isclose(Fraction(3, 2)), True)
self.assertEqual(Binary("+1.1").isclose(Fraction(3, 2)), True)
self.assertEqual(Binary("+1.1").isclose(3 / 2), True)
self.assertEqual(Binary("+1.1").isclose(1.5), True)
self.assertEqual(Binary("+1.0").isclose(1), True)
self.assertEqual(Binary("+1.0e+1").isclose(2), True)
self.assertEqual(Binary("-100.0e-1").isclose(-2), True)
self.assertEqual(Binary("+1.1").isclose(Fraction(4, 2)), False)
self.assertEqual(Binary("+1.1").isclose(Fraction(4, 2)), False)
self.assertEqual(Binary("+1.1").isclose(4 / 2), False)
self.assertEqual(Binary("+1.1").isclose(2.5), False)
self.assertEqual(Binary("+1.0").isclose(2), False)
self.assertEqual(Binary("+1.0e+1").isclose(3), False)
self.assertEqual(Binary("-100.0e-1").isclose(4), False)
self.assertEqual(
Binary("0.000000000000000101").isclose(Fraction(5, 2 ** 18)), True
)
self.assertEqual(
Binary("-100.00000001e-100").isclose("-100.0000000101e-100"), False
)
self.assertEqual(
Binary("-100.00000001e-100").isclose("-100.0000000101e-100", 0.1), True
)
self.assertEqual(
Binary("-100.00000001e-100").isclose(
"-100.000000010000000000000000000000000001e-100"
),
True,
)
with self.assertRaises(ValueError):
Binary("-0.01e-2").isclose("102") # should fail
with self.assertRaises(TypeError):
Binary("-0.01e-2").isclose(complex(1, 1)) # should fail
def test___eq__(self):
"""Test function/method."""
# indirect test of test__cmp()
self.assertEqual(Binary("inf") == Binary("infinity"), True)
self.assertEqual(Binary("-inf") == Binary("-infinity"), True)
self.assertEqual(Binary("nan") == 1, False)
self.assertEqual(Binary("nan") == "NaN", False)
self.assertEqual(Binary("nan") == Binary("nan"), False)
self.assertEqual(Binary("nan") == Binary("inf"), False)
self.assertEqual(Binary("-inf") == Binary("infinity"), False)
self.assertEqual(Binary("-0.01e-2") == Binary("-1e-4"), True)
self.assertEqual(Binary("-0.01e-2") == Binary(Fraction(-1, 16)), True)
self.assertEqual(Binary("+1.1") == Binary(Fraction(3, 2)), True)
self.assertEqual(Binary("+1.1") == Fraction(3, 2), True)
self.assertEqual(Binary("+1.1") == (3 / 2), True)
self.assertEqual(Binary("+1.1") == 1.5, True)
self.assertEqual(Binary("+1.0") == 1, True)
self.assertEqual(Binary("+1.0e+1") == 2, True)
self.assertEqual(Binary("-100.0e-1") == -2, True)
self.assertEqual(Binary("+1.1") == Binary(Fraction(4, 2)), False)
self.assertEqual(Binary("+1.1") == Fraction(4, 2), False)
self.assertEqual(Binary("+1.1") == (4 / 2), False)
self.assertEqual(Binary("+1.1") == 2.5, False)
self.assertEqual(Binary("+1.0") == 2, False)
self.assertEqual(Binary("+1.0e+1") == 3, False)
self.assertEqual(Binary("-100.0e-1") == 4, False)
self.assertEqual(Binary("0.000000000000000101") == Fraction(5, 2 ** 18), True)
with self.assertRaises(ArithmeticError):
Binary._cmp(Binary("Nan"), "Nan") # should fail
with self.assertRaises(ValueError):
Binary("-0.01e-2") == "102" # should fail
with self.assertRaises(TypeError):
Binary("-0.01e-2") == complex(1, 1) # should fail
def test___lt__(self):
"""Test function/method."""
# indirect test of test__cmp()
self.assertEqual(Binary("inf") < Binary("infinity"), False)
self.assertEqual(Binary("-inf") < Binary("-infinity"), False)
self.assertEqual(Binary("nan") < 1, False)
self.assertEqual(Binary("nan") < "NaN", False)
self.assertEqual(Binary("nan") < Binary("nan"), False)
self.assertEqual(Binary("nan") < Binary("inf"), False)
self.assertEqual(Binary("-inf") < Binary("inf"), True)
self.assertEqual(Binary("-0.0101e-2") < Binary("-1.0e-4"), True)
self.assertEqual(Binary("-0.01e-2") < Binary(Fraction(-0, 16)), True)
self.assertEqual(Binary("+1.1") < Binary(Fraction(4, 2)), True)
self.assertEqual(Binary("+1.1") < Fraction(4, 2), True)
self.assertEqual(Binary("+1.1") < (4 / 2), True)
self.assertEqual(Binary("+1.1") < 1.6, True)
self.assertEqual(Binary("+1.0") < 1.01, True)
self.assertEqual(Binary("+1.0e+1") < 2.2, True)
self.assertEqual(Binary("-100.0e-1") < -1.2, True)
self.assertEqual(Binary("+1.1") < Binary(Fraction(1, 2)), False)
self.assertEqual(Binary("+1.1") < Fraction(1, 2), False)
self.assertEqual(Binary("+1.1") < (1 / 2), False)
self.assertEqual(Binary("+1.1") < 0.5, False)
self.assertEqual(Binary("+1.0") < 0.5, False)
self.assertEqual(Binary("+1.0e+1") < 1, False)
self.assertEqual(Binary("-100.0e-1") < -13, False)
self.assertEqual(Binary("0.000000000000000101") < Fraction(6, 2 ** 18), True)
with self.assertRaises(ValueError):
Binary("-0.01e-2") < "102" # should fail
with self.assertRaises(TypeError):
Binary("-0.01e-2") < complex(1, 1) # should fail
def test___gt__(self):
"""Test function/method."""
# indirect test of test__cmp()
self.assertEqual(Binary("inf") > Binary("infinity"), False)
self.assertEqual(Binary("-inf") > Binary("-infinity"), False)
self.assertEqual(Binary("nan") > 1, False)
self.assertEqual(Binary("nan") > "NaN", False)
self.assertEqual(Binary("nan") > Binary("nan"), False)
self.assertEqual(Binary("nan") > Binary("inf"), False)
self.assertEqual(Binary("-inf") > Binary("inf"), False)
self.assertEqual(Binary("-0.0101e-2") > Binary("-1.0e-4"), False)
self.assertEqual(Binary("-0.01e-2") > Binary(Fraction(-0, 16)), False)
self.assertEqual(Binary("+1.1") > Binary(Fraction(4, 2)), False)
self.assertEqual(Binary("+1.1") > Fraction(4, 2), False)
self.assertEqual(Binary("+1.1") > (4 / 2), False)
self.assertEqual(Binary("+1.1") > 1.6, False)
self.assertEqual(Binary("+1.0") > 1.01, False)
self.assertEqual(Binary("+1.0e+1") > 2.2, False)
self.assertEqual(Binary("-100.0e-1") > -1.2, False)
self.assertEqual(Binary("+1.1") > Binary(Fraction(1, 2)), True)
self.assertEqual(Binary("+1.1") > Fraction(1, 2), True)
self.assertEqual(Binary("+1.1") > (1 / 2), True)
self.assertEqual(Binary("+1.1") > 0.5, True)
self.assertEqual(Binary("+1.0") > 0.5, True)
self.assertEqual(Binary("+1.0e+1") > 1, True)
self.assertEqual(Binary("-100.0e-1") > -13, True)
self.assertEqual(Binary("0.000000000000000101") > Fraction(6, 2 ** 18), False)
with self.assertRaises(ValueError):
Binary("-0.01e-2") > "102" # should fail
with self.assertRaises(TypeError):
Binary("-0.01e-2") > complex(1, 1) # should fail
def test___le__(self):
"""Test function/method."""
# indirect test of test__cmp()
self.assertEqual(Binary("inf") <= Binary("infinity"), True)
self.assertEqual(Binary("-inf") <= Binary("-infinity"), True)
self.assertEqual(Binary("nan") <= 1, False)
self.assertEqual(Binary("nan") <= "NaN", False)
self.assertEqual(Binary("nan") <= Binary("nan"), False)
self.assertEqual(Binary("nan") <= Binary("inf"), False)
self.assertEqual(Binary("-inf") <= Binary("inf"), True)
self.assertEqual(Binary("-0.0101e-2") <= Binary("-1.0e-4"), True)
self.assertEqual(Binary("-0.01e-2") <= Binary(Fraction(-0, 16)), True)
self.assertEqual(Binary("+1.1") <= Binary(Fraction(4, 2)), True)
self.assertEqual(Binary("+1.1") <= Fraction(4, 2), True)
self.assertEqual(Binary("+1.1") <= (4 / 2), True)
self.assertEqual(Binary("+1.1") <= 1.6, True)
self.assertEqual(Binary("+1.0") <= 1.01, True)
self.assertEqual(Binary("+1.0e+1") <= 2.2, True)
self.assertEqual(Binary("-100.0e-1") <= -1.2, True)
self.assertEqual(Binary("+1.1") <= Binary(Fraction(1, 2)), False)
self.assertEqual(Binary("+1.1") <= Fraction(1, 2), False)
self.assertEqual(Binary("+1.1") <= (1 / 2), False)
self.assertEqual(Binary("+1.1") <= 0.5, False)
self.assertEqual(Binary("+1.0") <= 0.5, False)
self.assertEqual(Binary("+1.0e+1") <= 1, False)
self.assertEqual(Binary("-100.0e-1") <= -13, False)
self.assertEqual(Binary("0.000000000000000101") <= Fraction(6, 2 ** 18), True)
self.assertEqual(Binary("1") <= Binary("1"), True)
self.assertEqual(Binary(1) <= Binary(1), True)
self.assertEqual(Binary(1 / 2) <= Binary(1 / 2), True)
with self.assertRaises(ValueError):
Binary("-0.01e-2") <= "102" # should fail
with self.assertRaises(TypeError):
Binary("-0.01e-2") <= complex(1, 1) # should fail
def test___ge__(self):
"""Test function/method."""
# indirect test of test__cmp()
self.assertEqual(Binary("inf") >= Binary("infinity"), True)
self.assertEqual(Binary("-inf") >= Binary("-infinity"), True)
self.assertEqual(Binary("nan") >= 1, False)
self.assertEqual(Binary("nan") >= "NaN", False)
self.assertEqual(Binary("nan") >= Binary("nan"), False)
self.assertEqual(Binary("nan") >= Binary("inf"), False)
self.assertEqual(Binary("-inf") >= Binary("inf"), False)
self.assertEqual(Binary("-0.0101e-2") >= Binary("-1.0e-4"), False)
self.assertEqual(Binary("-0.01e-2") >= Binary(Fraction(-0, 16)), False)
self.assertEqual(Binary("+1.1") >= Binary(Fraction(4, 2)), False)
self.assertEqual(Binary("+1.1") >= Fraction(4, 2), False)
self.assertEqual(Binary("+1.1") >= (4 / 2), False)
self.assertEqual(Binary("+1.1") >= 1.6, False)
self.assertEqual(Binary("+1.0") >= 1.01, False)
self.assertEqual(Binary("+1.0e+1") >= 2.2, False)
self.assertEqual(Binary("-100.0e-1") >= -1.2, False)
self.assertEqual(Binary("+1.1") >= Binary(Fraction(1, 2)), True)
self.assertEqual(Binary("+1.1") >= Fraction(1, 2), True)
self.assertEqual(Binary("+1.1") >= (1 / 2), True)
self.assertEqual(Binary("+1.1") >= 0.5, True)
self.assertEqual(Binary("+1.0") >= 0.5, True)
self.assertEqual(Binary("+1.0e+1") >= 1, True)
self.assertEqual(Binary("-100.0e-1") >= -13, True)
self.assertEqual(Binary("0.000000000000000101") >= Fraction(6, 2 ** 18), False)
self.assertEqual(Binary(1) >= Binary(1), True)
self.assertEqual(Binary(1 / 2) >= Binary(1 / 2), True)
with self.assertRaises(ValueError):
Binary("-0.01e-2") >= "102" # should fail
with self.assertRaises(TypeError):
Binary("-0.01e-2") >= complex(1, 1) # should fail
def test___add__(self):
"""Test function/method."""
self.assertEqual(Binary("inf") + Binary("inf"), Binary("infinity"))
self.assertEqual(Binary("inf") + 1, Binary("infinity"))
self.assertEqual(Binary("-inf") + Binary("-inf"), Binary("-infinity"))
self.assertEqual(Binary("-inf") + 1, Binary("-infinity"))
self.assertEqual((Binary("-inf") + Binary("inf")).isnan(), True)
self.assertEqual((Binary("inf") + Binary("-inf")).isnan(), True)
self.assertEqual((Binary("nan") + 1).isnan(), True)
self.assertEqual((Binary("inf") + Binary("nan")).isnan(), True)
self.assertEqual((Binary("-inf") + Binary("nan")).isnan(), True)
self.assertEqual(Binary(1) + Binary("1"), 2)
self.assertEqual(Binary(-1) + Binary("1"), 0)
self.assertEqual(Binary(0.5) + Binary(0.5), 1)
self.assertEqual(Binary("-1.1") + Binary("0.1"), -1)
self.assertEqual(Binary(1) + 1, 2)
self.assertEqual(Binary(-1) + 1, 0)
self.assertEqual(Binary(0.5) + 0.5, 1)
self.assertEqual(Binary("-1.1") + 0.5, -1)
with self.assertRaises(ValueError):
Binary("102") + "103" # should fail
with self.assertRaises(TypeError):
Binary(1) + complex(1, 1) # should fail
def test___sub__(self):
"""Test function/method."""
self.assertEqual((Binary("inf") - Binary("inf")).isnan(), True)
self.assertEqual(Binary("inf") - 1, Binary("infinity"))
self.assertEqual((Binary("-inf") - Binary("-inf")).isnan(), True)
self.assertEqual(Binary("-inf") - 1, Binary("-infinity"))
self.assertEqual(Binary("-inf") - Binary("inf"), Binary("-infinity"))
self.assertEqual(Binary("inf") - Binary("-inf"), Binary("infinity"))
self.assertEqual((Binary("nan") - 1).isnan(), True)
self.assertEqual((Binary("inf") - Binary("nan")).isnan(), True)
self.assertEqual((Binary("-inf") - Binary("nan")).isnan(), True)
self.assertEqual(
Binary(Fraction(1, 3)) - Binary(Fraction(2, 3)), Fraction(-1, 3)
)
self.assertEqual(Binary(1) - Binary(1), 0)
self.assertEqual(Binary(0) - Binary(1), -1)
self.assertEqual(Binary(0.1) - Binary(0.2), -0.1)
self.assertEqual(Binary(1) - Binary(0.5), 0.5)
self.assertEqual(Binary(1) - 1, 0)
self.assertEqual(Binary(0) - 1, -1)
self.assertEqual(Binary(0.1) - 0.2, -0.1)
self.assertEqual(Binary(1) - 0.5, 0.5)
with self.assertRaises(ValueError):
Binary("102") - "103" # should fail
with self.assertRaises(TypeError):
Binary(1) - complex(1, 1) # should fail
def test___mul__(self):
"""Test function/method."""
self.assertEqual(Binary("inf") * Binary("inf"), Binary("inf"))
self.assertEqual(Binary("inf") * 1, Binary("infinity"))
self.assertEqual(Binary("-inf") * Binary("-inf"), Binary("inf"))
self.assertEqual(Binary("-inf") * 1, Binary("-infinity"))
self.assertEqual(Binary("-inf") * Binary("inf"), Binary("-infinity"))
self.assertEqual(Binary("inf") * Binary("-inf"), Binary("-infinity"))
self.assertEqual((Binary("nan") * 1).isnan(), True)
self.assertEqual((Binary("inf") * Binary("nan")).isnan(), True)
self.assertEqual((Binary("-inf") * Binary("nan")).isnan(), True)
self.assertEqual(Binary(0) * Binary(1), 0)
self.assertEqual(Binary(1) * Binary(1), 1)
self.assertEqual(Binary(100) * Binary(Fraction(1, 10)), 10)
self.assertEqual(Binary(0) * 1, 0)
self.assertEqual(Binary(1) * 1, 1)
self.assertEqual((Binary(100) * (1 / 10)).isclose(10), True)
self.assertEqual(Binary(1) * 1.5, 1.5)
self.assertEqual((Binary(100) * (1.11 / 10)).isclose(11.1), True)
with self.assertRaises(ValueError):
Binary("102") * "103" # should fail
with self.assertRaises(TypeError):
Binary(1) * complex(1, 1) # should fail
def test___truediv__(self):
"""Test function/method."""
self.assertEqual((Binary("inf") / Binary("inf")).isnan(), True)
self.assertEqual(Binary("inf") / 1, Binary("infinity"))
self.assertEqual((Binary("-inf") / Binary("-inf")).isnan(), True)
self.assertEqual(Binary("-inf") / 1, Binary("-infinity"))
self.assertEqual((Binary("-inf") / Binary("inf")).isnan(), True)
self.assertEqual((Binary("inf") / Binary("-inf")).isnan(), True)
self.assertEqual((Binary("nan") / 1).isnan(), True)
self.assertEqual((Binary("inf") / Binary("nan")).isnan(), True)
self.assertEqual((Binary("-inf") / Binary("nan")).isnan(), True)
self.assertEqual(Binary(100) / Binary(Fraction(1, 10)), 1000)
self.assertEqual(Binary(0) / Binary(10), 0)
self.assertEqual(Binary(1) / Binary(2), 0.5)
self.assertEqual(Binary(100) / Fraction(1, 10), 1000)
self.assertEqual(Binary(0) / 10, 0)
self.assertEqual(Binary(1) / 2, 0.5)
self.assertEqual(Binary(0) / 10.5, 0)
self.assertEqual((Binary(1) / 2.5).isclose(0.4), True)
self.assertEqual(Binary(-1) / Fraction(5, 2), Fraction(-4, 10))
self.assertEqual((Binary(1) / (-2.5)).isclose(-0.4), True)
with self.assertRaises(ZeroDivisionError):
Binary(1) / Binary(0)
with self.assertRaises(ZeroDivisionError):
Binary(1) / 0.0
with self.assertRaises(ZeroDivisionError):
Binary(1) / 0
with self.assertRaises(ValueError):
Binary("102") / "103" # should fail
with self.assertRaises(TypeError):
Binary(1) / complex(1, 1) # should fail
def test___floordiv__(self):
"""Test function/method."""
self.assertEqual((Binary("inf") // Binary("inf")).isnan(), True)
self.assertEqual((Binary("inf") // 1).isnan(), True)
self.assertEqual((Binary("-inf") // Binary("-inf")).isnan(), True)
self.assertEqual((Binary("-inf") // 1).isnan(), True)
self.assertEqual((Binary("-inf") // Binary("inf")).isnan(), True)
self.assertEqual((Binary("inf") // Binary("-inf")).isnan(), True)
self.assertEqual((Binary("nan") // 1).isnan(), True)
self.assertEqual((Binary("inf") // Binary("nan")).isnan(), True)
self.assertEqual((Binary("-inf") // Binary("nan")).isnan(), True)
self.assertEqual(Binary(1234) // Binary(Fraction(1, 10)), 12340)
self.assertEqual(Binary(0) // Binary(10), 0)
self.assertEqual(Binary(1) // Binary(2), 0)
self.assertEqual(Binary(100) // Fraction(1, 10), 1000)
self.assertEqual(Binary(0) // 10, 0)
self.assertEqual(Binary(1) // 2, 0.0)
self.assertEqual(Binary(0) // 10.5, 0)
self.assertEqual((Binary(1) // 2.5).isclose(0), True)
self.assertEqual(Binary(-1) // Fraction(5, 2), -1)
self.assertEqual((Binary(1) // (-2.5)).isclose(-1), True)
self.assertEqual(Binary(10) // Binary(3), 3)
self.assertEqual(Binary(7) // Binary(2), 3)
self.assertEqual(Binary(8) // Binary(3), 2)
self.assertEqual(Binary(-10) // Binary(3), -4)
self.assertEqual(Binary(-7) // Binary(2), -4)
self.assertEqual(Binary(-8) // Binary(3), -3)
self.assertEqual(Binary(-6) // Binary(2), -3)
self.assertEqual(Binary(-6) // Binary("inf"), -1)
self.assertEqual(Binary(+6) // Binary("inf"), 0)
self.assertEqual(Binary(-6) // Binary("-inf"), 0)
self.assertEqual(Binary(+6) // Binary("-inf"), -1)
with self.assertRaises(ZeroDivisionError):
Binary(1) // Binary(0)
with self.assertRaises(ZeroDivisionError):
Binary(1) // 0.0
with self.assertRaises(ZeroDivisionError):
Binary(1) // 0
with self.assertRaises(ValueError):
Binary("102") // "103" # should fail
with self.assertRaises(TypeError):
Binary(1) // complex(1, 1) # should fail
def test___mod__(self):
"""Test function/method."""
self.assertEqual((Binary("inf") % Binary("inf")).isnan(), True)
self.assertEqual((Binary("inf") % 1).isnan(), True)
self.assertEqual((Binary("-inf") % Binary("-inf")).isnan(), True)
self.assertEqual((Binary("-inf") % 1).isnan(), True)
self.assertEqual((Binary("-inf") % Binary("inf")).isnan(), True)
self.assertEqual((Binary("inf") % Binary("-inf")).isnan(), True)
self.assertEqual((Binary("nan") % 1).isnan(), True)
self.assertEqual((Binary("inf") % Binary("nan")).isnan(), True)
self.assertEqual((Binary("-inf") % Binary("nan")).isnan(), True)
self.assertEqual(Binary(1234) % Binary(Fraction(1, 10)), 0)
self.assertEqual(Binary(0) % Binary(10), 0)
self.assertEqual(Binary(1) % Binary(2), 1)
self.assertEqual(Binary(100) % Fraction(1, 10), 0)
self.assertEqual((Binary(100.23) % Fraction(1, 10)).isclose(0.03), True)
self.assertEqual(Binary(0) % 10, 0)
self.assertEqual(Binary(1) % 2, 1)
self.assertEqual(Binary(0) % 10.5, 0)
self.assertEqual((Binary(1) % 2.5).isclose(1), True)
self.assertEqual(Binary(-1) % Fraction(5, 2), 1.5)
self.assertEqual((Binary(1) % (-2.5)).isclose(-1.5), True)
self.assertEqual(Binary(10) % Binary(3), 1)
self.assertEqual(Binary(7) % Binary(2), 1)
self.assertEqual(Binary(8) % Binary(3), 2)
self.assertEqual(Binary(-10) % Binary(3), 2)
self.assertEqual(Binary(-7) % Binary(2), 1)
self.assertEqual(Binary(-8) % Binary(3), 1)
self.assertEqual(Binary(-6) % Binary(2), 0)
self.assertEqual(Binary(-6) % Binary("inf"), Binary("inf"))
self.assertEqual(Binary(+6) % Binary("inf"), 6)
self.assertEqual(Binary(-6) % Binary("-inf"), -6)
self.assertEqual(Binary(+6) % Binary("-inf"), Binary("-inf"))
self.assertEqual(Binary(5) % Binary(3), 2)
self.assertEqual(Binary(5.5) % Binary(3), 2.5)
self.assertEqual(Binary(7) % Binary(4), 3)
self.assertEqual(Binary("111") % Binary("11"), 1)
self.assertEqual(Binary(5.0) % Binary(1.5), 0.5)
self.assertEqual(Binary("-101.0") % Binary("-1.1"), -0.5)
with self.assertRaises(ZeroDivisionError):
Binary(1) % Binary(0)
with self.assertRaises(ZeroDivisionError):
Binary(1) % 0.0
with self.assertRaises(ZeroDivisionError):
Binary(1) % 0
with self.assertRaises(ValueError):
Binary("102") % "103" # should fail
with self.assertRaises(TypeError):
Binary(1) % complex(1, 1) # should fail
def test___pow__(self):
"""Test function/method."""
self.assertEqual((Binary("inf") ** Binary("inf")).ispositiveinfinity(), True)
self.assertEqual((Binary("inf") ** 1).ispositiveinfinity(), True)
self.assertEqual(Binary("-inf") ** Binary("-inf"), 0)
self.assertEqual((Binary("-inf") ** 1).isnegativeinfinity(), True)
self.assertEqual((Binary("-inf") ** Binary("inf")).ispositiveinfinity(), True)
self.assertEqual(Binary("inf") ** Binary("-inf"), 0)
self.assertEqual((Binary("nan") ** 1).isnan(), True)
self.assertEqual((Binary("inf") ** Binary("nan")).isnan(), True)
self.assertEqual((Binary("-inf") ** Binary("nan")).isnan(), True)
self.assertEqual(Binary(1234) ** Binary(Fraction(1, 10)), 1234 ** 0.1)
self.assertEqual(Binary(0) ** Binary(10), 0)
self.assertEqual(Binary(1) ** Binary(2), 1)
self.assertEqual(Binary(100) ** Fraction(1, 10), 100 ** 0.1)
self.assertEqual(
(Binary(100.23) ** Fraction(1, 10)).isclose(100.23 ** 0.1), True
)
self.assertEqual(Binary(0) ** 10, 0)
self.assertEqual(Binary(1) ** 2, 1)
self.assertEqual(Binary(0) ** 10.5, 0)
self.assertEqual((Binary(1) ** 2.5).isclose(1), True)
self.assertEqual((Binary(1) ** (-2.5)).isclose(1), True)
self.assertEqual(Binary(10) ** Binary(3), 1000)
self.assertEqual(Binary(7) ** Binary(2), 49)
self.assertEqual(Binary(8) ** Binary(3), 64 * 8)
self.assertEqual(Binary(-10) ** Binary(3), -1000)
self.assertEqual(Binary(-7) ** Binary(2), 49)
self.assertEqual(Binary(-8) ** Binary(3), -64 * 8)
self.assertEqual(Binary(-6) ** Binary(2), 36)
self.assertEqual(Binary(-6) ** Binary("inf"), Binary("inf"))
self.assertEqual(Binary(+6) ** Binary("inf"), Binary("inf"))
self.assertEqual(Binary(-6) ** Binary("-inf"), 0)
self.assertEqual(Binary(+6) ** Binary("-inf"), 0)
self.assertEqual(Binary(5) ** Binary(3), 125)
self.assertEqual(Binary(5.5) ** Binary(3), 5.5 ** 3)
self.assertEqual(Binary(7) ** Binary(4), 49 * 49)
self.assertEqual(Binary("111") ** Binary("11"), 49 * 7)
self.assertEqual(Binary(5.0) ** Binary(1.5), 5 ** 1.5)
self.assertEqual((Binary(-3.4) ** Binary(-4)).isclose((-3.4) ** (-4)), True)
self.assertEqual((Binary(-3.4) ** Binary(+4)).isclose((-3.4) ** (+4)), True)
self.assertEqual((Binary(+3.4) ** Binary(-3.4)).isclose((+3.4) ** (-3.4)), True)
self.assertEqual(Binary(1) ** Binary(0), 1)
self.assertEqual(Binary(1) ** 0.0, 1)
self.assertEqual(Binary(1) ** 0, 1)
with self.assertRaises(ValueError):
Binary("102") ** "103" # should fail
with self.assertRaises(ArithmeticError):
Binary(-3.4) ** Binary(-3.4) # should fail
with self.assertRaises(ArithmeticError):
Binary(-3.4) ** Binary(+3.4) # should fail
with self.assertRaises(TypeError):
Binary(1) ** complex(1, 1) # should fail
def test___abs__(self):
"""Test function/method."""
self.assertIsInstance(abs(Binary(5)), Binary)
self.assertEqual(abs(Binary("inf")), Binary("inf"))
self.assertEqual(abs(Binary("-inf")), Binary("inf"))
self.assertEqual(abs(Binary("nan")).isnan(), True)
self.assertEqual(abs(Binary(5)), 5)
self.assertEqual(abs(Binary(-7)), 7)
self.assertEqual(abs(Binary("111")), 7)
self.assertEqual(abs(Binary(-1.5)), 1.5)
self.assertEqual(abs(Binary("-101.1")), 5.5)
with self.assertRaises(ValueError):
abs(Binary("102")) # should fail
with self.assertRaises(TypeError):
Binary.__abs__(1) # should fail
def test___ceil__(self):
"""Test function/method."""
self.assertIsInstance(math.ceil(Binary(5)), int)
self.assertEqual(math.ceil(Binary(5)), math.ceil(5))
self.assertEqual(math.ceil(Binary(-7)), math.ceil(-7))
self.assertEqual(math.ceil(Binary("111")), math.ceil(7))
self.assertEqual(math.ceil(Binary(-1.5)), math.ceil(-1.5))
self.assertEqual(math.ceil(Binary("-101.1")), math.ceil(-5.5))
with self.assertRaises(ValueError):
math.ceil(Binary("102")) # should fail
with self.assertRaises(TypeError):
Binary.__ceil__(1) # should fail
with self.assertRaises(ValueError):
math.ceil(Binary("Nan")) # should fail
with self.assertRaises(OverflowError):
math.ceil(Binary("inf")) # should fail
with self.assertRaises(OverflowError):
math.ceil(Binary("-inf")) # should fail
def test_ceil(self):
"""Test function/method."""
self.assertIsInstance(Binary(5).ceil(), Binary)
self.assertEqual(Binary(5).ceil(), Binary(math.ceil(5)))
self.assertEqual(Binary(-7).ceil(), Binary(math.ceil(-7)))
self.assertEqual(Binary("111").ceil(), Binary(math.ceil(7)))
self.assertEqual(Binary(-1.5).ceil(), Binary(math.ceil(-1.5)))
self.assertEqual(Binary("-101.1").ceil(), Binary(math.ceil(-5.5)))
with self.assertRaises(ValueError):
Binary("102").ceil() # should fail
with self.assertRaises(TypeError):
Binary.ceil(1) # should fail
with self.assertRaises(ValueError):
Binary("Nan").ceil() # should fail
with self.assertRaises(OverflowError):
Binary("inf").ceil() # should fail
with self.assertRaises(OverflowError):
Binary("-inf").ceil() # should fail
def test___floor__(self):
"""Test function/method."""
self.assertIsInstance(math.floor(Binary(5)), int)
self.assertEqual(math.floor(Binary(5)), math.floor(5))
self.assertEqual(math.floor(Binary(-7)), math.floor(-7))
self.assertEqual(math.floor(Binary("111")), math.floor(7))
self.assertEqual(math.floor(Binary(-1.5)), math.floor(-1.5))
self.assertEqual(math.floor(Binary("-101.1")), math.floor(-5.5))
with self.assertRaises(ValueError):
math.floor(Binary("102")) # should fail
with self.assertRaises(TypeError):
Binary.__floor__(1) # should fail
with self.assertRaises(ValueError):
math.floor(Binary("Nan")) # should fail
with self.assertRaises(OverflowError):
math.floor(Binary("inf")) # should fail
with self.assertRaises(OverflowError):
math.floor(Binary("-inf")) # should fail
def test_floor(self):
"""Test function/method."""
self.assertIsInstance(Binary(5).floor(), Binary)
self.assertEqual(Binary(5).floor(), Binary(math.floor(5)))
self.assertEqual(Binary(-7).floor(), Binary(math.floor(-7)))
self.assertEqual(Binary("111").floor(), Binary(math.floor(7)))
self.assertEqual(Binary(-1.5).floor(), Binary(math.floor(-1.5)))
self.assertEqual(Binary("-101.1").floor(), Binary(math.floor(-5.5)))
with self.assertRaises(ValueError):
Binary("102").floor() # should fail
with self.assertRaises(TypeError):
Binary.floor(1) # should fail
with self.assertRaises(ValueError):
Binary("Nan").floor() # should fail
with self.assertRaises(OverflowError):
Binary("inf").floor() # should fail
with self.assertRaises(OverflowError):
Binary("-inf").floor() # should fail
def test___rshift__(self):
"""Test function/method."""
self.assertIsInstance(Binary(1) >> 1, Binary)
self.assertEqual(Binary("inf") >> 1, Binary("inf"))
self.assertEqual(Binary("-inf") >> 1, Binary("-inf"))
self.assertEqual((Binary("nan") >> 1).isnan(), True)
self.assertEqual(Binary(1) >> 1, 0.5)
self.assertEqual(Binary(2) >> 3, 0.25)
self.assertEqual(Binary(0.25) >> 1, Fraction(1, 8))
self.assertEqual(Binary("1e1") >> 1, 1)
self.assertEqual(Binary("101e2") >> 2, 5)
self.assertEqual(Binary("101e2") >> 3, Fraction(5, 2 ** 1))
self.assertEqual(Binary("101e2") >> 3, Binary(Fraction(5, 2 ** 1)))
self.assertEqual(Binary("101e2") >> 4, Binary(Fraction(5, 2 ** 2)))
self.assertEqual(Binary("101e2") >> 4, Binary("101e-2"))
self.assertEqual(Binary("101e2") >> 20, Binary("101e-18"))
self.assertEqual(Binary("101e2") >> 20, Binary(Fraction(5, 2 ** 18)))
self.assertEqual(
(Binary("101e2") >> 20).compare_representation("101e-18"), True
)
self.assertEqual((Binary("101e2") >> 2).compare_representation("101"), True)
self.assertEqual((Binary("101e-2") >> 2).compare_representation("101e-4"), True)
self.assertEqual(
(Binary("101e2") >> 20).compare_representation("101e-18"), True
)
self.assertEqual((Binary("101") >> 2).compare_representation("1.01"), True)
self.assertEqual(
(Binary("101") >> 20).compare_representation("0." + "0" * 17 + "101"), True
)
self.assertEqual(
(Binary("101.01e2") >> 0).compare_representation("101.01e2"), True
)
self.assertEqual(
(Binary("101.01e2") >> 1).compare_representation("101.01e1"), True
)
self.assertEqual(
(Binary("101.01e2") >> 20).compare_representation("101.01e-18"), True
)
self.assertEqual((Binary("101.01") >> 2).compare_representation("1.0101"), True)
self.assertEqual((Binary("101.01") >> 1).compare_representation("10.101"), True)
self.assertEqual(
(Binary("101.01") >> 3).compare_representation("0.10101"), True
)
self.assertEqual(
(Binary("101.01") >> 20).compare_representation("0." + "0" * 17 + "10101"),
True,
)
with self.assertRaises(ValueError):
Binary("10") >> -3 # should fail
with self.assertRaises(TypeError):
Binary(1) >> complex(1, 1) # should fail
def test___lshift__(self):
"""Test function/method."""
self.assertIsInstance(Binary(1) << 1, Binary)
self.assertEqual(Binary("inf") >> 1, Binary("inf"))
self.assertEqual(Binary("-inf") >> 1, Binary("-inf"))
self.assertEqual((Binary("nan") >> 1).isnan(), True)
self.assertEqual(Binary(1) << 1, 2)
self.assertEqual(Binary(2) << 3, 16)
self.assertEqual(Binary(0.25) << 1, 0.5)
self.assertEqual(Binary(0.125) << 3, 1)
self.assertEqual(Binary("1e1") << 2, 8)
self.assertEqual(Binary("101e2") << 2, 5 * 2 ** 4)
self.assertEqual(Binary("101e2") << 20, 5 * 2 ** 22)
self.assertEqual((Binary("101e-2") << 2).compare_representation("101"), True)
self.assertEqual((Binary("101e2") << 2).compare_representation("101e4"), True)
self.assertEqual((Binary("101e2") << 20).compare_representation("101e22"), True)
self.assertEqual((Binary("101") << 2).compare_representation("10100"), True)
self.assertEqual(
(Binary("101") << 20).compare_representation("101" + "0" * 20), True
)
self.assertEqual(
(Binary("101.01e2") << 2).compare_representation("101.01e4"), True
)
self.assertEqual(
(Binary("101.01e2") << 20).compare_representation("101.01e22"), True
)
self.assertEqual((Binary("101.01") << 2).compare_representation("10101"), True)
self.assertEqual((Binary("101.01") << 1).compare_representation("1010.1"), True)
self.assertEqual((Binary("101.01") << 3).compare_representation("101010"), True)
self.assertEqual(
(Binary("101.01") << 20).compare_representation("10101" + "0" * 18), True
)
with self.assertRaises(ValueError):
Binary("10") << -3 # should fail
with self.assertRaises(TypeError):
Binary(1) << complex(1, 1) # should fail
def test___bool__(self):
"""Test function/method."""
self.assertIsInstance(bool(Binary(1)), bool)
self.assertEqual(bool(Binary("inf")), True)
self.assertEqual(bool(Binary("-inf")), True)
self.assertEqual(bool(Binary("Nan")), True)
self.assertEqual(bool(Binary(9)), True)
self.assertEqual(bool(Binary(-10.5)), True)
self.assertEqual(bool(Binary(0)), False)
self.assertEqual(bool(Binary(0.0)), False)
with self.assertRaises(TypeError):
Binary.__bool__(complex(1, 1)) # should fail
def test___not__(self):
"""Test function/method."""
self.assertIsInstance(not Binary(1), bool)
self.assertEqual(not Binary("inf"), False)
self.assertEqual(not Binary("-inf"), False)
self.assertEqual(not Binary("Nan"), False)
self.assertEqual(not Binary(9), False)
self.assertEqual(not Binary(-10.5), False)
self.assertEqual(not Binary(0), True)
self.assertEqual(not Binary(0.0), True)
with self.assertRaises(TypeError):
not Binary(complex(1, 1)) # should fail
def test___and__(self):
"""Test function/method."""
self.assertIsInstance(Binary(1) & Binary(1), Binary)
self.assertEqual(Binary(1) & Binary(1), Binary(1))
self.assertEqual(Binary(0) & Binary(1), Binary(0))
for ii in range(-30, 30, 1):
for jj in range(-30, 30, 1):
self.assertEqual(Binary(ii) & Binary(jj), ii & jj)
self.assertEqual(Binary("1000") & Binary("0"), Binary(0))
self.assertEqual(Binary("1010") & Binary("10"), Binary("10"))
self.assertEqual(Binary("1010") & Binary("11"), Binary("10"))
self.assertEqual(Binary("1111") & Binary("10"), Binary("10"))
self.assertEqual(Binary("1.1000") & Binary("0.0"), Binary(0))
self.assertEqual(Binary("1.1010") & Binary("0.10"), Binary("0.1"))
self.assertEqual(Binary("1.1010") & Binary("0.11"), Binary("0.1"))
self.assertEqual(Binary("1.1111") & Binary("0.10"), Binary("0.1"))
self.assertEqual(Binary("-0.1") & Binary("+1"), 1)
self.assertEqual(Binary(-5) & Binary(-6), -6)
self.assertEqual(Binary(-5) & Binary(-7), -7)
self.assertEqual(Binary(-5) & Binary(-8), -8)
self.assertEqual(Binary(-5) & Binary(-9), -13)
self.assertEqual(Binary(-5) & Binary(-10), -14)
self.assertEqual(Binary(5) & Binary(-10), 4)
self.assertEqual(Binary(5) & Binary(-9), 5)
self.assertEqual(Binary(5) & Binary(-8), 0)
self.assertEqual(Binary(5) & Binary(-7), 1)
self.assertEqual(Binary(5) & Binary(-6), 0)
self.assertEqual(Binary(5) & Binary(-5), 1)
with self.assertRaises(ValueError):
Binary("102") & "103" # should fail
with self.assertRaises(TypeError):
Binary(1) & complex(1, 1) # should fail
with self.assertRaises(ArithmeticError):
Binary("inf") & Binary(1)
with self.assertRaises(ArithmeticError):
Binary(1) & Binary("inf")
with self.assertRaises(ArithmeticError):
Binary("nan") & Binary(1)
with self.assertRaises(ArithmeticError):
Binary(1) & Binary("nan")
with self.assertRaises(ArithmeticError):
Binary("-inf") & Binary("-inf")
def test___or__(self):
"""Test function/method."""
self.assertIsInstance(Binary(1) | Binary(1), Binary)
self.assertEqual(Binary(1) | Binary(1), Binary(1))
self.assertEqual(Binary(0) | Binary(1), Binary(1))
for ii in range(-30, 30, 1):
for jj in range(-30, 30, 1):
self.assertEqual(Binary(ii) | Binary(jj), ii | jj)
self.assertEqual(Binary("1000") | Binary("0"), Binary("1000"))
self.assertEqual(Binary("1010") | Binary("10"), Binary("1010"))
self.assertEqual(Binary("1010") | Binary("11"), Binary("1011"))
self.assertEqual(Binary("1111") | Binary("10"), Binary("1111"))
self.assertEqual(Binary("1.1000") | Binary("0.0"), Binary("1.1000"))
self.assertEqual(Binary("1.1010") | Binary("0.10"), Binary("1.1010"))
self.assertEqual(Binary("1.1010") | Binary("0.11"), Binary("1.1110"))
self.assertEqual(Binary("1.1111") | Binary("0.10"), Binary("1.1111"))
self.assertEqual(Binary("-0.1") | Binary("+1"), -0.5)
self.assertEqual(Binary(-5) | Binary(-6), -5 | -6)
self.assertEqual(Binary(-5) | Binary(-7), -5 | -7)
self.assertEqual(Binary(-5) | Binary(-8), -5 | -8)
self.assertEqual(Binary(-5) | Binary(-9), -5 | -9)
self.assertEqual(Binary(-5) | Binary(-10), -5 | -10)
self.assertEqual(Binary(5) | Binary(-10), 5 | -10)
self.assertEqual(Binary(5) | Binary(-9), 5 | -9)
self.assertEqual(Binary(5) | Binary(-8), 5 | -8)
self.assertEqual(Binary(5) | Binary(-7), 5 | -7)
self.assertEqual(Binary(5) | Binary(-6), 5 | -6)
self.assertEqual(Binary(5) | Binary(-5), 5 | -5)
with self.assertRaises(ValueError):
Binary("102") | "103" # should fail
with self.assertRaises(TypeError):
Binary(1) | complex(1, 1) # should fail
with self.assertRaises(ArithmeticError):
Binary("inf") | Binary(1)
with self.assertRaises(ArithmeticError):
Binary(1) | Binary("inf")
with self.assertRaises(ArithmeticError):
Binary("nan") | Binary(1)
with self.assertRaises(ArithmeticError):
Binary(1) | Binary("nan")
with self.assertRaises(ArithmeticError):
Binary("-inf") | Binary("-inf")
def test___xor__(self):
"""Test function/method."""
self.assertIsInstance(Binary(1) ^ Binary(1), Binary)
self.assertEqual(Binary(1) ^ Binary(1), Binary(0))
self.assertEqual(Binary(0) ^ Binary(1), Binary(1))
for ii in range(-30, 30, 1):
for jj in range(-30, 30, 1):
self.assertEqual(Binary(ii) ^ Binary(jj), ii ^ jj)
self.assertEqual(Binary("1000") ^ Binary("0"), Binary("1000"))
self.assertEqual(Binary("1010") ^ Binary("10"), Binary("1000"))
self.assertEqual(Binary("1010") ^ Binary("11"), Binary("1001"))
self.assertEqual(Binary("1111") ^ Binary("10"), Binary("1101"))
self.assertEqual(Binary("1.1000") ^ Binary("0.0"), Binary("1.1000"))
self.assertEqual(Binary("1.1010") ^ Binary("0.10"), Binary("1.0010"))
self.assertEqual(Binary("1.1010") ^ Binary("0.11"), Binary("1.0110"))
self.assertEqual(Binary("1.1111") ^ Binary("0.10"), Binary("1.0111"))
self.assertEqual(Binary("-0.1") ^ Binary("+1"), -1.5)
self.assertEqual(Binary(-5) ^ Binary(-6), -5 ^ -6)
self.assertEqual(Binary(-5) ^ Binary(-7), -5 ^ -7)
self.assertEqual(Binary(-5) ^ Binary(-8), -5 ^ -8)
self.assertEqual(Binary(-5) ^ Binary(-9), -5 ^ -9)
self.assertEqual(Binary(-5) ^ Binary(-10), -5 ^ -10)
self.assertEqual(Binary(5) ^ Binary(-10), 5 ^ -10)
self.assertEqual(Binary(5) ^ Binary(-9), 5 ^ -9)
self.assertEqual(Binary(5) ^ Binary(-8), 5 ^ -8)
self.assertEqual(Binary(5) ^ Binary(-7), 5 ^ -7)
self.assertEqual(Binary(5) ^ Binary(-6), 5 ^ -6)
self.assertEqual(Binary(5) ^ Binary(-5), 5 ^ -5)
with self.assertRaises(ValueError):
Binary("102") ^ "103" # should fail
with self.assertRaises(TypeError):
Binary(1) ^ complex(1, 1) # should fail
with self.assertRaises(ArithmeticError):
Binary("inf") ^ Binary(1)
with self.assertRaises(ArithmeticError):
Binary(1) ^ Binary("inf")
with self.assertRaises(ArithmeticError):
Binary("nan") ^ Binary(1)
with self.assertRaises(ArithmeticError):
Binary(1) ^ Binary("nan")
with self.assertRaises(ArithmeticError):
Binary("-inf") ^ Binary("-inf")
def test___invert__(self):
"""Test function/method."""
self.assertIsInstance(~Binary(1), Binary)
self.assertEqual(~Binary(-2), 1)
self.assertEqual(~Binary(-1), 0)
self.assertEqual(~Binary(0), -1)
self.assertEqual(~Binary(1), -2)
self.assertEqual(~Binary(9), Binary(-10))
self.assertEqual(~Binary(-10), Binary(9))
self.assertEqual(~~Binary(-109), Binary(-109))
self.assertEqual(~~Binary(9), Binary(9))
with self.assertRaises(ValueError):
~Binary("-10.5") # should fail
with self.assertRaises(ValueError):
~Binary("+10.5") # should fail
with self.assertRaises(TypeError):
~Binary(complex(1, 1)) # should fail
with self.assertRaises(ArithmeticError):
~Binary("inf")
with self.assertRaises(ArithmeticError):
~Binary("-inf")
with self.assertRaises(ArithmeticError):
~Binary("nan")
def test_to_twoscomplement(self):
"""Test function/method."""
self.assertIsInstance(Binary(1).to_twoscomplement(), str)
self.assertEqual(Binary("10").to_twoscomplement(), Binary("10"))
self.assertEqual(Binary("1010").to_twoscomplement(), Binary("1010"))
self.assertEqual(Binary("-1").to_twoscomplement(length=12), "1" * 12)
self.assertEqual(Binary("-1.0").to_twoscomplement(length=12), "1" * 12)
self.assertEqual(Binary("-1.0010").to_twoscomplement(), "10.111")
self.assertEqual(Binary("-0.0010").to_twoscomplement(), "1.111")
self.assertEqual(Binary("-0.111").to_twoscomplement(), "1.001")
self.assertEqual(Binary("-0.10").to_twoscomplement(), "1.1")
self.assertEqual(Binary(0.25).to_twoscomplement(), "0.01")
self.assertEqual(Binary(-0.125).to_twoscomplement(), "1.111")
self.assertEqual(Binary(-0.25).to_twoscomplement(), "1.11")
self.assertEqual(Binary(-0.5).to_twoscomplement(), "1.1")
self.assertEqual(Binary(-1.0).to_twoscomplement(), "1")
self.assertEqual(Binary(-2).to_twoscomplement(), "10")
self.assertEqual(Binary(-3).to_twoscomplement(), "101")
self.assertEqual(Binary(-1.5).to_twoscomplement(), "10.1")
self.assertEqual(Binary(-2.5).to_twoscomplement(), "101.1")
self.assertEqual(Binary(-2).to_twoscomplement(4), "1110")
self.assertEqual(Binary(-3).to_twoscomplement(3), "101")
self.assertEqual(Binary(-1.5).to_twoscomplement(4), "10.1")
self.assertEqual(Binary(-2.5).to_twoscomplement(6), "1101.1")
self.assertEqual(Binary(+2).to_twoscomplement(5), "00010")
self.assertEqual(Binary(3).to_twoscomplement(3), "011")
self.assertEqual(Binary(1.5).to_twoscomplement(4), "01.1")
self.assertEqual(Binary(2.5).to_twoscomplement(6), "0010.1")
self.assertEqual(Binary(2).to_twoscomplement(8), "00000010")
self.assertEqual(Binary(+1975).to_twoscomplement(length=12), "011110110111")
self.assertEqual(Binary(+1975).to_twoscomplement(length=13), "0011110110111")
self.assertEqual(Binary(+1975).to_twoscomplement(length=16), "0000011110110111")
self.assertEqual(Binary(-1975).to_twoscomplement(length=12), "100001001001")
self.assertEqual(Binary(-1975).to_twoscomplement(length=16), "1111100001001001")
with self.assertRaises(OverflowError):
Binary(-3).to_twoscomplement(2)
with self.assertRaises(OverflowError):
Binary(3).to_twoscomplement(2)
with self.assertRaises(OverflowError):
Binary(-1.5).to_twoscomplement(3)
with self.assertRaises(OverflowError):
Binary(1.5).to_twoscomplement(2)
with self.assertRaises(OverflowError):
Binary(+3).to_twoscomplement(1)
with self.assertRaises(ValueError):
Binary(+3).to_twoscomplement(-2)
with self.assertRaises(TypeError):
Binary(+3).to_twoscomplement("1")
with self.assertRaises(TypeError):
Binary(+3).to_twoscomplement(1.0)
with self.assertRaises(ArithmeticError):
Binary("Inf").to_twoscomplement()
with self.assertRaises(ArithmeticError):
Binary("-inf").to_twoscomplement()
with self.assertRaises(ArithmeticError):
Binary("nan").to_twoscomplement()
def test_from_twoscomplement(self):
"""Test function/method."""
self.assertIsInstance(Binary.from_twoscomplement(TwosComplement("1")), str)
self.assertEqual(Binary.from_twoscomplement(TwosComplement("01")), "1")
self.assertEqual(Binary.from_twoscomplement(TwosComplement("0")), "0")
self.assertEqual(Binary.from_twoscomplement(TwosComplement("1")), "-1")
self.assertEqual(Binary.from_twoscomplement(TwosComplement("11")), "-1")
self.assertEqual(Binary.from_twoscomplement(TwosComplement("111")), "-1")
for ii in [-12, -11.57, -8, -1, -0.87, 0, 0.76, 1.2, 2, 2.4, 8, 2322.2343]:
self.assertEqual(
Binary(Binary.from_twoscomplement(Binary(ii).to_twoscomplement())),
Binary(ii),
)
self.assertEqual(Binary.from_twoscomplement(TwosComplement("10.1")), "-1.1")
self.assertEqual(Binary.from_twoscomplement(TwosComplement("11.1")), "-0.1")
self.assertEqual(Binary.from_twoscomplement(TwosComplement("11.11")), "-0.01")
self.assertEqual(Binary.from_twoscomplement(TwosComplement("11.111")), "-0.001")
self.assertEqual(
Binary.from_twoscomplement(TwosComplement("110.111")), "-1.001"
)
self.assertEqual(
Binary.from_twoscomplement(TwosComplement("110.001")), "-1.111"
)
self.assertEqual(Binary.from_twoscomplement(TwosComplement("110")), "-10")
self.assertEqual(Binary.from_twoscomplement(TwosComplement("00")), "0")
self.assertEqual(Binary.from_twoscomplement(TwosComplement("01")), "1")
self.assertEqual(Binary.from_twoscomplement(TwosComplement("00.11")), "0.11")
self.assertEqual(
Binary.from_twoscomplement(TwosComplement("00.11111111111110")),
"0.1111111111111",
)
self.assertEqual(
Binary.from_twoscomplement(TwosComplement("00.11e-5")), "0.11e-5"
)
self.assertEqual(
Binary.from_twoscomplement(TwosComplement("00.11111111111110")),
"0.1111111111111",
)
self.assertEqual(
Binary.from_twoscomplement(
TwosComplement("011100.00e+00", simplify=False), simplify=False
),
"011100.00e+00",
)
self.assertEqual(
Binary.from_twoscomplement(
TwosComplement("1110.00e+00", simplify=False), simplify=False
),
"-10e0",
)
self.assertEqual(
Binary.from_twoscomplement(
TwosComplement("1110.00e2", simplify=False), simplify=False
),
"-10e2",
)
self.assertEqual(
Binary.from_twoscomplement(
TwosComplement("1110.01e2", simplify=False), simplify=False
),
"-1.11e2",
)
self.assertEqual(
Binary.from_twoscomplement(
TwosComplement("1110.01e-2", simplify=False), simplify=False
),
"-1.11e-2",
)
self.assertEqual(
Binary.from_twoscomplement(
TwosComplement("00.00", simplify=False), simplify=False
),
"00.00",
)
with self.assertRaises(TypeError):
Binary.from_twoscomplement("10") # should fail
with self.assertRaises(ValueError):
Binary.from_twoscomplement(TwosComplement("102")) # should fail
with self.assertRaises(ValueError):
Binary.from_twoscomplement(TwosComplement("0b10")) # should fail
with self.assertRaises(TypeError):
Binary.from_twoscomplement(Binary(1)) # should fail
with self.assertRaises(TypeError):
Binary.from_twoscomplement("inf")
with self.assertRaises(TypeError):
Binary.from_twoscomplement("-Inf")
with self.assertRaises(TypeError):
Binary.from_twoscomplement("Nan")
##########################################################################
# Useful Constants (internal use only)
##########################################################################
""" Reusable defaults """
_Infinity = Binary(_INF) # "Inf"
_NegativeInfinity = Binary(_NINF) # "-Inf"
_NaN = Binary(_NAN) # "NaN"
_Zero = Binary(0)
_One = Binary(1)
_NegativeOne = Binary(-1)
# End of class
``` |
{
"source": "jonnyff/Outliers_NASA-Space-Apps",
"score": 2
} |
#### File: Outliers_NASA-Space-Apps/webserver/ProjetoSS.py
```python
from flask import Flask, request, render_template
from flask import json
from requests.auth import HTTPBasicAuth
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
ipcliente = request.remote_addr
programa = request.form['programa']
cmdchrome = "C:\ChromeSetup.exe /silent /install"
cmdnotepad = "C:\\npp.6.9.2.Installer.exe /S"
comando = ""
programafonte = ""
if programa == "googlechrome":
comando = cmdchrome
programafonte = "C:\ChromeSetup.exe"
elif programa == "notepad":
comando = cmdnotepad
programafonte = "C:\\npp.6.9.2.Installer.exe"
mensagem = {
'flowUuid': '3864e244-3ff8-4553-a5b4-38d6e5689744',
'inputs': {
'programafonte':programafonte, 'ipcliente': ipcliente, 'comando': comando}
}
r = requests.post('http://10.88.0.122:8080/oo/rest/v2/executions/',
data=json.dumps(mensagem),
auth=HTTPBasicAuth('admin', 'admin'), headers={'Content-Type': 'application/json'})
print(r.text)
return render_template('index.html')
else:
return render_template('index.html')
if __name__ == "__main__":
#Adicionar o host do servidor que vai rodar e a porta. EXEMPLO: app.run(host='192.168.0.1', port='8080')
app.run(host="noruega.unit.br", port="80")
``` |
{
"source": "JonnyFunFun/pyParty",
"score": 2
} |
#### File: pyParty/admin/settings.py
```python
from admin.models import Setting, PYPARTY_SETTINGS
def get_setting(name):
try:
setting = Setting.objects.get(name=name)
except Setting.DoesNotExist:
# save the default record for this item
setting = Setting()
setting.name = name
setting.value = PYPARTY_SETTINGS[name]
setting.save()
return setting.value
def save_setting(name, value):
try:
setting = Setting.objects.get(name=name)
except Setting.DoesNotExist:
setting = Setting()
setting.name = name
if value == 'on':
value = '1'
setting.value = value
setting.save()
TEMPLATE_DEBUG = True
```
#### File: admin/users/views.py
```python
from global_decorators import render_to
from accounts.models import UserProfile, FLAG_ADMIN, FLAG_OP, FLAG_VIP
from admin.decorators import admin_only
from django.contrib import messages
from django.http import HttpResponseRedirect
from admin.users.forms import AdminProfileForm
from django.contrib.auth.models import User
from django.views.decorators.http import require_POST
@admin_only
@render_to('accounts_list.html')
def index(request):
title = "Accounts"
icon = "user"
accounts = UserProfile.objects.all()
return locals()
@admin_only
@render_to("accounts_edit.html")
def edit(request, user_id):
try:
profile = UserProfile.objects.get(user_id=user_id)
except UserProfile.DoesNotExist:
messages.error(request, "Unable to find a user with ID %s" % user_id)
return HttpResponseRedirect('/admin/users/')
title = "Edit %s" % profile.user.username
icon = "users"
form = AdminProfileForm(instance=profile, initial={'username': profile.user.username,
'first_name': profile.user.first_name,
'last_name': profile.user.last_name,
'admin': profile.admin,
'op': profile.operator,
'vip': profile.vip})
form.helper.form_action = "/admin/users/%s/save/" % user_id
return locals()
@admin_only
@render_to("accounts_delete.html")
def delete(request, user_id):
try:
profile = UserProfile.objects.get(user_id=user_id)
except UserProfile.DoesNotExist:
messages.error(request, "Unable to find a user with ID %s" % user_id)
return HttpResponseRedirect('/admin/users/')
title = "Edit %s" % profile.user.username
icon = "users"
if request.POST.get('axn') == 'delete':
# do it!
profile.user.delete()
messages.success(request, "The user %s has been deleted!" % profile.user.username)
return HttpResponseRedirect("/admin/users/")
elif request.POST.get('axn') == 'cancel':
return HttpResponseRedirect("/admin/users/")
return locals()
@admin_only
@require_POST
@render_to("accounts_edit.html")
def save(request, user_id):
try:
profile = UserProfile.objects.get(user_id=user_id)
except UserProfile.DoesNotExist:
messages.error(request, "Unable to find a user with ID %s" % user_id)
return HttpResponseRedirect('/admin/users/')
title = "Edit %s" % profile.user.username
icon = "users"
if request.POST.get('save_changes'):
form = AdminProfileForm(data=request.POST, files=request.FILES, instance=profile)
form.helper.form_action = "/admin/users/%s/save/" % user_id
if form.is_valid():
if request.POST.get('username', profile.user.username) != profile.user.username:
# change username
try:
check = User.objects.get(username=request.POST.get('username'))
messages.error(request, 'That username has already been taken!')
return locals()
except User.DoesNotExist:
profile.user.username = request.POST.get('username')
profile.user.save()
form.save()
# flags
if request.POST.get('admin', 'off') == 'on' and not profile.admin:
profile.set_flag(FLAG_ADMIN)
if request.POST.get('op', 'off') == 'on' and not profile.operator:
profile.set_flag(FLAG_OP)
if request.POST.get('vip', 'off') == 'on' and not profile.vip:
profile.set_flag(FLAG_VIP)
profile.save()
# first/last name
profile.user.first_name = request.POST.get('first_name', profile.user.first_name)
profile.user.last_name = request.POST.get('last_name', profile.user.last_name)
profile.user.save()
messages.success(request, 'The profile has been updated!')
else:
messages.error(request, 'Unable to save changes to the profile!')
return locals()
return HttpResponseRedirect("/admin/users/")
```
#### File: pyParty/music/shoutcast.py
```python
from __future__ import print_function
from music.models import Music
from django.core.urlresolvers import resolve
from id3reader import id3reader
import os
import array
import logging
# shoutcast / buffer constants
CHUNKSIZE = 32 * 1024
CHUNKS_IN_BUFFER = 32
MINIMUM_BYTES_IN_BUFFER = 4 * CHUNKSIZE
class ShoutCastStream(object):
fd = None
def __init__(self, request):
self.data = array.array('B') # array to hold music data
self.request = request
self.url = self.request.path
self.response = False # we haven't sent the initial response
self.response_data = [
"ICY 200 OK\r\n",
"icy-notice1:<BR>This stream requires\r\n",
"icy-notice2:Winamp, or another streaming media player<BR>\r\n",
"icy-name:pyParty ShoutCast\r\n",
"icy-genre:Mixed\r\n",
"icy-url:%s\r\n" % self.url,
"icy-pub:1\r\n",
"icy-br:128\r\n\r\n"
]
print("Starting streaming to %s (%s)" % (request.META.get('REMOTE_ADDR'), request.META.get('HTTP_USER_AGENT')))
self.getNextSong()
def __iter__(self):
return self
# handle getting the next song from the song source
def getNextSong(self):
try:
song, request = Music.next_song_and_request()
# file is gone, delete it and move on to the next one
fileName = song.filename
if not os.path.exists(fileName):
song.delete()
return self.getNextSong()
if request:
request.fulfilled = True
request.save()
Music.objects.filter(playing=True).update(playing=False)
song.playing = True
song.save()
print("Next song to play: %s" % fileName)
self.fd = open(fileName, 'rb')
self.file_size = os.path.getsize(fileName)
# if there is valid ID3 data, read it out of the file first,
# so we can skip sending it to the client
try:
self.id3 = id3reader.Reader(self.fd)
if isinstance(self.id3.header.size, int) and self.id3.header.size < self.file_size: # read out the id3 data
self.fd.seek(self.id3.header.size + 1, os.SEEK_SET)
except id3reader.Id3Error:
self.id3 = None
except StopIteration:
fileName = None
self.fd = None
except IOError:
self.fd = None
# refill the buffer
def refill_buffer(self):
try:
if self.fd: # could be None
for i in range(0, CHUNKS_IN_BUFFER):
self.data.fromfile(self.fd, CHUNKSIZE)
except EOFError:
self.fd.close()
self.getNextSong()
def next(self):
if not self.response:
data = array.array("B")
for i in self.response_data:
for elem in i:
data.append(ord(elem))
self.response = True
else:
# send audio data
# figure out how much data there is to send and send it
data = self.data[0:CHUNKSIZE]
data_len = len(data)
# get rid of the chunk we just sent - this means the buffer for a client shouldn't exceed 1M in size
self.data = self.data[data_len:]
if len(self.data) < MINIMUM_BYTES_IN_BUFFER:
self.refill_buffer()
return data.tostring()
def __del__(self):
self.fd.close()
Music.objects.filter(playing=True).update(playing=False)
print("Shoutcast stream closed.")
```
#### File: music/templatetags/music_filters.py
```python
from django import template
from music.models import Request
register = template.Library()
@register.filter
def has_requested(user, music):
try:
req = Request.objects.get(fulfilled=False, song=music)
except Request.DoesNotExist:
return False
return req.requestvote_set.filter(requester=user).count() != 0
```
#### File: pyParty/servers/models.py
```python
from django.db import models
from django.contrib.auth.models import User
from servers.query.source import SourceQuery
from servers.query.minecraft import MinecraftQuery
from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM, socket
from hooks import PartyHooks
SERVER_TYPES = (
('HLDS', 'HLDS/Source'),
('MINE', 'Minecraft'),
('OTHR', 'Other')
)
class Server(models.Model):
name = models.CharField(max_length=128)
desc = models.TextField(blank=True, default="")
operator = models.ForeignKey(User, related_name="servers")
address = models.IPAddressField(null=True)
port = models.IntegerField(null=True)
game = models.CharField(max_length=128)
server_type = models.CharField(max_length=4, choices=SERVER_TYPES, null=False, default='OTHR')
mod_approved = models.BooleanField(default=False, verbose_name="Approval Status")
def info(self):
info = self.desc
if self.server_type == 'HLDS':
# query HLDS server
try:
q = SourceQuery(self.address, self.port or 27015)
info = q.getInfo()
except:
pass
elif self.server_type == 'MINE':
# query minecraft
try:
q = MinecraftQuery(self.address, self.port or 25565)
info = q.get_rules()
except:
pass
PartyHooks.execute_hook('server.info')
# default stuff
return info
@property
def host_alive(self):
try:
return (socket(AF_INET, SOCK_STREAM).connect_ex((self.address, self.port)) == 0)
except:
pass
return False
```
#### File: servers/query/minecraft.py
```python
import socket
import struct
import time
class MinecraftQuery:
MAGIC_PREFIX = b'\xFE\xFD'
PACKET_TYPE_CHALLENGE = 9
PACKET_TYPE_QUERY = 0
HUMAN_READABLE_NAMES = dict(
game_id = "Game Name",
gametype = "Game Type",
motd = "Message of the Day",
hostname = "Server Address",
hostport = "Server Port",
map = "Main World Name",
maxplayers = "Maximum Players",
numplayers = "Players Online",
players = "List of Players",
plugins = "List of Plugins",
raw_plugins = "Raw Plugin Info",
software = "Server Software",
version = "Game Version",
)
def __init__(self, host, port, timeout=10, id=0, retries=2):
self.addr = (host, port)
self.id = id
self.id_packed = struct.pack('>l', id)
self.challenge_packed = struct.pack('>l', 0)
self.retries = 0
self.max_retries = retries
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.settimeout(timeout)
def send_raw(self, data):
self.socket.sendto(self.MAGIC_PREFIX + data, self.addr)
def send_packet(self, type, data=b''):
self.send_raw(struct.pack('>B', type) + self.id_packed + self.challenge_packed + data)
def read_packet(self):
buff = self.socket.recvfrom(1460)[0]
type = struct.unpack('>B', buff[0])[0]
id = struct.unpack('>l', buff[1:5])[0]
return type, id, buff[5:]
def handshake(self, bypass_retries=False):
self.send_packet(self.PACKET_TYPE_CHALLENGE)
try:
type, id, buff = self.read_packet()
except:
if not bypass_retries:
self.retries += 1
if self.retries < self.max_retries:
self.handshake(bypass_retries=bypass_retries)
return
else:
raise
self.challenge = int(buff[:-1])
self.challenge_packed = struct.pack('>l', self.challenge)
def get_status(self):
if not hasattr(self, 'challenge'):
self.handshake()
before = time.time()
self.send_packet(self.PACKET_TYPE_QUERY)
try:
type, id, buff = self.read_packet()
except:
self.handshake()
return self.get_status()
after = time.time()
data = {}
data['motd'], data['gametype'], data['map'], data['numplayers'], data['maxplayers'], buff = buff.split('\x00', 5)
data['hostport'] = struct.unpack('<h', buff[:2])[0]
buff = buff[2:]
data['hostname'] = buff[:-1]
for key in ('numplayers', 'maxplayers'):
try:
data[key] = int(data[key])
except:
pass
data['ping'] = after - before
return data
def get_rules(self):
if not hasattr(self, 'challenge'):
self.handshake()
before = time.time()
self.send_packet(self.PACKET_TYPE_QUERY, self.id_packed)
try:
type, id, buff = self.read_packet()
except:
self.retries += 1
if self.retries < self.max_retries:
self.handshake(bypass_retries=True)
return self.get_rules()
else:
raise
after = time.time()
data = {}
buff = buff[11:] # splitnum + 2 ints
items, players = buff.split('\x00\x00\x01player_\x00\x00') # Shamefully stole from https://github.com/barneygale/MCQuery
if items[:8] == 'hostname':
items = 'motd' + items[8:]
items = items.split('\x00')
data = dict(zip(items[::2], items[1::2]))
players = players[:-2]
if players:
data['players'] = players.split('\x00')
else:
data['players'] = []
for key in ('numplayers', 'maxplayers', 'hostport'):
try:
data[key] = int(data[key])
except:
pass
data['raw_plugins'] = data['plugins']
data['software'], data['plugins'] = self.parse_plugins(data['raw_plugins'])
data['ping'] = after - before
return data
def parse_plugins(self, raw):
parts = raw.split(':', 1)
server = parts[0].strip()
plugins = []
if len(parts) == 2:
plugins = parts[1].split(';')
plugins = map(lambda s: s.strip(), plugins)
return server, plugins
``` |
{
"source": "jonnyg23/flask-rest-ecommerce",
"score": 2
} |
#### File: src/auth/auth.py
```python
import json
import os
from flask import request, abort
from functools import wraps
from jose import jwt
from urllib.request import urlopen
from dotenv import load_dotenv, find_dotenv
import constants
ENV_FILE = find_dotenv()
if ENV_FILE:
load_dotenv(ENV_FILE)
database_path = os.environ.get(constants.DATABASE_URL)
auth0_callback_url = os.environ.get(constants.AUTH0_CALLBACK_URL)
auth0_client_id = os.environ.get(constants.AUTH0_CLIENT_ID)
auth0_client_secret = os.environ.get(constants.AUTH0_CLIENT_SECRET)
auth0_domain = os.environ.get(constants.AUTH0_DOMAIN)
auth0_base_url = 'https://' + auth0_domain
auth0_api_audience = os.environ.get(constants.AUTH0_API_AUDIENCE)
algorithms = os.environ.get(constants.ALGORITHMS)
# ----------------------------------------------------------------------------#
# AuthError Exception
# A standardized way to communicate auth failure modes
# ----------------------------------------------------------------------------#
class AuthError(Exception):
def __init__(self, error, status_code):
self.error = error
self.status_code = status_code
# ----------------------------------------------------------------------------#
# Auth Header
# ----------------------------------------------------------------------------#
# get_token_auth_header() method should do the following:
# 1. Attempt to get the header from request.
# i. If header is not present - raise AuthError
# 2. Attempt to split bearer, as well as the token.
# i. If header is malformed - raise AuthError
# 3. Return the token part of the header
def get_token_auth_header():
"""
Obtains the Access Token from the Authorization Header.
--------------------
Inputs <datatype>:
- None
Returns <datatype>:
- Token <string> OR Raises error code 401
"""
auth = request.headers.get('Authorization', None)
if not auth:
raise AuthError({
'code': 'authorization_header_missing',
'description': 'Authorization header is expected.'
}, 401)
parts = auth.split()
if parts[0].lower() != 'bearer':
raise AuthError({
'code': 'invalid_header',
'description': 'Authorization header must start with "Bearer".'
}, 401)
elif len(parts) == 1:
raise AuthError({
'code': 'invalid_header',
'description': 'Token not found.'
}, 401)
elif len(parts) > 2:
raise AuthError({
'code': 'invalid_header',
'description': 'Authorization header must be bearer token.'
}, 401)
token = parts[1]
return token
# check_permissions() method should do the following:
# 1. Raise AuthError if permissions not in the payload.
# !!NOTE Review RBAC settings in Auth0
# 2. Raise an AuthError if the permission string is not in the payload
# permission array.
# i. If the permission string is in the payload - return True
def check_permissions(permission, payload):
"""
Checks if permissions are included in the payload.
Raises AuthError otherwise.
--------------------
Inputs <datatype>:
- permission <string>: (i.e. 'post:drink')
- payload <string>: Decoded JWT payload
Returns <datatype>:
- True <boolean> OR Raises error codes 400 or 403
"""
if 'permissions' not in payload:
raise AuthError({
'code': 'invalid_claims',
'description': 'Permissions not included in JWT.'
}, 400)
if permission not in payload['permissions']:
raise AuthError({
'code': 'unauthorized',
'description': 'Permission not found.'
}, 401)
return True
# verify_decode_jwt() method should do/verify the following:
# 1. The input token should be an Auth0 token with key id (kid)
# 2. The method should verify the token using Auth0 /.well-known/jwks.json
# 3. The method should decode the payload from the token.
# 4. The method should validate the claims.
# 5. Finally, it should return the decoded payload
# !!NOTE urlopen has a common certificate error described here:
# https://stackoverflow.com/questions/50236117/
# scraping-ssl-certificate-verify-failed-error-for-http-en-wikipedia-org
def verify_decode_jwt(token):
"""
Verifies the decoded JWT token.
Raises AuthError if invalid.
--------------------
Inputs <datatype>:
- token <string>: A JSON web token
Returns <datatype>:
- payload <string> OR Raises error codes 400 or 401
"""
jsonurl = urlopen(f'https://{auth0_domain}/.well-known/jwks.json')
jwks = json.loads(jsonurl.read())
unverified_header = jwt.get_unverified_header(token)
rsa_key = {}
if 'kid' not in unverified_header:
raise AuthError({
'code': 'invalid_header',
'description': 'Authorization malformed.'
}, 401)
for key in jwks['keys']:
if key['kid'] == unverified_header['kid']:
rsa_key = {
'kty': key['kty'],
'kid': key['kid'],
'use': key['use'],
'n': key['n'],
'e': key['e']
}
if rsa_key:
try:
payload = jwt.decode(
token,
rsa_key,
algorithms=algorithms,
audience=auth0_api_audience,
issuer='https://' + auth0_domain + '/'
)
return payload
except jwt.ExpiredSignatureError:
raise AuthError({
'code': 'token_expired',
'description': 'Token expired.'
}, 401)
except jwt.JWTClaimsError:
raise AuthError({
'code': 'invalid_claims',
'description': 'Incorrect claims. \
Please, check the audience and issuer.'
}, 401)
except Exception:
raise AuthError({
'code': 'invalid_header',
'description': 'Unable to parse authentication token.'
}, 400)
raise AuthError({
'code': 'invalid_header',
'description': 'Unable to find the appropriate key.'
}, 400)
# requires_auth() method should do the following:
# 1. It should use the get_token_auth_header method to get the token.
# 2. It should use the verify_decode_jwt method to decode the jwt.
# 3. It should use the check_permissions method to validate claims and
# check the requested permission
# 4. The method must return the decorator which passes the decoded payload
# to the decorated method
def requires_auth(permission=''):
def requires_auth_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
token = get_token_auth_header()
payload = verify_decode_jwt(token)
check_permissions(permission, payload)
return f(payload, *args, **kwargs)
except Exception as e:
abort(401)
return wrapper
return requires_auth_decorator
``` |
{
"source": "Jonnygibb/QnA-board-wmgtss",
"score": 2
} |
#### File: app/board/views.py
```python
from django.shortcuts import render, redirect
from django.urls.base import reverse
from django.views.generic.edit import FormView
from django.views.generic import (ListView,
CreateView,
UpdateView,
DeleteView)
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.hashers import make_password
from django.contrib.auth import authenticate
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.contrib import messages
from django.contrib.auth.mixins import UserPassesTestMixin
from .forms import SignUpForm, LogInForm
from .models import Comment, Answer, User, Questions
class BoardListView(ListView):
model = Questions
template_name = 'users/home.html'
context_object_name = 'questions'
ordering = ['created_at']
# Adds protection to home page by ensuring that only authenticated users can access it
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(BoardListView, self).dispatch(request, *args, **kwargs)
class QuestionCreateView(CreateView):
"""
Create view for Question model
"""
# Specifies which model the view should update.
model = Questions
# Points the view to which template the model should be rendered on.
template_name = 'users/questions_form.html'
# Specifies which fields from the model that the view should render.
fields = ['title', 'description']
# On successful object creation, success url is where the user should
# be redirected. In this case it is back to the home page.
success_url = '/'
# Method decorator adds protection to create view by ensuring
# that only authenticated users can access it.
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
"""
Overwrites Django dispatch method that handles incoming
http requests
"""
return super(CreateView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Overwrites the form valid method to ensure that the logged in
user is set as the questions creator automatically
"""
form.instance.user = self.request.user
return super().form_valid(form)
class QuestionUpdateView(UserPassesTestMixin, UpdateView):
"""
Update view for Question model
"""
# Specifies which model the view should update.
model = Questions
# Points the view to which template the model should be rendered on.
# The template is the same as the create view since the question
# can be created and updated using the same template.
template_name = 'users/questions_form.html'
# Specifies which fields from the model that the view should render.
fields = ['title', 'description']
# On successful object creation, success url is where the user should
# be redirected. In this case it is back to the home page.
success_url = '/'
# Method decorator adds protection to create view by ensuring
# that only authenticated users can access it.
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
"""
Overwrites Django dispatch method that handles incoming
http requests
"""
return super(UpdateView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Overwrites the form valid method to ensure that the logged in
user is set as the questions creator automatically
"""
form.instance.user = self.request.user
return super().form_valid(form)
def test_func(self):
"""
Uses a test to ensure that the creator of the question is only allowed to delete
questions created by themselves.
"""
question = self.get_object()
if self.request.user == question.user:
return True
else:
return False
class QuestionDeleteView(UserPassesTestMixin, DeleteView):
"""
Delete view for Question model
"""
# Specifies which model the view should update.
model = Questions
# Points the view to which template the model should be rendered on.
# The template is unique since the delete page only asks the user
# whether they are sure they want to delete the object.
template_name = 'users/questions_confirm_delete.html'
# On successful object creation, success url is where the user should
# be redirected. In this case it is back to the home page.
success_url = '/'
# Method decorator adds protection to create view by ensuring
# that only authenticated users can access it.
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(QuestionDeleteView, self).dispatch(request, *args, **kwargs)
def test_func(self):
"""
Uses a test to ensure that the creator of the question is only allowed to delete
questions created by themselves. If a user is a superuser (Tutor) they are also
able to delete a question.
"""
question = self.get_object()
if (self.request.user == question.user) or (self.request.user.is_superuser):
return True
else:
return False
class AnswerCreateView(CreateView):
model = Answer
template_name = 'users/answer_form.html'
fields = ['description']
success_url = '/'
# Adds protection to questions by ensuring that only authenticated users can access it
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
self.question = Questions.objects.get(slug=kwargs['slug'])
return super(CreateView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Overriding the form valid method to ensure that the logged in
user is set as the questions creator automatically
"""
form.instance.user = self.request.user
form.instance.question = self.question
return super().form_valid(form)
class AnswerUpdateView(UserPassesTestMixin, UpdateView):
model = Answer
template_name = 'users/answer_form.html'
fields = ['description']
success_url = '/'
# Adds protection to questions by ensuring that only authenticated users can access it
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(AnswerUpdateView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Overriding the form valid method to ensure that the logged in
user is set as the questions creator automatically
"""
form.instance.user = self.request.user
return super().form_valid(form)
def test_func(self):
"""
Uses a test to ensure that the creator of the question is only allowed to update
questions created by themselves
"""
answer = self.get_object()
if self.request.user == answer.user:
return True
else:
return False
class AnswerDeleteView(UserPassesTestMixin, DeleteView):
model = Answer
template_name = 'users/answer_confirm_delete.html'
success_url = '/'
# Adds protection to questions by ensuring that only authenticated users can access it
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(AnswerDeleteView, self).dispatch(request, *args, **kwargs)
def test_func(self):
"""
Uses a test to ensure that the creator of the question is only allowed to delete
questions created by themselves
"""
comment = self.get_object()
if (self.request.user == comment.user) or (self.request.user.is_superuser):
return True
else:
return False
class CommentCreateView(CreateView):
model = Comment
template_name = 'users/comment_form.html'
fields = ['description']
success_url = '/'
# Adds protection to questions by ensuring that only authenticated users can access it
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
self.question = Questions.objects.get(slug=kwargs['slug'])
return super(CreateView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Overriding the form valid method to ensure that the logged in
user is set as the questions creator automatically
"""
form.instance.user = self.request.user
form.instance.question = self.question
return super().form_valid(form)
class CommentUpdateView(UserPassesTestMixin, UpdateView):
model = Comment
template_name = 'users/comment_form.html'
fields = ['description']
success_url = '/'
# Adds protection to questions by ensuring that only authenticated users can access it
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(CommentUpdateView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""
Overriding the form valid method to ensure that the logged in
user is set as the questions creator automatically
"""
form.instance.user = self.request.user
return super().form_valid(form)
def test_func(self):
"""
Uses a test to ensure that the creator of the question is only allowed to update
questions created by themselves
"""
answer = self.get_object()
if self.request.user == answer.user:
return True
else:
return False
class CommentDeleteView(UserPassesTestMixin, DeleteView):
model = Comment
template_name = 'users/comment_confirm_delete.html'
success_url = '/'
# Adds protection to questions by ensuring that only authenticated users can access it
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(CommentDeleteView, self).dispatch(request, *args, **kwargs)
def test_func(self):
"""
Uses a test to ensure that the creator of the question is only allowed to delete
questions created by themselves
"""
comment = self.get_object()
if (self.request.user == comment.user) or (self.request.user.is_superuser):
return True
else:
return False
class SignUpView(FormView):
"""
Class view for sign up page.
Uses Django Forms to create a sign up page with first name,
last name, email, username and password.
Django authentication module handles password hashing.
User model is used to save users details to the database.
"""
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(SignUpView, self).dispatch(request, *args, **kwargs)
def get(self, request):
"""
Method for get request of signup page
"""
# Set website content equal to the sign up form
content = {}
content['form'] = SignUpForm
# Return the form rendered into html
return render(request, 'registration/register.html', content)
def post(self, request):
"""
Method for post request of signup page
"""
# Set content to sign up form
content = {}
form = SignUpForm(request.POST, request.FILES or None)
# If post content is valid, login the user and return them to the home page
if form.is_valid():
user = form.save(commit=False)
user.password = <PASSWORD>(form.cleaned_data['password'])
user.username = form.cleaned_data['username']
user.save()
login(request, user)
messages.success(request, 'Account created for {}!'.format(user.username))
return redirect(reverse('home'))
# Else, re render the sign in form again
content['form'] = form
template = 'registration/register.html'
messages.warning(request, 'Account could not be created')
return render(request, template, content)
class LogInView(FormView):
"""
Class view for login page.
Uses Django Forms to create a Form with a username and password field
along with a login button.
Django authentication module is used to log users in and out.
"""
# Set website content equal to the login form
content = {}
content['form'] = LogInForm
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(LogInView, self).dispatch(request, *args, **kwargs)
def get(self, request):
"""
Method for get request of login page
"""
content = {}
# If the user is already authenticated, redirect them to the home page
if request.user.is_authenticated:
return redirect(reverse('home'))
# Otherwise render the log in form
content['form'] = LogInForm
return render(request, 'login.html', content)
def post(self, request):
"""
Method for post request of login page
"""
content = {}
# Instanciate username and password from post request
username = request.POST['username']
password = request.POST['password']
try:
# Search for user object in User records for given username
users = User.objects.filter(username=username)
# Attempt to authenticate user
user = authenticate(request, username=users.first().username, password=password)
# If successful, log the user in and redirect them to the home page
login(request, user)
return(redirect(reverse('home')))
except Exception as e:
# If an error occurs during authentication, reload the login page and display the error message
content = {}
content['form'] = LogInForm
content['error'] = 'Could not login with provided information' + e
return render(request, 'login.html', content)
``` |
{
"source": "jonnygovish/News-Headlines",
"score": 3
} |
#### File: News-Headlines/test/test_articles.py
```python
import unittest
from app.models import Articles
class TestArticle(unittest.TestCase):
'''
Test Class to test the behaviour of the Article class
'''
def setUp(self):
'''
Set up that will run before every Test
'''
self.new_article = Articles("<NAME>","Redesigning the TechCrunch app","Over the last two years we have been working hard to improve the experience of TechCrunch products for our readers","https://techcrunch.com/2017/10/21/redesigning-the-techcrunch-app/","https://tctechcrunch2011.files.wordpress.com/2017/10/1-lead-image.jpg","2017-10-21T11:00:53Z")
def test_instance(self):
self.assertTrue(isinstance(self.new_article,Articles))
if __name__ == '__main__':
unittest.main(verbosity=2)
``` |
{
"source": "jonnygovish/pitch-hub",
"score": 3
} |
#### File: app/main/views.py
```python
from flask import render_template,request,redirect,url_for,abort
from . import main
from ..models import Pitch, Category,Comments
from flask_login import login_required, current_user
from .forms import PitchForm,CommentForm
from datetime import datetime
@main.route('/')
def index():
"""
"""
category = Category.get_categories()
pitch = Pitch.get_all_pitches()
title = "Welcome to Pitch Hub"
return render_template('index.html', title = title, category = category, pitch =pitch)
@main.route('/category/<int:id>')
def category(id):
"""
"""
category = Category.query.get(id)
pitch = Pitch.get_pitch(id)
form = PitchForm()
title = 'pitches'
return render_template('category.html', category = category, pitch = pitch, title = title, pitch_form = form)
@main.route('/category/pitch/new/<int:id>',methods = ["GET","POST"])
@login_required
def new_pitch(id):
category = Category.query.filter_by(id=id).first()
if category is None:
abort(404)
form = PitchForm()
if form.validate_on_submit():
content = form.content.data
new_pitch = Pitch(content = content,category_id = category.id,user_id = current_user.id)
new_pitch.save_pitch()
return redirect(url_for('.category', id=category.id))
title = "New pitch page"
return render_template('category.html', pitch_form = form, title = title )
@main.route('/pitch/<int:id>')
def single_pitch(id):
pitch = Pitch.query.get(id)
comment = Comments.get_comment(pitch.id)
title = "Pitch page"
return render_template('pitch.html', pitch = pitch, comment = comment, title= title)
@main.route('/pitch/new/<int:id>', methods = ["GET","POST"])
@login_required
def new_comment(id):
pitch = Pitch.query.filter_by(id =id).first()
if pitch is None:
abort(404)
form = CommentForm()
if form.validate_on_submit():
body = form.body.data
new_comment = Comments(body = body,pitch_id = pitch.id, user_id = current_user.id)
new_comment.save_comment()
return redirect(url_for('.single_pitch', id=pitch.id))
title = "New Comment"
return render_template('new_comment.html', comment_form = form, title = title)
```
#### File: migrations/versions/c50004780dce_version_1_1.py
```python
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c50004780dce'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('categories_pitch_id_fkey', 'categories', type_='foreignkey')
op.drop_column('categories', 'pitch_id')
op.add_column('pitches', sa.Column('category_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'pitches', 'categories', ['category_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'pitches', type_='foreignkey')
op.drop_column('pitches', 'category_id')
op.add_column('categories', sa.Column('pitch_id', sa.INTEGER(), autoincrement=False, nullable=True))
op.create_foreign_key('categories_pitch_id_fkey', 'categories', 'pitches', ['pitch_id'], ['id'])
# ### end Alembic commands ###
``` |
{
"source": "jonnygovish/The-Insta",
"score": 2
} |
#### File: The-Insta/gram/views.py
```python
from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from .forms import UserForm,ProfileForm,PostForm
from django.contrib import messages
from django.db import transaction
from django.contrib.auth.models import User
from .models import Profile,Post,Comment,Like
from django.core.urlresolvers import reverse
from django.http import JsonResponse
from annoying.decorators import ajax_request
# Create your views here.
@login_required(login_url='/accounts/login/')
def index(request):
# Only return posts from users that are being followed
users_followed = request.user.profile.following.all()
posts = Post.objects.filter(profile__in=users_followed).order_by('-posted_on')
return render(request,'index.html',{"posts":posts})
@login_required
@transaction.atomic
def update_profile(request, username):
user = User.objects.get(username = username)
if request.method == 'POST':
user_form = UserForm(request.POST, instance = request.user)
profile_form = ProfileForm(request.POST, instance = request.user.profile,files =request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, ('Your profile was successfully updated!'))
return redirect(reverse('profile', kwargs={'username': request.user.username}))
else:
messages.error(request, ('Please correct the error below.'))
else:
user_form = UserForm(instance = request.user)
profile_form = ProfileForm(instance = request.user.profile)
return render(request, 'profiles/profile_form.html', {"user_form": user_form,"profile_form": profile_form})
@login_required
def profile(request, username):
user = User.objects.get(username = username)
if not user:
return redirect('Home')
profile = Profile.objects.get(user =user)
title = f"{user.username}"
return render(request, 'profiles/profile.html', {"title": title, "user":user, "profile":profile})
def followers(request, username):
user = user = User.objects.get(username = username)
user_profile = Profile.objects.get(user=user)
profiles = user_profile.followers.all
title = "Followers"
return render(request, 'follow_list.html', {"title": title, "profiles":profiles})
def following(request, username):
user = user = User.objects.get(username = username)
user_profile = Profile.objects.get(user=user)
profiles = user_profile.following.all()
title = "Following"
return render(request, 'follow_list.html', {"title": title, "profiles":profiles})
@login_required
def posts(request):
if request.method == 'POST':
form = PostForm(request.POST,files = request.FILES)
if form.is_valid():
post = Post(profile = request.user.profile, title = request.POST['title'], image = request.FILES['image'])
post.save()
return redirect('profile', kwargs={'username':request.user.username})
else:
form = PostForm()
return render(request, 'post_picture.html', {"form": form})
def post(request, pk):
post = Post.objects.get(pk=pk)
try:
like = Like.objects.get(post=post, user=request.user)
liked = 1
except:
like = None
liked = 0
return render(request, 'post.html', {"post": post})
def explore(request):
random_posts = Post.objects.all().order_by('?')[:40]
return render(request, 'explore.html', {"posts":random_posts})
def likes(request, pk):
post = Post.objects.get(pk=pk)
profiles = Like.objects.filter(post=post)
title = 'Likes'
return render(request, 'follow_list.html', {"title": title, "profiles":profiles})
@ajax_request
@login_required
def add_like(request):
post_pk = request.POST.get('post_pk')
post = Post.objects.get(pk=post_pk)
try:
like = Like(post=post, user=request.user)
like.save()
result = 1
except Exception as e:
like = Like.objects.get(post=post, user=request.user)
like.delete()
result = 0
return {
'result': result,
'post_pk': post_pk
}
@ajax_request
@login_required
def add_comment(request):
comment_text = request.POST.get('comment_text')
post_pk = request.POST.get('post_pk')
post = Post.objects.get(pk=post_pk)
commenter_info = {}
try:
comment = Comment(comment=comment_text, user=request.user, post=post)
comment.save()
username = request.user.username
profile_url = reverse('profile', kwargs={'username': request.user})
commenter_info = {
'username': username,
'profile_url': profile_url,
'comment_text': comment_text
}
result = 1
except Exception as e:
print(e)
result = 0
return {
'result': result,
'post_pk': post_pk,
'commenter_info': commenter_info
}
@ajax_request
@login_required
def follow_toggle(request):
user_profile = Profile.objects.get(user=request.user)
follow_profile_pk = request.POST.get('follow_profile_pk')
follow_profile = Profile.objects.get(pk=follow_profile_pk)
try:
if user_profile != follow_profile:
if request.POST.get('type') == 'follow':
user_profile.following.add(follow_profile)
follow_profile.followers.add(user_profile)
elif request.POST.get('type') == 'unfollow':
user_profile.following.remove(follow_profile)
follow_profile.followers.remove(user_profile)
user_profile.save()
result = 1
else:
result = 0
except Exception as e:
print(e)
result = 0
return {
'result': result,
'type': request.POST.get('type'),
'follow_profile_pk': follow_profile_pk
}
``` |
{
"source": "jonnyhyman/Programming-Classes",
"score": 4
} |
#### File: Programming-Classes/Math You Will Actually Use/Week12_OrbitsimReprise.py
```python
import matplotlib.pyplot as plt
from time import time
import numpy as np
# First, enable interactive plotting
plt.ion() # this fancy function makes a matplotlib window ALIIVEEEEE!
# We want to draw the planet.... So let's do it in POLAR COORDINATES!
# First we need some angles...
# This gets 100 evenly spaced angles between 0 and 2pi
circle_angles = np.linspace(0, (2*np.pi), 100)
# ----------------------------- Getting planet set up
R0 = 6371 * 1e3 # km * 1e3 => meters, radius of the planet
planet_r = np.linspace(R0, R0, 100) # get 100 evenly spaced R0s
planet_X = planet_r*np.cos(circle_angles) # X = take the cos(all_angles) * R0
planet_Y = planet_r*np.sin(circle_angles) # Y = take the cos(all_angles) * R0
planet = plt.plot(planet_X,planet_Y)[0] # make a plot with x and y
# ----------------------------- Getting spaceship all set up
''' NOTE: numpy.arrays are used throughout. why?
If you try [1,0,0] * 3 with Python lists, you'll get an error.
If you try [1,0,0] * 3 with Numpy arrays, you'll get [3,0,0]... Useful!
'''
alt_initial = 408_773 # ISS altitude, meters
# let's start y = initial altitude + radius of planet
pos_initial = np.array([
0.,
alt_initial + R0
])
vel_initial = np.array([
7666.736,
0.
]) # ISS horizontal velocity, meters per second
trail_points = 500 # how many points should the trail keep?
spaceship_trail = { 'x': [pos_initial[0]], 'y': [pos_initial[1]] }
spaceship = plt.plot(*pos_initial)[0] # give plot the position intially
# ----------------------------- Getting physics set up
def gravity(pos):
G = 6.674 * 1e-11 # universal gravitational constant
M = 5.972 * 1e24 # mass of planet, kg
# g = GM / r**2
gravity_acceleration = G*M / (np.sqrt(pos[0]**2 + pos[1]**2))**2
# which direction?
# what vector tells us the direction of gravity?
# the "down" vector of course!
# also known as the negative of the position vector (normalized)!
# pos / the magnitude of pos * gravity_acceleration at this alt
g = (-pos/np.sqrt(pos[0]**2 + pos[1]**2)) * gravity_acceleration
return g
pos = pos_initial
vel = vel_initial
acc = gravity(pos)
dt = 10
while True:
acc = gravity(pos)
vel += (acc) * dt
pos += (vel) * dt
spaceship_trail['x'].append(pos[0])
spaceship_trail['y'].append(pos[1])
spaceship.set_xdata(spaceship_trail['x']) # get all the saved x data
spaceship.set_ydata(spaceship_trail['y']) # get all the saved y data
print('Trail N : ', len(spaceship_trail['x']), end =' | ')
print('Altitude: ', round(np.linalg.norm(pos),2), end =' | ')
print('Velocity: ', round(np.linalg.norm(vel),2), end =' | ')
print('Gravity : ', round(np.linalg.norm(acc),2))
if len(spaceship_trail['x']) > trail_points:
spaceship_trail['x'].pop(0)
spaceship_trail['y'].pop(0)
plt.pause(.01)
```
#### File: Programming-Classes/Python Projects/ASSERT.py
```python
class Hendrick:
def __init__(self):
self.value = None
h0 = Hendrick()
h1 = Hendrick()
h0.value = int(1)
h1.value = float(1.0)
print(h0.value == h1.value)
print(h0.value is h1.value)
```
#### File: Programming-Classes/Python Projects/QtGraphics.py
```python
from PyQt5 import QtGui, QtCore, QtWidgets
import sys
Window = QtWidgets.QMainWindow
Brush = QtGui.QBrush
Pen = QtGui.QPen
Color = QtGui.QColor
Stage = QtWidgets.QGraphicsScene
ImageItem = QtWidgets.QGraphicsPixmapItem
Image = QtGui.QPixmap
class View(QtWidgets.QGraphicsView):
def __init__(self, stage):
super().__init__(stage)
self.stage = stage
i = Image('moon.jpg')
i = i.scaledToHeight(600)
self.stage.addItem(ImageItem(i))
if __name__=='__main__':
app = QtWidgets.QApplication(sys.argv)
stage = Stage(0, 0, 800, 600)
view = View(stage)
view.show()
app.exec_() # complete all execution code in the GUI
``` |
{
"source": "jonnyhyman/QuantumWaves",
"score": 3
} |
#### File: QuantumWaves/schrodinger/schrodinger.py
```python
from pathlib import Path
from numpy import ( sin, cos, exp, pi, tan, log, sinh, cosh, tanh, sinc,
sqrt, cbrt, angle, real, imag, abs,
arcsin, arccos, arctan, arcsinh, arccosh, arctanh)
from numpy import pi, e
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation
import scipy.linalg
import scipy as sp
import scipy.sparse
import scipy.sparse.linalg
from numba import njit
from schrodinger import util
import sys
from time import time
""" Original french comments from
https://github.com/Azercoco/Python-2D-Simulation-of-Schrodinger-Equation
Le programme simule le comportement d'un paquet d'onde gaussien suivant
l'équation de Schrödinger. L'algorithme utilisé est la méthode
Alternating direction implicit method.
La simulation permet de configurer un potentiel constant avec le temps
ainsi que la présence d'obstacles (qui sont gérés comme des barrières
de potentiel très élévées).
La fonction d'onde complexe est affichée en convertissant les nombres
complexes en format de couleur HSV.
x , y : Les positions de départ du paquet d'onde
Kx, Ky : Ses nombres d'onde
Ax, Ay : Ses facteurs d'étalements selon x et y
V : L'expression du potentiel
O : L'expression de la présence d'obstacles
Le potentiel et la présence d'obstacle doivent être exprimés comme des
expressions Python valides dépendant de x et y (valant respectivement
un float et un boolean) car le progamme utilise la fonction Python
eval() pour les évaluer.
"""
""" Translated by Google Translate
https://github.com/Azercoco/Python-2D-Simulation-of-Schrodinger-Equation
The program simulates the behavior of a Gaussian wave packet following the
Schrödinger's equation. The algorithm used is the method
Alternating direction implicit method.
The simulation makes it possible to configure a constant potential over time
as well as the presence of obstacles (which are managed as barriers
very high potential).
Complex wave function is displayed by converting numbers
complex in HSV color format.
x, y: The starting positions of the wave packet
Kx, Ky: The numbers of the wave
Ax, Ay: Its spreading factors along x and y
V: The expression of potential
O: The expression of the presence of obstacles
The potential and the presence of obstacles must be expressed as
valid Python expressions depending on x and y (respectively
a float and a boolean) because the program uses the Python function
eval () to evaluate them.
"""
class Field:
def __init__(self):
self.potential_expr = None
self.obstacle_expr = None
def setPotential(self, expr):
self.potential_expr = expr
self.test_pot_expr()
def setObstacle(self, expr):
self.obstacle_expr = expr
self.test_obs_expr()
def test_pot_expr(self):
# required for eval()
x = 0
y = 0
try:
a = eval(self.potential_expr)
except:
print(self.potential_expr)
print('Potential calculation error: set to 0 by default')
self.potential_expr = '0'
def test_obs_expr(self):
# required for eval()
x = 0
y = 0
try:
a = eval(self.obstacle_expr)
except:
print('Error setting obstacle: Set to False by default')
self.obstacle_expr = 'False'
def isObstacle(self, x, y):
a = False
try:
a = eval(self.obstacle_expr)
except:
print(f'Invalid obstacle: {self.obstacle_expr}')
return a
def getPotential(self, x, y):
a = 0 + 0j
try:
a = eval(self.potential_expr)
except:
print(f'Invalid potential: {self.potential_expr}')
return a
def solve(wf, V_x, V_y, HX, HY, N, step, delta_t):
vector_wrt_x = util.x_concatenate(wf, N)
vector_derive_y_wrt_x = util.x_concatenate(util.dy_square(wf, N, step), N)
U_wrt_x = vector_wrt_x + (1j*delta_t/2 )*(vector_derive_y_wrt_x - V_x*vector_wrt_x)
U_wrt_x_plus = scipy.sparse.linalg.spsolve(HX, U_wrt_x)
wf = util.x_deconcatenate(U_wrt_x_plus, N)
vector_wrt_y = util.y_concatenate(wf, N)
vector_derive_x_wrt_y = util.y_concatenate(util.dx_square(wf, N, step), N)
U_wrt_y = vector_wrt_y + (1j*delta_t/2 )*(vector_derive_x_wrt_y - V_y *vector_wrt_y)
U_wrt_y_plus = scipy.sparse.linalg.spsolve(HY, U_wrt_y)
wf = util.y_deconcatenate(U_wrt_y_plus, N)
return wf
class Simulate:
SIZE = 10 # simulation self.size
# wavefunction collision
FPS = 60
DURATION = 5 # duration in seconds
DELTA_T = 0.005 # 0.125 #time elapsed per second of video
# wavefunction collapse
FPS = 60
DURATION = 5 # duration in seconds
DELTA_T = 0.01 # 0.125 #time elapsed per second of video
# wavefunction collapse 2 & 3
FPS = 60
DURATION = 5 # duration in seconds
DELTA_T = 0.03 # 0.125 #time elapsed per second of video
# wavefunction collapse 4
FPS = 60
DURATION = 5 # duration in seconds
DELTA_T = 0.005 # 0.125 #time elapsed per second of video
# entanglement1
FPS = 60
DURATION = 5 # duration in seconds
DELTA_T = 0.02 # 0.125 #time elapsed per second of video
# wavefunction movement
FPS = 60
DURATION = 5 # duration in seconds
DELTA_T = 0.005 # 0.125 #time elapsed per second of video
def __init__(self, N, collapse=False):
self.N = N # dimension in number of points of the simulation
self.FRAMES = self.DURATION * self.FPS
self.field = Field()
#Potential as a function of x and y
self.field.setPotential("0") # Ex: x**2+y**2"
#Obstacle: boolean expression in fct of x and y
# (set to False if you do not want an obstacle)
obstacles = ("(x > 0.5 and x < 1 and not "
"((y > 0.25 and y < 0.75) or "
"(y < -0.25 and y > -0.75)))")
obstacles = "False"
self.collapse = collapse
self.field.setObstacle(obstacles)
self.size = self.SIZE
#self.dataset = np.zeros((self.FRAMES,self.N,self.N), dtype='c16')
print(16*self.N*self.N*1e-9, 'GB of memory')
#if self.dataset.nbytes > 100e9:
# raise(Exception("TOO MUCH DATA FOR MEMORY"))
self.simulation_initialize()
""" ------ INITIAL CONDITIONS FOR WAVEFUNCTION COLLISION
x0 = [0, 0],
y0 = [0,1],
#number of waves
k_x = [0, 0],#5000
k_y = [0, 90000],#2500,
#spreading
a_x = [.2, .2], #.2, #.1,#.33,#0.05#.33
a_y = [.2, .2], #.2, #.1,#.33,#0.05#.33
"""
""" ------ INITIAL CONDITIONS FOR WAVEFUNCTION COLLISION 1
x0 = [0,0],
y0 = [0,1.5],
#number of waves
k_x = [10, 0],#5000
k_y = [0, 90000],#2500,
#spreading
a_x = [.15, .15], #.2, #.1,#.33,#0.05#.33
a_y = [.15, .15], #.2, #.1,#.33,#0.05#.33
"""
""" ------ INITIAL CONDITIONS FOR MOVEMENT SHOTS
x0 = [0],
y0 = [0],
#number of waves
k_x = [5000],
k_y = [2500],#2500,
#spreading
a_x = [.2], #.2, #.1,#.33,#0.05#.33
a_y = [.2], #.2, #.1,#.33,#0.05#.33
"""
""" ------ INITIAL CONDITIONS FOR WAVEFUNCTION COLLAPSE
x0 = [0],#0],
y0 = [0],
#number of waves
k_x = [50],
k_y = [25],#2500,
#spreading
a_x = [.25], #.2, #.1,#.33,#0.05#.33
a_y = [.25], #.2, #.1,#.33,#0.05#.33
"""
""" ------ INITIAL CONDITIONS FOR WAVEFUNCTION COLLAPSE 3
x0 = [0],#0],
y0 = [0],
#number of waves
k_x = [50],
k_y = [25],#2500,
#spreading
a_x = [.28], #.2, #.1,#.33,#0.05#.33
a_y = [.28], #.2, #.1,#.33,#0.05#.33
"""
""" ------ INITIAL CONDITIONS FOR ENTANGLEMENT
x0 = [0, 0],
y0 = [1,-1],
#number of waves
k_x = [0, 0],#5000
k_y = [-3000, 3000],#2500,
#spreading
a_x = [.15, .15], #.2, #.1,#.33,#0.05#.33
a_y = [.15, .15], #.2, #.1,#.33,#0.05#.33
"""
def simulation_initialize(self,
#characteristics of the wave packet gaussian 2D
#centre
x0 = [0],
y0 = [0],
#number of waves
k_x = [5000],
k_y = [2500],#2500,
#spreading
a_x = [.2], #.2, #.1,#.33,#0.05#.33
a_y = [.2], #.2, #.1,#.33,#0.05#.33
# keep below the same
wall_potential = 1e10,
):
""" initialize the wave packet """
N = self.N
step = self.SIZE/self.N
delta_t = self.DELTA_T/self.FPS
self.counter = 0
# create points at all xy coordinates in meshgrid
self.x_axis = np.linspace(-self.size/2, self.size/2, N)
self.y_axis = np.linspace(-self.size/2, self.size/2, N)
X, Y = np.meshgrid(self.x_axis, self.y_axis)
n = 0
phase = np.exp( 1j*(X*k_x[n] + Y*k_y[n]))
px = np.exp( - ((x0[n] - X)**2)/(4*a_x[n]**2))
py = np.exp( - ((y0[n] - Y)**2)/(4*a_y[n]**2))
wave_function = phase*px*py
norm = np.sqrt(util.integrate(np.abs(wave_function)**2, N, step))
self.wave_function = wave_function/norm
for n in range(1,len(x0)):
phase = np.exp( 1j*(X*k_x[n] + Y*k_y[n]))
px = np.exp( - ((x0[n] - X)**2)/(4*a_x[n]**2))
py = np.exp( - ((y0[n] - Y)**2)/(4*a_y[n]**2))
wave_function = phase*px*py
norm = np.sqrt(util.integrate(np.abs(wave_function)**2, N, step))
self.wave_function += wave_function/norm
LAPLACE_MATRIX = sp.sparse.lil_matrix(-2*sp.sparse.identity(N*N))
for i in range(N):
for j in range(N-1):
k = i*N + j
LAPLACE_MATRIX[k,k+1] = 1
LAPLACE_MATRIX[k+1,k] = 1
self.V_x = np.zeros(N*N, dtype='c16')
for j in range(N):
for i in range(N):
xx = i
yy = N*j
if self.field.isObstacle(self.x_axis[j], self.y_axis[i]):
self.V_x[xx+yy] = wall_potential
else:
self.V_x[xx+yy] = self.field.getPotential(self.x_axis[j],
self.y_axis[i])
self.V_y = np.zeros(N*N, dtype='c16')
for j in range(N):
for i in range(N):
xx = j*N
yy = i
if self.field.isObstacle(self.x_axis[i], self.y_axis[j]):
self.V_y[xx+yy] = wall_potential
else:
self.V_y[xx+yy] = self.field.getPotential(self.x_axis[i],
self.y_axis[j])
self.V_x_matrix = sp.sparse.diags([self.V_x], [0])
self.V_y_matrix = sp.sparse.diags([self.V_y], [0])
LAPLACE_MATRIX = LAPLACE_MATRIX/(step ** 2)
self.H1 = (1*sp.sparse.identity(N*N) - 1j*(delta_t/2)*(LAPLACE_MATRIX))
self.H1 = sp.sparse.dia_matrix(self.H1)
self.HX = (1*sp.sparse.identity(N*N) - 1j*(delta_t/2)*(LAPLACE_MATRIX - self.V_x_matrix))
self.HX = sp.sparse.dia_matrix(self.HX)
self.HY = (1*sp.sparse.identity(N*N) - 1j*(delta_t/2)*(LAPLACE_MATRIX - self.V_y_matrix))
self.HY = sp.sparse.dia_matrix(self.HY)
self.start_time = time()
self.i_time = time()
def simulate_frames(self):
for f in range(self.FRAMES):
start=time()
simulate_frame(f)
print('>>>',time()-start)
#dataname = f"C:/data/sim_{N}x{N}.npz"
#np.savez(dataname, self.dataset)
def simulate_frame(self, save=False, debug=True):
""" evolve according to schrodinger equation """
N = self.N
step = self.SIZE/self.N
delta_t = self.DELTA_T/self.FPS
self.wave_function = solve(self.wave_function,
self.V_x, self.V_y,
self.HX, self.HY,
N, step, delta_t)
if save:
self.save_wave(self.wave_function)
if debug:
self.print_update()
self.counter += 1
#if self.counter == self.FRAMES:
# self.simulation_initialize()
return self.wave_function
def collapse_wavefunction(self):
dist=np.abs(self.wave_function)**2 # joint pmf
dist/=dist.sum() # it has to be normalized
# generate the set of all x,y pairs represented by the pmf
pairs=np.indices(dimensions=(self.N, self.N)).T # here are all of the x,y pairs
# make n random selections from the flattened pmf without replacement
# whether you want replacement depends on your application
n=1
inds=np.random.choice(np.arange(self.N**2),
p=dist.reshape(-1),
size=n,
replace=False)
# inds is the set of n randomly chosen indicies into the flattened dist array...
# therefore the random x,y selections
# come from selecting the associated elements
# from the flattened pairs array
selection_place = pairs.reshape(-1,2)[inds][0]
# convert to sim coordinates
selection = (selection_place/self.N -.5) * (self.size)
selection = [selection[0], selection[1], 0, 0]
# collapsewidth
cw = 10 / self.N
print(">>> COLLAPSED TO =", selection, cw)
self.simulation_initialize(x0=[selection[0]],
y0=[selection[1]],
k_x = [selection[2]],
k_y = [selection[3]],
a_x=[cw], a_y=[cw])
return selection_place
def dual_collapse_wavefunction(self):
dist=np.abs(self.wave_function)**2 # joint pmf
dist/=dist.sum() # it has to be normalized
# generate the set of all x,y pairs represented by the pmf
pairs=np.indices(dimensions=(self.N, self.N)).T # here are all of the x,y pairs
# make n random selections from the flattened pmf without replacement
# whether you want replacement depends on your application
n=10
inds=np.random.choice(np.arange(self.N**2),
p=dist.reshape(-1),
size=n,
replace=False)
# inds is the set of n randomly chosen indicies into the flattened dist array...
# therefore the random x,y selections
# come from selecting the associated elements
# from the flattened pairs array
selection_place = pairs.reshape(-1,2)[inds][0]
# convert to sim coordinates
selection = (selection_place/self.N -.5) * (self.size)
momx, momy = 700, 1000
selection1 = [selection[0], selection[1], momx, momy]
# collapsewidth
cw = 10 / self.N
print(">>> COLLAPSED TO =", selection1, cw)
for i in range(1, n):
selection_place = pairs.reshape(-1,2)[inds][i]
# convert to sim coordinates
selection = (selection_place/self.N -.5) * (self.size)
normto1 = np.linalg.norm(selection - np.array([selection1[0],selection1[1]]))
if normto1 < 2:
print("CONTINUE, dist:", normto1)
continue
else:
print("FOUND IT!, dist:", normto1)
break
selection2 = [selection[0], selection[1], -momx, -momy]
# collapsewidth
cw = 10 / self.N
print(">>> COLLAPSED TO =", selection2, cw)
self.simulation_initialize(x0=[selection1[0], selection2[0]],
y0=[selection1[1], selection2[1]],
k_x = [selection1[2], selection2[2]],
k_y = [selection1[3], selection2[3]],
a_x=[cw, cw], a_y=[cw, cw])
return selection_place
def save_wave(self, data):
self.dataset[self.counter,:,:] = data
def print_update(self):
N = self.N
step = self.SIZE/self.N
delta_t = self.DELTA_T/self.FPS
NORM = np.sqrt(util.integrate(np.abs(self.wave_function)**2, N, step))
report = self.counter/(self.DURATION*self.FPS)
M = 20
k = int(report*M)
l = M - k
to_print = '[' + k*'#' + l*'-'+ '] {0:.3f} %'
d_time = time() - self.start_time
ETA = (time()-self.i_time) * (self.FRAMES-self.counter) # (time / frame) * frames remaining
ETA = (ETA / 60) # sec to min ... / 60 # seconds to hours
ETA = np.modf(ETA)
ETA = int(ETA[1]), int(round(ETA[0]*60))
ETA = str(ETA[0]) + ":" + str(ETA[1]).zfill(2)
self.i_time = time()
print('--- Simulation in progress ---')
print(to_print.format(report*100))
print('Time elapsed : {0:.1f} s'.format(d_time))
print(f'Estimated time remaining : {ETA}')
print('Function standard : {0:.3f} '.format(NORM))
``` |
{
"source": "jonnyhyman/SuccessiveConvexification",
"score": 3
} |
#### File: jonnyhyman/SuccessiveConvexification/dynamics_functions.py
```python
from numpy import sqrt
import numpy as np
class Dynamics:
def set_parameters(self, parms):
for name, val in parms.items():
setattr(self, name, val)
def A(self, x, u, s):
m, r0, r1, r2, v0, v1, v2, q0, q1, q2, q3, w0, w1, w2 = x
u0, u1, u2 = u
J = self.J
alpha = self.alpha
gx, gy, gz = self.g_I
rTB0, rTB1, rTB2 = self.rTB
Am = np.zeros((14, 14))
Am[1, 4]=s
Am[2, 5]=s
Am[3, 6]=s
Am[4, 0]=s*(-1.0*u0*(-2*q2**2 - 2*q3**2 + 1)/m**2 - 1.0*u1*(2*q0*q3 + 2*q1*q2)/m**2 - 1.0*u2*(-2*q0*q2 + 2*q1*q3)/m**2)
Am[4, 7]=s*(-2.0*q2*u2/m + 2.0*q3*u1/m)
Am[4, 8]=s*(2.0*q2*u1/m + 2.0*q3*u2/m)
Am[4, 9]=s*(-2.0*q0*u2/m + 2.0*q1*u1/m - 4.0*q2*u0/m)
Am[4, 10]=s*(2.0*q0*u1/m + 2.0*q1*u2/m - 4.0*q3*u0/m)
Am[5, 0]=s*(-1.0*u0*(-2*q0*q3 + 2*q1*q2)/m**2 - 1.0*u1*(-2*q1**2 - 2*q3**2 + 1)/m**2 - 1.0*u2*(2*q0*q1 + 2*q2*q3)/m**2)
Am[5, 7]=s*(2.0*q1*u2/m - 2.0*q3*u0/m)
Am[5, 8]=s*(2.0*q0*u2/m - 4.0*q1*u1/m + 2.0*q2*u0/m)
Am[5, 9]=s*(2.0*q1*u0/m + 2.0*q3*u2/m)
Am[5, 10]=s*(-2.0*q0*u0/m + 2.0*q2*u2/m - 4.0*q3*u1/m)
Am[6, 0]=s*(-1.0*u0*(2*q0*q2 + 2*q1*q3)/m**2 - 1.0*u1*(-2*q0*q1 + 2*q2*q3)/m**2 - 1.0*u2*(-2*q1**2 - 2*q2**2 + 1)/m**2)
Am[6, 7]=s*(-2.0*q1*u1/m + 2.0*q2*u0/m)
Am[6, 8]=s*(-2.0*q0*u1/m - 4.0*q1*u2/m + 2.0*q3*u0/m)
Am[6, 9]=s*(2.0*q0*u0/m - 4.0*q2*u2/m + 2.0*q3*u1/m)
Am[6, 10]=s*(2.0*q1*u0/m + 2.0*q2*u1/m)
Am[7, 8]=-0.5*s*w0
Am[7, 9]=-0.5*s*w1
Am[7, 10]=-0.5*s*w2
Am[7, 11]=-0.5*q1*s
Am[7, 12]=-0.5*q2*s
Am[7, 13]=-0.5*q3*s
Am[8, 7]=0.5*s*w0
Am[8, 9]=0.5*s*w2
Am[8, 10]=-0.5*s*w1
Am[8, 11]=0.5*q0*s
Am[8, 12]=-0.5*q3*s
Am[8, 13]=0.5*q2*s
Am[9, 7]=0.5*s*w1
Am[9, 8]=-0.5*s*w2
Am[9, 10]=0.5*s*w0
Am[9, 11]=0.5*q3*s
Am[9, 12]=0.5*q0*s
Am[9, 13]=-0.5*q1*s
Am[10, 7]=0.5*s*w2
Am[10, 8]=0.5*s*w1
Am[10, 9]=-0.5*s*w0
Am[10, 11]=-0.5*q2*s
Am[10, 12]=0.5*q1*s
Am[10, 13]=0.5*q0*s
Am[11, 12]=s*(J[1,1]*w2 - J[2,2]*w2)/J[0,0]
Am[11, 13]=s*(J[1,1]*w1 - J[2,2]*w1)/J[0,0]
Am[12, 11]=s*(-J[0,0]*w2 + J[2,2]*w2)/J[1,1]
Am[12, 13]=s*(-J[0,0]*w0 + J[2,2]*w0)/J[1,1]
Am[13, 11]=s*(J[0,0]*w1 - J[1,1]*w1)/J[2,2]
Am[13, 12]=s*(J[0,0]*w0 - J[1,1]*w0)/J[2,2]
return Am
def B(self, x, u, s):
m, r0, r1, r2, v0, v1, v2, q0, q1, q2, q3, w0, w1, w2 = x
u0, u1, u2 = u
J = self.J
alpha = self.alpha
gx, gy, gz = self.g_I
rTB0, rTB1, rTB2 = self.rTB
Bm = np.zeros((14, 3))
Bm[0, 0]=-1.0*alpha*s*u0**1.0/sqrt(u0**2.0 + u1**2.0 + u2**2.0)
Bm[0, 1]=-1.0*alpha*s*u1**1.0/sqrt(u0**2.0 + u1**2.0 + u2**2.0)
Bm[0, 2]=-1.0*alpha*s*u2**1.0/sqrt(u0**2.0 + u1**2.0 + u2**2.0)
Bm[4, 0]=1.0*s*(-2*q2**2 - 2*q3**2 + 1)/m
Bm[4, 1]=1.0*s*(2*q0*q3 + 2*q1*q2)/m
Bm[4, 2]=1.0*s*(-2*q0*q2 + 2*q1*q3)/m
Bm[5, 0]=1.0*s*(-2*q0*q3 + 2*q1*q2)/m
Bm[5, 1]=1.0*s*(-2*q1**2 - 2*q3**2 + 1)/m
Bm[5, 2]=1.0*s*(2*q0*q1 + 2*q2*q3)/m
Bm[6, 0]=1.0*s*(2*q0*q2 + 2*q1*q3)/m
Bm[6, 1]=1.0*s*(-2*q0*q1 + 2*q2*q3)/m
Bm[6, 2]=1.0*s*(-2*q1**2 - 2*q2**2 + 1)/m
Bm[11, 1]=-rTB2*s/J[0,0]
Bm[11, 2]=rTB1*s/J[0,0]
Bm[12, 0]=rTB2*s/J[1,1]
Bm[12, 2]=-rTB0*s/J[1,1]
Bm[13, 0]=-rTB1*s/J[2,2]
Bm[13, 1]=rTB0*s/J[2,2]
return Bm
def f(self, x, u):
m, r0, r1, r2, v0, v1, v2, q0, q1, q2, q3, w0, w1, w2 = x
u0, u1, u2 = u
J = self.J
alpha = self.alpha
gx, gy, gz = self.g_I
rTB0, rTB1, rTB2 = self.rTB
fm = np.zeros((14,))
fm[0]=-alpha*sqrt(u0**2.0 + u1**2.0 + u2**2.0)
fm[1]=v0
fm[2]=v1
fm[3]=v2
fm[4]=gx + 1.0*u0*(-2*q2**2 - 2*q3**2 + 1)/m + 1.0*u1*(2*q0*q3 + 2*q1*q2)/m + 1.0*u2*(-2*q0*q2 + 2*q1*q3)/m
fm[5]=gy + 1.0*u0*(-2*q0*q3 + 2*q1*q2)/m + 1.0*u1*(-2*q1**2 - 2*q3**2 + 1)/m + 1.0*u2*(2*q0*q1 + 2*q2*q3)/m
fm[6]=gz + 1.0*u0*(2*q0*q2 + 2*q1*q3)/m + 1.0*u1*(-2*q0*q1 + 2*q2*q3)/m + 1.0*u2*(-2*q1**2 - 2*q2**2 + 1)/m
fm[7]=-0.5*q1*w0 - 0.5*q2*w1 - 0.5*q3*w2
fm[8]=0.5*q0*w0 + 0.5*q2*w2 - 0.5*q3*w1
fm[9]=0.5*q0*w1 - 0.5*q1*w2 + 0.5*q3*w0
fm[10]=0.5*q0*w2 + 0.5*q1*w1 - 0.5*q2*w0
fm[11]=(J[1,1]*w1*w2 - J[2,2]*w1*w2 + rTB1*u2 - rTB2*u1)/J[0,0]
fm[12]=(-J[0,0]*w0*w2 + J[2,2]*w0*w2 - rTB0*u2 + rTB2*u0)/J[1,1]
fm[13]=(J[0,0]*w0*w1 - J[1,1]*w0*w1 + rTB0*u1 - rTB1*u0)/J[2,2]
return fm
```
#### File: SuccessiveConvexification/trajectory/plot.py
```python
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pickle
X_in = pickle.load(open("X.p", "rb"))
U_in = pickle.load(open("U.p", "rb"))
def plot_X():
''' state variable
0 1 2 3 4 5 6 7 8 9 10 11 12 13
x = [m, r0, r1, r2, v0, v1, v2, q0, q1, q2, q3, w0, w1, w2].T
control variable, thrust
u = [T0, T1, T2] in body axes
'''
x = np.array(X_in)
u = np.array(U_in)
T = np.array([np.linalg.norm(uk) for uk in u])
m = x[:,0]
r = x[:,1:4]
v = x[:,4:7]
q = x[:,7:11]
w = x[:,11:14]
vm = np.array([np.linalg.norm(vk) for vk in v])
qm = np.array([1. - 2.*(qk[2]**2 + qk[3]**2) for qk in q])
qm = np.arccos(qm)
qm = np.rad2deg(qm)
dm = np.array([uk[0]/np.linalg.norm(uk) for uk in u])
dm = np.arccos(dm)
dm = np.rad2deg(dm)
wm = np.array([wk for wk in w])
wm = np.rad2deg(wm)
plt.figure(1)
plt.subplot(321)
plt.plot( r[:,1], r[:,0], 'k', r[:,1], r[:,0],'g.', label='Up/East')
plt.quiver( r[:,1], r[:,0], u[:,1], u[:,0], label='Control Vectors',
scale=50,color='b',headwidth =2,pivot='tip')
plt.legend()
plt.subplot(322)
plt.plot(qm, 'k', qm, 'b.', label='Tilt Angle [deg]')
plt.plot((90,)*len(qm))
plt.legend()
plt.subplot(323)
plt.plot( T, 'k', T, 'c.', label='Thrust Magnitude')
plt.legend()
plt.subplot(324)
plt.plot(wm, 'k', wm, 'b.', label='Angular Rate [deg/UT]')
plt.plot((+60,)*len(wm))
plt.legend()
plt.subplot(325)
plt.plot( m, 'k', m, 'm.', label='Mass')
plt.legend()
plt.subplot(326)
plt.plot(dm,label='Thrust Pointing Angle [deg]')
plt.plot((20,)*len(dm))
plt.legend()
plt.show()
def cIB(q):
q0, q1, q2, q3 = q
cIB_m = np.zeros((3,3))
cIB_m[0,0] = 1-2*(q2**2 + q3**2)
cIB_m[0,1] = 2*(q1*q2 + q0*q3)
cIB_m[0,2] = 2*(q1*q3 - q0*q2)
cIB_m[1,0] = 2*(q1*q2 - q0*q3)
cIB_m[1,1] = 1-2*(q1**2 + q3**2)
cIB_m[1,2] = 2*(q2*q3 + q0*q1)
cIB_m[2,0] = 2*(q1*q3 + q0*q2)
cIB_m[2,1] = 2*(q2*q3 - q0*q1)
cIB_m[2,2] = 1-2*(q1**2 + q2**2)
return cIB_m
def plot_3D():
x = np.array(X_in)
u = np.array(U_in)
r = x[:,1:4]
v = x[:,4:7]
fig = plt.figure()
ax = fig.gca(projection='3d')
colors = []
for i, _ in enumerate(r[:, 0]):
vnorm = np.linalg.norm(v[i, :]) / 6.16
colori = plt.cm.plasma(vnorm)
colors.append(colori)
ax.plot(
r[i : i+2, 1],
r[i : i+2, 2],
r[i : i+2, 0],
color = colori,
)
ax.quiver( r[:,1], r[:,2], r[:,0],
u[:,1], u[:,2], u[:,0],
pivot='tip',
colors=colors,
arrow_length_ratio=0)
ax.set_aspect('equal')
plt.show()
plot_3D()
plot_X()
``` |
{
"source": "JonnyJD/targetcli-fb",
"score": 2
} |
#### File: targetcli-fb/targetcli/ui_backstore.py
```python
from ui_node import UINode, UIRTSLibNode
from rtslib import RTSRoot
from rtslib import FileIOBackstore, IBlockBackstore
from rtslib import PSCSIBackstore, RDDRBackstore, RDMCPBackstore
from rtslib import FileIOStorageObject, IBlockStorageObject
from rtslib import PSCSIStorageObject, RDDRStorageObject, RDMCPStorageObject
from rtslib.utils import get_block_type, is_disk_partition
from configshell import ExecutionError
def dedup_so_name(storage_object):
'''
Useful for migration from ui_backstore_legacy to new style with
1:1 hba:so mapping. If name is a duplicate in a backstore, returns
name_X where X is the HBA index.
'''
names = [so.name for so in RTSRoot().storage_objects
if so.backstore.plugin == storage_object.backstore.plugin]
if names.count(storage_object.name) > 1:
return "%s_%d" % (storage_object.name,
storage_object.backstore.index)
else:
return storage_object.name
class UIBackstores(UINode):
'''
The backstores container UI.
'''
def __init__(self, parent):
UINode.__init__(self, 'backstores', parent)
self.cfs_cwd = "%s/core" % self.cfs_cwd
self.refresh()
def refresh(self):
self._children = set([])
UIPSCSIBackstore(self)
UIRDDRBackstore(self)
UIRDMCPBackstore(self)
UIFileIOBackstore(self)
UIIBlockBackstore(self)
class UIBackstore(UINode):
'''
A backstore UI.
'''
def __init__(self, plugin, parent):
UINode.__init__(self, plugin, parent)
self.cfs_cwd = "%s/core" % self.cfs_cwd
self.refresh()
def refresh(self):
self._children = set([])
for so in RTSRoot().storage_objects:
if so.backstore.plugin == self.name:
ui_so = UIStorageObject(so, self)
ui_so.name = dedup_so_name(so)
def summary(self):
no_storage_objects = len(self._children)
if no_storage_objects > 1:
msg = "%d Storage Objects" % no_storage_objects
else:
msg = "%d Storage Object" % no_storage_objects
return (msg, None)
def prm_gen_wwn(self, generate_wwn):
generate_wwn = \
self.ui_eval_param(generate_wwn, 'bool', True)
if generate_wwn:
self.shell.log.info("Generating a wwn serial.")
else:
self.shell.log.info("Not generating a wwn serial.")
return generate_wwn
def prm_buffered(self, buffered):
generate_wwn = \
self.ui_eval_param(buffered, 'bool', True)
if buffered:
self.shell.log.info("Using buffered mode.")
else:
self.shell.log.info("Not using buffered mode.")
return buffered
def ui_command_delete(self, name):
'''
Recursively deletes the storage object having the specified I{name}. If
there are LUNs using this storage object, they will be deleted too.
EXAMPLE
=======
B{delete mystorage}
-------------------
Deletes the storage object named mystorage, and all associated LUNs.
'''
self.assert_root()
try:
child = self.get_child(name)
except ValueError:
self.shell.log.error("No storage object named %s." % name)
else:
hba = child.rtsnode.backstore
child.rtsnode.delete()
if not hba.storage_objects:
hba.delete()
self.remove_child(child)
self.shell.log.info("Deleted storage object %s." % name)
self.parent.parent.refresh()
def ui_complete_delete(self, parameters, text, current_param):
'''
Parameter auto-completion method for user command delete.
@param parameters: Parameters on the command line.
@type parameters: dict
@param text: Current text of parameter being typed by the user.
@type text: str
@param current_param: Name of parameter to complete.
@type current_param: str
@return: Possible completions
@rtype: list of str
'''
if current_param == 'name':
names = [child.name for child in self.children]
completions = [name for name in names
if name.startswith(text)]
else:
completions = []
if len(completions) == 1:
return [completions[0] + ' ']
else:
return completions
def next_hba_index(self):
self.shell.log.debug("%r" % [(backstore.plugin, backstore.index)
for backstore in RTSRoot().backstores])
indexes = [backstore.index for backstore in RTSRoot().backstores
if backstore.plugin == self.name]
self.shell.log.debug("Existing %s backstore indexes: %r"
% (self.name, indexes))
for index in range(1048576):
if index not in indexes:
backstore_index = index
break
if backstore_index is None:
raise ExecutionError("Cannot find an available backstore index.")
else:
self.shell.log.debug("First available %s backstore index is %d."
% (self.name, backstore_index))
return backstore_index
def assert_available_so_name(self, name):
names = [child.name for child in self.children]
if name in names:
raise ExecutionError("Storage object %s/%s already exist."
% (self.name, name))
class UIPSCSIBackstore(UIBackstore):
'''
PSCSI backstore UI.
'''
def __init__(self, parent):
UIBackstore.__init__(self, 'pscsi', parent)
def ui_command_create(self, name, dev):
'''
Creates a PSCSI storage object, with supplied name and SCSI device. The
SCSI device I{dev} can either be a path name to the device, in which
case it is recommended to use the /dev/disk/by-id hierarchy to have
consistent naming should your physical SCSI system be modified, or an
SCSI device ID in the H:C:T:L format, which is not recommended as SCSI
IDs may vary in time.
'''
self.assert_root()
self.assert_available_so_name(name)
backstore = PSCSIBackstore(self.next_hba_index(), mode='create')
try:
so = PSCSIStorageObject(backstore, name, dev)
except Exception, exception:
backstore.delete()
raise exception
ui_so = UIStorageObject(so, self)
self.shell.log.info("Created pscsi storage object %s using %s"
% (name, dev))
return self.new_node(ui_so)
class UIRDDRBackstore(UIBackstore):
'''
RDDR backstore UI.
'''
def __init__(self, parent):
UIBackstore.__init__(self, 'rd_dr', parent)
def ui_command_create(self, name, size, generate_wwn=None):
'''
Creates an RDDR storage object. I{size} is the size of the ramdisk, and
the optional I{generate_wwn} parameter is a boolean specifying whether
or not we should generate a T10 wwn serial for the unit (by default,
yes).
SIZE SYNTAX
===========
- If size is an int, it represents a number of bytes.
- If size is a string, the following units can be used:
- B{B} or no unit present for bytes
- B{k}, B{K}, B{kB}, B{KB} for kB (kilobytes)
- B{m}, B{M}, B{mB}, B{MB} for MB (megabytes)
- B{g}, B{G}, B{gB}, B{GB} for GB (gigabytes)
- B{t}, B{T}, B{tB}, B{TB} for TB (terabytes)
'''
self.assert_root()
self.assert_available_so_name(name)
backstore = RDDRBackstore(self.next_hba_index(), mode='create')
try:
so = RDDRStorageObject(backstore, name, size,
self.prm_gen_wwn(generate_wwn))
except Exception, exception:
backstore.delete()
raise exception
ui_so = UIStorageObject(so, self)
self.shell.log.info("Created rd_dr ramdisk %s with size %s."
% (name, size))
return self.new_node(ui_so)
class UIRDMCPBackstore(UIBackstore):
'''
RDMCP backstore UI.
'''
def __init__(self, parent):
UIBackstore.__init__(self, 'rd_mcp', parent)
def ui_command_create(self, name, size, generate_wwn=None):
'''
Creates an RDMCP storage object. I{size} is the size of the ramdisk,
and the optional I{generate_wwn} parameter is a boolean specifying
whether or not we should generate a T10 wwn Serial for the unit (by
default, yes).
SIZE SYNTAX
===========
- If size is an int, it represents a number of bytes.
- If size is a string, the following units can be used:
- B{B} or no unit present for bytes
- B{k}, B{K}, B{kB}, B{KB} for kB (kilobytes)
- B{m}, B{M}, B{mB}, B{MB} for MB (megabytes)
- B{g}, B{G}, B{gB}, B{GB} for GB (gigabytes)
- B{t}, B{T}, B{tB}, B{TB} for TB (terabytes)
'''
self.assert_root()
self.assert_available_so_name(name)
backstore = RDMCPBackstore(self.next_hba_index(), mode='create')
try:
so = RDMCPStorageObject(backstore, name, size,
self.prm_gen_wwn(generate_wwn))
except Exception, exception:
backstore.delete()
raise exception
ui_so = UIStorageObject(so, self)
self.shell.log.info("Created rd_mcp ramdisk %s with size %s."
% (name, size))
return self.new_node(ui_so)
class UIFileIOBackstore(UIBackstore):
'''
FileIO backstore UI.
'''
def __init__(self, parent):
UIBackstore.__init__(self, 'fileio', parent)
def ui_command_create(self, name, file_or_dev, size=None,
generate_wwn=None, buffered=None):
'''
Creates a FileIO storage object. If I{file_or_dev} is a path to a
regular file to be used as backend, then the I{size} parameter is
mandatory. Else, if I{file_or_dev} is a path to a block device, the
size parameter B{must} be ommited. If present, I{size} is the size of
the file to be used, I{file} the path to the file or I{dev} the path to
a block device. The optional I{generate_wwn} parameter is a boolean
specifying whether or not we should generate a T10 wwn Serial for the
unit (by default, yes). The I{buffered} parameter is a boolean stating
whether or not to enable buffered mode. It is disabled by default
(synchronous mode).
SIZE SYNTAX
===========
- If size is an int, it represents a number of bytes.
- If size is a string, the following units can be used:
- B{B} or no unit present for bytes
- B{k}, B{K}, B{kB}, B{KB} for kB (kilobytes)
- B{m}, B{M}, B{mB}, B{MB} for MB (megabytes)
- B{g}, B{G}, B{gB}, B{GB} for GB (gigabytes)
- B{t}, B{T}, B{tB}, B{TB} for TB (terabytes)
'''
self.assert_root()
self.assert_available_so_name(name)
self.shell.log.debug("Using params size=%s generate_wwn=%s buffered=%s"
% (size, generate_wwn, buffered))
is_dev = get_block_type(file_or_dev) is not None \
or is_disk_partition(file_or_dev)
if size is None and is_dev:
backstore = FileIOBackstore(self.next_hba_index(), mode='create')
try:
so = FileIOStorageObject(
backstore, name, file_or_dev,
gen_wwn=self.prm_gen_wwn(generate_wwn),
buffered_mode=self.prm_buffered(buffered))
except Exception, exception:
backstore.delete()
raise exception
self.shell.log.info("Created fileio %s with size %s."
% (name, size))
ui_so = UIStorageObject(so, self)
return self.new_node(ui_so)
elif size is not None and not is_dev:
backstore = FileIOBackstore(self.next_hba_index(), mode='create')
try:
so = FileIOStorageObject(
backstore, name, file_or_dev,
size,
gen_wwn=self.prm_gen_wwn(generate_wwn),
buffered_mode=self.prm_buffered(buffered))
except Exception, exception:
backstore.delete()
raise exception
self.shell.log.info("Created fileio %s." % name)
ui_so = UIStorageObject(so, self)
return self.new_node(ui_so)
else:
self.shell.log.error("For fileio, you must either specify both a "
+ "file and a size, or just a device path.")
class UIIBlockBackstore(UIBackstore):
'''
IBlock backstore UI.
'''
def __init__(self, parent):
UIBackstore.__init__(self, 'iblock', parent)
def ui_command_create(self, name, dev, generate_wwn=None):
'''
Creates an IBlock Storage object. I{dev} is the path to the TYPE_DISK
block device to use and the optional I{generate_wwn} parameter is a
boolean specifying whether or not we should generate a T10 wwn Serial
for the unit (by default, yes).
'''
self.assert_root()
self.assert_available_so_name(name)
backstore = IBlockBackstore(self.next_hba_index(), mode='create')
try:
so = IBlockStorageObject(backstore, name, dev,
self.prm_gen_wwn(generate_wwn))
except Exception, exception:
backstore.delete()
raise exception
ui_so = UIStorageObject(so, self)
self.shell.log.info("Created iblock storage object %s using %s."
% (name, dev))
return self.new_node(ui_so)
class UIStorageObject(UIRTSLibNode):
'''
A storage object UI.
'''
def __init__(self, storage_object, parent):
name = storage_object.name
UIRTSLibNode.__init__(self, name, storage_object, parent)
self.cfs_cwd = storage_object.path
self.refresh()
def ui_command_version(self):
'''
Displays the version of the current backstore's plugin.
'''
backstore = self.rtsnode.backstore
self.shell.con.display("Backstore plugin %s %s"
% (backstore.plugin, backstore.version))
def summary(self):
so = self.rtsnode
errors = []
if so.backstore.plugin.startswith("rd"):
path = "ramdisk"
else:
path = so.udev_path
if not path:
errors.append("BROKEN STORAGE LINK")
legacy = []
if self.rtsnode.name != self.name:
legacy.append("ADDED SUFFIX")
if len(self.rtsnode.backstore.storage_objects) > 1:
legacy.append("SHARED HBA")
if legacy:
errors.append("LEGACY: " + ", ".join(legacy))
if errors:
msg = ", ".join(errors)
if path:
msg += " (%s %s)" % (path, so.status)
return (msg, False)
else:
return ("%s %s" % (path, so.status), True)
``` |
{
"source": "jonnyk17/Fitbit-Dashboard",
"score": 3
} |
#### File: Fitbit-Dashboard/src/today.py
```python
import database_manager
from datetime import date
import dash
from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
import plotly.express as px
import plotly.graph_objects as go
dbm = database_manager.DatabaseManager()
def generate():
data = dbm.query('intraday', 'distance', period='15min')
dataset = data['activities-distance-intraday']['dataset']
datatotal = data['activities-distance'][0]
distance_fig = make_distance_chart(dataset)
return html.Div(children=[
dbc.Card(
dcc.Graph(figure=distance_fig, config={'displayModeBar':False}, style={
'padding':'1%'
}),
color='primary',
outline='True',
style={
'float':'left',
'margin':'auto',
'width':'75%'
}
),
make_goal_card(datatotal, style={
'float':'left',
'margin':'auto',
'width':'24%',
})
])
def make_distance_chart(data):
# Clumps data into half hour blocks
half_hourly_x = []
half_hourly_y = []
for i in range(0, len(data), 2):
half_hourly_x.append(data[i]['time'])
if i+1 == len(data):
half_hourly_y.append(data[i]['value'])
break
half_hourly_y.append(data[i]['value']+data[i+1]['value'])
# Gets cumulative distance for each time stamp so far in the day
cumulative_x = []
cumulative_y = []
total = 0
for d in data:
total = total + d['value']
cumulative_x.append(d['time'])
cumulative_y.append(total)
fig = px.line(
x=cumulative_x,
y=cumulative_y,
labels=dict(x="Time", y="Distance")
)
fig.add_bar(
x=half_hourly_x,
y=half_hourly_y
)
fig.update_layout(modebar_remove=['zoom', 'zoomIn', 'zoomOut', 'boxSelect'],
dragmode='pan')
return fig
def make_goal_card(data, style={}):
dist = float(data['value'])
return dbc.Card(
dbc.ListGroup(
[
dbc.ListGroupItem([
html.H4("Total Distance", className="card-title"),
html.H2("{:.2f}".format(dist), style={
'text-align':'center'
})
]),
dbc.ListGroupItem([
html.H4("Distance to Goal", className="card-title"),
html.H2("{:.2f}".format(4-dist), style={
'text-align':'center'
})
])
],
flush=True
),
style=style,
color='primary',
outline=True,
)
``` |
{
"source": "JonnyKelso/coinTicker",
"score": 3
} |
#### File: JonnyKelso/coinTicker/cryptobot.py
```python
import csv
import config
import time
from datetime import date
from enum import Enum
import os
import sys
from decimal import *
import math
#Binance
from binance.client import Client
from binance import exceptions
#Discord
import requests
from discord import Webhook, RequestsWebhookAdapter
import json
class State(Enum):
ACTIVE = 1
INACTIVE = 2
class DiscordHelper:
webhook = None
state = State.INACTIVE
def __init__(self, url):
self.webhook = Webhook.from_url(url, adapter=RequestsWebhookAdapter())
def sendDiscordMsg(self, message):
if self.state == State.ACTIVE:
self.webhook.send(message)
def SetState(self, state):
self.state = state
class BinanceHelper:
client = None
#currentBalance = -1.0
instrument_names = []
def __init__(self, api_key, api_secret):
try:
self.client = Client(api_key, api_secret)
except Exception as e: #exceptions.BinanceAPIException as err:
print(f"Binance exception during init: \n {e}")
self.client = None
def getPrices(self):
try:
prices = self.client.get_all_tickers()
except Exception as e: # exceptions.BinanceAPIException as err:
print(f"Binance exception during getPrices: \n {e}")
prices = None
return prices
def getPrice(self, symb):
try:
price = self.client.get_ticker(symbol=symb)
except Exception as e: # exceptions.BinanceAPIException as err:
print(f"Binance exception during getPrice: \n {e}")
price = None
return price
def getAccountBalanceForSymbol(self, symb):
coinBalance = 0.0
try:
response = self.client.get_account()
except Exception as e: # exceptions.BinanceAPIException as err:
print(f"Binance exception during getAccountBalanceForSymbol: \n {e}")
return None
else:
#print("getAccountBalanceForSymbol")
for balance in response['balances']:
if balance['asset'] == symb :
#print(f"asset = {symb}, num = {balance['free']}")
if Decimal(balance['free']) > 0.0:
coinBalance = Decimal(balance['free'])
return coinBalance
def getAccountBalances(self):
try:
response = self.client.get_account()
except Exception as e: # exceptions.BinanceAPIException as err:
print(f"Binance exception during getAccountBalances: \n {e}")
self.balances = None
else:
self.balances = response
#for balance in response['balances']:
# if balance['asset'] == symb :
# if float(balance['free']) > 0.0:
# self.currentBalance = float(balance['free'])
return self.balances
def getAllInstrumentNames(self):
prices = self.getPrices()
for price in prices:
#print(price)
self.instrument_names = price['symbol']
return self.instrument_names
class Instrument:
def __init__(self, symbol, pairs, notifyBalanceThresholdDelta, notifyPriceThresholdDelta):
self.symbol = symbol
self.pairs = pairs
self.cointTotal = 0.0
self.balanceUSDT = {
'balance': Decimal(0.0),
'min':Decimal(0.0),
'max':Decimal(0.0)
}
self.balanceGBP = {
'balance':Decimal(0.0),
'min':Decimal(0.0),
'max':Decimal(0.0)
}
self.coinPriceUSDT = Decimal(0.0)
self.coinPriceGBP = Decimal(0.0)
self.notifyBalanceThresholdDelta = Decimal(notifyBalanceThresholdDelta)
self.notifyBalanceThreshold = Decimal(0.0)
self.notifyPriceThresholdDelta = Decimal(notifyPriceThresholdDelta)
self.notifyPriceThreshold = Decimal(0.0)
self.distanceToPriceThreshold = Decimal(0.0)
def __str__(self):
return (f"{self.symbol}, \
{self.pairs}, \
{self.balanceUSDT}, \
{self.balanceGBP}, \
{self.coinPriceUSDT}, \
{self.coinPriceGBP}, \
{self.notifyBalanceThresholdDelta}, \
{self.notifyBalanceThreshold}, \
{self.notifyPriceThresholdDelta}, \
{self.notifyPriceThreshold}, \
{self.distanceToPriceThreshold}")
class Account:
def __init__(self):
self.instruments = []
self.baseCurrency = "GBP"
def calcDisplayMarkerPosition(instrument):
# global priceBaseline
adjusted_Coin_price = int(instrument.coinPriceUSDT * 1000.0) # in tenths of a cent
if instrument.priceBaseline == 0:
instrument.priceBaseline = adjusted_Coin_price / 10
instrument.priceBaseline = instrument.priceBaseline * 10
#print(f"{displayLineLength}, {adjusted_Coin_price}, {priceBaseline}")
return (displayLineLength / 2) + (adjusted_Coin_price - instrument.priceBaseline)
def printLogMessage(message):
msg = f"{getTime()}, {math.trunc(time.time())}, {message}"
print(msg)
def writeData(writer, message):
msg = f"{time.time()}, {getTime()}, {message}"
writer.writerow([msg])
def getTime():
t = time.localtime()
#return time.strftime("%H:%M:%S", t)
return time.strftime("%b %d %Y %H:%M:%S", t)
def getDateStr():
d = date.today()
t = time.localtime()
return (f"{d.isoformat()}T{time.strftime('%H%M%S', t)}")
def getCoinPriceInUSDT(instrument):
# get coin price
# requires that instrument contains a list of coin pairs required to convert from starting symbol to USDT
# e.g. for DOGEBTC, this would be ["DOGEBTC","BTCUSDT"]
# number of coins for getting initial price
conversionPrice = Decimal(1.0)
for pair in instrument.pairs:
#if symbolPair['2'] == baseCurrency:
# print(f"using base currency {baseCurrency} already in {symbolPair['1']}{symbolPair['2']}")
coin_price = binHelper.getPrice(f"{pair}") # returns a price object
coin_bid_price = Decimal(coin_price['bidPrice']) # extract the bidPrice from the object
conversionPrice = conversionPrice * coin_bid_price
#print(f"coin_bid_price:{coin_bid_price} for {pair}")
coin_price_in_USDT = conversionPrice
return coin_price_in_USDT
def getNotifyPriceThreshold(currentPrice):
#global notifyPriceThreshold
adj_price = int(currentPrice * 100)
return Decimal(adj_price) / 100.0
def printCoinBalances(accountBalances):
#:{str('total $').rjust(10,' ')}:{str('total £').rjust(10,' ')}")
#print(f"{str('coin').rjust(4,' ')}:{str('total').rjust(10,' ')}")
print("Number of coins:")
for balance in accountBalances['balances']:
if Decimal(balance['free']) > 0.0:
asset = balance['asset']
totalbalance = Decimal(balance['free'])
print(f"{asset.rjust(4,' ')}:{str(totalbalance).rjust(10,' ')}")
def printBalances(accountBalances):
pass
# print(f"{str('coin').rjust(4,' ')}:{str('total').rjust(10,' ')}:{str('total $').rjust(10,' ')}:{str('total £').rjust(10,' ')}")
# for balance in accountBalances['balances']:
# if float(balance['free']) > 0.0:
# asset = balance['asset']
# totalbalance = float(balance['free'])
# pairUSDT = f"{asset}USDT"
# pairGBP = f"{asset}GBP"
# totalBalanceUSDT = totalbalance * getCoinPrice(pairUSDT, 'USDT')
# totalBalanceGBP = totalbalance * getCoinPrice(pairGBP, 'GBP')
# print(f"{asset.rjust(4,' ')}:{rightJustifyString(totalbalance, 10)}:{rightJustifyString(totalBalanceUSDT,10)}:{rightJustifyString(totalBalanceGBP,10)}")
def rightJustifyString(value, totalLength):
return str(f"{value:.2f}")
def CheckNotifyAboutPrice(instrument):
if(CheckPrice == False):
return False
price = Decimal(instrument.coinPriceUSDT)
if instrument.notifyPriceThreshold == 0.0 :
instrument.notifyPriceThreshold = Decimal(instrument.notifyPriceThresholdDelta)
# if balance > balanceThreshold + notifyThreshold, then notify via Discord
if price > 0.0 : # 1.0:
upperThreshold = Decimal(instrument.notifyPriceThreshold + instrument.notifyPriceThresholdDelta)
if price > upperThreshold :
instrument.notifyPriceThreshold = Decimal((price // instrument.notifyPriceThresholdDelta) * instrument.notifyPriceThresholdDelta) + instrument.notifyPriceThresholdDelta
return True
#instrument.balanceThreshold = (instrument.balanceThreshold + instrument.notifyBalanceThreshold)
lowerThreshold = Decimal(instrument.notifyPriceThreshold - instrument.notifyPriceThresholdDelta)
if price < lowerThreshold :
instrument.notifyPriceThreshold = Decimal(price // instrument.notifyPriceThresholdDelta) * instrument.notifyPriceThresholdDelta
return True
return False
def CheckNotifyAboutBalance(instrument):
balance = Decimal(instrument.balanceGBP['balance'])
if instrument.notifyBalanceThreshold == 0.0 :
instrument.notifyBalanceThreshold = Decimal(instrument.notifyBalanceThresholdDelta)
# if balance > balanceThreshold + notifyThreshold, then notify via Discord
if balance > 0.0: # 1.0:
upperThreshold = Decimal(instrument.notifyBalanceThreshold + instrument.notifyBalanceThresholdDelta)
if balance > upperThreshold :
# find highest multiple of threshold delta below current balance, then add another delta
instrument.notifyBalanceThreshold = Decimal((balance // instrument.notifyBalanceThresholdDelta) * instrument.notifyBalanceThresholdDelta) + instrument.notifyBalanceThresholdDelta
return True
#instrument.balanceThreshold = (instrument.balanceThreshold + instrument.notifyBalanceThreshold)
lowerThreshold = Decimal(instrument.notifyBalanceThreshold - instrument.notifyBalanceThresholdDelta)
if balance < lowerThreshold :
# find highest multiple of threshold delta below current balance
instrument.notifyBalanceThreshold = Decimal(balance // instrument.notifyBalanceThresholdDelta) * instrument.notifyBalanceThresholdDelta
return True
return False
def NotifyAboutPrice(writer, discordHelper, oldThreshold, instrument):
movement = "DOWN"
if instrument.coinPriceUSDT > oldThreshold:
movement = "UP"
msg = (f"{instrument.symbol.rjust(4,' ')} price {movement} from {oldThreshold} to {instrument.coinPriceUSDT.quantize(Decimal('1.000'))}, new threshold at {instrument.notifyPriceThreshold.quantize(Decimal('1.000'))}")
printLogMessage(msg)
discordHelper.sendDiscordMsg(f"@here {getTime()} {msg}")
def NotifyAboutBalance(writer, discordHelper, oldThreshold, instrument):
movement = "DOWN"
if instrument.balanceGBP['balance'] > oldThreshold:
movement = "UP"
msg = (f"{instrument.symbol.rjust(4,' ')} balance {movement} from {oldThreshold} to {instrument.balanceGBP['balance'].quantize(Decimal('1.00'))}, new threshold at {instrument.notifyBalanceThreshold.quantize(Decimal('1.00'))}")
printLogMessage(msg)
discordHelper.sendDiscordMsg(f"@here {getTime()} {msg}")
if __name__ == '__main__':
priceBaseline = 0
displayLineLength = 100 # for display only - the number of character spaces used to display price marker
sleepDelayMin = 15 # time between querying the binance API
CheckPrice = True
useDiscord = True
binHelper = BinanceHelper(config.API_KEY, config.API_SECRET)
if binHelper is None:
sys.exit("Could not initialise Binance API, exiting.")
disHelper = DiscordHelper(config.DISCORD_WEBHOOK_URL)
if useDiscord :
disHelper.SetState(State.ACTIVE)
# set Decimal precision
getcontext().prec = 15
account = Account()
# Define instruments to track, and a list of instruments required to convert to a base of USDT
# final conversion of USDT to GBP will be done later.
# the notifyBalance threshold is in GBP and notifyPrice threshold is in USDT
account.instruments.append(Instrument("DOGE", ["DOGEUSDT"], 500, 0.1))
account.instruments.append(Instrument("BTC", ["BTCUSDT"], 500, 1000))
account.instruments.append(Instrument("ETH", ["ETHBTC", "BTCUSDT"], 250, 250))
balances = binHelper.getAccountBalances()
printCoinBalances(balances)
with open("data_file.json", "w") as write_file:
with open(f"cryptobot_log_{getDateStr()}.csv", 'w', newline ='') as csv_file :
data_writer = csv.writer(csv_file, delimiter=',')
printLogMessage(f"New run starting at {getDateStr()}")
print("starting loop")
while(True):
for instr in account.instruments:
# get number of coins
coin_total = binHelper.getAccountBalanceForSymbol(instr.symbol)
if coin_total is None:
print("couldn't get balance")
continue
instr.coinTotal = coin_total
if instr.coinTotal == 0.0:
continue
# get the coin value in BTC (used as stepping stone to calc value in GBP)
instr.coinPriceUSDT = getCoinPriceInUSDT(instr)
# calc price in GBP
GBPUSDT_price_obj = binHelper.getPrice("GBPUSDT")
GBPUSDT_price = Decimal(GBPUSDT_price_obj['bidPrice']) # extract the bidPrice from the object
instr.coinPriceGBP = instr.coinPriceUSDT / GBPUSDT_price
# set current and min/max balance values in GBP
instr.balanceGBP['balance'] = instr.coinPriceGBP * instr.coinTotal
instr.balanceGBP['max'] = max(instr.balanceGBP['balance'], instr.balanceGBP['max'])
if( instr.balanceGBP['min'] == 0.0) :
instr.balanceGBP['min'] = instr.balanceGBP['balance']
else :
instr.balanceGBP['min'] = min(instr.balanceGBP['balance'], instr.balanceGBP['min'])
# set current and min/max balance values in USD
instr.balanceUSDT['balance'] = instr.coinPriceUSDT * instr.coinTotal
instr.balanceUSDT['max'] = max (instr.balanceUSDT['balance'], instr.balanceUSDT['max'])
if ( instr.balanceUSDT['min'] == 0 ) :
instr.balanceUSDT['min'] = instr.balanceUSDT['balance']
else :
instr.balanceUSDT['min'] = min (instr.balanceUSDT['balance'], instr.balanceUSDT['min'])
# set threshold from which to measure price movement.
currentThreshold = instr.notifyPriceThreshold
if(CheckNotifyAboutPrice(instr)):
NotifyAboutPrice(data_writer, disHelper, currentThreshold, instr)
currentThreshold = instr.notifyBalanceThreshold
if(CheckNotifyAboutBalance(instr)):
NotifyAboutBalance(data_writer, disHelper, currentThreshold, instr)
# adjust (quantize) price values only for display
justCoinPriceGBP = str(Decimal(instr.coinPriceGBP).quantize(Decimal('1.000')))
justCoinPriceUSDT = str(Decimal(instr.coinPriceUSDT).quantize(Decimal('1.000')))
justCoinTotal = str(Decimal(instr.coinTotal).quantize(Decimal('1.00000000')))
justCoinBalance = str(Decimal(instr.balanceGBP['balance']).quantize(Decimal('1.00')))
# log to screen
#printLogMessage(data_writer, f"{instr.symbol.rjust(4,' ')} Price £:{justCoinPriceGBP.rjust(15,' ')}, Price $:{justCoinPriceUSDT.rjust(15,' ')}, Total coins:{justCoinTotal.rjust(15,' ')}, Upper Thr: { instr.notifyBalanceThreshold + instr.notifyBalanceThresholdDelta}, Lower Thr: { instr.notifyBalanceThreshold - instr.notifyBalanceThresholdDelta}, Balance £:{justCoinBalance.rjust(10,' ')}")
printLogMessage(f"{instr.symbol.rjust(4,' ')} Price £:{justCoinPriceGBP.rjust(15,' ')}, Price $:{justCoinPriceUSDT.rjust(15,' ')}, Total coins:{justCoinTotal.rjust(15,' ')}, Upper Thr: { str(instr.notifyBalanceThreshold + instr.notifyBalanceThresholdDelta).rjust(5,' ')}, Lower Thr: { str(instr.notifyBalanceThreshold - instr.notifyBalanceThresholdDelta).rjust(5,' ')}, Balance £:{justCoinBalance.rjust(10,' ')}")
# print balance line
msg = f"{instr.symbol} : {instr.coinPriceUSDT.quantize(Decimal('1.000'))} : {instr.balanceGBP['min'].quantize(Decimal('1.00'))} : {instr.balanceGBP['max'].quantize(Decimal('1.00'))} : {instr.balanceGBP['balance'].quantize(Decimal('1.00'))}"#round up == false
writeData(data_writer, [msg])
time.sleep(sleepDelayMin * 60)
#---------------------------------------------------------------------------
#candles = client.get_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_15MINUTE)
#csvfile = open('15minuites.csv', 'w', newline ='')
#candlestick_writer = csv.writer(csvfile, delimiter=',')
#for candlestick in candles:
# print(candlestick)
# candlestick_writer.writerow(candlestick)
#print(len(candles))
#wss://stream.binance.com/9443
#---------------------------------------------------------------------------
``` |
{
"source": "jonnykl/cpa-chacha",
"score": 3
} |
#### File: cpa-chacha/attack/chacha.py
```python
from tqdm import tqdm, trange
import numpy as np
import struct
# constants used in the initial state
chacha_consts = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574]
# hamming weight for 8 bits
HW8 = [bin(x).count("1") for x in range(256)]
# hamming weight
def HW(x):
return bin(x).count("1")
# 32-bit rotate left
def ROTL(x, n):
return ((x<<n) | (x>>(32-n))) & 0xFFFFFFFF
# 32-bit rotate right
def ROTR(x, n):
return ((x>>n) | (x<<(32-n))) & 0xFFFFFFFF
# 32-bit add
def ADD(a, b):
return (a+b) & 0xFFFFFFFF
# 32-bit subtract
def SUB(a, b):
return (a-b+0x100000000) & 0xFFFFFFFF
# chacha intermediate functions
def intermediate_a(a0, b0, c, d0):
d1 = d0 ^ ADD(a0, b0)
return d1
def intermediate_b(a0, b0, c0, d0):
d2 = ROTL(d0 ^ ADD(a0, b0), 16)
b1 = b0 ^ ADD(c0, d2)
return b1
def intermediate_c(a0, b0, c0, d0):
a1 = ADD(a0, b0)
d2 = ROTL(d0^a1, 16)
c1 = ADD(c0, d2)
b2 = ROTL(b0^c1, 12)
a2 = ADD(a1, b2)
d3 = d2^a2
return d3
def intermediate_d(a0, b0, c0, d0):
a1 = ADD(a0, b0)
d2 = ROTL(d0^a1, 16)
c1 = ADD(c0, d2)
return c1
def intermediate_e(a, b0, c0, d2):
b1 = b0 ^ ADD(c0, d2)
return b1
def intermediate_f(a1, b0, c0, d2):
b1 = b0 ^ ADD(c0, d2)
d3 = d2 ^ ADD(a1, ROTL(b1, 12))
return d3
def intermediate_g(a1, b, c0, d0):
c1 = ADD(c0, ROTL(d0 ^ a1, 16))
return c1
def intermediate_h(a1, b0, c0, d0):
d2 = ROTL(d0 ^ a1, 16)
b1 = b0 ^ ADD(c0, d2)
return b1
# key_known=True when calculating intermediate for TVLA/NICV
def intermediate(step, state0, state1, key_known):
# use meaningful names where possible
consts = state0[0]
subkeys = state0[1:3].flatten()
counter = state0[3,0]
nonce = state0[3,1:4]
# output of the first round
a0, b0, c0, d0 = state1[:,0]
a1, b1, c1, d1 = state1[:,1]
a2, b2, c2, d2 = state1[:,2]
a3, b3, c3, d3 = state1[:,3]
if step == 0:
f = intermediate_a
a = consts[0]
b = subkeys[0]
c = None
d = counter
elif step == 1:
f = intermediate_a
a = consts[1]
b = subkeys[1]
c = None
d = nonce[0]
elif step == 2:
f = intermediate_b
a = consts[0]
b = subkeys[0]
c = subkeys[4]
d = counter
elif step == 3:
f = intermediate_b
a = consts[1]
b = subkeys[1]
c = subkeys[5]
d = nonce[0]
elif step == 4:
f = intermediate_a
a = consts[2]
b = subkeys[2]
c = None
d = nonce[1]
elif step == 5:
f = intermediate_a
a = consts[3]
b = subkeys[3]
c = None
d = nonce[2]
elif step == 6:
f = intermediate_b
a = consts[2]
b = subkeys[2]
c = subkeys[6]
d = nonce[1]
elif step == 7:
f = intermediate_b
a = consts[3]
b = subkeys[3]
c = subkeys[7]
d = nonce[2]
elif step == 8:
f = intermediate_a
a = a3
b = b0
c = None
d = d2
elif step == 9:
f = intermediate_b
a = a3
b = b0
c = c1
d = d2
elif step == 10:
f = intermediate_a
a = a2
b = b3
c = None
d = d1
elif step == 11:
f = intermediate_b
a = a2
b = b3
c = c0
d = d1
elif step == 12:
if key_known:
f = intermediate_b
a = a1
b = b2
c = c3
d = d0
else:
f = intermediate_e
a = None
b = b2
c = c3
d = d0
elif step == 13:
if key_known:
f = intermediate_c
a = a1
b = b2
c = c3
d = d0
else:
f = intermediate_f
a = a1
b = b2
c = c3
d = d0
elif step == 14:
if key_known:
f = intermediate_d
a = a0
b = b1
c = c2
d = d3
else:
f = intermediate_g
a = a0
b = None
c = c2
d = d3
elif step == 15:
if key_known:
f = intermediate_b
a = a0
b = b1
c = c2
d = d3
else:
f = intermediate_h
a = a0
b = b1
c = c2
d = d3
return f(a, b, c, d)
# generates the initial state
def initial_state(key=[0]*8, counter=0, nonce=[0]*3):
state = np.zeros((4, 4), dtype=np.int)
state[0] = chacha_consts
state[1] = key[0:4]
state[2] = key[4:8]
state[3] = [counter, *nonce]
return state
# arrays of (state, row, col)
# specifies the subkey word which is calculated in the corresponding step
idx_subkey_by_step = [
(0, 1, 0), # 0 v4 -> key[0]
(0, 1, 1), # 1 v5 -> key[1]
(0, 2, 0), # 2 v8 -> key[4]
(0, 2, 1), # 3 v9 -> key[5]
(0, 1, 2), # 4 v6 -> key[2]
(0, 1, 3), # 5 v7 -> key[3]
(0, 2, 2), # 6 v10 -> key[6]
(0, 2, 3), # 7 v11 -> key[7]
(1, 1, 0), # 8 v4' -> key[0]
(1, 2, 1), # 9 v9' -> key[5]
(1, 3, 1), # 10 v13' -> nonce[0]
(1, 2, 0), # 11 v8' -> key[4]
(1, 3, 0), # 12 v12' -> counter
(1, 0, 1), # 13 v1' -> consts[1]
(1, 0, 0), # 14 v0' -> consts[0]
(1, 1, 1) # 15 v5' -> key[1]
]
# calculate correlations for a given trace and all 8-bit subkeys
def calc_corrs8(trace_array, counter_array, nonce_array, step, int_subkey, samples, state0, state1, subkey, show_progress=False):
# copy the states because they are modified in this function
state0 = np.copy(state0)
state1 = np.copy(state1)
state01 = (state0, state1)
# bit position of the current subkey byte (for the input data)
bit_pos = int_subkey*8
# bit position of the current subkey byte (for the output of the intermediate)
intermediate_bit_pos = bit_pos
if step == 14:
# shifting the result needed because of the ROTL operation in the intermediate function
intermediate_bit_pos = (bit_pos+16)%32
if show_progress:
progress = tqdm(total=256, leave=False, desc="subkey guess")
corrs = []
for subkey_guess in range(256):
# calculate the model
model = []
for i in range(len(trace_array)):
counter = unpack_counter(counter_array[i])
nonce = unpack_nonce(nonce_array[i])
# set the counter and nonce in the state
state0[3] = [counter, *nonce]
if step >= 8:
# run the first round for the third/4th column
state1[:,2] = quarter_round(*state0[:,2])
state1[:,3] = quarter_round(*state0[:,3])
# set the subkey guess in the corresponding state
state01[idx_subkey_by_step[step][0]][idx_subkey_by_step[step][1:3]] = (subkey_guess<<bit_pos) | subkey
# calculate the intermediate value
x = HW8[(intermediate(step, state0, state1, key_known=False)>>intermediate_bit_pos) & 0xFF]
model.append(x)
# calculate the correlation for each point
corr_per_point = []
for i in samples:
corr = np.corrcoef(trace_array[:,i], model)[0,1]
corr_per_point.append(corr)
corrs.append(corr_per_point)
if show_progress:
progress.update()
if show_progress:
progress.close()
return corrs
# calculate correlations for a given trace and all 32-bit subkeys
def calc_corrs32(trace_array, counter_array, nonce_array, step, samples, state0, state1, subkeys):
# copy the states because they are modified in this function
state0 = np.copy(state0)
state1 = np.copy(state1)
state01 = (state0, state1)
corrs = []
for subkey in subkeys:
# calculate the model
model = []
for i in range(len(trace_array)):
counter = unpack_counter(counter_array[i])
nonce = unpack_nonce(nonce_array[i])
# set the counter and nonce in the state
state0[3] = [counter, *nonce]
if step >= 8:
# run the first round for the third/4th column
state1[:,2] = quarter_round(*state0[:,2])
state1[:,3] = quarter_round(*state0[:,3])
# set the subkey guess in the corresponding state
state01[idx_subkey_by_step[step][0]][idx_subkey_by_step[step][1:3]] = subkey
# calculate the intermediate value
x = HW(intermediate(step, state0, state1, key_known=False))
model.append(x)
# calculate the correlation for each point
corr_per_point = []
for i in samples:
corr = np.corrcoef(trace_array[:,i], model)[0,1]
corr_per_point.append(corr)
corrs.append(corr_per_point)
return corrs
# calculates a', b', c', d' for the given input (quarter round)
def quarter_round(a, b, c, d):
a = ADD(a, b)
d = ROTL(d^a, 16)
c = ADD(c, d)
b = ROTL(b^c, 12)
a = ADD(a, b)
d = ROTL(d^a, 8)
c = ADD(c, d)
b = ROTL(b^c, 7)
return a, b, c, d
# calculates a', b', c', d' for the given input (inverse quarter round)
def inv_quarter_round(a, b, c, d):
b = c ^ ROTR(b, 7)
c = SUB(c, d)
d = a ^ ROTR(d, 8)
a = SUB(a, b)
b = c ^ ROTR(b, 12)
c = SUB(c, d)
d = a ^ ROTR(d, 16)
a = SUB(a, b)
return a, b, c, d
# extracts a 32-bit subkey word from a key (32x 8-bit bytes)
def extract_subkey(key, n):
return struct.unpack("<I", bytes(key[n*4:(n+1)*4]))[0]
# calculates a group for the given step and input data
def group32(step, counter, nonce, correct_key):
counter = unpack_counter(counter)
nonce = unpack_nonce(nonce)
# construct states
state0 = np.array([
chacha_consts,
[extract_subkey(correct_key, i) for i in range(0, 4)],
[extract_subkey(correct_key, i) for i in range(4, 8)],
[counter, *nonce]
])
state1 = np.zeros((4, 4), dtype=np.int)
for col in range(4):
state1[:,col] = quarter_round(*state0[:,col])
# calculate the hamming weight of the intermediate value
hw = HW(intermediate(step, state0, state1, key_known=True))
return hw >= 16
# calculates a group for the given step/byte and input data
def group8(step, int_subkey, counter, nonce, correct_key):
counter = unpack_counter(counter)
nonce = unpack_nonce(nonce)
# construct states
state0 = np.array([
chacha_consts,
[extract_subkey(correct_key, i) for i in range(0, 4)],
[extract_subkey(correct_key, i) for i in range(4, 8)],
[counter, *nonce]
])
state1 = np.zeros((4, 4), dtype=np.int)
for col in range(4):
state1[:,col] = quarter_round(*state0[:,col])
# bit position of the current subkey byte (for the output of the intermediate)
intermediate_bit_pos = int_subkey*8
if step == 14:
# shifting the result needed because of the ROTL operation in the intermediate function
intermediate_bit_pos = (intermediate_bit_pos+16)%32
# calculate the hamming weight of the intermediate value
hw = HW8[(intermediate(step, state0, state1, key_known=True)>>intermediate_bit_pos) & 0xFF]
return hw >= 4
# calculate the three 32-bit words from 12 nonce bytes
def unpack_nonce(nonce):
nonce = struct.unpack("<III", bytes(nonce))
return nonce
# calculate the 32-bit word from 4 counter bytes
def unpack_counter(counter):
counter = struct.unpack("<I", bytes(counter))[0]
return counter
```
#### File: cpa-chacha/attack/common.py
```python
import chipwhisperer as cw
import time
import numpy as np
# reset target
def reset_target(scope):
scope.io.nrst = "low"
time.sleep(0.05)
scope.io.nrst = "high"
time.sleep(0.05)
# init scope and reset target
# returns scope, target and programmer
def init_scope():
scope = cw.scope()
target = cw.target(scope)
prog = cw.programmers.STM32FProgrammer
time.sleep(0.05)
scope.default_setup()
reset_target(scope)
time.sleep(0.05)
return scope, target, prog
# load previously captured traces
# returns arrays of: traces, counters, nonces; known key
def load_traces(filename="traces.npy", N=None):
data = np.load(filename)
if N is None:
N = data["trace_array"].shape[0]
known_key = None
if "known_key" in data:
known_key = data["known_key"]
if len(known_key) == 0:
known_key = None
return data["trace_array"][:N], data["counter_array"][:N], data["nonce_array"][:N], known_key
```
#### File: cpa-chacha/attack/test_chacha_implementation.py
```python
from common import *
from chipwhisperer.common.utils import util
import argparse
def main():
# parse args
parser = argparse.ArgumentParser(description="Test ChaCha implementation with a known-answer-test")
parser.parse_args()
# init scope, target
scope, target, _ = init_scope()
target.output_len = 0
# test data
key = util.hexStrToByteArray("00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F")
nonce = util.hexStrToByteArray("00 00 00 09 00 00 00 4A 00 00 00 00")
counter = util.hexStrToByteArray("01 00 00 00")
pt_a = bytes([0]*32)
pt_b = bytes([0]*32)
expected_ct_a = util.hexStrToByteArray("10 F1 E7 E4 D1 3B 59 15 50 0F DD 1F A3 20 71 C4 C7 D1 F4 C7 33 C0 68 03 04 22 AA 9A C3 D4 6C 4E")
expected_ct_b = util.hexStrToByteArray("D2 82 64 46 07 9F AA 09 14 C2 D7 05 D9 8B 02 A2 B5 12 9C D1 DE 16 4E B9 CB D0 83 E8 A2 50 3C 4E")
# send test data to the target
target.simpleserial_write('c', counter)
if target.simpleserial_wait_ack(timeout=250) is None:
raise Warning("Device failed to ack")
target.simpleserial_write('n', nonce)
if target.simpleserial_wait_ack(timeout=250) is None:
raise Warning("Device failed to ack")
target.simpleserial_write('a', pt_a)
if target.simpleserial_wait_ack(timeout=250) is None:
raise Warning("Device failed to ack")
target.simpleserial_write('b', pt_b)
if target.simpleserial_wait_ack(timeout=250) is None:
raise Warning("Device failed to ack")
# capture a trace (performs the encrpytion)
cw.capture_trace(scope, target, bytes(1), key)
# read the encrypted data
target.simpleserial_write('A', bytes())
ct_a = target.simpleserial_read('A', 32)
target.simpleserial_write('B', bytes())
ct_b = target.simpleserial_read('B', 32)
# compare read ciphertext with expected ciphertext
if ct_a == expected_ct_a and ct_b == expected_ct_b:
print("OK")
else:
print("FAIL")
if __name__ == "__main__":
main()
```
#### File: cpa-chacha/attack/tvla_specific.py
```python
from common import *
from chacha import *
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import sys
import argparse
def main():
# parse agrs
parser = argparse.ArgumentParser(description="Calculate and plot TVLA", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("TRACES_NPZ", help="set of traces")
parser.add_argument("-b", "--subkey-bytes", action="store_true", help="calculate TVLA for every byte (instead of 32-bit word)")
parser.add_argument("-s", "--step", type=int, help="number of step")
parser.add_argument("-i", "--int-subkey", type=int, help="number of internal subkey")
args = parser.parse_args()
# load traces and associated input data
trace_array, counter_array, nonce_array, correct_key = load_traces(args.TRACES_NPZ)
# calculate TVLA and plot the output
plt.title("TVLA")
if not args.subkey_bytes:
for step in range(16):
if args.step is not None and step != args.step:
continue
testout = calc_tvla32(step, trace_array, counter_array, nonce_array, correct_key)
plt.plot(testout, label=("%d" % step))
else:
for step in range(16):
if args.step is not None and step != args.step:
continue
for int_subkey in range(4):
if args.int_subkey is not None and int_subkey != args.int_subkey:
continue
testout = calc_tvla8(step, int_subkey, trace_array, counter_array, nonce_array, correct_key)
plt.plot(testout, label=("%d/%d" % (step, int_subkey)))
num_points = trace_array.shape[1]
plt.plot([-4.5]*num_points, color="black")
plt.plot([4.5]*num_points, color="black")
plt.legend()
plt.show()
def calc_tvla32(step, trace_array, counter_array, nonce_array, correct_key):
# group the traces
groups = np.array([group32(step, counter_array[i], nonce_array[i], correct_key) for i in range(len(trace_array))])
# calculate the TVLA using the welch's t-test
return welch_ttest(trace_array, groups)
def calc_tvla8(step, int_subkey, trace_array, counter_array, nonce_array, correct_key):
# group the traces
groups = np.array([group8(step, int_subkey, counter_array[i], nonce_array[i], correct_key) for i in range(len(trace_array))])
# calculate the TVLA using the welch's t-test
return welch_ttest(trace_array, groups)
# perform the welch's t-test
# returns zeros if all traces are in the same group
def welch_ttest(traces, group):
traces_true = traces[group]
traces_false = traces[~group]
if len(traces_true) == 0 or len(traces_false) == 0:
return [0]*traces.shape[1]
ttrace = sp.stats.ttest_ind(traces_true, traces_false, axis=0, equal_var=False)[0]
return np.nan_to_num(ttrace)
if __name__ == "__main__":
main()
``` |
{
"source": "jonnykohl/ABBA-QuPath-RegistrationAnalysis",
"score": 3
} |
#### File: regexport/utils/atlas.py
```python
from typing import Optional
from bg_atlasapi import BrainGlobeAtlas
from treelib import Tree, Node
def create_brain_region_tree(atlas: Optional[BrainGlobeAtlas]) -> Tree:
if atlas is None:
return Tree()
new_tree = Tree()
for id in (tree := atlas.hierarchy).expand_tree(mode=Tree.DEPTH):
region_name = atlas._get_from_structure(id, "name")
node = Node(identifier=id, data=region_name)
new_tree.add_node(node, parent=tree.parent(id))
return new_tree
```
#### File: regexport/utils/filters.py
```python
from typing import Tuple, Any
from treelib import Tree
def is_parent(id: Any, selected_ids: Tuple[Any, ...], tree: Tree) -> bool:
if id in selected_ids:
return True
else:
return any(tree.is_ancestor(selected_id, id) for selected_id in selected_ids)
```
#### File: regexport/views/checkbox.py
```python
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QCheckBox, QLabel, QWidget, QHBoxLayout
from traitlets import HasTraits, Bool, link, Unicode
from regexport.model import AppState
from regexport.views.utils import HasWidget
class CheckboxModel(HasTraits):
label = Unicode(default_value='')
checked = Bool(default_value=True)
def register(self, model: AppState, model_property: str):
link(
(self, 'checked'),
(model, model_property)
)
def click(self):
self.checked = not self.checked
print('checked:', self.checked)
class CheckboxView(HasWidget):
def __init__(self, model: CheckboxModel):
self.checkbox = QCheckBox(model.label)
HasWidget.__init__(self, widget=self.checkbox)
self.checkbox.setChecked(model.checked)
self.checkbox.clicked.connect(model.click)
model.observe(self.render, 'checked')
def render(self, changed):
self.checkbox.setChecked(changed.new)
```
#### File: regexport/views/histogram2.py
```python
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from PySide2.QtWidgets import QVBoxLayout, QWidget
from traitlets import HasTraits, Instance, Bool, directional_link
from regexport.model import AppState
from regexport.views.utils import HasWidget
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT
from matplotlib.figure import Figure
class PlotModel(HasTraits):
selected_data = Instance(np.ndarray, allow_none=True)
data = Instance(np.ndarray, allow_none=True)
show = Bool(default_value=True)
def register(self, model: AppState):
self.model = model
model.observe(self.update, ['cells', 'selected_cells', 'column_to_plot', 'show_plots'])
directional_link((model, 'show_plots'), (self, 'show'))
def update(self, change):
model = self.model
if model.selected_cells is None or model.selected_cells[model.column_to_plot].dtype.name == 'category':
self.selected_data = None
else:
self.data = model.cells[model.column_to_plot].values
self.selected_data = model.selected_cells[model.column_to_plot].values
class PlotView(HasWidget):
# Code from https://www.pythonguis.com/tutorials/plotting-matplotlib/
def __init__(self, model: PlotModel, width=5, height=4, dpi=100):
# Make a figure, turn it into a canvas widget
widget = QWidget()
layout = QVBoxLayout()
widget.setLayout(layout)
HasWidget.__init__(self, widget=widget)
self.fig, self.axes = plt.subplots(ncols=2, figsize=(width, height), dpi=dpi)
self.canvas = FigureCanvasQTAgg(figure=self.fig)
layout.addWidget(self.canvas)
self.toolbar = NavigationToolbar2QT(self.canvas, widget)
layout.addWidget(self.toolbar)
self.model = model
self.model.observe(self.render)
def render(self, change):
if self.model.show:
for ax in self.axes:
ax.cla()
if change.new is None:
return
else:
selected_data = self.model.selected_data
if selected_data is not None:
data = selected_data
_, edges = np.histogram(data[data > 0], bins='auto')
all_edges = np.concatenate([[0, 1], edges])
self.axes[0].hist(
data,
bins=all_edges,
cumulative=False,
# density=True,
)
data = self.model.data
ax: plt.Axes = self.axes[1]
ax.hist(
data,
bins=50,
cumulative=True,
density=True,
)
if selected_data is not None:
ax.vlines(selected_data.max(), 0, 1, colors='black', linestyles='dotted')
# self.axes[1].set_ylim(0, 1)
self.canvas.draw()
```
#### File: regexport/views/sidebar.py
```python
from typing import Tuple
from PySide2.QtWidgets import QVBoxLayout, QWidget, QHBoxLayout
from .utils import HasWidget
class Layout(HasWidget):
def __init__(self, widgets: Tuple[HasWidget, ...] = (), horizontal=False):
self._widget = QWidget()
HasWidget.__init__(self, widget=self._widget)
layout = QHBoxLayout() if horizontal else QVBoxLayout()
self._widget.setLayout(layout)
self.widgets = widgets
for widget in widgets:
layout.addWidget(widget.widget)
``` |
{
"source": "jonnyli1125/gector-ja",
"score": 3
} |
#### File: gector-ja/utils/preprocess_output_vocab.py
```python
import argparse
import os
import json
import math
from collections import Counter
def get_class_weights(classes, freqs):
n_samples = sum(freqs[c] for c in classes)
class_weights = [1.] * len(classes)
for i, c in enumerate(classes):
if c in freqs:
w = math.log(n_samples / freqs[c])
class_weights[i] = max(w, 1.0)
return class_weights
def preprocess_output_vocab(output_file, weights_file):
"""Generate output vocab from all corpora."""
labels = ['[PAD]', '[UNK]']
with open('data/corpora/jawiki/edit_freq.json') as f:
jawiki_edit_freq = json.load(f)
with open('data/corpora/lang8/edit_freq.json') as f:
lang8_edit_freq = json.load(f)
edit_freq = Counter(jawiki_edit_freq)
edit_freq.update(lang8_edit_freq)
ordered = sorted(edit_freq.items(), key=lambda x: x[1], reverse=True)
labels += [edit for edit, freq in ordered if freq >= 500]
n_samples = sum(edit_freq[edit] for edit in labels)
dist = [freq / n_samples for edit, freq in ordered]
print(ordered[:100])
print(dist[:100])
n_classes = len(labels)
class_weights = [1.] * n_classes
labels_class_weights = get_class_weights(labels, edit_freq)
n_correct = edit_freq['$KEEP']
detect_class_weights = get_class_weights(
['CORRECT', 'INCORRECT'],
{'CORRECT': n_correct, 'INCORRECT': n_samples-n_correct}
)
detect_class_weights = [1.] + detect_class_weights
with open(weights_file, 'w', encoding='utf-8') as f:
json.dump([labels_class_weights, detect_class_weights], f)
with open(output_file, 'w', encoding='utf-8') as f:
f.writelines(f'{label}\n' for label in labels)
print(f'{n_classes} edits output to {output_file}.')
print(f'Class weights output to {weights_file}.')
def main(args):
preprocess_output_vocab(args.output, args.weights)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output',
help='Path to output file',
required=True)
parser.add_argument('-w', '--weights',
help='Path to class weights output file',
required=True)
args = parser.parse_args()
main(args)
``` |
{
"source": "jonnylin13/agarthon",
"score": 3
} |
#### File: jonnylin13/agarthon/blob.py
```python
__author__ = 'jono'
class Blob(object):
def __init__(self, id, x, y, size, red, green, blue, is_virus, is_agitated, uri, name):
self.id = id
self.x = x
self.y = y
self.size = size
self.red = red
self.green = green
self.blue = blue
self.is_virus = is_virus
self.is_agitated = is_agitated
self.uri = uri
self.name = name
def update(self, blob_info):
self.x = blob_info[0]
self.y = blob_info[1]
self.size = blob_info[2]
self.red = blob_info[3]
self.green = blob_info[4]
self.blue = blob_info[5]
self.is_virus = blob_info[6]
self.is_agitated = blob_info[7]
self.uri = blob_info[8]
self.name = blob_info[9]
```
#### File: jonnylin13/agarthon/client.py
```python
__author__ = 'jono'
import session, world, gameview, packet
import constants
c2s_opcodes = {'protocol_handshake':254, 'game_version_handshake':255, 'token':80,
'set_nickname':0, 'spectate':1, 'mouse_move':16, 'split':17, 'q_pressed':18,
'q_released':19, 'eject_mass':21}
s2c_opcodes = {16:'world_update', 17:'view_update', 20:'reset', 21:'draw_debug_line', 32:'owns_blob',
'ffa_leaderboard':49, 'game_area_size':64, 'blob_experience_info':81}
class Client:
def __init__(self, agarthon, client_id):
self.client_id = client_id
self.main = agarthon
self.packet = packet.Packet()
self.session = session.Session(self.main)
self.session.start()
self.gameview = gameview.GameView(self.main)
self.gameview.start()
def is_connected(self):
return self.is_connected()
def start(self):
self.send_handshake()
self.gameview.start()
def stop(self):
self.world.stop()
self.session.disconnect()
self.gameview.stop()
def parse_packets(self):
for packet in self.session.data_in:
print('Parsing packet: '.join(packet))
# Loads one packet into packet.input
self.packet.read_session(self.session)
opcode = self.packet.read_uint8()
if s2c_opcodes[opcode] == 'world_update':
self.world_update()
elif s2c_opcodes[opcode] == 'view_update':
self.view_update()
elif s2c_opcodes[opcode] == 'reset':
self.reset()
elif s2c_opcodes[opcode] == 'draw_debug_line':
self.draw_debug_line()
elif s2c_opcodes[opcode] == 'owns_blob':
self.owns_blob()
elif s2c_opcodes[opcode] == 'ffa_leaderboard':
self.ffa_leaderboard()
elif s2c_opcodes[opcode] == 'blob_experience_info':
self.blob_experience_info()
elif s2c_opcodes[opcode] == 'game_area_size':
self.game_size()
else:
print('Could not handle packet with opcode: ' + str(opcode))
# Clears packet.input for the next iteration
self.packet.clear_input()
def world_update(self):
count_eats = self.packet.read_uint16()
# Dictionary stores by key=eater_id value=victim_id THESE ARE BLOB EVENTS
eats = {}
for x in range(0, count_eats):
eater_id = self.packet.read_uint32()
victim_id = self.packet.read_uint32()
eats[eater_id] = victim_id
# blobs is a dict with key=player_id and value=a tuple with player information
blobs = {}
# Next block is sent until player id is 0
while True:
player_id = self.packet.read_uint32()
if player_id == 0:
break
x = self.packet.read_uint32()
y = self.packet.read_uint32()
size = self.packet.read_uint16()
r = self.packet.read_uint16()
g = self.packet.read_uint16()
b = self.packet.read_uint16()
byte = self.packet.read_uint8()
is_virus = byte & 0
# Assuming this is for agitated viruses?
is_agitated = byte & 4
if byte & 1:
self.packet.skip(4)
elif byte & 2:
# Blob has a skin - just skip
skin_uri = self.packet.read_str8()
name = self.packet.read_str16()
blobs[player_id] = (x, y, size, r, g, b, is_virus, is_agitated, skin_uri, name)
# Loop amt of removals, store in list of player_ids to remove
count_removals = self.packet.read_uint32()
removals = []
for x in range(0, count_removals):
removals.append(self.packet.read_uint32())
self.world.update(eats, blobs, removals)
def view_update(self):
view_x = self.packet.read_float32()
view_y = self.packet.read_float32()
view_zoom = self.packet.read_float32()
self.gameview.update(view_x, view_y, view_zoom)
def reset(self):
# Does nothing for now I guess
print('Reset sent from server to client!')
def draw_debug_line(self):
line_x = self.packet.read_uint16
line_y = self.packet.read_uint16
self.gameview.draw_debug_line(line_x, line_y)
# Sent when respawned or split - updates the player's blobs
def owns_blob(self):
blob_id = self.packet.read_uint32()
self.world.update_player_blobs(blob_id)
def ffa_leaderboard(self):
count = self.packet.read_uint32()
blobs = {}
for x in range(0, count):
blob_id = self.packet.read_uint32()
name = self.packet.read_str16()
blobs[blob_id] = name
self.gameview.update_ffa_leaderboard(blobs)
# Player EXP info
def blob_experience_info(self):
level = self.packet.read_uint32()
current_xp = self.packet.read_uint32()
next_xp = self.packet.read_uint32()
self.world.update_player_exp(level, current_xp, next_xp)
def game_size(self):
min_x = self.packet.read_float64()
min_y = self.packet.read_float64()
max_x = self.packet.read_float64()
max_y = self.packet.read_float64()
self.gameview.update_game_size(min_x, min_y, max_x, max_y)
# Specifically passes socket arg because must send connection token immediately after connection?
def send_handshake(self):
try:
# send protocol version
self.packet.write_uint8(c2s_opcodes['protocol_handshake'])
self.packet.write_uint32(constants.protocol_version)
self.packet.flush_session(self.session)
# send game version
self.packet.write_uint8(c2s_opcodes['game_version_handshake'])
self.packet.write_uint32(constants.game_version)
self.packet.flush_session(self.session)
# send connection token
self.packet.write_uint8(c2s_opcodes['token'])
self.packet.write_string(self.session.token)
self.packet.flush_session(self.session)
print('Connection token sent!')
except Exception as ex:
print('Could not send connection token for reason: ' + str(ex))
def send_set_nickname(self, name):
try:
self.packet.write_uint8(c2s_opcodes['set_nickname'])
self.packet.write_string(name)
self.packet.flush_session(self.session)
except Exception as ex:
print('Could not send set_nickname for reason: ' + str(ex))
def send_spectate(self):
try:
self.packet.write_uint8(c2s_opcodes['spectate'])
self.packet.flush_session(self.session)
except Exception as ex:
print('Could not send spectate for reason: ' + str(ex))
def send_mouse_move(self, mouse_x, mouse_y, node_id):
try:
self.packet.write_uint8(c2s_opcodes['mouse_move'])
self.packet.write_float64(mouse_x)
self.packet.write_float64(mouse_y)
self.packet.write_uint32(node_id)
self.packet.flush_session(self.session)
except Exception as ex:
print('Could not send mouse_move for reason: ' + str(ex))
def send_split(self):
try:
self.packet.write_uint8(c2s_opcodes['split'])
self.packet.flush_session(self.session)
except Exception as ex:
print('Could not send send_split for reason: ' + str(ex))
def send_q_pressed(self):
try:
self.packet.write_uint8(c2s_opcodes['q_pressed'])
self.packet.flush_session(self.session)
except Exception as ex:
print('Could not send q_pressed for reason: ' + str(ex))
def send_q_released(self):
try:
self.packet.write_uint8(c2s_opcodes['q_released'])
self.packet.flush_session(self.session)
except Exception as ex:
print('Could not send q_released for reason: ' + str(ex))
def send_eject_mass(self):
try:
self.packet.write_uint8(c2s_opcodes['eject_mass'])
self.packet.flush_session(self.session)
except Exception as ex:
print('Could not send eject_mass for reason: ' + str(ex))
``` |
{
"source": "jonnymaserati/jonnymaserati.github.io",
"score": 3
} |
#### File: assets/code/create_casing_connections_graph_2.py
```python
import numpy as np
import ray
import graph_tool as gt
from graph_tool.all import *
import import_from_tenaris_catalogue # our code from part 1
def make_graph(catalogue):
# Now we want to initiate our graph - we'll make the edges directional, i.e.
# they will go from large to small
graph = gt.Graph(directed=True)
return graph
def calculate_pipe_burst_pressure(
yield_strength,
wall_thickness,
pipe_outside_diameter,
safety_factor=1.0
):
burst_pressure = (
(2 * yield_strength * 1000 * wall_thickness)
/ (pipe_outside_diameter * safety_factor)
)
return burst_pressure
def add_burst_pressure_to_graph(graph, yield_min=55, yield_max=125):
attrs = ['pipe_burst_pressure_min', 'pipe_burst_pressure_max']
for a in attrs:
graph.vertex_properties[a] = (
graph.new_vertex_property("double")
)
burst_min = calculate_pipe_burst_pressure(
yield_strength=yield_min,
wall_thickness=graph.vp['pipe_body_wall_thickness'].get_array(),
pipe_outside_diameter=(
graph.vp['pipe_body_inside_diameter'].get_array()
+ 2 * graph.vp['pipe_body_wall_thickness'].get_array()
),
safety_factor=1.0
)
# lazy calculation of burst max - factoring the burt min result
burst_max = (
burst_min / yield_min * yield_max
)
# add the calculated results to our graph vertex properties
for k, v in {
'pipe_burst_pressure_min': burst_min,
'pipe_burst_pressure_max': burst_max
}.items():
graph.vp[k].a = v
return graph
def add_vertices(
graph, manufacturer, type, type_name, tags, data
):
"""
Function for adding a node with attributes to a graph.
Parameters
----------
graph: Graph object
manufacturer: str
The manufacturer of the item being added as a node.
type: str
The type of item being added as a node.
type_name: str
The (product) name of the item being added as a node.
tags: list of str
The attribute tags (headers) of the attributes of the item.
data: list or array of floats
The data for each of the attributes of the item.
Returns
-------
graph: Graph object
Returns the Graph object with the additional node(s).
"""
# when we start adding more conections, we need to be careful with indexing
# so here we make a note of the current index of the last vertex and the
# number of vertices we're adding
start_index = len(list(graph.get_vertices()))
number_of_vertices = len(data)
graph.add_vertex(number_of_vertices)
# here we initate our string vertex property maps
vprops = {
'manufacturer': manufacturer,
'type': type,
'name': type_name
}
# and then add these property maps as internal property maps (so they're)
# included as part of our Graph
for key, value in vprops.items():
# check if property already exists
if key in graph.vertex_properties:
continue
else:
graph.vertex_properties[key] = (
graph.new_vertex_property("string")
)
for i in range(start_index, number_of_vertices):
graph.vertex_properties[key][graph.vertex(i)] = value
# initiate our internal property maps for the data and populate them
for t, d in zip(tags, data.T):
# check if property already exists
if t in graph.vertex_properties:
continue
else:
graph.vertex_properties[t] = (
graph.new_vertex_property("double")
)
# since these properties are scalar we can assign with arrays
graph.vertex_properties[t].get_array()[
start_index: number_of_vertices
] = d
# overwrite the size - in case it didn't import properly from the pdf
graph.vertex_properties['size'].get_array()[
start_index: number_of_vertices
] = (
graph.vertex_properties['pipe_body_inside_diameter'].get_array()[
start_index: number_of_vertices
] + 2 * graph.vertex_properties['pipe_body_wall_thickness'].get_array()[
start_index: number_of_vertices
]
)
# calculate and add our min and max pipe body burst pressures
graph = add_burst_pressure_to_graph(graph)
return graph
def add_connection_edges(graph, cut_off=0.7):
"""
Function to add edges between connection components in a network graph.
Parameters
----------
graph: (Di)Graph object
cut_off: 0 < float < 1
A ration of the nominal component size used as a filter, e.g. if set
to 0.7, if node 1 has a size of 5, only a node with a size greater than
3.5 will be considered.
Returns
-------
graph: (Di)Graph object
Graph with edges added for connections that can drift through other
connections.
"""
# get indexes of casing connections - we're thinking ahead since in the
# future we might be adding more than just casing connections to our graph
idx = [
i for i, type in enumerate(graph.vp['type'])
if type == 'casing_connection'
]
# ensure that all the vertex properties exist - this list will likely
# expand so at some point we might want a parameters file to store all our
# property names that can be edited outside of this code
vps = ['coupling_outside_diameter', 'box_outside_diameter']
for vp in vps:
if vp not in graph.vp:
graph.vertex_properties[vp] = (
graph.new_vertex_property("double")
)
# hold onto your seats... we're using array methods to do this super fast
# calculate the clearance for every combination of connections
clearance = np.amin((
graph.vp['pipe_body_drift'].get_array()[idx],
graph.vp['connection_inside_diameter'].get_array()[idx]
), axis=0).reshape(-1, 1) - np.amax((
graph.vp['coupling_outside_diameter'].get_array()[idx],
graph.vp['box_outside_diameter'].get_array()[idx],
graph.vp['pipe_body_inside_diameter'].get_array()[idx]
+ 2 * graph.vp['pipe_body_wall_thickness'].get_array()[idx]
), axis=0).T
# our data is raw and ideally needs cleaning, but in the meantime we'll
# just ignore errors so that we don't display them to the console
with np.errstate(invalid='ignore'):
clearance_idx = np.where(
np.all((
clearance > 0,
(
graph.vp['size'].get_array()[idx].T
/ graph.vp['size'].get_array()[idx].reshape(-1, 1)
> cut_off
)
), axis=0)
)
# make a list of our edges
edges = np.vstack(clearance_idx).T
# initiate an internal property map for storing clearance data
graph.edge_properties['clearance'] = (
graph.new_edge_property('double')
)
# add our edges to the graph along with their associated clearances
# although we're not using this property yet, we might want to when
# filtering our options later
graph.add_edge_list(
np.concatenate(
(edges, clearance[clearance_idx].reshape(-1, 1)), axis=1
), eprops=[graph.edge_properties['clearance']]
)
return graph
# def get_roots_and_leaves(graph, surface_casing_size=18.625):
# roots = np.where(graph.get_in_degrees(graph.get_vertices()) == 0)
# roots = roots[0][np.where(
# graph.vp['size'].get_array()[roots] == surface_casing_size
# )]
# leaves = np.where(graph.get_out_degrees(graph.get_vertices()) == 0)[0]
# return roots, leaves
def get_roots_and_leaves(graph, surface_casing_size=18.625):
roots = np.where(np.all((
graph.vp['vertices_filter'].a,
graph.vp['size'].a == surface_casing_size
), axis=0))[0]
leaves = graph.get_vertices()[np.where(
graph.get_out_degrees(graph.get_vertices()) == 0
)[0]]
return roots, leaves
@ray.remote
def get_paths(graph, source, target):
paths = [
tuple(path) for path in gt.topology.all_paths(
graph, source, target
)
]
return paths
def set_vertex_filter(
graph,
surface_casing_size=18.625,
surface_casing_wall_thickness=0.5,
production_envelope_id_min=6.2
):
# first let's filter out all vertices that are 18 5/8" except for the
# one with the wall thickness of 0.5" that we desire
filter_surface_casing = np.invert(np.all((
graph.vp['size'].a >= surface_casing_size,
graph.vp['pipe_body_wall_thickness'].a != surface_casing_wall_thickness
), axis=0))
# we can also filter out anything that has an internal drift diameter of
# 6.2" or smaller
filter_leaves = np.invert(np.any((
graph.vp['pipe_body_drift'].a <= production_envelope_id_min,
graph.vp['pipe_body_inside_diameter'].a <= production_envelope_id_min,
graph.vp['connection_inside_diameter'].a <= production_envelope_id_min
), axis=0))
# create a boolean mask that we can apply to our graph
graph_filter = np.all((
filter_surface_casing,
filter_leaves
), axis=0)
# create a PropertyMap to store our mask/filter and assign our array to it
graph.vp['vertices_filter'] = graph.new_vertex_property('bool')
graph.vp['vertices_filter'].a = graph_filter
# apply the filter to the graph
graph.set_vertex_filter(graph.vp['vertices_filter'])
# return the filtered graph
return graph
def main():
# this runs the code from part 1 (make sure it's in your working directory)
# and assigns the data to the variable catalogue
catalogue = import_from_tenaris_catalogue.main()
# initiate our graph and ray
graph = make_graph(catalogue)
ray.init()
# add the casing connections from our catalogue to the network graph
for product, data in catalogue.items():
graph = add_vertices(
graph,
manufacturer='Tenaris',
type='casing_connection',
type_name=product,
tags=data.get('headers'),
data=data.get('data')
)
# determine which connections fit through which and add the appropriate
# edges to the graph.
graph = add_connection_edges(graph)
graph = set_vertex_filter(graph)
# place a copy of the graph in shared memory
graph_remote = ray.put(graph)
# # determine roots and leaves
roots, leaves = get_roots_and_leaves(graph)
# generate pairs of source and target nodes/vertices
# we do this primarily to maximise utility of multiprocessing, to minimise
# processor idling
input = np.array(
[data for data in map(np.ravel, np.meshgrid(roots, leaves))]
).T
# loop through inputs and append paths to a list, using ray
paths = ray.get([
get_paths.remote(graph, s, t)
for s, t in input
])
# we end up with a list of lists which we need to flatten to a simple list
paths = [item for sublist in paths for item in sublist]
# we're only interested in paths of 7 or more
paths_filtered_number_of_strings = [p for p in paths if len(p) == 5]
# we only want paths where the production casing (which is the 3rd string
# from the end) has a maximum burst pressure larger than the 10,000 psi
# requirement from our Production Technologist
paths_filtered_production_casing_burst = [
p for p in paths_filtered_number_of_strings
if graph.vp['pipe_burst_pressure_max'].a[p[-3]] > 10000
]
first_five = [
[
f"{graph.vp['size'][p]} in - {graph.vp['nominal_weight'][p]} ppf"
for p in path
] for path in paths_filtered_number_of_strings[:5]
]
print(
f"Number of casing design permutations: "
f"{len(paths_filtered_number_of_strings):,}"
)
print("First five permutations (size - nominal weight):")
for path in first_five:
print(path)
# filter results
paths_filtered_first_position = [
p for p in paths_filtered_number_of_strings
if max(
graph.vp['box_outside_diameter'].a[p[1]],
graph.vp['coupling_outside_diameter'].a[p[1]]
) < 14.0
]
paths_filtered_second_position = [
p for p in paths_filtered_first_position
if max(
graph.vp['box_outside_diameter'].a[p[2]],
graph.vp['coupling_outside_diameter'].a[p[2]]
) < 11
]
paths_filtered_production_casing_wt_max = [
p for i, p in enumerate(paths_filtered_second_position)
if i in np.where(
graph.vp['pipe_body_wall_thickness'].a == max([
graph.vp['pipe_body_wall_thickness'].a[p[-1]]
for p in paths_filtered_second_position
])
)[0]
]
def get_clearance(graph, path):
upper = path[:-1]
lower = path[1:]
clearance = sum([
graph.ep['clearance'].a[graph.edge_index[graph.edge(u, l)]]
for u, l in zip(upper, lower)
])
return clearance
clearance = [
get_clearance(graph, p)
for p in paths_filtered_production_casing_wt_max
]
selected_concept = paths_filtered_production_casing_wt_max[
np.argmax(clearance)
]
plot(graph, paths_filtered_production_casing_wt_max, selected_concept)
[
f"{graph.vp['size'][p]} in - {graph.vp['nominal_weight'][p]} ppf"
for p in selected_concept
]
return graph
def plot(graph, paths, preferred_path=None):
import plotly.graph_objects as go
casing_sizes = np.unique(graph.vp['size'].a).tolist()
casing_weights = {}
for s in casing_sizes:
if np.isnan(s):
continue
idx = np.where(graph.vp['size'].a == s)
weight = graph.vp['nominal_weight'].a[idx]
casing_weights[s] = {
'weight_min': float(np.min(weight)),
'weight_range': float(np.max(weight) - np.min(weight))
}
def get_edge_trace(graph, paths, color='blue', width=1.0):
edge_x = []
edge_y = []
edge_c = []
pos = {}
for path in paths:
upper = path[:-1]
lower = path[1:]
for items in zip(upper, lower):
for i in items:
edge_x.append((
graph.vp['nominal_weight'].a[i]
- casing_weights[
graph.vp['size'].a[i]
]['weight_min']
) / casing_weights[
graph.vp['size'].a[i]
]['weight_range'])
edge_y.append(graph.vp['size'].a[i])
edge_x.append(None)
edge_y.append(None)
edge_trace = go.Scatter(
x=edge_x, y=edge_y,
line=dict(
width=width,
color=color
),
mode='lines',
showlegend=False
)
return edge_trace
edge_trace = get_edge_trace(graph, paths)
if preferred_path:
preferred_edge_trace = get_edge_trace(
graph, [preferred_path], color='red', width=2.0
)
else:
preferred_edge_trace = []
# flatten the paths and get unique list of nodes
nodes = list(set([item for sublist in paths for item in sublist]))
node_x = []
node_y = []
node_text = []
for node in nodes:
node_x.append((
graph.vp['nominal_weight'].a[node]
- casing_weights[
graph.vp['size'].a[node]
]['weight_min']
) / casing_weights[
graph.vp['size'].a[node]
]['weight_range'])
node_y.append(graph.vp['size'].a[node])
node_text.append(
f"{graph.vp['size'].a[node]} in"
f" : {graph.vp['nominal_weight'].a[node]} ppf"
)
node_trace = go.Scatter(
x=node_x, y=node_y,
mode='markers+text',
text=node_text,
textposition="top center",
marker=dict(
size=20,
line_width=2
),
showlegend=False
)
layout = go.Layout(
title="Casing Design Concepts",
xaxis=dict(
title="Normalized Weight (ppf)",
autorange=True,
# showgrid=False,
ticks='',
showticklabels=False
),
yaxis=dict(
title="Nominal Size (inches)"
)
)
fig = go.Figure(
data=[edge_trace, preferred_edge_trace, node_trace],
layout=layout
)
fig.show()
if __name__ == '__main__':
graph = main()
print("Done")
```
#### File: assets/code/create_casing_connections_graph.py
```python
import numpy as np
import networkx as nx
import import_from_tenaris_catalogue # our code from part 1
class Counter:
def __init__(self, start=0):
"""
A simple counter class for storing a number that you want to increment
by one.
"""
self.counter = start
def count(self):
"""
Calling this method increments the counter by one and returns what was
the current count.
"""
self.counter += 1
return self.counter - 1
def current(self):
"""
If you just want to know the current count, use this method.
"""
return self.counter
def make_graph(catalogue):
# Now we want to initiate our graph - we'll make the edges directional, i.e.
# they will go from large to small
graph = nx.DiGraph()
return graph
def add_node(
counter, graph, manufacturer, type, type_name, tags, data
):
"""
Function for adding a node with attributes to a graph.
Parameters
----------
counter: Counter object
graph: (Di)Graph object
manufacturer: str
The manufacturer of the item being added as a node.
type: str
The type of item being added as a node.
type_name: str
The (product) name of the item being added as a node.
tags: list of str
The attribute tags (headers) of the attributes of the item.
data: list or array of floats
The data for each of the attributes of the item.
Returns
-------
graph: (Di)Graph object
Returns the (Di)Graph object with the addition of a new node.
"""
# we'll first create a dictionary with all the node attributes
node = {
'manufacturer': manufacturer,
'type': type,
'name': type_name
}
# loop through the tags and data
for t, d in zip(tags, data):
node[t] = d
# get a UID and assign it
uid = counter.count()
node['uid'] = uid
# overwrite the size - in case it didn't import properly from the pdf
size = (
node['pipe_body_inside_diameter']
+ 2 * node['pipe_body_wall_thickness']
)
# use the class method to add the node, unpacking the node dictionary
# and naming the node with its UID
graph.add_node(uid, **node)
return graph
def check_connection_clearance(graph, node1, node2, cut_off=0.7):
"""
Function for checking if one component will pass through another.
Parameters
----------
graph: (Di)Graph object
node1: dict
A dictionary of node attributes.
node2: dict
A dictionary of node attributes.
cut_off: 0 < float < 1
A ration of the nominal component size used as a filter, e.g. if set
to 0.7, if node 1 has a size of 5, only a node with a size greater than
3.5 will be considered.
Returns
-------
graph: (Di)Graph object
Graph with an edge added if node2 will drift node1, with a `clearance`
attribute indicating the clearance between the critical outer diameter
of node2 and the drift of node1.
"""
try:
node2_connection_od = node2['coupling_outside_diameter']
except KeyError:
node2_connection_od = node2['box_outside_diameter']
clearance = min(
node1['pipe_body_drift'],
node1['connection_inside_diameter']
) - max(
node2_connection_od,
node2['pipe_body_inside_diameter']
+ 2 * node2['pipe_body_wall_thickness']
)
if all((
clearance > 0,
node2['size'] / node1['size'] > cut_off
)):
graph.add_edge(node1['uid'], node2['uid'], **{'clearance': clearance})
return graph
def add_connection_edges(graph, cut_off=0.7):
"""
Function to add edges between connection components in a network graph.
Parameters
----------
graph: (Di)Graph object
cut_off: 0 < float < 1
A ration of the nominal component size used as a filter, e.g. if set
to 0.7, if node 1 has a size of 5, only a node with a size greater than
3.5 will be considered.
Returns
-------
graph: (Di)Graph object
Graph with edges added for connections that can drift through other
connections.
"""
for node_outer in graph.nodes:
# check if the node is a casing connection
if graph.nodes[node_outer]['type'] != 'casing_connection':
continue
for node_inner in graph.nodes:
if graph.nodes[node_inner]['type'] != 'casing_connection':
continue
graph = check_connection_clearance(
graph,
graph.nodes[node_outer],
graph.nodes[node_inner],
cut_off
)
return graph
def main():
# this runs the code from part 1 (make sure it's in your working directory)
# and assigns the data to the variable catalogue
catalogue = import_from_tenaris_catalogue.main()
# initiate our counter and graph
counter = Counter()
graph = make_graph(catalogue)
# add the casing connections from our catalogue to the network graph
for product, data in catalogue.items():
for row in data['data']:
graph = add_node(
counter,
graph,
manufacturer='Tenaris',
type='casing_connection',
type_name=product,
tags=data['headers'],
data=row
)
# determine which connections fit through which and add the appropriate
# edges to the graph.
graph = add_connection_edges(graph)
return graph
if __name__ == '__main__':
graph = main()
# as a QAQC step we can use matplotlib to draw the edges between connected
# casing connections
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use("TKAgg") # Ubuntu sometimes needs some help
nx.draw_networkx(graph, pos=nx.circular_layout(graph))
plt.show()
print("Done")
```
#### File: assets/code/import_connections_from_tenaris_catalogue.py
```python
import camelot
from pathlib import Path
import wget
import numpy as np
import pandas as pd
# the URL for the Tenaris catalogue so I can claim I'm not copying anything
url = 'https://www.tenaris.com/media/isfmuyog/tenarishydril-premium-connections-catalog.pdf'
# check if the catalogue has already been downloaded
file = "tenarishydril-premium-connections-catalog.pdf"
if not Path(file):
file = wget.download(url)
# I'm not proud of manually typing these headers - and if this must
# be done it'd be better to place all this inside a yaml file and import it
# but I struggled to get camelot to interpret these
template = {
'Wedge 521': {
'pages': '49, 50',
'connection_type': 'threaded',
'headers': [
'size', 'nominal_weight',
'pipe_body_wall_thickness', 'pipe_body_inside_diameter',
'pipe_body_drift', 'box_outside_diameter',
'connection_inside_diameter', 'make_up_loss',
'critical_section_area', 'tensile_efficiency',
'compression_efficiency',
'joint_yield_55', 'joint_yield_80', 'joint_yield_90',
'joint_yield_95', 'joint_yield_110', 'joint_yield_125',
]
}
}
def import_tables(file, pages):
"""
Function for extracting table data from a pdf file.
Parameters
----------
file: string
The variable name or the path and filename of the pdf.
pages: string
The pages in the pdf where the tables are located, e.g. '1, 2, 3' or
'1-3'.
Returns
-------
tables: TableList object
"""
tables = camelot.read_pdf(
file, pages=pages,
flavor='stream',
)
return tables
def convert_to_float(frac_str):
"""
It wouldn't be the oilfield without a healthy mix of units and fractions.
This function attempts to deal with fractions care of someone on stack
overflow (thank you).
Parameters
----------
frac_str: string
Returns
-------
result: float
Exceptions
----------
ValueError: if the string is not a number or a fraction
"""
try:
return float(frac_str)
except ValueError:
num, denom = frac_str.split('/')
try:
leading, num = num.split(' ')
whole = float(leading)
except ValueError:
whole = 0
frac = float(num) / float(denom)
result = whole - frac if whole < 0 else whole + frac
return result
def extract_data(table, start_row=1, end_row=None):
"""
This is where the real fun starts. I'm not proud of this processing
workflow, but it works and cost me less time than arseing about with
camelot's settings, especially since there's subtle differences between
the tables in Tenaris' catalogue.
Parameters
----------
table: TableList object
start_row: int
If you're confident that the table header is a specific number of rows
then enter that here and skip these rows.
end_row: int or None
If you only want to read a finite number of rows. The default 'None'
reads them all.
Returns
-------
datas: list of (n, m) arrays
"""
# Define a list of characters in the table that we want to ignore
characters = ['(', ')', '*']
datas = []
skip_header = True
for i, row in enumerate(table.data[start_row:end_row]):
if skip_header:
# Read the first item of each row to determine if we're passed the
# header and into the table data. We know the first row of data
# begins with a number (or a fraction).
try:
convert_to_float(row[0])
except ValueError:
continue
skip_header = False
data = []
for j, item in enumerate(row):
# We don't want new line characters
if '\n' in item:
item = item.split('\n')[-1]
# Skip and unwanted characters
if any(c in item for c in characters):
continue
# Manage blank data - there's rogue columns in the read data
if item == '':
if j == 0:
data.append(datas[-1][j])
else:
continue
# If it's a number add to the data, otherwise add a NaN
else:
try:
data.append(
convert_to_float(item)
)
except ValueError:
data.append(np.nan)
# Remove and rows of NaNs
if np.all(np.isnan(np.array(data)[1:])):
continue
else:
datas.append(data)
return datas
def main():
# initiate our catalogue dictionary
catalogue = {}
# loop over out template dictionary we made with the table headers
for k, v in template.items():
# import the data
catalogue[k] = {}
data = []
temp = import_tables(file, pages=v['pages'])
# process the data
for t in temp:
data.extend(extract_data(t))
# some of the data might not import correctly - for now we're just
# going to ignore these rows (which may be longer or shorter)
length = [len(l) for l in data]
filtered_data = [
d for d in data
if len(d) == max(set(length), key=length.count)
]
# just in case some rows with NaNs imported, we'll mask them off and
# filer them out of the data
mask = np.all(np.isnan(filtered_data), axis=1)
catalogue[k]['data'] = np.vstack(np.array(filtered_data)[~mask])
catalogue[k]['headers'] = v['headers']
return catalogue
if __name__ == '__main__':
catalogue = main()
print("Done")
``` |
{
"source": "jonnymccullagh/ansible-playbook-summary-to-dd",
"score": 3
} |
#### File: jonnymccullagh/ansible-playbook-summary-to-dd/playbook_summary_to_dd.py
```python
import argparse
import os
from datadog import initialize, api
DD_API_KEY = os.environ["DATADOG_API_KEY"]
DD_APP_KEY = os.environ["DATADOG_APP_KEY"]
def parse_arguments():
"""Get parameters passed at runtime"""
parser = argparse.ArgumentParser()
parser.add_argument("--playbook-file",
dest="playbook_file",
default=None,
type=str)
parser.add_argument("--env",
dest="env",
default="dev",
type=str)
if not parser.parse_args().playbook_file:
parser.error(
"No playbook file specified: e.g. --playbook-file my-playbook-file.yml"
)
return parser.parse_args()
def main(): # pylint: disable=W0613
"""Main starting point"""
args = parse_arguments()
options = {"api_key": DD_API_KEY, "app_key": DD_APP_KEY}
print("Initializing DataDog Client...\n")
initialize(**options)
# Open the summary of the playbook run
ansible_log = open("playbook_summary.txt", "r")
metrics = []
while ansible_line := ansible_log.readline():
# someservername-10-100-1-2 : ok=145
# changed=0 unreachable=0 failed=0
# skipped=96 rescued=0 ignored=0
host_name = ansible_line.split()[0]
stats_string = ansible_line.split(":")[1]
stats_dict = dict(x.split("=") for x in stats_string.split())
for key, value in stats_dict.items():
metrics.append(
{
"type": "metric",
"metric": "ansible.tasks." + key,
"points": int(value),
"host": host_name,
"tags": [
f"playbook:{args.playbook_file.split('.')[0]}",
],
}
)
print(metrics)
response = api.Metric.send(metrics)
print(response)
if __name__ == "__main__": # pylint: disable=W0621, C0103, W0613
main()
``` |
{
"source": "jonnymcgow7/locust",
"score": 3
} |
#### File: locust/tests/test_parse.py
```python
import json
import os
import unittest
from google.protobuf.json_format import MessageToDict, Parse
from locust import git, parse
from . import config
class TestLocustParse(unittest.TestCase):
maxDiff = None
def test_parse_run(self):
repo_dir = config.TESTCASES_DIR
test_input_fixture = os.path.join(config.TESTS_DIR, "fixtures", "test_git.json")
with open(test_input_fixture) as ifp:
test_input_str = repo_dir.join(
ifp.read().strip().split(config.REPO_DIR_TOKEN)
)
test_input = Parse(test_input_str, git.GitResult())
expected_result_fixture = os.path.join(
config.TESTS_DIR, "fixtures", "test_parse.json"
)
with open(expected_result_fixture) as ifp:
expected_result_str = repo_dir.join(
ifp.read().strip().split(config.REPO_DIR_TOKEN)
)
expected_result_json = json.loads(expected_result_str)
result = parse.run(test_input, [])
result_json = MessageToDict(result, preserving_proto_field_name=True)
self.assertDictEqual(result_json, expected_result_json)
def test_parse_dependencies(self):
repo_dir = config.TESTCASES_DIR
test_input_fixture = os.path.join(
config.TESTS_DIR, "fixtures", "test_git_dependencies.json"
)
with open(test_input_fixture) as ifp:
test_input_str = repo_dir.join(
ifp.read().strip().split(config.REPO_DIR_TOKEN)
)
test_input = Parse(test_input_str, git.GitResult())
expected_result_fixture = os.path.join(
config.TESTS_DIR, "fixtures", "test_parse_dependencies.json"
)
with open(expected_result_fixture) as ifp:
expected_result_str = repo_dir.join(
ifp.read().strip().split(config.REPO_DIR_TOKEN)
)
expected_result_json = json.loads(expected_result_str)
result = parse.run(test_input, [])
result_json = MessageToDict(result, preserving_proto_field_name=True)
self.assertDictEqual(result_json, expected_result_json)
``` |
{
"source": "JONNY-ME/Games-pygame",
"score": 3
} |
#### File: Games-pygame/space war/main.py
```python
import pygame
import random
import time
pygame.init() #initialize pygame
screen = pygame.display.set_mode((800, 600)) #game size
pygame.display.set_caption('game by jo') #title
icon = pygame.image.load('images/48.png') # load icon
pygame.display.set_icon(icon) # set icon to the game
font = pygame.font.SysFont('Comic Sans MS', 50)
win_text = font.render('You Win', False, (124, 0, 124))
start_new = font.render('press s to start new game', False, (124, 0, 124))
playerim = pygame.image.load('images/63.png')
px = 400
py = 520
cx = 0
enemyim = pygame.image.load('images/91.png')
def create_enemy():
ex = fx = random.randint(0, 736)
fy = ey = random.randint(20, 100)
return ex, ey, fx, fy
def enemy(x, y):
screen.blit(enemyim, (x, y))
def player(x, y):
screen.blit(playerim, (x, y))
def fire(x, y):
pygame.draw.rect(screen, (255, 0, 0), (x, y, 5, 12))
def random_dirc(x, y, dx, dy):
if abs(x-dx)<4 and abs(y - dy)<4:
dx = random.randint(0, 736)
dy = random.randint(20, 100)
if dx > x:
x += .3
elif dx < x:
x -= .3
if dy > y:
y += .3
elif dy < y:
y -= .3
return x, y, dx, dy
constant_nenemy = 15
n_enemy = constant_nenemy
enemies = [create_enemy() for i in range(n_enemy)]
fires = []
start = time.time()
xt = interval = .2
running = True
display_time = 1
while running:
screen.fill((0, 0, 0))
curr = time.time() - start
if curr > display_time and n_enemy != 0:
display_time += 1
if curr >= interval:
interval += xt
fires.append([px+30, py-30])
fire_backup = []
for fr in fires:
if fr[1] > 0:
fire_backup.append(fr)
fires = fire_backup
skey = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
cx =- 1
elif event.key == pygame.K_d:
cx =+ 1
elif event.key == pygame.K_s:
skey = 1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
cx = 0
if px+cx >= 0 and px+cx < 736:
px += cx
player(px, py)
en_bc = []
for en in enemies:
ex, ey, fx, fy = en
enemy(ex, ey)
en_bc.append(random_dirc(ex, ey, fx, fy))
enemies = en_bc
enemy_survived = [1 for _ in range(n_enemy)]
fire_backup = []
for i, j in fires:
fire(i, j)
fire_backup.append([i, j-1])
for k in range(n_enemy):
if abs(enemies[k][0] - i) + abs(enemies[k][1] - j) <= 16:
enemy_survived[k] = 0
fires = fire_backup
en_bc = []
for i in range(n_enemy):
if enemy_survived[i]:
en_bc.append(enemies[i])
enemies = en_bc
n_enemy = sum(enemy_survived)
if n_enemy == 0:
screen.fill((0, 0, 0))
screen.blit(win_text,(200,280))
screen.blit(start_new,(200,400))
screen.blit(font.render(f'{display_time} seconds', False, (124, 0, 124)), (200, 500))
if skey:
n_enemy = constant_nenemy
enemies = [create_enemy() for i in range(n_enemy)]
start = curr
pygame.display.update()
```
#### File: Games-pygame/twocars/main.py
```python
import pygame
import random
import time
pygame.init() #initialize pygame
screen = pygame.display.set_mode((200, 600)) #game size
pygame.display.set_caption('Two Cars') #title
icon = pygame.image.load('image/icon.png') # load icon
pygame.display.set_icon(icon) # set icon to the game
font = pygame.font.SysFont('Comic Sans MS', 23)
obb = pygame.image.load('image/obb.png')
obr = pygame.image.load('image/obr.png')
fdb = pygame.image.load('image/fdb.png')
fdr = pygame.image.load('image/fdr.png')
crr = pygame.image.load('image/crr.png')
crb = pygame.image.load('image/crb.png')
def draw_obb(x, y):
screen.blit(obb, (x, y))
def draw_obr(x, y):
screen.blit(obr, (x, y))
def draw_fdb(x, y):
screen.blit(fdb, (x, y))
def draw_fdr(x, y):
screen.blit(fdr, (x, y))
def generate_next_blue(blues):
b = blues.copy()
b.append([random.choice([7, 57]), 0, random.choice([0, 1])])
return b
def generate_next_red(reds):
r = reds.copy()
r.append([random.choice([107, 157]), 0, random.choice([0, 1])])
return r
def draw_thing(s, x, y):
screen.blit(font.render(s, False, (255, 255, 255)), (x, y))
drr = [7, 57, 107, 157]
xb = drr[0]
xr = drr[3]
yb = yr = 520
red = generate_next_red([])
blue = generate_next_blue([])
speed = .1
running = True
score = None
high_score = 0
playing = False
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if (event.key == 1073741918 or event.key == pygame.K_d) and playing:
xr = drr[-2:][xr == drr[2]]
elif (event.key == 1073741916 or event.key == pygame.K_a) and playing:
xb = drr[:2][xb == drr[0]]
elif event.key == pygame.K_s:
playing = True
xb = drr[0]
xr = drr[3]
yb = yr = 520
red = generate_next_red([])
blue = generate_next_blue([])
speed = .1
score = 0
if playing:
# adding next fd or ob
if blue[-1][1] > 120 + 20*random.random():
blue = generate_next_blue(blue)
if red[-1][1] > 120 + 20*random.random():
red = generate_next_red(red)
bac_red = []
for i in range(len(red)):
if red[i][1] < 600:
bac_red.append([red[i][0], red[i][1]+speed, red[i][2]])
red = bac_red
bac_blue = []
for i in range(len(blue)):
if blue[i][1] < 600:
bac_blue.append([blue[i][0], blue[i][1]+speed, blue[i][2]])
blue = bac_blue
if abs(red[0][1] - yr) <= 20 and xr == red[0][0]:
if red[0][2] == 1:
red = red[1:]
if score == None:
score = 1
else:
score += 1
else:
playing = False
if abs(blue[0][1] - yb) <= 20 and xb == blue[0][0]:
if blue[0][2] == 1:
blue = blue[1:]
if score == None:
score = 1
else:
score += 1
else:
playing = False
if red[0][1] > 545 and red[0][2]:
playing = False
if blue[0][1] > 545 and blue[0][2]:
playing = False
pygame.draw.rect(screen, (173,216,230), (50, 0, 2, 600))
pygame.draw.rect(screen, (173,216,230), (100, 0, 2, 600))
pygame.draw.rect(screen, (173,216,230), (150, 0, 2, 600))
screen.blit(crb, (xb, yb))
screen.blit(crr, (xr, yr))
for x, y, t in red:
if t == 1:
draw_fdr(x, y)
else:
draw_obr(x, y)
for x, y, t in blue:
if t == 1:
draw_fdb(x, y)
else:
draw_obb(x, y)
if score == None:
score = 0
draw_thing(str(score), 157, 0)
speed +=0.000005
else:
if score == None:
draw_thing('press s to start new game', 0, 150)
else:
pygame.draw.rect(screen, (173,216,230), (50, 0, 2, 600))
pygame.draw.rect(screen, (173,216,230), (100, 0, 2, 600))
pygame.draw.rect(screen, (173,216,230), (150, 0, 2, 600))
screen.blit(crb, (xb, yb))
screen.blit(crr, (xr, yr))
for x, y, t in red:
if t == 1:
draw_fdr(x, y)
else:
draw_obr(x, y)
for x, y, t in blue:
if t == 1:
draw_fdb(x, y)
else:
draw_obb(x, y)
high_score = max(high_score, score)
draw_thing(f'your score = {score}', 40, 150)
draw_thing(f'high score = {high_score}', 40, 220)
draw_thing('press s to start new game', 0, 300)
pygame.display.update()
``` |
{
"source": "jonnyMejia/pysocial",
"score": 2
} |
#### File: base/models/message.py
```python
import os
# Django Library
from djongo import models
from django.utils.translation import ugettext_lazy as _
# Localfolder Library
from ..rename_image import RenameImage
from .usercustom import PyUser
def image_path(instance, filename):
return os.path.join('friends', str(instance.pk) + '.' + filename.rsplit('.', 1)[1])
class PyConversation(models.Model):
'''Conversation Model
'''
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(_("Created_at"), auto_now_add = True)
sender_id = models.ForeignKey(PyUser, on_delete=models.CASCADE, related_name='+', null=False, blank=False)
receptor_id = models.ForeignKey(PyUser, on_delete=models.CASCADE, related_name='+', null=False, blank=False)
class Meta:
verbose_name = _('Conversation')
verbose_name_plural = _('Conversations')
class PyMessage(models.Model):
'''Conversation Model
'''
id = models.AutoField(primary_key=True)
content = models.CharField(_("Content"), max_length=300)
created_at = models.DateTimeField(_("Created_at"), auto_now_add = True)
user_id = models.ForeignKey(PyUser, related_name='+', on_delete=models.CASCADE, null=False, blank=False)
conversation_id = models.ForeignKey(PyConversation, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
class Meta:
verbose_name = _('Message')
verbose_name_plural = _('Messages')
``` |
{
"source": "jonnynabors/guet",
"score": 2
} |
#### File: usercommands/start/hook_strategy.py
```python
from guet.git.git import Git
from guet.commands.strategies.strategy import CommandStrategy
class HookStrategy(CommandStrategy):
def __init__(self, git: Git):
self.git = git
def apply(self):
self._hook_apply()
print('guet successfully started in this repository.')
def _hook_apply(self) -> None:
raise NotImplementedError
``` |
{
"source": "Jonnyneill/talking-clock",
"score": 4
} |
#### File: talking-clock/src/clock.py
```python
import time
numbers = ("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty")
clockface = ("o'clock", "quarter", "half", "quarter")
def talk(time_input):
"""
Converts a time string to the equivalent english language sentence
:param time_input: The time string to convert
:return: The english language equivalent of the provided time string
"""
hour, minute, context = get_context(time_input)
words = convert_to_words(hour, minute, context)
return " ".join(filter(None, words)).strip().capitalize()
def get_context(time_input):
"""
Determine if we want to talk in the context of the current hour or the next hour
Sets the time values relevant to the context
:param time_input: The time string from which to base context
:return: a tuple containing the contextualised hour and minute,
"""
try:
formatted_time = time.strptime(time_input, "%H:%M")
separator = ":"
except ValueError:
try:
formatted_time = time.strptime(time_input, "%H.%M")
separator = "."
except ValueError:
formatted_time = time.strptime(time_input, "%H%M")
separator = ""
twelve_hour_time = time.strftime("%I{}%M".format(separator), formatted_time)
if separator:
hour, minute = map(int, twelve_hour_time.split(separator))
else:
hour = int(twelve_hour_time[:2])
minute = int(twelve_hour_time[-2:])
context = "past"
if minute > 30:
if hour == 12:
hour = 0
minute = 60 - minute
context = "to"
hour += 1
return hour, minute, context
def convert_to_words(hour, minute, context):
"""
Convert the given hour and minute into words,
:param hour: int representing the hour
:param minute: int representing the minute
:param context: The context of how the current time is expressed, must be 'to' or 'past'
:return: a list of the words giving a meaningful english language representation of the time
"""
if minute == 0:
# if it's zero then we are on the hour
return [numbers[hour], clockface[minute]]
# check if the minute hand would be on one of the quarter increments i.e. o'clock, quarter, half
if (minute % 15) == 0:
return [clockface[int(minute / 15)], context, numbers[hour]]
# if we arent at a quarter increment then just convert the numbers to words
tens = (minute // 10) * 10
ones = minute % 10
words = []
if tens == 10:
# if it's a teen then just get the word
words.append(numbers[minute])
else:
# if it's not a teen then we need separate words for the tens and ones
words.extend([numbers[tens], numbers[ones]])
# commonly times are expressed without the word 'minutes' when its a multiple of 5
# if it's not a multiple of 5 we normally add 'minutes', since saying '18 past 12' for example, sounds odd
if ones % 5 != 0:
words.append("minutes")
words.extend([context, numbers[hour]])
return words
```
#### File: talking-clock/test/test_api.py
```python
import pytest
from fixtures import client
from freezegun import freeze_time
api_path = "/api/humantime"
# Test scenarios with invalid times
@pytest.mark.parametrize(
"numeric_time",
[
"sometime",
"123456",
"Ten o' clock",
"2500",
],
)
def test_with_invalid_times(client, numeric_time):
result = client.get("{}?numeric_time={}".format(api_path, numeric_time))
body = result.json
assert result.status_code == 400
assert body["errorMessage"] is not None
# Test scenarios with different time formats
@pytest.mark.parametrize(
"numeric_time",
[
"1:00",
"01:00",
"13:00",
"13.00",
"1300"
],
)
def test_with_different_time_formats(client, numeric_time):
result = client.get("{}?numeric_time={}".format(api_path, numeric_time))
body = result.json
assert result.status_code == 200
assert body["humanTime"] == "One o'clock"
# Test scenarios with different time formats
@pytest.mark.parametrize(
"numeric_time, expected_result",
[
("00:00", "Twelve o'clock"),
("12:40", "Twenty to one"),
("13:00", "One o'clock"),
("13:11", "Eleven minutes past one"),
("13:15", "Quarter past one"),
("13:25", "Twenty five past one"),
("13:30", "Half past one"),
("13:32", "Twenty eight minutes to two"),
("13:35", "Twenty five to two"),
("13:45", "Quarter to two"),
("13:50", "Ten to two"),
("13:55", "Five to two"),
("13:57", "Three minutes to two"),
],
)
def test_with_different_times(client, numeric_time, expected_result):
result = client.get("{}?numeric_time={}".format(api_path, numeric_time))
body = result.json
assert result.status_code == 200
assert body["humanTime"] == expected_result
# Test when not providing a time
def test_with_no_time(client):
with freeze_time("2020-08-26 15:00:00.000000"):
result = client.get(api_path)
body = result.json
assert result.status_code == 200
assert body["humanTime"] == "Three o'clock"
``` |
{
"source": "jonnyniv/bitcoinpricing",
"score": 4
} |
#### File: bitcoinpricing/bitcoinpricing/api.py
```python
from decimal import Decimal
import requests
from typing import List
def get_api_price(url: str, decode: List[str], params: dict = {}) -> Decimal:
""" Calls a generic api and returns the bitcoin price
:param url: The API url to call
:param decode: A list of strings which will act as dictionary keys
:param params: A dictionary of keyword arguments passed to the request
:return: The bitcoin price in a decimal format
"""
response = requests.get(url=url, **params)
js = response.json()
for key in decode:
js = js.get(key)
return Decimal(js)
def get_currency_conversion(to: str, base: str) -> Decimal:
url = f'http://api.fixer.io/latest?base={base}'
response = requests.get(url)
return Decimal(response.json()['rates'][to])
def get_site_prices(config: List[dict]) -> dict:
""" Uses the loaded config file and gets the current bitcoin prices from each site
:param config: The pre-validated config file
:return: The dictionary of decimal price values, with the names as keys
"""
prices = {}
for site in config:
prices[site['name']] = get_api_price(url=site['url'], decode=site['decode'], params=site.get('params', {}))
return prices
if __name__ == '__main__':
print('API test:')
import yaml
with open('sites.yml', 'r') as f:
config_file = yaml.load(f)
print(get_site_prices(config_file))
```
#### File: bitcoinpricing/bitcoinpricing/config.py
```python
from typing import List
import yaml
from jsonschema import validate
from jsonschema.exceptions import ValidationError
schema = {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'url': {'type': 'string'},
'decode': {'type': 'array', 'items': {'type': 'string'}},
'params': {'type': 'object'}
},
'required': ['name', 'url', 'decode']
}
}
def load_site_config(filename: str, config_schema: dict) -> List[dict]:
with open(filename, 'r') as f:
config = yaml.load(f)
try:
validate(config, config_schema)
except ValidationError:
raise
else:
return config
if __name__ == '__main__':
with open('sites.yml', 'r') as f:
validate(yaml.load(f), schema)
``` |
{
"source": "JonnyNoog/reddit-bot",
"score": 3
} |
#### File: JonnyNoog/reddit-bot/core.py
```python
import datetime
import random
import sys
import math
import praw
import thoughts
try:
from secrets import SECRETS
except ImportError as ex:
print("secrets.py file can't be accessed\n")
print(ex)
sys.exit()
except SyntaxError as ex:
print("There is a syntax error in the secrets.py\n")
print(ex)
sys.exit()
# Set a descriptive user agent to avoid getting banned.
# Do not use the word 'bot' in your user agent.
def get_reddit():
return praw.Reddit(
client_id=SECRETS["client_id"],
client_secret=SECRETS["client_secret"],
username=SECRETS["username"],
password=SECRETS["password"],
user_agent='40kLoreModServitor'
)
def imperial_date_now():
current_date_time = datetime.datetime.now()
start_of_year = datetime.datetime(current_date_time.year, 1, 1)
end_of_year = datetime.datetime(current_date_time.year, 12, 31)
difference_to_date = current_date_time - start_of_year
seconds_since_start_of_year = difference_to_date.total_seconds()
total_seconds_in_year = (end_of_year - start_of_year).total_seconds()
year_fraction = math.floor(
(seconds_since_start_of_year / total_seconds_in_year) * 1000)
year = current_date_time.strftime("%y").zfill(3)
return "0 " + "%03d" % year_fraction + " " + year + ".M3"
def build_message(author, subject, message):
ref = "%016d" % random.randint(0, 9999999999999999)
body = (
"\\+ + + + + + + + + + + + + + TRANSMITTED: Terra\n\n"
"\\+ + + + + + + + + + + + + + RECEIVED: /u/" + author + "\n\n"
"\\+ + + + + + + + + + + + + + DATE: " + imperial_date_now() + "\n\n"
"\\+ + + + + + + + + + + + + + TELEPATHIC DUCT: Snoo\n\n"
"\\+ + + + + + + + + + + + + + REF: HLT/" + ref + "/LA\n\n"
"\\+ + + + + + + + + + + + + + AUTHOR: /u/40kLoreModServitor\n\n"
"\\+ + + + + + + + + + + + + + SUBJECT: " + subject + "\n\n"
"\\+ + + + + + + + + + + + + + THOUGHT FOR THE DAY: " \
+ thoughts.get_thought_for_the_day() + "\n\n"
"\\>>BEGIN TRANSMISSION<<\n\n"
"\\>>PROCESSING<<\n\n"
"\\>>DOWNLOAD COMPLETE<<\n\n"
+ message + "\n\n"
"\\>>END CODED MESSAGE<<\n\n"
"\\>>TRANSMISSION TERMINATED<<"
)
return body
```
#### File: JonnyNoog/reddit-bot/flair_bot.py
```python
import sys
import os
import time
import core
try:
from flairs import FLAIRS
except ImportError as ex:
print("flairs.py file can't be accessed\n")
print(ex)
sys.exit()
except SyntaxError as ex:
print("There is a syntax error in the flair list\n")
print(ex)
sys.exit()
class FlairBot:
# User blacklist
BLACKLIST = [] # For example: ['sampleuser', 'sampleUSER2']
# Sub-reddit to operate on.
TARGET_SUBREDDIT = "40kLore"
# Turn on output to log file in current directory - log.txt.
LOGGING = True
# Allow users to set their own flair text or not.
ALLOW_CUSTOM_FLAIR_TEXT = False
# PRAW object.
reddit = core.get_reddit()
# Class variable to hold the unread PMs.
pms = None
def __init__(self):
if self.LOGGING:
os.chdir(os.path.dirname(os.path.abspath(__file__)))
self.fetch_pms()
def fetch_pms(self):
# Get a listing of all unread PMs sent to the bot user account.
self.pms = self.reddit.inbox.unread(limit=None)
if self.pms is not None:
self.process_pms()
def process_pms(self):
for pm in self.pms:
flair_id = str(pm.subject)
author = str(pm.author)
flair_text = str(pm.body)
if author.lower() in (user.lower() for user in self.BLACKLIST):
continue
if flair_id in FLAIRS:
# Extra categories beyond the one corresponding to the
# spritesheet name aren't required for actual display of flair,
# and can potentially mess up flair display. The extra
# categories are only relevant for the JS filter code running on
# the flair selection page. So remove any extra categories.
flair_id_parts = flair_id.split(" ")
flair_position = flair_id_parts[0]
flair_sheet_name = flair_id_parts[1]
if not self.ALLOW_CUSTOM_FLAIR_TEXT or not flair_text:
flair_text = str(FLAIRS[flair_id])
try:
self.reddit.subreddit(self.TARGET_SUBREDDIT).flair.set(
author,
flair_text,
flair_position + " " + flair_sheet_name)
pm.reply(self.get_message(author, flair_id, "success"))
except:
pm.mark_read()
else:
pm.reply(self.get_message(author, flair_id, "failure"))
if self.LOGGING:
self.log(author, flair_id, flair_text)
pm.mark_read()
sys.exit()
def get_success_message(self, author, flair_id):
flair_name = FLAIRS[flair_id]
message = (
"Greetings loyal imperial citizen, designation `" + author + "`. "
"Your request for flair assignment has been considered by the Cult "
"Mechanicus and you have been found worthy "
"(praise the Emperor). Your chosen flair icon (designation `"
+ flair_name + "`) is now in effect.\n\n"
"Your loyalty to the Imperium continues to be monitored and "
"assessed. All transgressions will be reported to the Holy "
"Inquisition.\n\n"
"The Emperor protects."
)
return message
def get_failure_message(self, author, flair_id):
message = (
"Greetings imperial citizen, designation `" + author + "`. Your "
"request for flair assignment has been considered by the Cult "
"Mechanicus and rejected. Your requested flair icon (designation `"
+ flair_id + "`) is not found on the Mechanicum sanctioned list of "
"authorised flair icons. Your loyalty to the Imperium has now been "
"brought into question and this transgression has been reported to "
"the Holy Inquisition.\n\n"
"In future, ensure that you do not alter the automatically "
"generated flair request message in any way before sending it. "
"Should you require assistance or hope to beg forgiveness, you may "
"[send a transmission to the High Lords of Terra]"
"(https://www.reddit.com/message/compose?to=%2Fr%2F40kLore).\n\n"
"The Emperor protects."
)
return message
def get_message(self, author, flair_id, message_type):
if message_type == "success":
message = self.get_success_message(author, flair_id)
elif message_type == "failure":
message = self.get_failure_message(author, flair_id)
else:
raise ValueError("Unknown message_type")
subject = "Flair assignment " + message_type
body = core.build_message(author, subject, message)
return body
def log(self, author, flair_id, flair_text):
with open('flair_bot_log.txt', 'a') as logfile:
time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
log_text = "Author: " + author + " - Flair ID: '" + flair_id + \
"' Flair text: '" + flair_text + "' @ " + time_now + "\n"
logfile.write(log_text)
logfile.close()
FlairBot()
``` |
{
"source": "jonnyns/sosi_files_importer",
"score": 2
} |
#### File: scripts/sosi_files_importer/__init__.py
```python
bl_info = {
"name": "SosiImporter",
"author": "<NAME>",
"version": (1, 2, 1),
"blender": (2, 93, 0),
"location": "File > Import > SosiImporter",
"description": "Import objects from SOSI files (.sos)",
"warning": "",
"wiki_url": "",
"category": "Import-Export",
}
import os
# Determine if the code is running from within Blender
env_blender = True
try:
import bpy
env_blender = os.path.basename(bpy.app.binary_path or '').lower().startswith('blender')
except ModuleNotFoundError:
env_blender = False
print('INFO: Blender environment:', env_blender)
# To support reload properly, try to access a package var,
# if it's there, reload everything
#if "bpy" in locals():
# import imp
# imp.reload(blender_temporary)
#else:
# from . import blender_temporary as bldtmp
from . import sosi_importer as sosimp
#from . import blender_temporary as bldtmp
# -----------------------------------------------------------------------------
def main(context):
sosimp.do_imports()
# -----------------------------------------------------------------------------
class ImportSOSIData(bpy.types.Operator):
"""Tooltip"""
bl_idname = "import_files.sosi_data"
bl_label = "Import SOSI Data"
def execute(self, context):
main(context)
return {'FINISHED'}
# -----------------------------------------------------------------------------
def menu_func_import(self, context):
self.layout.operator(ImportSOSIData.bl_idname)
# -----------------------------------------------------------------------------
def register():
bpy.utils.register_class(ImportSOSIData)
bpy.utils.register_class(sosimp.SosiImporterPreferences)
bpy.types.TOPBAR_MT_file_import.append(menu_func_import)
# -----------------------------------------------------------------------------
def unregister():
bpy.utils.unregister_class(sosimp.SosiPreferences)
bpy.utils.unregister_class(ImportSOSIData)
bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)
# -----------------------------------------------------------------------------
if __name__ == "__main__":
register()
# test call
#bpy.ops.import_files.sosi_data()
``` |
{
"source": "jonnyoboy2110/JonnyOlveraSite",
"score": 3
} |
#### File: jonnyoboy2110/JonnyOlveraSite/test.py
```python
x=5
# if x < 3:
# print("True")
# elif x < 5:
# print("Bob")
# elif x < 7:
# print("Carl", end="\t")
# if x == 6:
# print("Jr")
# else:
# print("Alice")
# y = "7"
# print(str(x)+"\t"+y)
# print(x+int(y))
a = [1,2]
a.append(3)
a += [4]
a = [5] + a
# for i in range(len(a)):
# print(i, end=" ")
# print(a[i])
# print(list(range(0,len(a),2)))
# i = 0
# while i<len(a):
# print(a[i])
# i+=1
# for el in a:
# print(el)
# f = open("Dockerfile","r")
# for line in f:
# if "code" in line or "WORKDIR" in line:
# stripped_line = line.rstrip()
# print(stripped_line)
# a += ["hi"]
# a += [3.0]
# a += [True]
# print(a)
# def x():
# print("bob")
d = {True:x}
# d["key"] = "value"
# d["key"] += "value2"
# d["key"] = [1,2,3,4]
# d["key2"] = {"key3":"value"}
# d[3<4]()
t = (1,2,3)
# a = [4,5,6]
d[t]="bob"
# d[a]="alice"
# print(d)
def fun(a,b="bob",c="alice"):
print(a)
print(b)
print(c)
# fun("hi", c="carl")
# fun(b="a",c="b",a="c")
# def create_adder(x):
# def adder(y):
# return x + y
# return adder
# add_10 = create_adder(10)
# print(add_10(3))
class Human:
species = "H. sapiens"
def __init__(self, name):
self.name = name
self.age = 0
def about(self):
print(self.name + " is "
+ str(self.age) + " years old"
+ " and is of species " + self.species)
class Student(Human):
def __init__(self, name, year):
self.year = year
super().__init__(name)
def about(self):
print(self.name + " is "
+ str(self.age) + " years old"
+ " and a " + self.year)
i = Human(name="Bob")
i.about()
s = Student(name="alice",year="Sophomore")
s.about()
``` |
{
"source": "jonnypetraglia/Esyncteric",
"score": 2
} |
#### File: jonnypetraglia/Esyncteric/main.py
```python
import json, os, subprocess, shutil, multiprocessing, argparse
import threading, signal, sys
APP_NAME = "Esyncteric"
VERSION = "0.0.1"
AUTHOR = "Qweex LLC"
AUTHOR_URL = "qweex.com"
class DirListing:
def __str__(self):
return json.dumps(self.fileList, sort_keys=True, indent=4, separators=(',', ': '))
def __init__(self, dirPath):
if not dirPath:
self.fileList = {}
return
if isinstance(dirPath, dict):
self.dirPath = None
self.fileList = self.fromJSON(dirPath)
else:
self.dirPath = dirPath
self.fileList = {}
self.walkDir(self.dirPath, self.fileList)
def fromJSON(self, json):
result = {}
if "." in json:
result["."] = {}
for f in json["."]:
if isinstance(json["."], list):
splitext = os.path.splitext(f)
result["."][splitext[0]] = splitext[1]
elif isinstance(json["."], dict):
result["."][f] = json["."][f]
for key, value in json.items():
if key!=".":
result[key] = self.fromJSON(value)
return result
def walkDir(self, dir, files):
if not os.path.exists(dir):
return
for f in os.listdir(dir):
if os.path.isfile(os.path.join(dir, f)):
files.setdefault('.',{})
splitext = os.path.splitext(f)
files["."][splitext[0]] = splitext[1]
else:
files[f] = {}
self.walkDir(os.path.join(dir, f), files[f])
def minus(self, other):
# TODO: really need to adjust his to account for filetypes.to
def helper(myList, otherList):
result = {}
for key in myList:
if key == ".":
for basename in myList[key]:
if key not in otherList or basename not in otherList[key]:
result.setdefault(key,{})[basename] = myList[key][basename]
elif key in otherList:
if isinstance(myList[key], dict):
result[key] = helper(myList[key], otherList[key])
if result[key] == {}:
del result[key]
else:
result[key] = myList[key]
return result
return DirListing(helper(self.fileList, other.fileList))
def altered(self, other):
def helper(myList, otherList):
result = {}
for key in myList:
if key == ".":
for basename in myList[key]:
if key in otherList and basename in otherList[key] and myList[key][basename] != otherList[key][basename]:
result.setdefault(key,{})[basename] = myList[key][basename]
elif key in otherList:
if isinstance(myList[key], dict):
result[key] = helper(myList[key], otherList[key])
if result[key] == {}:
del result[key]
elif myList[key] != otherList[key]:
result[key] = myList[key]
return result
return DirListing(helper(self.fileList, other.fileList))
def intersection(self, other):
def helper(myList, otherList):
result = {}
for key in myList:
if key == ".":
for basename in myList[key]:
if key in otherList and basename in otherList[key] and myList[key][basename] == otherList[key][basename]:
result.setdefault(key,{})[basename] = myList[key][basename]
elif key in otherList:
if isinstance(myList[key], dict):
result[key] = helper(myList[key], otherList[key])
if result[key] == {}:
del result[key]
elif myList[key] == otherList[key]:
result[key] = myList[key]
return result
return DirListing(helper(self.fileList, other.fileList))
def toConfig(self):
def helper(myList):
result = {}
for key in myList:
if key == ".":
for basename, ext in myList[key].items():
result.setdefault(key,[]).append(basename + ext)
else:
result[key] = helper(myList[key])
if result[key] == {}:
del result[key]
return result
return helper(self.fileList)
def addFiles(self, sourcePath, destPath, filetypes, callback, err_callback, dry_run=False):
def compileList(fileList, path=""):
res = []
if "." in fileList:
srcDir = os.path.join(sourcePath, path)
destDir = os.path.join(destPath, path)
if not os.path.isdir(destDir) and not dry_run:
os.makedirs(destDir)
for name, ext in fileList["."].items():
if ext.lower() not in filetypes:
if dry_run:
print("COPY:", os.path.join(path, name + ext), "->", os.path.join(path, name + ext))
else:
res.append({
"label": os.path.join(path, name + ext),
"cmd": shutil.copy2,
"args": [os.path.join(srcDir, name + ext), os.path.join(destDir, name + ext)]
})
continue
filetype = filetypes[ext.lower()]
cmd = list(filetype['cmd'])
srcFile = os.path.join(srcDir, name + ext)
destFile = os.path.join(destDir, name + filetype['to'])
if "{0}" in cmd:
cmd[cmd.index("{0}")] = srcFile
if "{1}" in cmd:
cmd[cmd.index("{1}")] = destFile
elif "{}" in cmd:
cmd[cmd.index("{}")] = srcFile
if dry_run:
print("CALL:", cmd)
else:
res.append({
"label": os.path.join(path, name+ext),
"cmd": cmd,
"args": [srcFile, destFile]
})
for name in fileList:
if name != ".":
res.extend( compileList(fileList[name], os.path.join(path, name)) )
return res
return compileList(self.fileList)
def removeFiles(self, destPath, callback, err_callback, dry_run=False):
def rm(target):
os.remove(target)
dirpath = os.path.dirname(target)
if dirpath!= "" and not os.listdir(dirpath):
if dry_run:
print("RMDIR:", dirpath)
else:
os.rmdir(dirpath)
def helper(fileList, path=""):
res = []
destDir = os.path.join(destPath, path)
if "." in fileList:
for name, ext in fileList["."].items():
if dry_run:
print("REMOVE:", os.path.join(path, name + ext))
else:
res.append({
"label": os.path.join(path, name + ext),
"cmd": rm,
"args": [os.path.join(destDir, name + ext)]
})
for name in fileList:
if name != ".":
res.extend( helper(fileList[name], os.path.join(path, name)) )
return res
return helper(self.fileList)
class ConsistentProcess:
def __init__(self, cmd, args, label):
self.cmd = cmd
self.args = args
self.label = label
if self.callable():
self.proc = multiprocessing.Process(target=cmd, args=args)
else:
self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.killed = False
def callable(self):
return callable(self.cmd)
def kill(self):
self.killed = True
if self.callable():
self.proc.terminate()
else:
self.proc.send_signal(signal.SIGINT)
def stdout(self):
if self.callable():
return ""
else:
return self.proc.stdout.read()
def stderr(self):
if self.callable():
return ""
else:
return self.proc.stderr.read()
def is_alive(self):
if self.callable():
return self.proc.is_alive()
else:
return self.proc.poll()==None
def returncode(self):
if self.callable():
return self.proc.exitcode
else:
return self.proc.returncode
def wait(self):
if self.callable():
self.proc.start()
self.proc.join()
else:
self.proc.wait()
class StupidSimpleProcessPool:
def __init__(self, commands, cb, ercb):
self.commands = commands
self.tasks = []
self.active = []
self.success_callback = cb
self.error_callback = ercb
self.stop_on_error = True
while self.another():
pass
self.running = len(self.active) > 0
self.oldSignalHandler = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, self.sigint_handler)
def kill_all(self):
for p in self.tasks:
if p.is_alive():
p.kill()
def sigint_handler(self, signal, frame):
self.kill_all()
if self.oldSignalHandler:
return self.oldSignalHandler(signal, frame)
def wait(self):
while self.running:
pass
def another(self):
if len(self.commands)==0 or len(self.active) >= args.concurrent:
return False
cmd = self.commands.pop()
def runInThread():
proc = ConsistentProcess(label=cmd['label'], cmd=cmd['cmd'], args=cmd['args'])
self.tasks.append(proc)
proc.wait()
self.active.remove(thread)
if proc.returncode()==0:
if self.success_callback:
self.success_callback(proc)
else:
if self.error_callback:
self.error_callback(proc)
if self.stop_on_error:
self.kill_all()
self.running = False
return
if not self.another() and len(self.active)==0:
self.running = False;
thread = threading.Thread(target=runInThread)
self.active.append(thread)
thread.start()
return True
class Data(object):
def __init__(self, dataFile):
self._loaded = False
self.jsonFile = dataFile
self.syncConfig = dict(jsonFile=None, files=None)
if self.jsonFile:
self.reload()
else:
self.original = None
def resetOriginals(self):
self.original = {
'sourceDir': self.getField('sourceDir'),
'destDir': self.getField('destDir'),
'files': self.getField('files'),
'filetypes': self.getField('filetypes')
}
return self
def reload(self):
with open(self.jsonFile) if isinstance(self.jsonFile, str) else self.jsonFile as jsonContents:
self.syncConfig = json.load(jsonContents)
if not isinstance(self.jsonFile, str):
self.jsonFile = self.jsonFile.name
self.resetOriginals()
self.filetypes = self.syncConfig['filetypes'] if 'filetypes' in self.syncConfig else {}
return self.rescan()
def rescan(self):
self.config = DirListing(self.syncConfig['files'] if 'files' in self.syncConfig else dict())
self.source = DirListing(self.syncConfig['sourceDir'])
self.dest = DirListing(self.syncConfig['destDir'])
self.added = self.source.minus(self.dest)
self.removed = self.dest.minus(self.source)
self.missing = self.config.minus(self.source)
#TODO: better handling of missing files rather than just ignoring them
notMissing = self.config.minus(self.missing)
self.toTransfer = notMissing.intersection(self.added)
self.toRemove = self.dest.minus(self.config)
self._loaded = True
return self
def performSync(self, cb=None, ecb=None, dry=False):
cmds = self.toTransfer.addFiles(self.source.dirPath, self.dest.dirPath, self.filetypes, cb, ecb, dry)
cmds.extend( self.toRemove.removeFiles(self.dest.dirPath, cb, ecb, dry) )
return StupidSimpleProcessPool(cmds, cb, ecb)
def setField(self, field, value):
if field not in ['files', 'sourceDir', 'destDir', 'filetypes']:
raise ValueError("Field error:" + field)
self.syncConfig[field] = value
if field=="files":
self.config = DirListing(self.syncConfig['files'])
def getField(self, field):
if field in self.syncConfig:
return self.syncConfig[field]
return {}
def toConfig(self):
output = {
"sourceDir": self.syncConfig['sourceDir'],
"destDir": self.syncConfig['destDir'],
"files": self.config.toConfig()
}
if self.filetypes:
output['filetypes'] = self.filetypes
return json.dumps(output, sort_keys=False, indent=4, separators=(',', ': '))
def hasChanged(self):
if not self.original:
return False
for key in self.original:
if key == "gui" or key == "files":
continue
if key not in self.syncConfig or self.original[key] != self.syncConfig[key]:
return True
return False
def printj(j):
print(json.dumps(j, sort_keys=True, indent=4, separators=(',', ': ')))
def check_negative(value):
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError("%s is an invalid int value" % value)
return ivalue
################################################
parser = argparse.ArgumentParser(description='One-way file-based syncronization with per-file selection & custom commands')
parser.add_argument('jsonfile', type=argparse.FileType('r'), nargs="?",
help='path to a JSON file containing a sync configuration')
parser.add_argument('--print',
choices=['all', 'config', 'source', 'dest', 'added', 'removed', 'missing', 'toTransfer', 'toRemove'],
help='prints JSON data but does not perform sync')
parser.add_argument('-d', '--dry', action='store_true',
help='simulate the sync but do not perform')
parser.add_argument('-g', '--gui', action='store_true',
help='show a GUI instead of performing the sync')
parser.add_argument('-c', '--concurrent', metavar="N", type=check_negative, default=multiprocessing.cpu_count(),
help='maximum number of concurrent transcoding processes; defaults to number of cores')
args = parser.parse_args()
if args.gui is False and args.jsonfile is None:
parser.error("the following arguments are required: jsonfile")
def handle_siginit(signal, frame):
print("SIGINT received, exiting")
sys.exit(1)
signal.signal(signal.SIGINT, handle_siginit)
if args.gui:
import gui
gui.GuiApp(
APP_NAME,
AUTHOR,
AUTHOR_URL,
VERSION,
Data(args.jsonfile))
else:
data = Data(args.jsonfile)
if args.print:
printables = {
'config': data.config,
'source': data.source,
'dest': data.dest,
'added': data.added,
'removed': data.removed,
'missing': data.missing,
'toTransfer': data.toTransfer,
'toRemove': data.toRemove
}
if args.print=="all":
for p in printables:
print(printables[p])
else:
print(printables[args.print])
exit(0)
else:
def cb(x):
sys.stdout.write(".")
#print(x.stdout())
def err(x):
if x.killed:
# Just canceled
#print("canceled", x.cmd)
pass
else:
# An actual error occurred
print(x.stderr())
pool = data.performSync(cb, err, args.dry)
pool.wait()
print("Done")
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.