metadata
dict | text
stringlengths 60
3.49M
|
---|---|
{
"source": "Joe676/brainfuck-interpreter",
"score": 3
} |
#### File: Joe676/brainfuck-interpreter/brainfuck.py
```python
class BFArray:
def __init__(self, n):
self.arr = [0 for _ in range(n)]
self.pointer = 0
self.cell_width = 256
def right(self):
self.pointer += 1
self.pointer %= len(self.arr)
def left(self):
self.pointer -= 1
self.pointer %= len(self.arr)
def inc(self):
self.arr[self.pointer] += 1
self.arr[self.pointer] %= self.cell_width
def dec(self):
self.arr[self.pointer] -= 1
self.arr[self.pointer] %= self.cell_width
def get(self):
return self.arr[self.pointer]
def put(self, x):
self.arr[self.pointer] = x
class BFInterpreter:
def __init__(self, n):
self.arr = BFArray(n)
self.lines = []
self.program_counter = (0, 0)
self.loops = []
self.open_brackets = 0
self.looped = False
self.input_buffer = []
self.op_codes = {
'+':self.arr.inc,
'-':self.arr.dec,
'<':self.arr.left,
'>':self.arr.right,
'.':self.output,
',':self.input,
'[':self.start_loop,
']':self.loop,
'#':self.debug
}
def debug(self):
print('Program counter:', self.program_counter)
print('Array pointer:', self.arr.pointer)
print('Value at {}:'.format(self.arr.pointer), self.arr.get())
print('Top of the stack:', self.loops[-1] if len(self.loops)>0 else '-')
def open_file(self, file_name):
with open(file_name, 'r') as file:
self.lines.extend(file.readlines())
def read_line(self):
l = input("BF > ")
self.lines.append(l)
if l[0] == '0':
return False
else:
return True
def step(self):
#extract program counter
i = self.program_counter[0]
j = self.program_counter[1]
#if looping forward
if self.open_brackets > 0:
#'[' goes deeper
if self.lines[i][j] == '[':
self.open_brackets += 1
#']' goes up
elif self.lines[i][j] == ']':
self.open_brackets -= 1
if self.open_brackets == 0:
if self.lines[i][j] in self.op_codes.keys():
self.op_codes[self.lines[i][j]]()
if not self.looped:
j += 1
if j == len(self.lines[i]):
j = 0
i += 1
self.program_counter = (i, j)
else:
self.looped = False
return (self.program_counter[0] < len(self.lines))
def output(self):
print(chr(self.arr.get()), end = '')
def input(self):
if len(self.input_buffer) == 0:
self.input_buffer = list(str(input()))
c = self.input_buffer.pop(0)
self.arr.put(ord(c))
def start_loop(self):
self.loops.append(self.program_counter)
if self.arr.get() == 0:
self.open_brackets = 1
def loop(self):
pc = self.loops.pop()
if self.arr.get() != 0:
self.program_counter = pc
self.looped = True
def main():
bf = BFInterpreter(1000)
menu = str(input("Choose mode [live|file]: ")).casefold()
while menu != 'live' and menu != 'file':
menu = str(input("Choose mode [live|file]: "))
if menu == 'file':
file_name = input('File name: ')
bf.open_file(file_name)
while(bf.step()):
pass
else:
print("--- Live mode ---")
print("Type a line of code, enter to run, # for debug, 0 to end")
while True:
print()
if not bf.read_line():
return
while bf.step():
pass
if __name__ == '__main__':
main()
``` |
{
"source": "joe733/Calendario",
"score": 3
} |
#### File: Calendario/bots/config.py
```python
import tweepy
import logging
import os
logger = logging.getLogger()
def create_api():
consumer_key = os.getenv("CONSUMER_KEY")
consumer_secret = os.getenv("CONSUMER_SECRET")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
try:
api.verify_credentials()
except Exception as e:
logger.error("Error creating API", exc_info=True)
raise e
logger.info("API created")
return api
``` |
{
"source": "joe733/client",
"score": 2
} |
#### File: client/tests/test_meta.py
```python
import os
import pytest
import platform
import sys
import subprocess
import threading
import wandb
from six.moves import queue
from wandb.sdk.internal.meta import Meta
from wandb.sdk.internal.sender import SendManager
from wandb.sdk.interface.interface_queue import InterfaceQueue
@pytest.fixture()
def record_q():
return queue.Queue()
@pytest.fixture()
def result_q():
return queue.Queue()
@pytest.fixture()
def interface(record_q):
return InterfaceQueue(record_q=record_q)
@pytest.fixture()
def meta(test_settings, interface):
return Meta(settings=test_settings, interface=interface)
@pytest.fixture()
def sm(
runner,
git_repo,
record_q,
result_q,
test_settings,
meta,
mock_server,
mocked_run,
interface,
):
test_settings.save_code = True
sm = SendManager(
settings=test_settings,
record_q=record_q,
result_q=result_q,
interface=interface,
)
meta._interface.publish_run(mocked_run)
sm.send(record_q.get())
yield sm
def test_meta_probe(mock_server, meta, sm, record_q, log_debug, monkeypatch):
orig_exists = os.path.exists
orig_call = subprocess.call
monkeypatch.setattr(
os.path,
"exists",
lambda path: True if "conda-meta" in path else orig_exists(path),
)
monkeypatch.setattr(
subprocess,
"call",
lambda cmd, **kwargs: kwargs["stdout"].write("CONDA YAML")
if "conda" in cmd
else orig_call(cmd, **kwargs),
)
with open("README", "w") as f:
f.write("Testing")
meta.probe()
meta.write()
sm.send(record_q.get())
sm.finish()
print(mock_server.ctx)
assert len(mock_server.ctx["storage?file=wandb-metadata.json"]) == 1
assert len(mock_server.ctx["storage?file=requirements.txt"]) == 1
# py27 doesn't like my patching for conda-environment, just skipping
if sys.version_info > (3, 0):
assert len(mock_server.ctx["storage?file=conda-environment.yaml"]) == 1
assert len(mock_server.ctx["storage?file=diff.patch"]) == 1
def test_executable_outside_cwd(mock_server, meta):
meta._settings.update(program="asdf.py")
meta.probe()
assert meta.data.get("codePath") is None
assert meta.data["program"] == "asdf.py"
def test_jupyter_name(meta, mocked_ipython):
meta._settings.update(notebook_name="test_nb")
meta.probe()
assert meta.data["program"] == "test_nb"
def test_jupyter_path(meta, mocked_ipython):
# not actually how jupyter setup works but just to test the meta paths
meta._settings.update(_jupyter_path="dummy/path")
meta.probe()
assert meta.data["program"] == "dummy/path"
assert meta.data.get("root") is not None
# TODO: test actual code saving
def test_commmit_hash_sent_correctly(test_settings, git_repo):
# disable_git is False is by default
# so run object should have git info
run = wandb.init(settings=test_settings)
assert run._last_commit is not None
assert run._last_commit == git_repo.last_commit
assert run._remote_url is None
run.finish()
def test_commit_hash_not_sent_when_disable(test_settings, git_repo, disable_git_save):
run = wandb.init(settings=test_settings)
assert git_repo.last_commit
assert run._last_commit is None
run.finish()
```
#### File: sklearn/plot/classifier.py
```python
from warnings import simplefilter
import numpy as np
from sklearn import naive_bayes
import wandb
import wandb.plots
from wandb.sklearn import utils
from wandb.sklearn import calculate
from . import shared
# ignore all future warnings
simplefilter(action="ignore", category=FutureWarning)
def classifier(
model,
X_train,
X_test,
y_train,
y_test,
y_pred,
y_probas,
labels,
is_binary=False,
model_name="Classifier",
feature_names=None,
log_learning_curve=False,
):
"""Generates all sklearn classifier plots supported by W&B.
The following plots are generated:
feature importances, confusion matrix, summary metrics,
class propotions, calibration curve, roc curve, precision-recall curve.
Should only be called with a fitted classifer (otherwise an error is thrown).
Arguments:
model: (classifier) Takes in a fitted classifier.
X_train: (arr) Training set features.
y_train: (arr) Training set labels.
X_test: (arr) Test set features.
y_test: (arr) Test set labels.
y_pred: (arr) Test set predictions by the model passed.
y_probas: (arr) Test set predicted probabilities by the model passed.
labels: (list) Named labels for target varible (y). Makes plots easier to
read by replacing target values with corresponding index.
For example if `labels=['dog', 'cat', 'owl']` all 0s are
replaced by dog, 1s by cat.
is_binary: (bool) Is the model passed a binary classifier? Defaults to False
model_name: (str) Model name. Defaults to 'Classifier'
feature_names: (list) Names for features. Makes plots easier to read by
replacing feature indexes with corresponding names.
log_learning_curve: (bool) Whether or not to log the learning curve.
Defaults to False.
Returns:
None: To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
```python
wandb.sklearn.plot_classifier(model, X_train, X_test, y_train, y_test, y_pred, y_probas,
['cat', 'dog'], False, RandomForest',
['barks', 'drools, 'plays_fetch', 'breed'])
```
"""
wandb.termlog("\nPlotting %s." % model_name)
if not isinstance(model, naive_bayes.MultinomialNB):
feature_importances(model, feature_names)
wandb.termlog("Logged feature importances.")
if log_learning_curve:
shared.learning_curve(model, X_train, y_train)
wandb.termlog("Logged learning curve.")
confusion_matrix(y_test, y_pred, labels)
wandb.termlog("Logged confusion matrix.")
shared.summary_metrics(model, X=X_train, y=y_train, X_test=X_test, y_test=y_test)
wandb.termlog("Logged summary metrics.")
class_proportions(y_train, y_test, labels)
wandb.termlog("Logged class proportions.")
if not isinstance(model, naive_bayes.MultinomialNB):
calibration_curve(model, X_train, y_train, model_name)
wandb.termlog("Logged calibration curve.")
roc(y_test, y_probas, labels)
wandb.termlog("Logged roc curve.")
precision_recall(y_test, y_probas, labels)
wandb.termlog("Logged precision-recall curve.")
def roc(
y_true=None,
y_probas=None,
labels=None,
plot_micro=True,
plot_macro=True,
classes_to_plot=None,
):
"""Logs the receiver-operating characteristic curve.
Arguments:
y_true: (arr) Test set labels.
y_probas: (arr) Test set predicted probabilities.
labels: (list) Named labels for target variable (y). Makes plots easier to
read by replacing target values with corresponding index.
For example if `labels=['dog', 'cat', 'owl']` all 0s are
replaced by dog, 1s by cat.
Returns:
None: To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
```python
wandb.sklearn.plot_roc(y_true, y_probas, labels)
```
"""
roc_chart = wandb.plots.roc.roc(
y_true, y_probas, labels, plot_micro, plot_macro, classes_to_plot
)
wandb.log({"roc": roc_chart})
def confusion_matrix(
y_true=None,
y_pred=None,
labels=None,
true_labels=None,
pred_labels=None,
normalize=False,
):
"""Logs a confusion matrix to W&B.
Confusion matrices depict the pattern of misclassifications by a model.
Arguments:
y_true: (arr) Test set labels.
y_probas: (arr) Test set predicted probabilities.
labels: (list) Named labels for target variable (y). Makes plots easier to
read by replacing target values with corresponding index.
For example if `labels=['dog', 'cat', 'owl']` all 0s are
replaced by dog, 1s by cat.
Returns:
None: To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
```python
wandb.sklearn.plot_confusion_matrix(y_true, y_probas, labels)
```
"""
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
not_missing = utils.test_missing(y_true=y_true, y_pred=y_pred)
correct_types = utils.test_types(y_true=y_true, y_pred=y_pred)
if not_missing and correct_types:
confusion_matrix_chart = calculate.confusion_matrix(
y_true, y_pred, labels, true_labels, pred_labels, normalize,
)
wandb.log({"confusion_matrix": confusion_matrix_chart})
def precision_recall(
y_true=None, y_probas=None, labels=None, plot_micro=True, classes_to_plot=None
):
"""Logs a precision-recall curve to W&B.
Precision-recall curves depict the tradeoff between positive predictive value (precision)
and true positive rate (recall) as the threshold of a classifier is shifted.
Arguments:
y_true: (arr) Test set labels.
y_probas: (arr) Test set predicted probabilities.
labels: (list) Named labels for target variable (y). Makes plots easier to
read by replacing target values with corresponding index.
For example if `labels=['dog', 'cat', 'owl']` all 0s are
replaced by dog, 1s by cat.
Returns:
None: To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
```python
wandb.sklearn.plot_precision_recall(y_true, y_probas, labels)
```
"""
precision_recall_chart = wandb.plots.precision_recall(
y_true, y_probas, labels, plot_micro, classes_to_plot
)
wandb.log({"precision_recall": precision_recall_chart})
def feature_importances(
model=None, feature_names=None, title="Feature Importance", max_num_features=50
):
"""Logs a plot depicting the relative importance of each feature for a classifier's decisions.
Should only be called with a fitted classifer (otherwise an error is thrown).
Only works with classifiers that have a feature_importances_ attribute, like trees.
Arguments:
model: (clf) Takes in a fitted classifier.
feature_names: (list) Names for features. Makes plots easier to read by
replacing feature indexes with corresponding names.
Returns:
None: To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
```python
wandb.sklearn.plot_feature_importances(model, ['width', 'height, 'length'])
```
"""
not_missing = utils.test_missing(model=model)
correct_types = utils.test_types(model=model)
model_fitted = utils.test_fitted(model)
if not_missing and correct_types and model_fitted:
feature_importance_chart = calculate.feature_importances(model, feature_names)
wandb.log({"feature_importances": feature_importance_chart})
def class_proportions(y_train=None, y_test=None, labels=None):
"""Plots the distribution of target classses in training and test sets.
Useful for detecting imbalanced classes.
Arguments:
y_train: (arr) Training set labels.
y_test: (arr) Test set labels.
labels: (list) Named labels for target variable (y). Makes plots easier to
read by replacing target values with corresponding index.
For example if `labels=['dog', 'cat', 'owl']` all 0s are
replaced by dog, 1s by cat.
Returns:
None: To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
```python
wandb.sklearn.plot_class_proportions(y_train, y_test, ['dog', 'cat', 'owl'])
```
"""
not_missing = utils.test_missing(y_train=y_train, y_test=y_test)
correct_types = utils.test_types(y_train=y_train, y_test=y_test)
if not_missing and correct_types:
y_train, y_test = np.array(y_train), np.array(y_test)
class_proportions_chart = calculate.class_proportions(y_train, y_test, labels)
wandb.log({"class_proportions": class_proportions_chart})
def calibration_curve(clf=None, X=None, y=None, clf_name="Classifier"):
"""Logs a plot depicting how well-calibrated the predicted probabilities of a classifier are.
Also suggests how to calibrate an uncalibrated classifier. Compares estimated predicted
probabilities by a baseline logistic regression model, the model passed as
an argument, and by both its isotonic calibration and sigmoid calibrations.
The closer the calibration curves are to a diagonal the better.
A sine wave like curve represents an overfitted classifier, while a cosine
wave like curve represents an underfitted classifier.
By training isotonic and sigmoid calibrations of the model and comparing
their curves we can figure out whether the model is over or underfitting and
if so which calibration (sigmoid or isotonic) might help fix this.
For more details, see https://scikit-learn.org/stable/auto_examples/calibration/plot_calibration_curve.html.
Should only be called with a fitted classifer (otherwise an error is thrown).
Please note this function fits variations of the model on the training set when called.
Arguments:
clf: (clf) Takes in a fitted classifier.
X: (arr) Training set features.
y: (arr) Training set labels.
model_name: (str) Model name. Defaults to 'Classifier'
Returns:
None: To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
```python
wandb.sklearn.plot_calibration_curve(clf, X, y, 'RandomForestClassifier')
```
"""
not_missing = utils.test_missing(clf=clf, X=X, y=y)
correct_types = utils.test_types(clf=clf, X=X, y=y)
is_fitted = utils.test_fitted(clf)
if not_missing and correct_types and is_fitted:
y = np.asarray(y)
if not ((y == 0) | (y == 1)).all():
raise ValueError(
"This function only supports binary classification at the moment and therefore expects labels to be binary."
)
calibration_curve_chart = calculate.calibration_curves(clf, X, y, clf_name)
wandb.log({"calibration_curve": calibration_curve_chart})
def decision_boundaries(binary_clf=None, X=None, y=None):
"""Visualizes decision boundaries of a binary classifier.
Works by sampling from the feature space where the classifier's uncertainty
if greater than > 0.5 and projecting these point to 2D space.
Useful for measuring model (decision boundary) complexity, visualizing
regions where the model falters, and to determine whether any over or
underfitting occured.
Should only be called with a fitted **binary** classifer (otherwise an error is
thrown). Please note this function fits variations of the model on the
training set when called.
Arguments:
model: (clf) Takes in a fitted binary classifier.
X_train: (arr) Training set features.
y_train: (arr) Training set labels.
Returns:
None: To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
```python
wandb.sklearn.plot_decision_boundaries(binary_classifier, X, y)
```
"""
if utils.test_missing(binary_clf=binary_clf, X=X, y=y) and utils.test_types(
binary_clf=binary_clf, X=X, y=y
):
y = np.asarray(y)
# plot high-dimensional decision boundary
db = DBPlot(binary_clf)
db = None
db.fit(X, y)
(
decision_boundary_x,
decision_boundary_y,
decision_boundary_color,
train_x,
train_y,
train_color,
test_x,
test_y,
test_color,
) = db.plot()
wandb.log(
{
"decision_boundaries": calculate.decision_boundaries(
decision_boundary_x,
decision_boundary_y,
decision_boundary_color,
train_x,
train_y,
train_color,
test_x,
test_y,
test_color,
)
}
)
``` |
{
"source": "joe733/pip-upgrader",
"score": 3
} |
#### File: pip-upgrader/pip_upgrader/packages_upgrader.py
```python
import os
import subprocess
from subprocess import CalledProcessError
import re
from colorclass import Color
class PackagesUpgrader(object):
selected_packages = None
requirements_files = None
upgraded_packages = None
dry_run = False
check_gte = False
def __init__(self, selected_packages, requirements_files, options):
self.selected_packages = selected_packages
self.requirements_files = requirements_files
self.upgraded_packages = []
self.dry_run = options['--dry-run']
self.check_gte = options['--check-greater-equal']
skip_pkg_install = options.get('--skip-package-installation', False)
if 'PIP_UPGRADER_SKIP_PACKAGE_INSTALLATION' in os.environ:
skip_pkg_install = True # pragma: nocover
self.skip_package_installation = skip_pkg_install
def do_upgrade(self):
for package in self.selected_packages:
self._update_package(package)
return self.upgraded_packages
def _update_package(self, package):
""" Update (install) the package in current environment,
and if success, also replace version in file """
try:
if not self.dry_run and not self.skip_package_installation: # pragma: nocover
pinned = '{}=={}'.format(package['name'],
package['latest_version'])
subprocess.check_call(['pip', 'install', pinned])
else:
# dry run has priority in messages
if self.dry_run:
lbl = 'Dry Run'
else:
lbl = "Skip Install" # pragma: nocover
print('[{}]: skipping package installation:'.format(lbl),
package['name'])
# update only if installation success
self._update_requirements_package(package)
except CalledProcessError: # pragma: nocover
print(Color('{{autored}}Failed to install package "{}"{{/autored}}'.format(package['name'])))
def _update_requirements_package(self, package):
for filename in set(self.requirements_files):
lines = []
# read current lines
with open(filename, 'r') as frh:
for line in frh:
lines.append(line)
try:
# write updates lines
with open(filename, 'w') as fwh:
for line in lines:
line = self._maybe_update_line_package(line, package)
fwh.write(line)
except Exception as e: # pragma: nocover
# at exception, restore old file
with open(filename, 'w') as fwh:
for line in lines:
fwh.write(line)
raise e
def _maybe_update_line_package(self, line, package):
original_line = line
pin_type = r'[>=]=' if self.check_gte else '=='
pattern = r'\b({package}(?:\[\w*\])?{pin_type})[a-zA-Z0-9\.]+\b'.format(
package=re.escape(package['name']),
pin_type=pin_type
)
repl = r'\g<1>{}'.format(package['latest_version'])
line = re.sub(pattern, repl, line)
if line != original_line:
self.upgraded_packages.append(package)
if self.dry_run: # pragma: nocover
print('[Dry Run]: skipping requirements replacement:',
original_line.replace('\n', ''), ' / ',
line.replace('\n', ''))
return original_line
return line
``` |
{
"source": "joe733/TinkerHub-Learning",
"score": 4
} |
#### File: Python/Day_001/day_001.py
```python
from flask import Flask
# Flask constructor takes the name of current module (__name__) as argument.
app = Flask(__name__)
# app.route(rule, options)
# The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function.
# The `rule` parameter represents URL binding with the function.
# The `options` is a list of parameters to be forwarded to the underlying Rule object.
# ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be rendered.
@app.route('/')
def index():
# The return type must be a string, dict, tuple
# 'Hello World!<br>Hey There!' HTML ignores \n\t etc.
# ('121', 212, '11')
# {'key': 'values', '112': [358, 1321], 'single-type-key': {2: 36, 18: (108, 1944)}}
return '''<h3>Hello</h3>
<h3>Flask</h3>
<h3>Mini</h3>
<h3>Web</h3>
<h3>Framework</h3><br>
<marquee behavior="alternate">Not gonna regret this TLFH program...</marquee>
<ul>
<li>
<a href="http://127.0.0.1:5000">Index</a>
</li>
<li>
<a href="http://127.0.0.1:5000/home">Home</a>
</li>
<li>
<a href="http://127.0.0.1:5000/contact_us">Contact Us</a>
</li>
<ul>'''
@app.route("/home")
def home():
return "<h1>You're @ Home</h1>Goto: <a href=http://127.0.0.1:5000/>Index</a>"
@app.route("/contact_us")
def contact_us():
return "<h1>You're @ Contact Us</h1>Goto: <a href=http://127.0.0.1:5000/>Index</a>"
if __name__ == '__main__':
# the run() method of Flask class runs the application on the local development server. `app.run(host, port, debug, options)`
app.run(debug=True)
'''
A Flask application is started by calling the run() method.
However, while the application is under development, it should be restarted manually for each change in the code.
To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application.
The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method.
'''
``` |
{
"source": "joe733/vudoku",
"score": 3
} |
#### File: joe733/vudoku/extractor.py
```python
import cv2 as cv
import numpy as np
from keras import models
class DigitExtractor:
def __init__(self):
self.cells = []
self.string = ''
def splitGrid(self, frame):
# perform additional preprocessing if required
rows = np.array_split(ary=frame, indices_or_sections=9, axis=0)
for idx, row in enumerate(rows):
columns = np.array_split(ary=row, indices_or_sections=9, axis=1)
for jdx, column in enumerate(columns):
resized_img = cv.resize(column[3:-3, 3:-3], # the 3:-3 slice removes the borders from each image
dsize=(28, 28),
interpolation=cv.INTER_CUBIC)
cv.imwrite(
filename=f'assets/images/out/cells/cell{idx}{jdx}.jpg', img=resized_img)
self.cells.append(resized_img)
def genString(self):
# check if model exists if not, prompt user to run classifier
model = models.load_model(filepath='assets/models/mnist_trained_model_v1.h5')
for cell in self.cells:
# Mark empty cells are marked as zero the converted into a string
rs_cell = cell.reshape(1, 28, 28, 1)
predictions = model.predict(rs_cell)
digit = predictions[0].tolist().index(max(predictions[0].tolist()))
self.string += str(digit)
def miner(self, image):
self.splitGrid(frame=image)
self.genString()
return self.string
dex = DigitExtractor()
``` |
{
"source": "joe7hu/FBGEMM",
"score": 2
} |
#### File: FBGEMM/fbgemm_gpu/split_embedding_configs.py
```python
import enum
@enum.unique
class EmbOptimType(enum.Enum):
SGD = "sgd" # uses non-deterministic updates (atomicAdd(..)) with duplicate ids
EXACT_SGD = (
"exact_sgd" # uses deterministic updates (via sorting + segment reduction)
)
LAMB = "lamb"
ADAM = "adam"
# exact/dedup: gradients to the same row are applied with coalesce then apply
# together, instead of applied in sequence (approx).
EXACT_ADAGRAD = "exact_adagrad"
EXACT_ROWWISE_ADAGRAD = "exact_row_wise_adagrad"
LARS_SGD = "lars_sgd"
PARTIAL_ROWWISE_ADAM = "partial_row_wise_adam"
PARTIAL_ROWWISE_LAMB = "partial_row_wise_lamb"
def __str__(self):
return self.value
@enum.unique
class SparseType(enum.Enum):
FP32 = "fp32"
FP16 = "fp16"
INT8 = "int8"
def __str__(self):
return self.value
``` |
{
"source": "Joe811/raspberry-pilot",
"score": 2
} |
#### File: selfdrive/controls/controlsd.py
```python
import capnp
from cereal import car, log
from common.numpy_fast import clip
from common.params import Params
import selfdrive.messaging as messaging
from selfdrive.services import service_list
from selfdrive.boardd.boardd import can_list_to_can_capnp
from selfdrive.car.car_helpers import get_car, get_startup_alert
from selfdrive.controls.lib.drive_helpers import get_events, \
create_event, \
EventTypes as ET, \
update_v_cruise, \
initialize_v_cruise
from selfdrive.controls.lib.latcontrol_pid import LatControlPID
from selfdrive.controls.lib.alertmanager import AlertManager
from setproctitle import setproctitle
ThermalStatus = log.ThermalData.ThermalStatus
State = log.ControlsState.OpenpilotState
def isActive(state):
"""Check if the actuators are enabled"""
return state in [State.enabled, State.softDisabling]
def isEnabled(state):
"""Check if openpilot is engaged"""
return (isActive(state) or state == State.preEnabled)
def events_to_bytes(events):
# optimization when comparing capnp structs: str() or tree traverse are much slower
ret = []
for e in events:
if isinstance(e, capnp.lib.capnp._DynamicStructReader):
e = e.as_builder()
ret.append(e.to_bytes())
return ret
def wait_for_can(logcan):
print("Waiting for CAN messages...")
while len(messaging.recv_one(logcan).can) == 0:
pass
def data_sample(CI, CC, can_sock, carstate, lac_log):
"""Receive data from sockets and create events for battery, temperature and disk space"""
# TODO: Update carstate twice per cycle to prevent dropping frames, but only update controls once
can_strs = [can_sock.recv()]
CS = CI.update(CC, can_strs, lac_log)
events = list(CS.events)
# carState
if False:
cs_send = messaging.new_message()
cs_send.init('carState')
cs_send.valid = CS.canValid
cs_send.carState = CS
cs_send.carState.events = events
carstate.send(cs_send.to_bytes())
return CS, events
def state_transition(frame, CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM):
"""Compute conditional state transitions and execute actions on state transitions"""
enabled = isEnabled(state)
v_cruise_kph_last = v_cruise_kph
# if stock cruise is completely disabled, then we can use our own set speed logic
if not CP.enableCruise:
v_cruise_kph = update_v_cruise(v_cruise_kph, CS.buttonEvents, enabled)
elif CP.enableCruise and CS.cruiseState.enabled:
v_cruise_kph = CS.cruiseState.speed #* CV.MS_TO_KPH
# decrease the soft disable timer at every step, as it's reset on
# entrance in SOFT_DISABLING state
soft_disable_timer = max(0, soft_disable_timer - 1)
# DISABLED
if state == State.disabled:
if get_events(events, [ET.ENABLE]):
if get_events(events, [ET.NO_ENTRY]):
for e in get_events(events, [ET.NO_ENTRY]):
AM.add(frame, str(e) + "NoEntry", enabled)
else:
if get_events(events, [ET.PRE_ENABLE]):
state = State.preEnabled
else:
state = State.enabled
AM.add(frame, "enable", enabled)
v_cruise_kph = initialize_v_cruise(CS.vEgo, CS.buttonEvents, v_cruise_kph_last)
# ENABLED
elif state == State.enabled:
if get_events(events, [ET.USER_DISABLE]):
state = State.disabled
AM.add(frame, "disable", enabled)
elif get_events(events, [ET.IMMEDIATE_DISABLE]):
state = State.disabled
for e in get_events(events, [ET.IMMEDIATE_DISABLE]):
AM.add(frame, e, enabled)
elif get_events(events, [ET.SOFT_DISABLE]):
state = State.softDisabling
soft_disable_timer = 300 # 3s
for e in get_events(events, [ET.SOFT_DISABLE]):
AM.add(frame, e, enabled)
# SOFT DISABLING
elif state == State.softDisabling:
if get_events(events, [ET.USER_DISABLE]):
state = State.disabled
AM.add(frame, "disable", enabled)
elif get_events(events, [ET.IMMEDIATE_DISABLE]):
state = State.disabled
for e in get_events(events, [ET.IMMEDIATE_DISABLE]):
AM.add(frame, e, enabled)
elif not get_events(events, [ET.SOFT_DISABLE]):
# no more soft disabling condition, so go back to ENABLED
state = State.enabled
elif get_events(events, [ET.SOFT_DISABLE]) and soft_disable_timer > 0:
for e in get_events(events, [ET.SOFT_DISABLE]):
AM.add(frame, e, enabled)
elif soft_disable_timer <= 0:
state = State.disabled
# PRE ENABLING
elif state == State.preEnabled:
if get_events(events, [ET.USER_DISABLE]):
state = State.disabled
AM.add(frame, "disable", enabled)
elif get_events(events, [ET.IMMEDIATE_DISABLE, ET.SOFT_DISABLE]):
state = State.disabled
for e in get_events(events, [ET.IMMEDIATE_DISABLE, ET.SOFT_DISABLE]):
AM.add(frame, e, enabled)
elif not get_events(events, [ET.PRE_ENABLE]):
state = State.enabled
return state, soft_disable_timer, v_cruise_kph, v_cruise_kph_last
def state_control(frame, lkasMode, path_plan, CS, CP, state, events, AM, LaC, lac_log):
"""Given the state, this function returns an actuators packet"""
actuators = car.CarControl.Actuators.new_message()
enabled = isEnabled(state)
active = isActive(state)
# Steering PID loop and lateral MPC
actuators.steer, actuators.steerAngle, lac_log = LaC.update(CS.lkMode and (active or lkasMode), CS.vEgo, CS.steeringAngle, CS.steeringTorqueEps, CS.steeringPressed, CP, path_plan, CS.canTime)
# parse warnings from car specific interface
for e in get_events(events, [ET.WARNING]):
extra_text = ""
AM.add(frame, e, enabled, extra_text_2=extra_text)
# Parse permanent warnings to display constantly
for e in get_events(events, [ET.PERMANENT]):
extra_text_1, extra_text_2 = "", ""
AM.add(frame, str(e) + "Permanent", enabled, extra_text_1=extra_text_1, extra_text_2=extra_text_2)
AM.process_alerts(frame)
return actuators, lac_log
def data_send(sm, CS, CI, CP, state, events, actuators, carstate, carcontrol, carevents, carparams, controlsstate, sendcan, AM, LaC, start_time, lac_log, events_prev):
"""Send actuators and hud commands to the car, send controlsstate and MPC logging"""
CC = car.CarControl.new_message()
CC.enabled = isEnabled(state)
CC.actuators = actuators
CC.cruiseControl.override = True
CC.cruiseControl.cancel = not CP.enableCruise or (not isEnabled(state) and CS.cruiseState.enabled)
#CC.hudControl.setSpeed = float(v_cruise_kph * CV.KPH_TO_MS)
CC.hudControl.speedVisible = isEnabled(state)
CC.hudControl.lanesVisible = isEnabled(state)
right_lane_visible = sm['pathPlan'].rProb > 0.5
left_lane_visible = sm['pathPlan'].lProb > 0.5
CC.hudControl.rightLaneVisible = bool(right_lane_visible)
CC.hudControl.leftLaneVisible = bool(left_lane_visible)
CC.hudControl.visualAlert = AM.visual_alert
CC.hudControl.audibleAlert = AM.audible_alert
can_sends = CI.apply(CC)
sendcan.send(can_list_to_can_capnp(can_sends, msgtype='sendcan', valid=CS.canValid))
events_bytes = None
# carState
if True:
cs_send = messaging.new_message()
cs_send.init('carState')
cs_send.valid = CS.canValid
cs_send.carState = CS
cs_send.carState.events = events
carstate.send(cs_send.to_bytes())
return CC, events_bytes
def controlsd_thread(gctx=None):
setproctitle('controlsd')
params = Params()
print(params)
# Pub Sockets
sendcan = messaging.pub_sock(service_list['sendcan'].port)
controlsstate = messaging.pub_sock(service_list['controlsState'].port)
carstate = messaging.pub_sock(service_list['carState'].port)
carcontrol = messaging.pub_sock(service_list['carControl'].port)
carevents = messaging.pub_sock(service_list['carEvents'].port)
carparams = messaging.pub_sock(service_list['carParams'].port)
sm = messaging.SubMaster(['pathPlan'])
logcan = messaging.sub_sock(service_list['can'].port)
wait_for_can(logcan)
CI, CP = get_car(logcan, sendcan, False)
logcan.close()
# TODO: Use the logcan socket from above, but that will currenly break the tests
can_timeout = None #if os.environ.get('NO_CAN_TIMEOUT', False) else 100
can_sock = messaging.sub_sock(service_list['can'].port, timeout=can_timeout)
# Write CarParams for radard and boardd safety mode
params.put("CarParams", CP.to_bytes())
params.put("LongitudinalControl", "1" if CP.openpilotLongitudinalControl else "0")
CC = car.CarControl.new_message()
AM = AlertManager()
startup_alert = get_startup_alert(True, True)
AM.add(sm.frame, startup_alert, False)
LaC = LatControlPID(CP)
lkasMode = int(float(LaC.kegman.conf['lkasMode']))
#CI.CS.lkasMode = (lkasMode == 0)
lac_log = None #car.CarState.lateralControlState.pidState.new_message()
state = State.disabled
soft_disable_timer = 0
v_cruise_kph = 255
events_prev = []
sm['pathPlan'].sensorValid = True
sm['pathPlan'].posenetValid = True
while True:
start_time = 0 # time.time() #sec_since_boot()
# Sample data and compute car events
CS, events = data_sample(CI, CC, can_sock, carstate, lac_log)
state, soft_disable_timer, v_cruise_kph, v_cruise_kph_last = \
state_transition(sm.frame, CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM)
# Compute actuators (runs PID loops and lateral MPC)
sm.update(0)
actuators, lac_log = state_control(sm.frame, lkasMode, sm['pathPlan'], CS, CP, state, events, AM, LaC, lac_log)
# Publish data
CC, events_prev = data_send(sm, CS, CI, CP, state, events, actuators, carstate, carcontrol, carevents, carparams,
controlsstate, sendcan, AM, LaC, start_time, lac_log, events_prev)
def main(gctx=None):
controlsd_thread(gctx)
if __name__ == "__main__":
main()
```
#### File: controls/lib/latcontrol_pid.py
```python
from selfdrive.controls.lib.pid import PIController
from selfdrive.kegman_conf import kegman_conf
from common.numpy_fast import gernterp, interp, clip
import numpy as np
import time
from cereal import car
#from common.realtime import sec_since_boot
from common.params import Params
from numpy import array
import json
class LatControlPID(object):
def __init__(self, CP):
self.kegman = kegman_conf(CP)
self.frame = 0
self.pid = PIController((CP.lateralTuning.pid.kpBP, CP.lateralTuning.pid.kpV),
(CP.lateralTuning.pid.kiBP, CP.lateralTuning.pid.kiV),
k_f=CP.lateralTuning.pid.kf)
self.angle_steers_des = 0.
self.polyReact = 1. #max(0.0, CP.lateralTuning.pid.polyReactTime + CP.lateralTuning.pid.polyDampTime)
self.poly_smoothing = max(1.0, CP.lateralTuning.pid.polyDampTime * 100.)
#self.poly_scale = CP.lateralTuning.pid.polyScale
self.poly_factor = CP.lateralTuning.pid.polyFactor
self.poly_scale = CP.lateralTuning.pid.polyScale
self.path_error_comp = 0.0
#self.last_path_error = 0.0
#self.cur_poly_scale = 0.0
#self.p_poly = [0., 0., 0., 0.]
#self.s_poly = [0., 0., 0., 0.]
#self.p_prob = 0.
self.damp_angle_steers = 0.
self.damp_angle_rate = 0.
self.damp_time = 0.1
self.react_mpc = 0.0
self.damp_mpc = 0.25
self.angle_ff_ratio = 0.0
#self.gernbySteer = True
#self.standard_ff_ratio = 0.0
self.angle_ff_gain = 1.0
self.rate_ff_gain = CP.lateralTuning.pid.rateFFGain
self.angle_ff_bp = [[0.5, 5.0],[0.0, 1.0]]
#self.steer_p_scale = CP.lateralTuning.pid.steerPscale
#self.calculate_rate = True
#self.prev_angle_steers = 0.0
#self.rough_steers_rate = 0.0
#self.steer_counter = 1
#self.lane_change_adjustment = 0.0
#self.lane_changing = 0.0
#self.starting_angle = 0.0
#self.half_lane_width = 0.0
#self.steer_counter_prev = 1
self.params = Params()
#self.prev_override = False
#self.driver_assist_offset = 0.0
#self.driver_assist_hold = False
#self.angle_bias = 0.
self.previous_integral = 0.0
self.damp_angle_steers= 0.0
self.damp_rate_steers_des = 0.0
self.damp_angle_steers_des = 0.0
self.old_plan_count = 0
self.last_plan_time = 0
self.path_age = 0
#self.lane_compensation = 0.
#self.future_centers = 0.
self.angle_index = 0.
self.avg_plan_age = 0.
#self.lane_error = 0.
self.min_index = 0
self.max_index = 0
self.c_prob = 0.
#self.damp_limit = 0
#self.des_angle_change_rate = 0.
self.projected_lane_error = 0.
self.prev_projected_lane_error = 0.
#self.poly_range = None #np.concatenate((np.zeros((5)),np.arange((25.))))
self.path_index = None #np.arange((30.))*100.0/15.0
#self.mpc_angles = None #np.zeros((30))
try:
lateral_params = self.params.get("LateralGain")
lateral_params = json.loads(lateral_params)
self.angle_ff_gain = max(1.0, float(lateral_params['angle_ff_gain']))
except:
self.angle_ff_gain = 1.0
def live_tune(self, CP):
if False and self.frame % 3600 == 0:
self.params.put("LateralGain", json.dumps({'angle_ff_gain': self.angle_ff_gain}))
if self.frame % 300 == 0:
try:
self.kegman = kegman_conf() #.read_config()
self.pid._k_i = ([0.], [float(self.kegman.conf['Ki'])])
self.pid._k_p = ([0.], [float(self.kegman.conf['Kp'])])
self.pid.k_f = (float(self.kegman.conf['Kf']))
self.damp_time = (float(self.kegman.conf['dampTime']))
self.react_mpc = (float(self.kegman.conf['reactMPC']))
self.damp_mpc = (float(self.kegman.conf['dampMPC']))
self.polyReact = max(0.0, float(self.kegman.conf['polyReact']) * 0.1)
self.poly_smoothing = max(1.0, float(self.kegman.conf['polyDamp']) * 100.)
self.poly_factor = max(0.0, float(self.kegman.conf['polyFactor']) * 0.001)
except:
print(" Kegman error")
def reset(self):
self.pid.reset()
def adjust_angle_gain(self):
if (self.pid.f > 0) == (self.pid.i > 0) and abs(self.pid.i) >= abs(self.previous_integral):
if not abs(self.pid.f + self.pid.i) > 1: self.angle_ff_gain *= 1.0001
elif self.angle_ff_gain > 1.0:
self.angle_ff_gain *= 0.9999
self.previous_integral = self.pid.i
def update(self, active, v_ego, angle_steers, angle_steers_rate, steer_override, CP, path_plan, canTime):
pid_log = car.CarState.LateralPIDState.new_message()
if path_plan.canTime != self.last_plan_time and len(path_plan.mpcAngles) > 1:
path_age = (canTime - path_plan.canTime) * 1e-3
if self.path_age > 0.23: self.old_plan_count += 1
if self.path_index is None:
self.avg_plan_age = path_age
self.path_index = np.arange((len(path_plan.mpcAngles)))*100.0/15.0
self.last_plan_time = path_plan.canTime
self.avg_plan_age += 0.01 * (path_age - self.avg_plan_age)
self.c_prob = max(self.c_prob - 0.0333, min(self.c_prob + 0.0333, path_plan.cProb))
self.projected_lane_error = self.c_prob * self.poly_factor * (sum(path_plan.cPoly) + self.polyReact * 15 * (path_plan.cPoly[-1] - path_plan.cPoly[-2]))
if abs(self.projected_lane_error) < abs(self.prev_projected_lane_error) and (self.projected_lane_error > 0) == (self.prev_projected_lane_error > 0):
self.projected_lane_error *= gernterp(angle_steers, [0, 4], [0.25, 1.0])
#self.damp_adjust = gernterp(abs(path_plan.cPoly[-1]), [0,50], [1., 0.5])
self.prev_projected_lane_error = self.projected_lane_error
self.angle_index = max(0., 100. * (self.react_mpc + path_age))
else:
self.angle_index += 1.0
self.min_index = min(self.min_index, self.angle_index)
self.max_index = max(self.max_index, self.angle_index)
if self.frame % 300 == 0 and self.frame > 0:
print("old plans: %d avg plan age: %0.3f min index: %d max_index: %d" % (self.old_plan_count, self.avg_plan_age, self.min_index, self.max_index))
self.min_index = 100
self.max_index = 0
self.frame += 1
self.live_tune(CP)
if v_ego < 0.3 or not active:
output_steer = 0.0
self.previous_integral = 0.0
self.previous_lane_error = 0.0
self.path_error_comp = 0.0
self.damp_angle_steers= 0.0
self.damp_rate_steers_des = 0.0
self.damp_angle_steers_des = 0.0
pid_log.active = False
self.pid.reset()
else:
try:
self.damp_angle_steers += (angle_steers + angle_steers_rate * self.damp_time - self.damp_angle_steers) / max(1.0, self.damp_time * 100.)
self.damp_angle_rate += (angle_steers_rate - self.damp_angle_rate) / max(1.0, self.damp_time * 100.)
self.angle_steers_des = interp(self.angle_index, self.path_index, path_plan.mpcAngles)
self.damp_angle_steers_des += (self.angle_steers_des - self.damp_angle_steers_des) / max(1.0, self.damp_mpc * 100.)
self.damp_rate_steers_des += ((path_plan.mpcAngles[4] - path_plan.mpcAngles[3]) - self.damp_rate_steers_des) / max(1.0, self.damp_mpc * 100.)
except:
print(" angle error!")
pass
angle_feedforward = float(self.damp_angle_steers_des - path_plan.angleOffset)
self.angle_ff_ratio = float(gernterp(abs(angle_feedforward), self.angle_ff_bp[0], self.angle_ff_bp[1]))
rate_feedforward = (1.0 - self.angle_ff_ratio) * self.rate_ff_gain * self.damp_rate_steers_des
steer_feedforward = float(v_ego)**2 * (rate_feedforward + angle_feedforward * self.angle_ff_ratio * self.angle_ff_gain)
if v_ego * self.projected_lane_error > self.path_error_comp and self.pid.p2 < 1 and self.pid.control < 1 or \
v_ego * self.projected_lane_error < self.path_error_comp and self.pid.p2 > -1 and self.pid.control > -1:
self.path_error_comp += (v_ego * self.projected_lane_error - self.path_error_comp) / self.poly_smoothing
if not steer_override and v_ego > 10.0:
if abs(angle_steers) > (self.angle_ff_bp[0][1] / 2.0):
self.adjust_angle_gain()
else:
self.previous_integral = self.pid.i
deadzone = 0.0
output_steer = self.pid.update(self.damp_angle_steers_des, self.damp_angle_steers, check_saturation=(v_ego > 10), override=steer_override,
add_error=float(self.path_error_comp), feedforward=steer_feedforward, speed=v_ego, deadzone=deadzone)
pid_log.active = True
pid_log.p = float(self.pid.p)
pid_log.i = float(self.pid.i)
pid_log.f = float(self.pid.f)
pid_log.output = float(output_steer)
pid_log.p2 = float(self.pid.p2) #float(self.path_error_comp) * float(self.pid._k_p[1][0])
pid_log.saturated = bool(self.pid.saturated)
pid_log.angleFFRatio = self.angle_ff_ratio
pid_log.steerAngle = float(self.damp_angle_steers)
pid_log.steerAngleDes = float(self.damp_angle_steers_des)
if abs(self.projected_lane_error - self.path_error_comp) < abs(self.projected_lane_error) and pid_log.p * pid_log.p2 < 0:
output_steer -= pid_log.p
pid_log.p *= max(0, min(1, 1 - abs(2 * pid_log.p2)))
output_steer += pid_log.p
pid_log.output = float(output_steer)
#self.prev_angle_steers = angle_steers
#self.prev_override = steer_override
self.sat_flag = self.pid.saturated
return output_steer, float(self.angle_steers_des), pid_log
``` |
{
"source": "joe917/vnpy",
"score": 2
} |
#### File: app/cta_strategy/moving_average_meanrever_multi.py
```python
from vnpy.app.cta_strategy import (
CtaTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager,
)
import numpy as np
import pandas as pd
from sqlalchemy import create_engine, VARCHAR, TIMESTAMP
from datetime import datetime
class MVA_Meanrever_mul(CtaTemplate):
""""""
author = "Allen"
mva_1 = 10
mva_2 = 70
fixed_size = 1
trailing_percent_long_loose = 20
trailing_percent_short_loose = 15
short_quantile = 95
buy_quantile = 5
mean_rever_range = 100
intra_trade_high = 0
intra_trade_low = 0
parameters = [
"mva_1",
"mva_2",
"fixed_size",
"trailing_percent_long_loose",
"trailing_percent_short_loose",
"short_quantile",
"buy_quantile",
"mean_rever_range"
]
variables = [
"intra_trade_high",
"intra_trade_low"
]
def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
""""""
super().__init__(cta_engine, strategy_name, vt_symbol, setting)
self.bg = BarGenerator(self.on_bar)
self.am = ArrayManager()
engine = create_engine('')
self.signal = pd.read_sql(f"SELECT * FROM `dbbardata` WHERE `symbol` = \'Bond_price\';", engine) # 从数据库调取标的所有数据
self.signal['datetime'] = self.signal['datetime'].apply(lambda x: x.to_pydatetime().date())
self.signal = self.signal.reset_index(drop=True)
def on_init(self):
"""
Callback when strategy is inited.
"""
self.write_log("策略初始化")
self.load_bar(10)
def on_start(self):
"""
Callback when strategy is started.
"""
self.write_log("策略启动")
def on_stop(self):
"""
Callback when strategy is stopped.
"""
self.write_log("策略停止")
def on_tick(self, tick: TickData):
"""
Callback of new tick data update.
"""
self.bg.update_tick(tick)
def on_bar(self, bar: BarData):
"""
Callback of new bar data update.
"""
self.cancel_all()
am = self.am
am.update_bar(bar)
if not am.inited:
return
signal_m = self.signal[self.signal['datetime'] <= bar.datetime.date()]['close_price']
#均线开仓
if self.pos == 0:
self.intra_trade_high = bar.high_price
self.intra_trade_low = bar.low_price
if signal_m[-self.mva_1-1:-1].mean() > signal_m[-self.mva_2-1:-1].mean():
self.buy(bar.close_price + 500, self.fixed_size)
elif signal_m[-self.mva_1-1:-1].mean() < signal_m[-self.mva_2-1:-1].mean():
self.short(bar.close_price - 500, self.fixed_size)
else:
pass
elif self.pos > 0:
if signal_m[-self.mva_1-1:-1].mean() < signal_m[-self.mva_2-1:-1].mean():
self.sell(bar.close_price - 500, self.fixed_size)
self.short(bar.close_price - 500, self.fixed_size)
else:
pass
elif self.pos < 0:
if signal_m[-self.mva_1-1:-1].mean() > signal_m[-self.mva_2-1:-1].mean():
self.cover(bar.close_price + 500, self.fixed_size)
self.buy(bar.close_price + 500, self.fixed_size)
else:
pass
else:
pass
#止损条件
if self.pos > 0:
self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
self.intra_trade_low = min(self.intra_trade_low, bar.low_price)
long_stop_loose = self.intra_trade_high * \
(1 - self.trailing_percent_long_loose / 1000)
self.sell(long_stop_loose, abs(self.pos), stop=True)
elif self.pos < 0:
self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
self.intra_trade_low = min(self.intra_trade_low, bar.low_price)
short_stop_loose = self.intra_trade_low * \
(1 + self.trailing_percent_short_loose / 1000)
self.cover(short_stop_loose, abs(self.pos), stop=True)
else:
pass
#均值回归策略
if signal_m[-self.mean_rever_range:].mean() > np.quantile(signal_m[:], self.short_quantile/100):
if self.pos > 0:
self.cancel_all()
self.sell(bar.close_price - 500, self.fixed_size)
elif self.pos == 0:
self.cancel_all()
self.short(bar.close_price - 500, self.fixed_size)
else:
pass
elif signal_m[-self.mean_rever_range:].mean() < np.quantile(signal_m[:], self.buy_quantile/100):
if self.pos < 0:
self.cancel_all()
self.cover(bar.close_price + 500, self.fixed_size)
elif self.pos == 0:
self.cancel_all()
self.buy(bar.close_price + 500, self.fixed_size)
else:
pass
else:
pass
self.put_event()
def on_order(self, order: OrderData):
"""
Callback of new order data update.
"""
pass
def on_trade(self, trade: TradeData):
"""
Callback of new trade data update.
"""
self.put_event()
def on_stop_order(self, stop_order: StopOrder):
"""
Callback of stop order update.
"""
pass
```
#### File: app/cta_strategy/moving_average.py
```python
from vnpy.app.cta_strategy import (
CtaTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager,
)
class MVA(CtaTemplate):
""""""
author = "Allen"
mva_1 = 20
mva_2 = 60
fixed_size = 1
parameters = [
"mva_1",
"mva_2",
"fixed_size"
]
variables = [
]
def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
""""""
super().__init__(cta_engine, strategy_name, vt_symbol, setting)
self.bg = BarGenerator(self.on_bar)
self.am = ArrayManager()
def on_init(self):
"""
Callback when strategy is inited.
"""
self.write_log("策略初始化")
self.load_bar(10)
def on_start(self):
"""
Callback when strategy is started.
"""
self.write_log("策略启动")
def on_stop(self):
"""
Callback when strategy is stopped.
"""
self.write_log("策略停止")
def on_tick(self, tick: TickData):
"""
Callback of new tick data update.
"""
self.bg.update_tick(tick)
def on_bar(self, bar: BarData):
"""
Callback of new bar data update.
"""
self.cancel_all()
am = self.am
am.update_bar(bar)
if not am.inited:
return
print(bar.close_price)
if self.pos == 0:
if self.am.close_array[-self.mva_1-1:-1].mean() > self.am.close_array[-self.mva_2-1:-1].mean():
self.buy(bar.close_price + 1, self.fixed_size)
elif self.am.close_array[-self.mva_1-1:-1].mean() < self.am.close_array[-self.mva_2-1:-1].mean():
self.short(bar.close_price - 1, self.fixed_size)
else:
pass
elif self.pos > 0:
if self.am.close_array[-self.mva_1-1:-1].mean() < self.am.close_array[-self.mva_2-1:-1].mean():
self.sell(bar.close_price - 1, self.fixed_size)
else:
pass
elif self.pos < 0:
if self.am.close_array[-self.mva_1-1:-1].mean() > self.am.close_array[-self.mva_2-1:-1].mean():
self.cover(bar.close_price + 1, self.fixed_size)
else:
pass
else:
pass
self.put_event()
def on_order(self, order: OrderData):
"""
Callback of new order data update.
"""
pass
def on_trade(self, trade: TradeData):
"""
Callback of new trade data update.
"""
self.put_event()
def on_stop_order(self, stop_order: StopOrder):
"""
Callback of stop order update.
"""
pass
``` |
{
"source": "joe94113/python-",
"score": 3
} |
#### File: python-/ch1/try_connect.py
```python
import requests
from bs4 import BeautifulSoup
def main():
h1 = get_head_text('http://blog.castman.net/web-crawler-tutorial/ch1/connect.html', 'h1')
print(h1)
h2 = get_head_text('http://blog.castman.net/web-crawler-tutorial/ch1/connect.html', 'h2')
print(h2)
def get_head_text(url, head_tag):
try:
resp = requests.get(url)
if resp.status_code == 200:
soup = BeautifulSoup(resp.text, 'html.parser')
return soup.find(head_tag).text
except Exception as e:
return None
if __name__ == '__main__':
main()
``` |
{
"source": "joealcorn/berth.cc",
"score": 2
} |
#### File: berth.cc/berth/mixins.py
```python
from django.contrib.auth.decorators import login_required
class LoginRequired(object):
@classmethod
def as_view(cls, **initkwargs):
view = super(LoginRequired, cls).as_view(**initkwargs)
return login_required(view)
```
#### File: berth.cc/berth/models.py
```python
from django.db import models
class Model(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def _do_insert(self, manager, *a, **kw):
'''
This is required as part of the `insert...returning` hack.
All it does is replaces the base manager in the call
with the specified manager, which does the rest of the work.
'''
if getattr(self.__class__.objects, 'insert_returning', False):
manager = self.__class__.objects
return super(Model, self)._do_insert(manager, *a, **kw)
class Meta:
abstract = True
```
#### File: berth/webhooks/views.py
```python
from django.conf import settings
from rest_framework import response, views, generics
from berth.job.models import Job
from berth.job import constants as job_constants
from berth.project import constants as project_constants
from berth.project.models import Project
from berth.webhooks.serializers import GithubWebhookSerializer
class GithubWebhook(generics.GenericAPIView):
serializer_class = GithubWebhookSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
if not serializer.is_valid():
return response.Response(status=400)
try:
project = Project.objects.get(
repo_identifier=serializer.data['repository']['id'],
repo_source=project_constants.GITHUB,
)
except Project.DoesNotExist:
return response.Response(status=404)
job = Job.objects.create(
project=project,
state=job_constants.BUILD_STATUS_QUEUED,
)
job.build()
return response.Response()
``` |
{
"source": "joealcorn/celery-dedupe",
"score": 2
} |
#### File: celery-dedupe/celery_dedupe/tasks.py
```python
import hashlib
import logging
import warnings
from celery import Task
from celery.result import EagerResult
from celery.utils import uuid
logger = logging.getLogger('celery_dedupe')
class DedupeTask(Task):
abtract = True
storage = None
def apply_async(self, args=None, kwargs=None, **kw):
key = self._create_key(args, kwargs)
task_id = kw.setdefault('task_id', uuid())
if self.storage.obtain_lock(key, task_id):
logger.debug('Queueing %s [%s]', task_id, key)
return super(DedupeTask, self).apply_async(args=args, kwargs=kwargs, **kw)
existing_task_id = self.storage.get(key)
if existing_task_id == task_id:
# This should be a retry, so add it to the broker anyway
logger.debug('Queueing %s for retry [%s]', task_id, key)
return super(DedupeTask, self).apply_async(args=args, kwargs=kwargs, **kw)
app = self._get_app()
if app.conf.CELERY_ALWAYS_EAGER:
warnings.warn('Using DedupeTask in conjunction with CELERY_ALWAYS_EAGER, can not return EagerResult')
logger.debug('%s already queued, returning AsyncResult [%s]', task_id, key)
return self.AsyncResult(existing_task_id)
def on_success(self, retval, task_id, args, kwargs):
key = self._create_key(args, kwargs)
self.storage.release_lock(key)
def on_failure(self, exception, task_id, args, kwargs, einfo):
key = self._create_key(args, kwargs)
self.storage.release_lock(key)
def _create_key(self, args, kwargs):
args = args or tuple()
kwargs = kwargs or dict()
arg_string = ','.join([str(a) for a in args])
kwarg_string = ','.join(['%s=%s' % (k, v) for k, v in kwargs.iteritems()])
arg_hash = hashlib.md5(arg_string + kwarg_string).hexdigest()
import_path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
return 'cd:%s:%s' % (import_path, arg_hash)
```
#### File: celery-dedupe/tests/test_storages.py
```python
from uuid import uuid4
from redis import StrictRedis
from celery_dedupe.storage.redis import RedisStorage
class TestRedisStorage(object):
@property
def redis(self):
if hasattr(self, '_redis'):
return self._redis
self._redis = StrictRedis()
return self._redis
def test_lock_obtained(self):
storage = RedisStorage(self.redis)
assert storage.obtain_lock(uuid4(), '1')
def test_lock_obtained_with_expiry(self):
key = uuid4()
storage = RedisStorage(self.redis, expiry=10)
assert storage.obtain_lock(key, '1')
assert self.redis.ttl(key) == 10
def test_already_locked(self):
key = uuid4()
self.redis.setex(key, 10, '1')
storage = RedisStorage(self.redis, expiry=10)
assert not storage.obtain_lock(key, '1')
def test_release_lock(self):
key = uuid4()
self.redis.setex(key, 10, '1')
storage = RedisStorage(self.redis, expiry=10)
storage.release_lock(key)
assert not self.redis.get(key)
def test_get(self):
key = uuid4()
self.redis.setex(key, 10, '1')
storage = RedisStorage(self.redis)
assert storage.get(key) == '1'
``` |
{
"source": "joealcorn/chatter",
"score": 2
} |
#### File: joealcorn/chatter/chatter.py
```python
from datetime import datetime
import hashlib
import json
import logging
from flask import Flask, request, jsonify, Response
from flask_cors import CORS
import boto3
import pytz
import simpleflake
logger = logging.getLogger(__name__)
app = Flask(__name__)
CORS(app, origins=[
'http://127.0.0.1:4000',
'https://joealcorn.co.uk',
])
s3 = boto3.resource('s3')
bucket = s3.Bucket('zappa-comments-input')
@app.route('/', methods=['POST'])
def submit_comment():
'''
Hit by a user's browser to add a new comment
'''
# slug should be something like a url
slug = request.form.get('slug')
comment_text = request.form.get('comment')
name = request.form.get('name')
email = request.form.get('email')
if not comment_text or not name or not slug:
return jsonify({
'error': '`comment`, `name` and `slug` needed',
}), 400
comment_id = str(simpleflake.simpleflake())
comment = {
'id': comment_id,
'text': comment_text,
'name': name,
'email': email,
'version': '0',
'ip_address': request.remote_addr,
'created_at': datetime.utcnow().replace(tzinfo=pytz.utc).isoformat(),
}
comment_json = json.dumps(comment)
# store comment in appropriate place in bucket
file_name = 'comments/%s/%s.json' % (slug, comment_id)
bucket.put_object(
Body=bytes(comment_json, encoding='utf8'),
Key=file_name,
ACL='private',
ContentType='application/json',
)
return Response(comment_json, headers={
'Access-Control-Allow-Origin': '*',
}, content_type='application/json')
def get_comments_from_bucket(slug):
prefix = 'comments/%s/' % slug
comments = []
etags = []
print('Getting comments from bucket with prefix %s' % prefix)
for obj in bucket.objects.filter(Prefix=prefix):
file_name = obj.key.rsplit('/', 1)[1]
comment_id = file_name.rsplit('.', 1)[0]
try:
comment_json = json.loads(obj.get()['Body'].read().decode('utf8'))
assert comment_json['id'] == comment_id
comments.append({
'id': comment_json['id'],
'text': comment_json['text'],
'name': comment_json['name'],
'version': comment_json['version'],
'created_at': comment_json['created_at'],
})
etags.append(obj.e_tag)
except Exception as ex:
logger.exception('Error when fetting comment')
continue
return (comments, etags)
def handle_s3_object_event(event, context):
'''
This event handler fires when a file is added or removed from the bucket.
It triggers a rebuild of the appropriate index file.
'''
obj = event['Records'][0]['s3']['object']
directory, file_name = obj['key'].rsplit('/', 1)
# if this file is in not in a comments/<slug>/ directory,
# do not process
if not directory.startswith('comments/'):
return
_, slug = directory.split('/', 1)
index_slug(slug)
def index_slug(slug):
comments, etags = get_comments_from_bucket(slug)
etag = bytes('.'.join(etags), encoding='utf8')
etag = hashlib.md5(etag).hexdigest()
data = {
'comments': comments,
'etag': etag,
}
bucket.put_object(
Key='indexes/%s.json' % slug,
Body=bytes(json.dumps(data), encoding='utf8'),
ACL='public-read',
ContentType='application/json',
)
if __name__ == '__main__':
app.run(debug=True)
``` |
{
"source": "joealcorn/PyPaste",
"score": 2
} |
#### File: joealcorn/PyPaste/fabfile.py
```python
from getpass import getpass
import os
from glob import glob
from fabric.api import task, env, cd, run, local, prefix
from PyPaste.models.pastes import Paste
from PyPaste.models.users import User
from PyPaste.utils import create_paste_url
env.hosts = ['paste.buttscicl.es']
@task
def deploy(remote='origin', branch='master'):
with cd('~/projects/PyPaste/'):
run('git pull %s %s' % (remote, branch))
with prefix('source ~/venvs/pypaste/bin/activate'):
run('pip install -r requirements.txt')
run('pkill -f --signal HUP "gunicorn: master \[PyPaste\]"')
@task
def test():
os.environ['PYPASTE_TESTING'] = '1'
local('nosetests -v')
os.environ.pop('PYPASTE_TESTING')
@task
def highlight_examples():
extensions = {
'py': 'python',
'json': 'json'
}
files = glob('/home/joe/git/PyPaste/PyPaste/views/api/v1/templates/examples/*')
files = [f for f in files if not f.endswith('.html')]
for f in files:
extension = f.rsplit('.', 1)[1]
local('{pygments} -f html -l {ext} -O {opt} -o {output} {input}'.format(
pygments='/home/joe/.venvs/pypaste/bin/pygmentize',
ext=extensions[extension],
opt='linenos=1,lineanchors=line,anchorlinenos=1',
input=f,
output=f.replace('.' + extension, '.html')
))
@task
def add_user(username=None):
if username is None:
username = raw_input('Username: ')
password = getpass('Password: ')
if User.new(username, password):
print 'Success.'
else:
print 'Failure, try again.'
@task
def shortlink_backfill():
cur = Paste._cursor()
cur.execute(
"""
SELECT * from pastes
WHERE shortlink is null
"""
)
pastes = cur.fetchall()
for paste in pastes:
if paste['unlisted']:
url = 'https://paste.buttscicl.es/u/' + paste['hash']
else:
url = 'https://paste.buttscicl.es/p/' + str(paste['id'])
shortlink = Paste.get_shortlink(url)
if shortlink is not None:
cur.execute(
"""
UPDATE pastes SET shortlink = %s
WHERE hash = %s
""", (shortlink, paste['hash'])
)
Paste.conn.commit()
print 'Done #' + str(paste['id'])
cur.close()
```
#### File: PyPaste/models/__init__.py
```python
from os import environ
import bcrypt
import psycopg2
from psycopg2.extras import DictCursor
from psycopg2.extensions import register_type, UNICODE
from PyPaste import config
class BaseModel(object):
"""
Base class for both models providing
some useful shared methods
"""
db = config.PG_DB
if environ.get('PYPASTE_TESTING'):
# Tests are being run,
# use a seperate db
db = 'pypastetesting'
conn = psycopg2.connect(
database=db,
user=config.PG_USER,
password=config.PG_PASSWORD,
host=config.PG_HOST,
port=config.PG_PORT
)
@classmethod
def _cursor(self):
"""
Returns a psycopg2 DictCursor
"""
cur = self.conn.cursor(cursor_factory=DictCursor)
register_type(UNICODE, cur)
return cur
@classmethod
def _by_param(self, param, value, table='pastes', fetch_all=False):
"""
Executes SQL query equivalent to
'SELECT * FROM $table WHERE $param = $value'
Only trusted input should be used for $table and $param
"""
cur = self._cursor()
# Although we should never use string
# formatting techniques on sql strings,
# it's OK here because only $value is
# untrusted
cur.execute(
'SELECT * FROM {0} WHERE {1} = %s'.format(table, param),
(value,)
)
if fetch_all:
result = cur.fetchall()
else:
result = cur.fetchone()
cur.close()
return result
@staticmethod
def _hash_password(password, hashed=None):
if hashed is None:
# First time a pw has been hashed, gen a salt
return bcrypt.hashpw(password, bcrypt.gensalt())
else:
return bcrypt.hashpw(password, hashed)
@classmethod
def _password_match(self, attr, password, _type='paste'):
"""
Checks if $password is the correct password for $attr.
$attr should be a paste_id or username
$_type should be set to 'user' or 'paste' respectively
$password should be plaintext.
"""
if _type == 'paste':
thing = self.by_hash(attr)
elif _type == 'user':
thing = self.by_username(attr)
if thing is None:
return False
current = thing['password']
if not self._hash_password(password, current) == current:
return False
return True
```
#### File: api/legacy/__init__.py
```python
from flask import Blueprint, request, jsonify
from PyPaste.utils import create_paste_url
from PyPaste.models.pastes import Paste
legacy = Blueprint('legacy', __name__)
@legacy.route('/api/add', methods=['POST'])
def add():
form = request.form
errors = []
if form.get('unlisted', type=int) in (0, 1):
unlisted = bool(form.get('unlisted', type=int))
else:
unlisted = False
paste = {
'text': form.get('contents'),
'title': form.get('title'),
'password': form.get('password'),
'unlisted': unlisted,
'language': form.get('language', 'text')
}
if paste['text'] is None:
errors.append('No contents specified')
if paste['unlisted'] not in (True, False):
errors.append(
"Invalid value: (unlisted: '{0}')".format(paste['unlisted'])
)
if errors:
return jsonify(
success=False,
url=None,
password=None,
error=errors
)
p = Paste.new(**paste)
if p is None:
return jsonify(
success=False,
url=None,
password=None,
error=errors
)
return jsonify(
success=True,
url=create_paste_url(p),
password=paste['password']
)
```
#### File: views/pastes/__init__.py
```python
from flask import (
abort,
Blueprint,
flash,
make_response,
redirect,
request,
render_template,
session,
)
from PyPaste.utils import pypaste_url_for as url_for
from PyPaste.forms import NewPaste, PastePassword
from PyPaste.models.pastes import Paste
pastes = Blueprint('pastes', __name__, template_folder='templates')
@pastes.route('/', methods=['GET', 'POST'])
def index():
form = NewPaste()
if form.validate_on_submit():
# WTForms passes '' for empty text values,
# this lambda switches them to None
f = lambda s: s if s != '' else None
vals = {
'text': form.paste.data,
'title': f(form.title.data),
'language': f(form.language.data),
'password': f(<PASSWORD>.password.data),
'unlisted': f(form.unlisted.data)
}
paste = Paste.new(**vals)
if paste is None:
return redirect(url_for('pastes.index'))
else:
authorise_viewing(paste['hash'])
if paste['unlisted']:
url = url_for('pastes.unlisted', paste_hash=paste['hash'])
else:
url = url_for('pastes.public', paste_id=paste['id'])
return redirect(url)
elif request.method == 'POST':
# Form submitted but failed validation
for field, error in form.errors.items():
errormsg = '{0}: {1}'.format(field, error[0])
flash(errormsg, 'error')
return render_template('index.html', form=form)
@pastes.route('/p/authorise', methods=['POST'])
def submit_password():
form = PastePassword()
if form.validate_on_submit():
p_hash = form.paste_hash.data
password = form.password.data
if Paste.password_match(p_hash, password):
# Password correct, add paste hash to authorised_pastes
authorise_viewing(p_hash)
else:
# Todo: log & cap number of incorrect tries
flash('Incorrect password', 'error')
return redirect(form.redirect.data)
else:
return redirect(form.redirect.data)
@pastes.route('/p/<int:paste_id>/')
@pastes.route('/p/<int:paste_id>/<raw>/')
def public(paste_id, raw=None):
return view_paste(False, paste_id, raw)
@pastes.route('/u/<paste_hash>/')
@pastes.route('/u/<paste_hash>/<raw>/')
def unlisted(paste_hash, raw=None):
return view_paste(True, paste_hash, raw)
@pastes.route('/recent')
def recent():
if session.get('logged_in'):
pastes = Paste.recent(include_unlisted=True)
else:
pastes = Paste.recent()
return render_template(
'recent.html',
pastes=pastes,
title='recent pastes'
)
def authorise_viewing(p_hash):
if not 'authorised_pastes' in session:
session['authorised_pastes'] = []
session['authorised_pastes'].append(p_hash)
session.modified = True
def view_paste(unlisted, attr, raw=None):
if unlisted:
paste = Paste.by_hash(attr)
else:
paste = Paste.by_id(attr)
if paste is None or paste['unlisted']:
abort(404)
if paste is None:
abort(404)
# Check if paste is password protected, and if so,
# whether the client is allowed to access it or not
authorised = session.get('authorised_pastes', [])
if (
paste['password'] is not None and
paste['hash'] not in authorised
):
return render_template(
'enter_password.html',
paste=paste,
form=PastePassword()
), 401
if raw is not None:
r = make_response(paste['text'])
r.mimetype = 'text/plain'
return r
return render_template(
'view_paste.html',
title=paste['title'],
paste=paste,
)
``` |
{
"source": "joealcorn/TweetPoster",
"score": 3
} |
#### File: TweetPoster/TweetPoster/__init__.py
```python
import json
import time
import sqlite3
from os import path, environ
import requests
from raven import Client
from TweetPoster import utils
from TweetPoster.signals import pre_request
def load_config():
config = json.loads(open('config.json').read())
for key in config['twitter'].keys():
if environ.get(key):
config['twitter'][key] = environ[key]
return config
config = load_config()
sentry = Client(config['sentry'].get('dsn', ''), processors=(
'TweetPoster.utils.SanitizeCredentialsProcessor',
))
template_path = path.dirname(path.realpath(__file__)) + '/templates/'
class Database(object):
@property
def conn(self):
if not hasattr(self, '_connection'):
self._connection = sqlite3.connect(config['database'])
return self._connection
def cursor(self):
return self.conn.cursor()
def init(self, clean=False):
cur = self.cursor()
if clean:
cur.execute('DROP TABLE IF EXISTS posts')
cur.execute(
'CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY ASC, thing_id TEXT UNIQUE)'
)
self.conn.commit()
def has_processed(self, thing_id):
c = self.cursor()
c.execute('SELECT thing_id FROM posts WHERE thing_id = ?', (thing_id,))
return c.fetchone() is not None
def mark_as_processed(self, thing_id):
c = self.cursor()
c.execute('INSERT INTO posts (thing_id) VALUES (?)', (thing_id,))
self.conn.commit()
class User(object):
"""
Base user object that takes care of making requests
"""
timeout = 3
headers = {
'User-Agent': 'https://github.com/buttscicles/TweetPoster'
}
def __init__(self):
self.session = requests.session()
def get(self, url, **kw):
"""
Shortcut function to make a GET request as authed user.
"""
return self.request(url, 'GET', **kw)
def post(self, url, data, **kw):
"""
Shortcut function to make a POST request as authed user.
"""
return self.request(url, 'POST', data=data)
def request(self, url, method, **kw):
"""
Makes a request as the authenticated user.
All keyword arguments are passed directly to requests
"""
assert method in ('POST', 'GET'), 'Unsupported HTTP Method'
kw['timeout'] = self.timeout
if 'headers' in kw:
# Merge self.headers with headers passed in
# The passed in headers take preference
kw['headers'] = dict(self.headers.items() + kw['headers'].items())
else:
kw['headers'] = self.headers
# Send a pre-request signal.
# This allows us to abide by different
# ratelimits for different user accounts.
pre_request.send(self)
if method == 'POST':
return self.session.post(url, **kw)
elif method == 'GET':
return self.session.get(url, **kw)
def main():
from TweetPoster.reddit import Redditor
from TweetPoster.twitter import Twitter
db = Database()
db.init()
twitter = Twitter()
reddit = Redditor().login(
config['reddit']['username'],
config['reddit']['password']
)
while True:
try:
posts = reddit.get_new_posts(db)
for post in posts:
handle_submission(post, twitter, reddit)
except KeyboardInterrupt:
import sys
sys.exit(0)
except requests.exceptions.Timeout:
# These are exceptions we don't
# want to tell sentry about
pass
except:
sentry.captureException()
finally:
print 'sleeping'
time.sleep(90)
def handle_submission(post, twitter, reddit):
url = twitter.tweet_re.match(post.url)
if not url:
# This post links to the twitter domain
# but not to a tweet or picture
post.mark_as_processed()
return
tweet_id = url.group(1)
try:
tweet = twitter.get_tweet(tweet_id)
except AssertionError as e:
code = e.args[0]
if code == 429:
# We've hit Twitter's ratelimit
print 'Ratelimited by Twitter, sleeping for 15 minutes'
time.sleep(60 * 15)
elif code == 404:
post.mark_as_processed()
return
if utils.tweet_in_title(tweet, post):
print 'Tweet in title, skipping'
post.mark_as_processed()
return
with open(template_path + 'footer.txt') as f:
footer_markdown = f.read().format(**post.__dict__)
tweets = []
while True:
tweets.insert(0, tweet.markdown)
if tweet.reply_to is None:
break
else:
tweet = tweet.reply_to
tweets_markdown = '\n'.join(tweets)
full_comment = tweets_markdown + footer_markdown
reddit.comment(post.fullname, full_comment)
post.mark_as_processed()
```
#### File: TweetPoster/TweetPoster/reddit.py
```python
import time
from socket import timeout
from requests.exceptions import RequestException
from TweetPoster import User, Database
from TweetPoster.signals import pre_request
db = Database()
class Redditor(User):
authenticated = False
last_request = None
def __init__(self, bypass_ratelimit=False, *a, **kw):
super(Redditor, self).__init__(*a, **kw)
if not bypass_ratelimit:
pre_request.connect(self._ratelimit, sender=self)
def login(self, username, password):
"""
Logs a user in, stores modhash in Redditor.modhash
"""
login_url = 'https://ssl.reddit.com/api/login'
params = {
'passwd': password,
'rem': False,
'user': username,
'api_type': 'json',
}
print 'Logging in...'
r = self.post(login_url, params)
if 'data' not in r.json()['json']:
raise Exception('login failed')
self.modhash = r.json()['json']['data']['modhash']
self.authenticated = True
return self
def comment(self, thing_id, comment):
"""
Replies to :thing_id: with :comment:
"""
url = 'http://www.reddit.com/api/comment'
params = {
'uh': self.modhash,
'thing_id': thing_id,
'comment': comment,
'api_type': 'json',
}
print 'Commenting on ' + thing_id
return self.post(url, params)
def get_new_posts(self, db=db):
"""
Returns a list of posts that haven't already
been processed
"""
print 'Fetching new posts...'
url = 'http://www.reddit.com/domain/twitter.com/new.json'
try:
r = self.get(url, params=dict(limit=100))
assert r.status_code == 200
all_posts = r.json()['data']['children']
except (RequestException, ValueError, AssertionError, timeout):
return []
posts = [
Submission(p) for p in all_posts
if not db.has_processed(p['data']['name'])
]
return posts
def _ratelimit(self, sender):
"""
Helps us abide by reddit's API usage limitations.
https://github.com/reddit/reddit/wiki/API#rules
"""
if self.last_request is not None:
diff = time.time() - self.last_request
if diff < 2:
time.sleep(2 - diff)
self.last_request = time.time()
class Submission(object):
def __init__(self, json):
self.title = json['data']['title']
self.url = json['data']['url']
self.id = json['data']['id']
self.fullname = json['data']['name']
def mark_as_processed(self, db=db):
db.mark_as_processed(self.fullname)
```
#### File: TweetPoster/test/test_twitter.py
```python
from os import path
import httpretty
from nose.plugins.attrib import attr
from TweetPoster.twitter import Twitter
json_dir = path.dirname(path.realpath(__file__)) + '/json/'
tweet_url = 'https://api.twitter.com/1.1/statuses/show.json'
def mock_tweet():
f = open(json_dir + 'tweet.json')
body = f.read()
f.close()
httpretty.register_uri(
httpretty.GET,
tweet_url,
body=body,
content_type='application/json'
)
@httpretty.activate
def test_oauth():
mock_tweet()
Twitter().get_tweet('347087814833344512')
req = httpretty.last_request()
assert 'Authorization' in req.headers
assert 'oauth_token="' in req.headers['Authorization']
assert 'oauth_consumer_key="' in req.headers['Authorization']
@attr('network')
def test_get_tweet():
t = Twitter().get_tweet('352056725160988672')
assert t.id == 352056725160988672
assert isinstance(t.markdown, unicode)
@attr('network')
def test_unicode_tweet():
Twitter().get_tweet('351969339991277568')
``` |
{
"source": "JoeAmmar/curate_science",
"score": 2
} |
#### File: curate/migrations/0036_author_name.py
```python
from django.db import migrations, models
def touch_authors(apps, schema_editor):
Author = apps.get_model('curate', 'Author')
for instance in Author.objects.all():
instance.name = ' '.join(
[x for x in [instance.first_name, instance.middle_name, instance.last_name]
if x is not None]
)
instance.save() # Will trigger name update
class Migration(migrations.Migration):
dependencies = [
('curate', '0035_auto_20190224_2214'),
]
operations = [
migrations.AddField(
model_name='author',
name='name',
field=models.CharField(null=True, blank=True, max_length=255),
),
migrations.RunPython(
touch_authors,
migrations.RunPython.noop,
)
]
```
#### File: curate_science/curate/models.py
```python
from django.db import models
from django.db.models.signals import pre_save
from django.shortcuts import reverse
from django.contrib.auth.models import User, Group
from django.contrib.postgres.fields import JSONField
from autoslug import AutoSlugField
import re
import os
from io import BytesIO
from django.db import models
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage as storage
from PIL import Image
from django.conf import settings
from invitations.models import Invitation
import datetime
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
# Creation flows
#
# 1. User signs up on their own
# 2. Admin invites user
# 3. Admin creates author page then invites the user
# Auto-fill User's username with e-mail on save
@receiver(pre_save, sender=User)
def fill_username_with_email(sender, instance, **kwargs):
instance.username = instance.email
# When a User is created, find an Author with matching e-mail and link if exists
@receiver(post_save, sender=User)
def link_user_to_author(sender, instance, created, **kwargs):
if created and not hasattr(instance, 'author'):
invite = Invitation.objects.filter(email=instance.email).first()
if invite and hasattr(invite, 'author'):
invite.author.user = instance
invite.author.save()
else:
Author.objects.create(user=instance, name=instance.first_name)
def populate_slug(instance):
return ' '.join(
[x for x in [instance.first_name, instance.middle_name, instance.last_name]
if x is not None]
)
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT, null=True)
orcid = models.CharField(max_length=255, null=True, blank=True)
position_title = models.CharField(max_length=255, null=True, blank=True)
affiliations = models.CharField(max_length=255, null=True, blank=True)
profile_urls = JSONField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
articles = models.ManyToManyField('Article', related_name='authors', blank=True)
curation_contributions = JSONField(null=True, blank=True)
browsing_history = JSONField(null=True, blank=True)
tracked_content = JSONField(null=True, blank=True)
recommended_content = JSONField(null=True, blank=True)
account_settings = JSONField(null=True, blank=True)
research_interests = JSONField(null=True, blank=True)
invite = models.OneToOneField(Invitation, on_delete=models.DO_NOTHING, null=True)
name = models.CharField(max_length=255, null=True, blank=True)
slug = AutoSlugField(
populate_from = 'name',
unique=True,
editable=True,
null=True,
)
is_activated = models.BooleanField(default=False)
def __str__(self):
return self.name if self.name else "Unnamed Author"
class Article(models.Model):
"""A written work with one or more Authors, reporting the results of a scientific Study."""
ORIGINAL = 'ORIGINAL'
CONCEPTUAL = 'CONCEPTUAL'
REPLICATION = 'REPLICATION'
REPRODUCIBILITY = 'REPRODUCIBILITY'
META_ANALYSIS = 'META_ANALYSIS'
META_RESEARCH = 'META_RESEARCH'
ORIGINAL_META_RESEARCH = 'ORIGINAL_META_RESEARCH'
COMMENTARY = 'COMMENTARY'
BASIC_4_7_RETROACTIVE = 'BASIC_4_7_RETROACTIVE'
BASIC_4_AT_SUBMISSION = 'BASIC_4_AT_SUBMISSION'
CONSORT_SPI = 'CONSORT_SPI'
CONSORT = 'CONSORT'
JARS = 'JARS'
STROBE = 'STROBE'
ARRIVE = 'ARRIVE'
NATURE_NEUROSCIENCE = 'NATURE_NEUROSCIENCE'
MARS = 'MARS'
PRISMA = 'PRISMA'
PRISMA_P = 'PRISMA_P'
SOCIAL_SCIENCE = 'SOCIAL_SCIENCE'
MEDICAL_LIFE_SCIENCE = 'MEDICAL_LIFE_SCIENCE'
standards_choices = (
(BASIC_4_7_RETROACTIVE, "Basic 4/Basic 7 (retroactive)"),
(BASIC_4_AT_SUBMISSION, "Basic-4 (at submission; PSCI, 2014)"),
(CONSORT_SPI, "CONSORT-SPI (2018)"),
(CONSORT, "CONSORT (2010)"),
(JARS, "JARS (2018)"),
(STROBE, "STROBE (2007)"),
(ARRIVE, "ARRIVE (2010)"),
(NATURE_NEUROSCIENCE, "Nature Neuroscience (2015)"),
(MARS, "MARS (2018)"),
(PRISMA, "PRISMA (2009)"),
(PRISMA_P, "PRISMA-P (2015)")
)
PREREG_STUDY_DESIGN_ANALYSIS = "PREREG_STUDY_DESIGN_ANALYSIS"
PREREG_STUDY_DESIGN = "PREREG_STUDY_DESIGN"
REGISTERED_REPORT = "REGISTERED_REPORT"
prereg_choices = (
(PREREG_STUDY_DESIGN_ANALYSIS, "Preregistered study design + analysis"),
(PREREG_STUDY_DESIGN, "Preregistered study design"),
(REGISTERED_REPORT, "Registered report"),
)
PROPRIETARY = 'PROP'
ETHICAL = 'ETHI'
nontransparency_reason_choices = (
(PROPRIETARY, 'Proprietary/IP'),
(ETHICAL, 'Ethical reasons'),
)
doi = models.CharField(max_length=255, null=True, blank=True, unique=True)
journal = models.CharField(max_length=255, null=True, blank=True)
author_list = models.CharField(max_length=255, null=True, blank=True)
year = models.PositiveIntegerField(null=True, blank=True)
in_press = models.BooleanField(default=False)
title = models.CharField(max_length=255)
abstract = models.TextField(null=True, blank=True, max_length=4000)
keywords = models.CharField(max_length=255, null=True, blank=True)
article_type = models.CharField(
max_length=255,
choices=(
(ORIGINAL, 'original'),
(CONCEPTUAL, 'conceptual'),
(REPLICATION, 'replication'),
(REPRODUCIBILITY, 'reanalysis - reproducibility'),
(META_ANALYSIS, 'reanalysis - meta-analysis'),
(META_RESEARCH, 'reanalysis - meta-research'),
(ORIGINAL_META_RESEARCH, 'original - meta-research'),
(COMMENTARY, 'commentary'),
),
default='original'
)
reporting_standards_type = models.CharField(
max_length=255,
null=True,
blank=True,
choices=standards_choices,
default=BASIC_4_7_RETROACTIVE,
)
number_of_reps = models.PositiveIntegerField(default=0)
original_study = models.CharField(max_length=255, null=True, blank=True)
target_effects = models.CharField(max_length=255, null=True, blank=True)
original_article_url = models.URLField(null=True, blank=True, max_length=1000)
prereg_protocol_type = models.CharField(max_length=255, choices=prereg_choices, null=True, blank=True)
pdf_url = models.URLField(null=True, blank=True, max_length=1000)
html_url = models.URLField(null=True, blank=True, max_length=1000)
preprint_url = models.URLField(null=True, blank=True, max_length=1000)
research_area = models.CharField(max_length=255,
choices=(
(SOCIAL_SCIENCE, 'Social Science'),
(MEDICAL_LIFE_SCIENCE, 'Medical/Life Science'),
),
default=SOCIAL_SCIENCE
)
pdf_citations = models.PositiveIntegerField(default=0)
pdf_downloads = models.PositiveIntegerField(default=0)
pdf_views = models.PositiveIntegerField(default=0)
html_views = models.PositiveIntegerField(default=0)
preprint_downloads = models.PositiveIntegerField(default=0)
preprint_views = models.PositiveIntegerField(default=0)
author_contributions = models.TextField(null=True, blank=True)
competing_interests = models.TextField(null=True, blank=True)
funding_sources = models.TextField(max_length=4000, null=True, blank=True)
peer_review_editor = models.CharField(max_length=255, null=True, blank=True)
peer_reviewers = models.CharField(max_length=255, null=True, blank=True)
peer_review_url = models.URLField(null=True, blank=True, max_length=1000)
is_live = models.BooleanField(default=True)
under_peer_review = models.BooleanField(default=False)
reproducibility_original_study = models.CharField(max_length=255, null=True, blank=True)
reproducibility_original_study_url = models.URLField(null=True, blank=True, max_length=1000)
commentary_target = models.CharField(max_length=255, null=True, blank=True)
commentary_target_url = models.URLField(null=True, blank=True, max_length=1000)
excluded_data = models.TextField(null=True, blank=True)
excluded_data_all_details_reported = models.BooleanField(default=False)
conditions = models.TextField(null=True, blank=True)
conditions_all_details_reported = models.BooleanField(default=False)
outcomes = models.TextField(null=True, blank=True)
outcomes_all_details_reported = models.BooleanField(default=False)
sample_size = models.TextField(null=True, blank=True)
sample_size_all_details_reported = models.BooleanField(default=False)
analyses = models.TextField(null=True, blank=True)
analyses_all_details_reported = models.BooleanField(default=False)
unreported_studies = models.TextField(null=True, blank=True)
unreported_studies_all_details_reported = models.BooleanField(default=False)
other_disclosures = models.TextField(null=True, blank=True)
other_disclosures_all_details_reported = models.BooleanField(default=False)
disclosure_date = models.DateField(null=True, blank=True, auto_now_add=True)
materials_nontransparency_reason = models.CharField(
max_length=4,
choices=nontransparency_reason_choices,
null=True,
blank=True
)
data_nontransparency_reason = models.CharField(
max_length=4,
choices=nontransparency_reason_choices,
null=True,
blank=True
)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
year = self.year or "In Press"
return f"{self.author_list} ({year}) {self.title}"
def get_absolute_url(self):
return reverse('view-article', args=[str(self.id)])
class Meta:
unique_together=('title', 'year')
def _check_basic_7_fields(self):
BASIC_7_FIELDS = [
('excluded_data', 'excluded_data_all_details_reported'),
('conditions', 'conditions_all_details_reported'),
('outcomes', 'outcomes_all_details_reported'),
('sample_size', 'sample_size_all_details_reported'),
('analyses', 'analyses_all_details_reported'),
('unreported_studies', 'unreported_studies_all_details_reported'),
('other_disclosures', 'other_disclosures_all_details_reported'),
]
def check_field_pair(field_pair):
# If either field is truthy (non-empty text field or True boolean) we return True
(text_field, bool_field) = field_pair
if getattr(self, text_field):
return True
return getattr(self, bool_field) is True
return [check_field_pair(field_pair) for field_pair in BASIC_7_FIELDS]
@property
def is_basic_4_retroactive(self):
if self.reporting_standards_type != self.BASIC_4_7_RETROACTIVE:
return False
fields_done = self._check_basic_7_fields()
return all(fields_done[:4]) and not all(fields_done)
@property
def is_basic_7_retroactive(self):
if self.reporting_standards_type != self.BASIC_4_7_RETROACTIVE:
return False
fields_done = self._check_basic_7_fields()
return all(fields_done)
class TransparencyURL(models.Model):
DATA = 'DATA'
CODE = 'CODE'
MATERIALS = 'MATERIALS'
PREREG = 'PREREGISTRATION'
transparency_type_choices = (
(DATA, 'Data'),
(CODE, 'Code'),
(MATERIALS, 'Materials'),
(PREREG, 'Preregistration'),
)
article = models.ForeignKey(
Article,
on_delete=models.CASCADE,
related_name='transparency_urls',
null=True,
blank=True
)
transparency_type = models.CharField(
max_length=255,
null=True,
blank=True,
choices=transparency_type_choices
)
protected_access = models.BooleanField(default=False)
url = models.URLField(blank=True, max_length=1000)
def __str__(self):
protected_string = ' - PROTECTED' if self.protected_access else ''
return f'{self.transparency_type}: {self.url}{protected_string}'
class MediaCoverage(models.Model):
article = models.ForeignKey(
Article,
on_delete=models.CASCADE,
related_name='media_coverage',
)
media_source_name = models.CharField(max_length=255)
url = models.URLField(null=True, blank=True, max_length=1000)
def __str__(self):
url = self.url or 'No URL'
return f'{self.media_source_name} ({url})'
class Video(models.Model):
article = models.ForeignKey(
Article,
on_delete=models.CASCADE,
related_name='videos',
)
url = models.URLField(max_length=1000)
def __str__(self):
return self.url
class Presentation(models.Model):
article = models.ForeignKey(
Article,
on_delete=models.CASCADE,
related_name='presentations',
)
url = models.URLField(max_length=1000)
def __str__(self):
return self.url
class SupplementalMaterials(models.Model):
article = models.ForeignKey(
Article,
on_delete=models.CASCADE,
related_name='supplemental_materials',
)
url = models.URLField(max_length=1000)
def __str__(self):
return self.url
class KeyFigure(models.Model):
article = models.ForeignKey(Article,
on_delete=models.CASCADE,
related_name='key_figures',
null=True,
blank=True)
height = models.PositiveIntegerField(null=True)
width = models.PositiveIntegerField(null=True)
thumb_height = models.PositiveIntegerField(null=True)
thumb_width = models.PositiveIntegerField(null=True)
image = models.ImageField(
upload_to='key_figures/',
null=True,
height_field='height',
width_field='width',
)
thumbnail = models.ImageField(
upload_to='key_figures/',
null=True,
height_field='thumb_height',
width_field='thumb_width',
)
def save(self, *args, **kwargs):
"""
Make and save the thumbnail for the photo here.
"""
super(KeyFigure, self).save(*args, **kwargs)
self.make_thumbnail()
#if not self.make_thumbnail():
# raise Exception('File not one of supported image file types: JPEG, GIF, PNG')
def make_thumbnail(self):
fh = storage.open(self.image.name, 'rb')
try:
image = Image.open(fh)
except:
return False
image.thumbnail(settings.THUMB_SIZE, Image.ANTIALIAS)
fh.close()
# Path to save to, name, and extension
thumb_name, thumb_extension = os.path.splitext(self.image.name)
_, thumb_fname = os.path.split(thumb_name)
thumb_extension = thumb_extension.lower()
thumb_filename = thumb_fname + '_thumb' + thumb_extension
if thumb_extension in ['.jpg', '.jpeg']:
FTYPE = 'JPEG'
elif thumb_extension == '.gif':
FTYPE = 'GIF'
elif thumb_extension == '.png':
FTYPE = 'PNG'
else:
return False # Unrecognized file type
# Save thumbnail to in-memory file as StringIO
temp_thumb = BytesIO()
image.save(temp_thumb, FTYPE)
temp_thumb.seek(0)
# Load a ContentFile into the thumbnail field so it gets saved
self.thumbnail.save(thumb_filename, ContentFile(temp_thumb.read()), save=False)
temp_thumb.close()
return True
class Commentary(models.Model):
article = models.ForeignKey(Article,
on_delete=models.CASCADE,
related_name='commentaries',
null=True,
blank=True)
authors_year = models.CharField(max_length=255,null=True, blank=True)
commentary_url = models.URLField(null=True, blank=True, max_length=1000)
```
#### File: curate_science/curate/test_api.py
```python
from django.test import TestCase
from django.test import Client
from django.contrib.auth.models import User
from rest_framework.test import APIClient
from django.shortcuts import reverse
from django.contrib import auth
from invitations.models import Invitation
import json
from curate import models
from django.conf import settings
import os, shutil
class TestAPIViews(TestCase):
def setUp(self):
self.client = Client()
admin_user = models.User.objects.create(email='<EMAIL>', first_name="<NAME>")
admin_user.set_password('password')
admin_user.is_staff = True
admin_user.save()
user = models.User.objects.create(email='<EMAIL>', first_name="<NAME>")
user.set_password('<PASSWORD>')
user.save()
user2 = models.User.objects.create(email='<EMAIL>', first_name="<NAME>")
user2.set_password('<PASSWORD>')
user2.save()
directory = settings.MEDIA_ROOT + '/key_figures/'
if not os.path.exists(directory):
os.makedirs(directory)
def tearDown(self):
folder = settings.MEDIA_ROOT + '/key_figures/'
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
#elif os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)
# Article tests
# List Articles
def test_anon_can_list_articles_api(self):
self.client=Client()
article_count = len(models.Article.objects.all())
url = reverse('api-list-articles')
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
assert(len(d) == article_count)
assert r.status_code == 200
def test_only_live_articles_are_listed(self):
self.client = Client()
url = reverse('api-list-articles')
live_article = models.Article.objects.create(title='live', is_live=True)
not_live_article = models.Article.objects.create(title='not live', is_live=False)
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
article_ids = [article['id'] for article in d]
self.assertTrue(live_article.id in article_ids)
self.assertTrue(not_live_article.id not in article_ids)
def list_articles_for_author(self):
self.client = Client()
a = Author.objects.first()
article_count = len(a.articles.all())
url = reverse('api-list-articles-for-author', kwargs={'slug': a.slug})
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
assert(len(d) == article_count)
assert r.status_code == 200
# View Articles
def test_anonymous_user_can_view_article_api(self):
self.client=Client()
article = models.Article.objects.first()
url = reverse('api-view-article', kwargs={'pk': article.id})
r = self.client.get(url)
assert r.status_code == 200
assert "title" in r.content.decode('utf-8')
def test_invalid_article_id_404(self):
self.client = Client()
url = reverse('api-view-article', kwargs={'pk': 99999})
r = self.client.get(url)
assert r.status_code == 404
# Create Articles
def test_authenticated_user_can_create_article_with_api(self):
self.client.login(email='<EMAIL>', password='password')
url = reverse('api-create-article')
r = self.client.post(url, {
"doi": "001",
"year": 2018,
"journal": "Science",
"title": "api test article",
"article_type": "ORIGINAL",
"research_area": "SOCIAL_SCIENCE",
"author_list": "<NAME> al",
})
a = models.Article.objects.get(doi="001")
assert a.title == "api test article"
def test_non_admin_user_create_article_linked_to_author(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
u = User.objects.get(email='<EMAIL>')
url = reverse('api-create-article')
r = self.client.post(url, {
"doi": "004",
"year": 2019,
"journal": "Science",
"title": "api test article",
"article_type": "ORIGINAL",
"research_area": "SOCIAL_SCIENCE",
"author_list": "<NAME> al",
"authors": [u.author.id]
})
article = models.Article.objects.get(doi="004")
assert str(article.authors.first()) == 'New User'
# def test_non_admin_author_can_only_update_own_articles(self):
# self.client.login(email='<EMAIL>', password='<PASSWORD>')
# u = User.objects.get(email='<EMAIL>')
# author = models.Author.objects.create(user=u, name='New User')
# article = models.Article.objects.first()
# url = reverse('api-update-article', kwargs={'pk': article.id})
# r = self.client.patch(url, {
# "title": "api test article updated",
# }, content_type="application/json")
# assert r.status_code == 403
def test_create_invalid_article_400(self):
self.client.login(email='<EMAIL>', password='password')
url = reverse('api-create-article')
r = self.client.post(url, {
"journal": "Science",
"title": "api test article",
"article_type": "ORIGINAL",
"research_area": "SOCIAL_SCIENCE",
"authors": [models.Author.objects.first().id,]
})
assert r.status_code == 400
def test_article_year_can_be_in_press(self):
self.client.login(email='<EMAIL>', password='password')
url = reverse('api-create-article')
r = self.client.post(url, {
"doi": "000",
"year": "",
"in_press": True,
"author_list": "LeBel et al",
"journal": "Science",
"title": "api test article",
"article_type": "ORIGINAL",
"research_area": "SOCIAL_SCIENCE",
"authors": [models.Author.objects.first().id,]
})
a = models.Article.objects.get(doi="000")
assert str(a) == "LeBel et al (In Press) api test article"
def test_anonymous_user_cannot_create_article_with_api(self):
self.client=Client()
url = reverse('api-create-article')
r = self.client.post(
url,
{
"doi": "002",
"year": 2018,
"journal": "Science",
"title": "api test article 2",
"article_type": "ORIGINAL",
"research_area": "SOCIAL_SCIENCE",
"authors": [models.Author.objects.first().id,]
},
content_type="application/json"
)
assert r.status_code == 403
def test_authorized_user_can_get_article_create_form(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
url = reverse('api-create-article')
r = self.client.get(url)
assert r.status_code == 200
def test_admin_can_create_article_nested(self):
self.client.login(email='<EMAIL>', password='password')
url = reverse('api-create-article')
r = self.client.post(url, {
"key_figures": [],
"commentaries": [
{
"authors_year": "Tester (2016)",
"commentary_url": "https://curatescience.org/"
}
],
"authors": [1],
"doi": "doi test nested create",
"journal": "",
"author_list": "Beavis and Butthead",
"year": 2019,
"in_press": False,
"title": "title test nested create",
"article_type": "ORIGINAL",
"number_of_reps": 0,
"research_area": "SOCIAL_SCIENCE"
})
assert r.status_code == 201
# Update Articles
def test_authenticated_user_can_edit_article_with_api(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
article=models.Article.objects.first()
user = User.objects.get(email='<EMAIL>')
article.authors.add(user.author)
url = reverse('api-update-article', kwargs={'pk': article.id})
r = self.client.patch(
url, {
"id": article.id,
"html_url": "http://www.curatescience.org/"
},
content_type="application/json")
assert r.status_code == 200
def test_authenticated_user_can_edit_article_empty_doi(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
article=models.Article.objects.first()
user = User.objects.get(email='<EMAIL>')
article.authors.add(user.author)
url = reverse('api-update-article', kwargs={'pk': article.id})
r = self.client.patch(
url, {
"id": article.id,
"doi": "",
"html_url": "http://www.curatescience.org/"
},
content_type="application/json")
d = json.loads(r.content.decode('utf-8'))
updated_doi = d.get('doi')
assert r.status_code == 200
assert bool(updated_doi) == False
def test_anonymous_user_cannot_edit_article_api(self):
self.client=Client()
article=models.Article.objects.first()
url = reverse('api-update-article', kwargs={'pk': article.id})
r = self.client.patch(url, {
"id": article.id,
"keywords": ["testing"]
})
assert r.status_code == 403
def test_update_invalid_article_id_404(self):
self.client=Client()
self.client.login(email='<EMAIL>', password='<PASSWORD>')
url = reverse('api-update-article', kwargs={'pk': 99999})
r = self.client.put(url, {"title": "_"})
assert r.status_code == 404
def test_admin_can_edit_article_nested(self):
self.client.login(email='<EMAIL>', password='password')
article=models.Article.objects.first()
url = reverse('api-update-article', kwargs={'pk': article.id})
r = self.client.patch(
url,
{
"id": article.id,
"commentaries": [
{
"authors_year": "Test",
"commentary_url": "https://www.curatescience.org/",
}
]
},
content_type="application/json")
assert r.status_code == 200
assert article.commentaries.first().authors_year == "Test"
def test_doi_validation_in_article_update(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
article=models.Article.objects.first()
TEST_DOI = '500'
url = reverse('api-update-article', kwargs={'pk': article.id})
r = self.client.patch(
url, {
"id": article.id,
"doi": "http://dx.doi.org/%s" % TEST_DOI
},
content_type="application/json")
d = json.loads(r.content.decode('utf-8'))
updated_doi = d.get('doi')
assert updated_doi == TEST_DOI
def test_doi_validation_in_article_update_doi_unchanged(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
article=models.Article.objects.first()
TEST_DOI = '500'
# First update to test DOI
url = reverse('api-update-article', kwargs={'pk': article.id})
r = self.client.patch(
url, {
"id": article.id,
"doi": TEST_DOI
},
content_type="application/json")
# Second update with same DOI
url = reverse('api-update-article', kwargs={'pk': article.id})
r = self.client.patch(
url, {
"id": article.id,
"doi": TEST_DOI
},
content_type="application/json")
assert r.status_code == 200
d = json.loads(r.content.decode('utf-8'))
updated_doi = d.get('doi')
assert updated_doi == TEST_DOI
# Delete Articles
def test_anon_cannot_delete_article_api(self):
self.client=Client()
article=models.Article.objects.first()
url = reverse('api-delete-article', kwargs={'pk': article.id})
r = self.client.delete(url)
assert r.status_code == 403
def test_user_can_delete_article_if_only_author(self):
new_user = User.objects.get(email='<EMAIL>')
self.client.login(email=new_user.email, password='<PASSWORD>')
new_article = models.Article.objects.create(doi="75643527", year = 1999, title = "New Article")
new_article.authors.add(new_user.author)
url = reverse('api-delete-article', kwargs={'pk': new_article.id})
r = self.client.delete(url)
assert r.status_code == 200
def test_user_cannot_delete_multi_author_article(self):
new_user = User.objects.get(email='<EMAIL>')
new_user_2 = User.objects.get(email='<EMAIL>')
self.client.login(email=new_user.email, password='<PASSWORD>')
new_article = models.Article.objects.create(doi="71564527", year = 2000, title = "New Article 2")
new_article.authors.add(new_user.author)
new_article.authors.add(new_user_2.author)
url = reverse('api-delete-article', kwargs={'pk': new_article.id})
r = self.client.delete(url)
assert r.status_code == 405
def test_admin_can_delete_article_api(self):
self.client.login(email='<EMAIL>', password='password')
url = reverse('api-create-article')
r = self.client.post(url, {
"doi": "003",
"year": 2017,
"journal": "Science",
"title": "api test article 3",
"article_type": "ORIGINAL",
"research_area": "SOCIAL_SCIENCE",
"authors": [models.Author.objects.first().id,]
})
article = models.Article.objects.get(doi="003")
url = reverse('api-delete-article', kwargs={'pk': article.id})
r = self.client.delete(url)
assert r.status_code == 200
assert len(models.Article.objects.filter(id=article.id)) == 0
def test_delete_invalid_article_404(self):
self.client.login(email='<EMAIL>', password='password')
url = reverse('api-delete-article', kwargs={'pk': 9999})
r = self.client.delete(url)
assert r.status_code == 404
# Author tests
# List Authors
def test_anon_can_list_authors_api(self):
self.client=Client()
author_count = len(models.Author.objects.all())
url = reverse('api-list-authors')
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
assert(len(d) == author_count)
assert r.status_code == 200
# View Authors
def test_anon_can_view_author_api(self):
self.client=Client()
author = models.Author.objects.filter(name='<NAME>').first()
url = reverse('api-view-author', kwargs={'slug': author.slug})
r = self.client.get(url)
assert r.status_code == 200
assert "LeBel" in r.content.decode('utf-8')
def test_invalid_author_id_404(self):
self.client = Client()
url = reverse('api-view-author', kwargs={'slug': 'foo'})
r = self.client.get(url)
assert r.status_code == 404
# Create Authors
def test_anon_cannot_create_author_api(self):
self.client=Client()
url = reverse('api-create-author')
r = self.client.post(
url,
{
'name':'test',
},
content_type="application/json"
)
assert r.status_code == 403
def test_user_with_author_cannot_create_another(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
url = reverse('api-create-author')
r = self.client.post(url, {
"name": "<NAME>",
})
assert r.status_code == 403
def test_associated_user_can_update_author_api(self):
self.client=Client()
user = User.objects.get(email='<EMAIL>')
self.client.login(email=user.email, password='<PASSWORD>')
url = reverse('api-update-author', kwargs={'slug': user.author.slug})
r = self.client.patch(
url, {
"name": 'Jimmy'
},
content_type="application/json")
assert r.status_code == 200
def test_other_user_cannot_update_author_api(self):
self.client=Client()
self.client.login(email='<EMAIL>', password='<PASSWORD>')
author=models.Author.objects.first()
url = reverse('api-update-author', kwargs={'slug': author.slug})
r = self.client.patch(url, {
"id": author.id,
"name": "test"
})
assert r.status_code == 401
def test_superuser_create_author(self):
self.client.login(email='<EMAIL>', password='password')
url = reverse('api-create-author')
r = self.client.post(url, {
"name": "<NAME>",
})
a = models.Author.objects.get(name = "<NAME>")
assert a.name == "<NAME>"
assert a.user is None
def test_admin_user_can_get_author_create_form(self):
self.client.login(email='<EMAIL>', password='password')
url = reverse('api-create-author')
r = self.client.get(url)
assert r.status_code == 200
# Update Authors
def test_anon_cannot_edit_author_api(self):
self.client=Client()
author=models.Author.objects.first()
url = reverse('api-update-author', kwargs={'slug': author.slug})
r = self.client.patch(url, {
"id": author.id,
"name": "test"
})
assert r.status_code == 403
def test_authorized_user_can_patch_author(self):
self.client.login(email='<EMAIL>', password='password')
author=models.Author.objects.first()
url = reverse('api-update-author', kwargs={'slug': author.slug})
r = self.client.patch(
url, {
"name": 'Jimmy'
},
content_type="application/json")
assert r.status_code == 200
def test_authorized_user_can_put_author(self):
self.client.login(email='<EMAIL>', password='password')
author=models.Author.objects.first()
url = reverse('api-update-author', kwargs={'slug': author.slug})
r = self.client.put(
url, {
"name": '<NAME>',
},
content_type="application/json")
author=models.Author.objects.first()
assert r.status_code == 200
assert str(author) == '<NAME>'
# Delete Authors
def test_anon_cannot_delete_author_api(self):
self.client=Client()
author=models.Author.objects.first()
url = reverse('api-delete-author', kwargs={'slug': author.slug})
r = self.client.delete(url)
assert r.status_code == 403
def test_user_cannot_delete_author_api(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
author=models.Author.objects.first()
url = reverse('api-delete-author', kwargs={'slug': author.slug})
r = self.client.delete(url)
assert r.status_code == 403
def test_admin_can_delete_author_api(self):
self.client.login(email='<EMAIL>', password='password')
url = reverse('api-create-author')
r = self.client.post(url, {
"name": "<NAME>",
})
author = models.Author.objects.get(name="<NAME>")
url = reverse('api-delete-author', kwargs={'slug': author.slug})
r = self.client.delete(url)
assert auth.get_user(self.client).is_authenticated
assert auth.get_user(self.client).is_staff
assert r.status_code == 200
assert len(models.Author.objects.filter(id=author.id)) == 0
def test_authorized_user_can_create_key_figure(self):
client = APIClient()
client.login(email='<EMAIL>', password='<PASSWORD>')
article = models.Article.objects.first()
url = reverse('api-create-key-figure', kwargs={'article_pk': article.id})
f = open('curate/fixtures/image.jpg', mode='rb')
res = client.put(url, {'file': f})
assert len(article.key_figures.all()) == 1
kf = article.key_figures.first()
assert kf.image is not None
assert kf.thumbnail is not None
assert kf.width == 319
assert kf.height == 400
def test_unauthorized_cannot_create_key_figure(self):
client = APIClient()
article = models.Article.objects.first()
url = reverse('api-create-key-figure', kwargs={'article_pk': article.id})
f = open('curate/fixtures/image.jpg', mode='rb')
res = client.put(url, {'file': f})
assert res.status_code == 403
def test_admin_can_delete_key_figure(self):
client = APIClient()
client.login(email='<EMAIL>', password='password')
article = models.Article.objects.first()
url = reverse('api-create-key-figure', kwargs={'article_pk': article.id})
f = open('curate/fixtures/image.jpg', mode='rb')
res = client.put(url, {'file': f})
kf = article.key_figures.first()
url = reverse('api-delete-key-figure', kwargs={'pk': kf.id})
r = client.delete(url)
assert r.status_code == 200
assert len(article.key_figures.all()) == 0
def test_non_admin_cannot_delete_key_figure(self):
client = APIClient()
client.login(email='<EMAIL>', password='<PASSWORD>')
article = models.Article.objects.first()
url = reverse('api-create-key-figure', kwargs={'article_pk': article.id})
f = open('curate/fixtures/image.jpg', mode='rb')
res = client.put(url, {'file': f})
kf = article.key_figures.first()
url = reverse('api-delete-key-figure', kwargs={'pk': kf.id})
r = client.delete(url)
assert r.status_code == 403
def test_authenticated_user_can_add_media_coverage(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
article = models.Article.objects.create(title='test article')
user = User.objects.get(email='<EMAIL>')
article.authors.add(user.author)
url = reverse('api-update-article', kwargs={'pk': article.id})
coverage = {
"media_source_name": "New York Times",
"url": "https://nyt.com",
}
r = self.client.patch(
url,
{
"id": article.id,
"media_coverage": [coverage]
},
content_type="application/json"
)
self.assertEqual(r.status_code, 200)
d = json.loads(r.content.decode('utf-8'))
self.assertEqual(d['media_coverage'][0]['media_source_name'], coverage['media_source_name'])
self.assertEqual(d['media_coverage'][0]['url'], coverage['url'])
article.refresh_from_db()
media_coverage = article.media_coverage.all()
self.assertEqual(len(media_coverage), 1)
self.assertEqual(media_coverage[0].media_source_name, 'New York Times')
self.assertEqual(media_coverage[0].url, 'https://nyt.com')
def test_authenticated_user_can_add_video_to_article(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
article = models.Article.objects.create(title='test article')
user = User.objects.get(email='<EMAIL>')
article.authors.add(user.author)
url = reverse('api-update-article', kwargs={'pk': article.id})
video = {
"url": "https://youtube.com",
}
r = self.client.patch(
url,
{
"id": article.id,
"videos": [video]
},
content_type="application/json"
)
self.assertEqual(r.status_code, 200)
d = json.loads(r.content.decode('utf-8'))
self.assertEqual(d['videos'][0]['url'], video['url'])
article.refresh_from_db()
videos = article.videos.all()
self.assertEqual(len(videos), 1)
self.assertEqual(videos[0].url, video['url'])
def test_authenticated_user_can_add_presentation_to_article(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
article = models.Article.objects.create(title='test article')
user = User.objects.get(email='<EMAIL>')
article.authors.add(user.author)
url = reverse('api-update-article', kwargs={'pk': article.id})
presentation = {
"url": "https://presentation.com",
}
r = self.client.patch(
url,
{
"id": article.id,
"presentations": [presentation]
},
content_type="application/json"
)
self.assertEqual(r.status_code, 200)
d = json.loads(r.content.decode('utf-8'))
self.assertEqual(d['presentations'][0]['url'], presentation['url'])
article.refresh_from_db()
presentations = article.presentations.all()
self.assertEqual(len(presentations), 1)
self.assertEqual(presentations[0].url, presentation['url'])
def test_authenticated_user_can_add_supplemental_materials_to_article(self):
self.client.login(email='<EMAIL>', password='<PASSWORD>')
article = models.Article.objects.create(title='test article')
user = User.objects.get(email='<EMAIL>')
article.authors.add(user.author)
url = reverse('api-update-article', kwargs={'pk': article.id})
supplemental_materials = {
"url": "https://supplementalmaterials.com",
}
r = self.client.patch(
url,
{
"id": article.id,
"supplemental_materials": [supplemental_materials]
},
content_type="application/json"
)
self.assertEqual(r.status_code, 200)
d = json.loads(r.content.decode('utf-8'))
self.assertEqual(d['supplemental_materials'][0]['url'], supplemental_materials['url'])
article.refresh_from_db()
article_supplemental_materials = article.supplemental_materials.all()
self.assertEqual(len(article_supplemental_materials), 1)
self.assertEqual(article_supplemental_materials[0].url, supplemental_materials['url'])
def test_create_invitation(self):
client = APIClient()
client.login(email='<EMAIL>', password='password')
url = reverse('api-create-invitation')
res = client.post(url, {
"email": "<EMAIL>",
"author": {
"name": "<NAME>"
}
}, format="json")
print(res.content.decode('utf-8'))
assert res.status_code == 201
i = Invitation.objects.get(email="<EMAIL>")
assert i.author.slug == "test-user"
def test_cannot_invite_duplicate_email(self):
client = APIClient()
client.force_authenticate(user = User.objects.get(email="<EMAIL>"))
email = '<EMAIL>'
u = User.objects.create(email=email, first_name='<NAME>')
user_with_same_email = User.objects.filter(email=email).first()
assert user_with_same_email is not None
url = reverse('api-create-invitation')
res = client.post(url, {
"email": email,
"author": {
"name": "<NAME>"
}
}, format="json")
print(res.content.decode('utf-8'))
print(res.status_code)
assert res.status_code == 400
def test_link_article(self):
client = APIClient()
client.login(email='<EMAIL>', password='password')
url = reverse('api-create-article')
r = client.post(url, {
"doi": "005",
"year": 2019,
"journal": "Science",
"title": "api test article 005",
"article_type": "ORIGINAL",
"research_area": "SOCIAL_SCIENCE",
"author_list": "LeBel et al",
"commentaries": [],
"authors": [],
}, format='json')
print(r.content.decode('utf-8'))
self.assertEqual(r.status_code, 201)
article = models.Article.objects.get(doi="005")
author = models.Author.objects.first()
url = reverse('api-link-articles-to-author', kwargs={'slug': author.slug})
r2 = client.post(url, [
{
"article": article.id,
"linked": True,
},
], format='json')
self.assertEqual(r2.status_code, 200)
assert article in author.articles.all()
r3 = client.post(url, [
{
"article": article.id,
"linked": False,
},
], format='json')
assert article not in author.articles.all()
r4 = client.post(url, [
{
"article": 12345,
"linked": True,
},
], format='json')
self.assertEqual(r4.status_code, 400)
# def test_article_search(self):
# self.client.login(email='<EMAIL>', password='<PASSWORD>')
# url = reverse('api-search-articles') + "?q=A"
# r = self.client.get(url)
# d = json.loads(r.content.decode('utf-8'))
# assert r.status_code == 200
# assert d[0].get('title') == "A brief guide to evaluate replications"
# def test_article_search_pagination(self):
# self.client.login(email='<EMAIL>', password='<PASSWORD>')
# url = reverse('api-search-articles') + "?q=LeBel&page_size=2"
# r = self.client.get(url)
# d = json.loads(r.content.decode('utf-8'))
# assert r.status_code == 200
# assert len(d) == 2
def test_api_ordering_by_created(self):
new_article = models.Article.objects.create(title='new article')
url = '{base_url}?ordering=created'.format(base_url=reverse('api-list-articles'))
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
assert d[0]['id'] == new_article.id
created = d[0]['created']
for article in d[1:]:
assert article['created'] <= created
created = article['created']
def test_api_ordering_by_impact(self):
article_impact_100 = models.Article.objects.create(title='100 views', pdf_views=100)
article_impact_10 = models.Article.objects.create(title='10 views', pdf_views=10)
article_impact_5000 = models.Article.objects.create(title='5000 views', pdf_views=5000)
url = '{base_url}?ordering=impact'.format(base_url=reverse('api-list-articles'))
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
article_ids = [article['id'] for article in d]
assert (
article_ids.index(article_impact_10.id) >
article_ids.index(article_impact_100.id) >
article_ids.index(article_impact_5000.id)
)
def _get_filtered_article_ids(self, filters):
filter_query = '&'.join([f'transparency={filter}' for filter in filters])
base_url = reverse('api-list-articles')
url = f'{base_url}?{filter_query}'
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
return [article['id'] for article in d]
def test_api_list_filtering_open_code(self):
new_article = models.Article.objects.create(title='new article')
assert new_article.id not in self._get_filtered_article_ids(['open_code'])
models.TransparencyURL.objects.create(
article=new_article, transparency_type=models.TransparencyURL.CODE, url='http://example.com'
)
assert new_article.id in self._get_filtered_article_ids(['open_code'])
def test_api_list_filtering_open_data(self):
new_article = models.Article.objects.create(title='new article')
assert new_article.id not in self._get_filtered_article_ids(['open_data'])
models.TransparencyURL.objects.create(
article=new_article, transparency_type=models.TransparencyURL.DATA, url='http://example.com/data'
)
assert new_article.id in self._get_filtered_article_ids(['open_data'])
def test_api_list_filtering_open_materials(self):
new_article = models.Article.objects.create(title='new article')
assert new_article.id not in self._get_filtered_article_ids(['open_materials'])
models.TransparencyURL.objects.create(
article=new_article, transparency_type=models.TransparencyURL.MATERIALS, url='http://example.com/materials'
)
assert new_article.id in self._get_filtered_article_ids(['open_materials'])
def test_api_list_filtering_reporting_standards(self):
new_article = models.Article.objects.create(title='new article', reporting_standards_type=None)
assert new_article.id not in self._get_filtered_article_ids(['reporting_standards'])
new_article.reporting_standards_type = models.Article.BASIC_4_AT_SUBMISSION
new_article.save()
assert new_article.id in self._get_filtered_article_ids(['reporting_standards'])
def test_api_list_filtering_combined_filter(self):
new_article = models.Article.objects.create(title='new article')
open_code_data_article = models.Article.objects.create(title='open code & data')
models.TransparencyURL.objects.bulk_create([
models.TransparencyURL(article=open_code_data_article, transparency_type=models.TransparencyURL.CODE, url='http://example.com/code'),
models.TransparencyURL(article=open_code_data_article, transparency_type=models.TransparencyURL.DATA, url='http://example.com/data'),
])
assert open_code_data_article.id in self._get_filtered_article_ids(['open_code'])
assert open_code_data_article.id in self._get_filtered_article_ids(['open_code', 'open_data'])
assert open_code_data_article.id not in self._get_filtered_article_ids(['open_code', 'open_data', 'open_materials'])
def test_prereg_filtering(self):
def get_filtered_article_ids(filters):
filter_query = '&'.join([f'transparency={filter}' for filter in filters])
base_url = reverse('api-list-articles')
url = f'{base_url}?{filter_query}'
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
return [article['id'] for article in d]
new_article = models.Article.objects.create(title='article')
# Registered design analysis
assert new_article.id not in get_filtered_article_ids(['registered_design_analysis'])
new_article.prereg_protocol_type = models.Article.PREREG_STUDY_DESIGN_ANALYSIS
new_article.save()
assert new_article.id in get_filtered_article_ids(['registered_design_analysis'])
# Multiple values should combine like OR
assert new_article.id in get_filtered_article_ids(['registered_design_analysis', 'registered_report'])
# Registered report
assert new_article.id not in get_filtered_article_ids(['registered_report'])
new_article.prereg_protocol_type = models.Article.REGISTERED_REPORT
new_article.save()
assert new_article.id in get_filtered_article_ids(['registered_report'])
def test_api_list_pagination(self):
# Create 11 new articles
models.Article.objects.bulk_create([models.Article(title=f'Article {i}') for i in range(11)])
# First page should return `page_size` articles
base_url = reverse('api-list-articles')
page_size = 10
url = f'{base_url}?page_size={page_size}'
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
assert len(d) == page_size
# Last page should have the remainder of the articles (e.g. 2 if page_size=10, number_of_articles=12)
number_of_articles = models.Article.objects.count()
last_page = (number_of_articles // page_size) + 1
url += f'&page={last_page}'
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
assert len(d) == number_of_articles % page_size
# Requests for invalid pages should return a 404
url += f'&page={last_page + 1}'
r = self.client.get(url)
assert r.status_code == 404
def test_api_list_content_filtering(self):
new_article = models.Article.objects.create(title='article')
def get_filtered_article_ids(filters):
base_url = reverse('api-list-articles')
query_string = '&content='.join(filters)
url = f'{base_url}?content={query_string}'
r = self.client.get(url)
d = json.loads(r.content.decode('utf-8'))
return [article['id'] for article in d]
# Original
self.assertTrue(new_article.id not in get_filtered_article_ids([models.Article.ORIGINAL]))
new_article.article_type = models.Article.ORIGINAL
new_article.save()
self.assertTrue(new_article.id in get_filtered_article_ids([models.Article.ORIGINAL]))
# Replication
self.assertTrue(new_article.id not in get_filtered_article_ids([models.Article.REPLICATION]))
new_article.article_type = models.Article.REPLICATION
new_article.save()
self.assertTrue(new_article.id in get_filtered_article_ids([models.Article.REPLICATION]))
# Reproducibility
self.assertTrue(new_article.id not in get_filtered_article_ids([models.Article.REPRODUCIBILITY]))
new_article.article_type = models.Article.REPRODUCIBILITY
new_article.save()
self.assertTrue(new_article.id in get_filtered_article_ids([models.Article.REPRODUCIBILITY]))
# Meta-analysis
self.assertTrue(new_article.id not in get_filtered_article_ids([models.Article.META_ANALYSIS]))
new_article.article_type = models.Article.META_ANALYSIS
new_article.save()
self.assertTrue(new_article.id in get_filtered_article_ids([models.Article.META_ANALYSIS]))
# Invalid filter
number_of_articles = models.Article.objects.count()
self.assertEqual(number_of_articles, len(get_filtered_article_ids('nonsense')))
# Multiple filters
new_article.article_type = models.Article.REPRODUCIBILITY
new_article.save()
self.assertTrue(
new_article.id in get_filtered_article_ids([models.Article.META_ANALYSIS, models.Article.REPRODUCIBILITY])
)
self.assertTrue(
new_article.id not in get_filtered_article_ids([models.Article.META_ANALYSIS, models.Article.REPLICATION])
)
def test_api_search_article_title(self):
self.client = Client()
url = reverse('api-search-articles-and-authors')
article = models.Article.objects.create(title='Test Search Article')
r = self.client.get(f'{url}?q=test')
d = json.loads(r.content.decode('utf-8'))
article_ids = [article['id'] for article in d['articles']]
self.assertTrue(article.id in article_ids)
def test_api_search_article_author_list(self):
self.client = Client()
url = reverse('api-search-articles-and-authors')
article = models.Article.objects.create(title='Article', author_list='<NAME>')
r = self.client.get(f'{url}?q=matt')
d = json.loads(r.content.decode('utf-8'))
article_ids = [article['id'] for article in d['articles']]
self.assertTrue(article.id in article_ids)
def test_api_search_article_author(self):
self.client = Client()
url = reverse('api-search-articles-and-authors')
author = models.Author.objects.create(name='<NAME>', is_activated=True)
article = models.Article.objects.create(title='Article')
article.authors.add(author)
r = self.client.get(f'{url}?q=dickens')
d = json.loads(r.content.decode('utf-8'))
article_ids = [article['id'] for article in d['articles']]
self.assertTrue(article.id in article_ids)
def test_api_search_author_name(self):
self.client = Client()
url = reverse('api-search-articles-and-authors')
author = models.Author.objects.create(name='<NAME>', is_activated=True)
r = self.client.get(f'{url}?q=bus')
d = json.loads(r.content.decode('utf-8'))
author_ids = [author['id'] for author in d['authors']]
self.assertTrue(author.id in author_ids)
def test_api_search_author_affiliations(self):
self.client = Client()
url = reverse('api-search-articles-and-authors')
author = models.Author.objects.create(name='Nick', affiliations='UCC', is_activated=True)
r = self.client.get(f'{url}?q=UCC')
d = json.loads(r.content.decode('utf-8'))
author_ids = [author['id'] for author in d['authors']]
self.assertTrue(author.id in author_ids)
def test_api_returns_only_live_articles(self):
live_article = models.Article.objects.create(title='Live Article', author_list='<NAME>', is_live=True)
not_live_article = models.Article.objects.create(title='Test Article', author_list='<NAME>', is_live=False)
url = reverse('api-search-articles-and-authors')
r = self.client.get(f'{url}?q=matt')
d = json.loads(r.content.decode('utf-8'))
article_ids = [article['id'] for article in d['articles']]
self.assertTrue(live_article.id in article_ids)
self.assertTrue(not_live_article.id not in article_ids)
def test_api_returns_only_activated_authors(self):
activated_author = models.Author.objects.create(name='<NAME>', is_activated=True)
not_activated_author = models.Author.objects.create(name='<NAME> Active', is_activated=False)
url = reverse('api-search-articles-and-authors')
r = self.client.get(f'{url}?q=nick')
d = json.loads(r.content.decode('utf-8'))
author_ids = [author['id'] for author in d['authors']]
self.assertTrue(activated_author.id in author_ids)
self.assertTrue(not_activated_author.id not in author_ids)
``` |
{
"source": "JoeanAmiee/Mastering-Python-Design-Patterns-Second-Edition",
"score": 3
} |
#### File: chapter15/cache_aside/populate_db.py
```python
import sys
import sqlite3
import csv
from random import randint
from faker import Faker
fake = Faker()
def setup_db():
try:
db = sqlite3.connect('data/quotes.sqlite3')
# Get a cursor object
cursor = db.cursor()
cursor.execute('''
CREATE TABLE quotes(id INTEGER PRIMARY KEY, text TEXT)
''')
db.commit()
except Exception as e:
print(e)
finally:
db.close()
def add_quotes(quotes_list):
quotes = []
try:
db = sqlite3.connect('data/quotes.sqlite3')
cursor = db.cursor()
quotes = []
for quote_text in quotes_list:
quote_id = randint(1, 100)
quote = (quote_id, quote_text)
try:
cursor.execute('''INSERT INTO quotes(id, text) VALUES(?, ?)''', quote)
quotes.append(quote)
except Exception as e:
print(f"Error with quote id {quote_id}: {e}")
db.commit()
except Exception as e:
print(e)
finally:
db.close()
return quotes
def main():
args = sys.argv
if args[1] == 'init':
setup_db()
elif args[1] == 'update_db_and_cache':
quotes_list = [fake.sentence() for _ in range(1, 11)]
quotes = add_quotes(quotes_list)
print("New (fake) quotes added to the database:")
for q in quotes:
print(f"Added to DB: {q}")
# Populate the cache with this content
with open('data/quotes_cache.csv', "a", newline="") as csv_file:
writer = csv.DictWriter(csv_file,
fieldnames=['id', 'text'],
delimiter=";")
for q in quotes:
print(f"Adding '{q[1]}' to cache")
writer.writerow({'id': str(q[0]), 'text': q[1]})
elif args[1] == 'update_db_only':
quotes_list = [fake.sentence() for _ in range(1, 11)]
quotes = add_quotes(quotes_list)
print("New (fake) quotes added to the database ONLY:")
for q in quotes:
print(f"Added to DB: {q}")
if __name__ == "__main__":
main()
```
#### File: Mastering-Python-Design-Patterns-Second-Edition/chapter15/retry_write_file.py
```python
import time
import sys
import os
def create_file(filename, after_delay=5):
time.sleep(after_delay)
with open(filename, 'w') as f:
f.write('A file creation test')
def append_data_to_file(filename):
if os.path.exists(filename):
with open(filename, 'a') as f:
f.write(' ...Updating the file')
else:
raise OSError
FILENAME = 'file1.txt'
if __name__ == "__main__":
args = sys.argv
if args[1] == 'create':
create_file(FILENAME)
print(f"Created file '{FILENAME}'")
elif args[1] == 'update':
while True:
try:
append_data_to_file(FILENAME)
print("Success! We are done!")
break
except OSError as e:
print("Error... Try again")
```
#### File: Mastering-Python-Design-Patterns-Second-Edition/chapter15/service_first.py
```python
from nameko.rpc import rpc
from faker import Faker
fake = Faker()
class PeopleListService:
name = 'peoplelist'
@rpc
def populate(self, number=20):
names = []
for _ in range(0, number):
n = fake.name()
names.append(n)
return names
```
#### File: Mastering-Python-Design-Patterns-Second-Edition/chapter15/test_service_second.py
```python
from nameko.testing.services import worker_factory
from nameko.standalone.rpc import ClusterRpcProxy
from service_second import PeopleDataPersistenceService
config = {
'AMQP_URI': "pyamqp://guest:[email protected]"
}
def test_peopledata_persist():
with ClusterRpcProxy(config) as cluster_rpc:
out = cluster_rpc.people_data_persistence.save.call_async('people.csv')
print(out.result())
if __name__ == "__main__":
test_peopledata_persist()
``` |
{
"source": "joe-antognini/euler",
"score": 3
} |
#### File: euler/023/23.py
```python
from bisect import bisect_left
maxnum = 28123
#maxnum = 10000
file = open('23.dat', 'r')
abundant = map(int, file.readlines())
file.close()
def binary_search(a, x, lo=0, hi=None):
hi = hi if hi is not None else len(a)
pos = bisect_left(a, x, lo, hi)
return (pos if pos != hi and a[pos] == x else -1)
def calc_total(maxnum, sums):
'''Calculate the total of all numbers not in sums up to maxnum.'''
total = 0
for i in range(maxnum):
if i not in sums:
total += i
return total
def all_sums(maxnum):
'''Perform the calculation by computing every possible sum.'''
i = 0
sums = []
abundant_iter_i = iter(abundant)
abundant_i = abundant_iter_i.next()
while abundant_i < maxnum / 2:
abundant_iter_j = iter(abundant[i:])
abundant_j = abundant_iter_j.next()
while abundant_i + abundant_j < maxnum:
sum = abundant_i + abundant_j
# This may be the bottleneck for the code. Do a binary search instead.
if binary_search(sums, sum) == -1:
#if sum not in sums:
sums.append(sum)
abundant_j = abundant_iter_j.next()
abundant_i = abundant_iter_i.next()
i += 1
return calc_total(maxnum, sums)
def some_sums(maxnum):
'''Perform the calculation by computing whether the sums exist for each
number.'''
no_sum = []
for x in range(maxnum):
abundant_iter = iter(abundant)
while True:
try:
abundant_i = abundant_iter.next()
except StopIteration:
no_sum.append(x)
break
if binary_search(abundant, x - abundant_i) != -1:
break
return sum(no_sum)
print some_sums(maxnum)
```
#### File: euler/193/squarefree.py
```python
from math import sqrt
from sympy import sieve
import time
def count_squarefree(N):
'''Return the number of squarefree integers below N.'''
mobius = [1] * int(sqrt(N))
for p in sieve.primerange(2, int(sqrt(N))):
for i in xrange(p, int(sqrt(N)), p):
mobius[i-1] = -mobius[i-1]
for i in xrange(p**2, int(sqrt(N)), p**2):
mobius[i-1] = 0
return sum([(N / p**2) * mobius[p-1] for p in xrange(1, int(sqrt(N)))])
if __name__ == '__main__':
n = 50
N = 2**n
print "N: 2^%d" % n
start_time = time.time()
print "Answer:", count_squarefree(N)
end_time = time.time()
print "Computing time: %g" % (end_time - start_time)
``` |
{
"source": "joe-antognini/or-wait-times",
"score": 3
} |
#### File: joe-antognini/or-wait-times/or_wait_times.py
```python
import numpy
import sys
def model_ors(n_day_oprooms,
distribution_parameters,
n_night_oprooms=None,
min_dayonly_class=3,
night_length=8,
converge_time=1e5,
experiment_length=2e6,
cleaning_time=60):
'''Run a Monte Carlo simulation of patients moving through a hospital's
operating room system.
Parameters:
n_day_oprooms: int
The number of operating rooms during the day
distribution_parameters: list or tuple
A list or tuple describing the probability distribution of arrival
times and surgery times. This parameter must be as long as the number
of classes. Each element must consist of a list or tuple of three
elements. The first describes the mean arrival rate, the second
describes the mean surgery length, and the third describes the
standard deviation of the surgery length.
n_night_oprooms: int, optional
The number of operating rooms during the night. By default this is
the same as the number of operating rooms during the day.
min_dayonly_class: int, optional
The lowest class that only enters surgery during the day.
night_length: float
The number of hours per day that only night operating rooms are used.
converge_time: float, optional
The number of minutes to discard at the beginning of the program to
let the program converge.
experiment_length: number, optional
The number of minutes to run the experiment (in addition to the
seconds discarded after converge_time)
cleaning_time: number, optional
The number of minutes before and after a surgery that the operating
room is unavailable because it is being prepared or cleaned.
Returns: (results, utilization_results)
results: (priority_class, in_time, time_of_day, wait_time, surgery_time)
priority_class: The class of the patient (e.g., emergent)
in_time: The time the patient entered the emergency room.
time_of_day: Whether the patient entered during the day or night
wait_time: How long the patient had to wait (in minutes)
surgery_time: How long the surgery took (in minutes)
utilization_results: list
Element i of this list is the fraction of times that i operating rooms
are occupied.
Important data structures in this program:
emergent_queue: This is a list of patients in the emergency queue. Each
patient is recorded in the list by the time that the patient arrived.
The list is sorted in order of increasing time. Thus the first
patient in the queue is the patient who has been waiting the longest,
and is the first patient who will be removed from the queue when an
operating room frees up.
urgent1_queue, urgent2_queue, etc.: Identical to emergent_queue, except
for the other classes of patients. These patients are served after
the emergent patients.
operating_rooms: This is a list of all operating rooms currently in use.
Each operating room in use is recorded in this list by the time when
the operating room will be available again.
utilization_frac: This is a list used to calculate how often the
operating rooms are used. The first element of this list is the total
amount of time that exactly zero operating rooms have been in use,
the second element is the total amount of time that exactly one
operating room was in use, etc. The utilization fraction is then
calculated by taking these numbers and dividing by the total length of
the experiment.
'''
if n_night_oprooms is None:
n_night_oprooms = n_day_oprooms
# A few constants
day_to_min = 1440 # Number of minutes in a day
hour_to_min = 60 # Number of minutes in an hour
###
### Typechecking
###
if type(n_day_oprooms) is not int:
raise TypeError('model_ors(): n_day_oprooms must be int!')
elif n_day_oprooms <= 0:
raise ValueError('model_ors(): n_day_oprooms must be positive!')
if type(distribution_parameters) not in (list, tuple):
raise TypeError('distribution_parameters must be tuple!')
for elem in distribution_parameters:
if type(elem) not in (list, tuple):
raise TypeError('model_ors(): ' + str(elem) +
' must be list or tuple')
if len(elem) != 3:
raise ValueError('model_ors(): ' + str(elem) +
' must have exactly three elements!')
for item in elem:
if type(item) not in (int, float, long):
raise TypeError('model_ors(): ' + str(item) + ' in ' + str(elem)
+ ' is not a number!')
elif item < 0:
raise ValueError('model_ors(): ' + str(item) + ' in ' + str(elem)
+ ' must be positive!')
if n_night_oprooms is not None:
if type(n_night_oprooms) is not int:
raise TypeError('model_ors(): n_night_oprooms must be int!')
elif n_night_oprooms > n_day_oprooms:
raise ValueError(\
'model_ors(): n_night_oprooms must be less than n_day_oprooms!')
elif n_night_oprooms < 0:
raise ValueError(\
'model_ors(): n_night_oprooms must be non-negative!')
if type(night_length) not in (int, float, long):
raise TypeError('model_ors(): night_length must be a number!')
elif night_length < 0:
raise ValueError('model_ors(): night_length must be non-negative!')
if type(converge_time) not in (int, float, long):
raise TypeError('model_ors(): converge_time must be a number!')
elif converge_time < 0:
raise ValueError('model_ors(): converge_time must be positive!')
if type(experiment_length) not in (int, float, long):
raise TypeError('model_ors(): experiment_length must be a number!')
elif experiment_length < 0:
raise ValueError('model_ors(): experiment_length must be positive!')
if type(cleaning_time) not in (int, float, long):
raise TypeError('model_ors(): cleaning_time must be a number!')
elif cleaning_time < 0:
raise ValueError('model_ors(): cleaning_time must be positive!')
###
### Done typechecking
###
n_classes = len(distribution_parameters)
# These lines initialize the queues to be empty.
operating_rooms = []
queues = [[] for i in range(n_classes)]
utilization_frac = (n_day_oprooms + 1) * [0]
results = []
# Now we start at time 0, and step through minute by minute.
for time in range(int(experiment_length + converge_time)):
# First we see how many patients have arrived this minute.
n_patients = [numpy.random.poisson(x[0]) for x in
distribution_parameters]
# If any patients have arrived, add them to the queue.
for j in range(n_classes):
for k in range(n_patients[j]):
queues[j].append(time)
# Check to see if any operating rooms have opened up this minute.
operating_rooms = [x for x in operating_rooms if x != time]
# Change the number of operating rooms based on the time of day.
# Currently the program is set up to assume that night lasts eight hours.
if time % day_to_min > night_length * hour_to_min:
n_oprooms = n_day_oprooms
else:
n_oprooms = n_night_oprooms
for j in range(n_classes):
# Check to see if there are any open operating rooms and any patients in
# the emergency queue.
if len(operating_rooms) < n_oprooms and len(queues[j]) > 0:
# If a patient from the emergency queue can be put in an operating room
# this minute, calculate the time the patient had to wait.
wait_time = time - queues[j][0]
# Draw the amount of time that the patient has to spend in surgery from
# a log-normal distribution.
surgery_time = int(round(numpy.random.lognormal(
distribution_parameters[j][1], distribution_parameters[j][2])))
# Print the data about this patient.
if queues[j][0] > converge_time:
if queues[j][0] % day_to_min > night_length * hour_to_min:
time_of_day = "day"
else:
time_of_day = "night"
results.append([j, int(queues[j][0] - converge_time), time_of_day,
wait_time, surgery_time])
# Because the patient has been put in an operating room, he can be
# removed from the emergency queue.
queues[j].remove(queues[j][0])
# 60 minutes is added to the surgery time for clean up.
out_time = time + surgery_time + cleaning_time
# Lastly, record the time that the operating room will be free in the
# operating rooms list.
operating_rooms.append(out_time)
if time > converge_time:
utilization_frac[len(operating_rooms)] += 1
utilization_results = []
for i, elem in enumerate(utilization_frac):
utilization_results.append([str(i) + '/' + str(n_oprooms), float(elem) /
(experiment_length - converge_time)])
return (results, utilization_results)
if __name__ == '__main__':
if len(sys.argv) != 2:
print "usage: or_wait_times.py n_oprooms"
sys.exit(1)
# These lines read in the number of operating rooms that the user has
# supplied.
N_DAY_OPROOMS = int(sys.argv[1])
# These numbers describe the observed probabilities of for patient arrival
# time rates and surgery times. See the notebook for the derivation of
# these numbers.
DISTRIBUTION_PARAMETERS = ((.001607686, 5.00716, .583642),
(.003232496, 4.96477, .677607),
(.002665525, 5.05842, .651279),
(.000334855, 5.00069, .570812),
(.00, 4.95519, .665382),
(.001288052, 5.01655, .713405))
RESULTS, UTILIZATION_RESULTS = model_ors(N_DAY_OPROOMS,
DISTRIBUTION_PARAMETERS, experiment_length=2.628e6)
for elem in RESULTS:
for item in elem:
print item,
print
for elem in UTILIZATION_RESULTS:
for item in elem:
print >> sys.stderr, item,
print >> sys.stderr
``` |
{
"source": "joe-antognini/praxis",
"score": 4
} |
#### File: praxis/ex007/multiple_dwellings.py
```python
def all_perms(elements):
if len(elements) <= 1:
yield elements
else:
for perm in all_perms(elements[1:]):
for i in range(len(elements)):
yield perm[:i] + elements[0:1] + perm[i:]
building = ['b', 'c', 'f', 'm', 's']
for perm in all_perms(building):
# Baker does not live on the top floor
if perm[4] == 'b':
continue
# Cooper does not live on the bottom floor
if perm[0] == 'c':
continue
# Fletcher does not live on either the top or bottom floor
if perm[0] == 'f' or perm[4] == 'f':
continue
# Miller lives on a higher floor than Cooper
cont = False
for elem in perm:
if elem == 'c':
break
elif elem == 'm':
cont = True
break
if cont:
continue
# Smith does not live on a floor next to Fletcher
for i, elem in enumerate(perm):
if elem == 'f':
if i >= 1:
if perm[i-1] == 's':
cont = True
break
if i <= 3:
if perm[i+1] == 's':
cont = True
break
if cont:
continue
# Fletcher does not live on a floor next to Cooper.
for i, elem in enumerate(perm):
if elem == 'c':
if i >= 1:
if perm[i-1] == 'f':
cont = True
break
if i <= 3:
if perm[i+1] == 'f':
cont = True
break
if cont:
continue
print perm
```
#### File: praxis/ex256/legendre_pi.py
```python
from math import log, sqrt
from sieve_erato import sieve_erato
def memoize(f):
class memodict(dict):
def __init__(self, f):
self.f = f
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = self.f(*key)
return ret
return memodict(f)
def prime_n(n):
'''Return the n'th prime.'''
if n == 0:
return 1
j = 0
count = 1
while count != n:
primes = sieve_erato(int(2**j * log(n) * n))
count = 1
for i, elem in enumerate(primes):
if elem:
count += 1
if count == n:
break
j += 1
return 2*i + 3
@memoize
def legendre_phi(x, a, acc=0):
'''Calculate Legendre's phi function.'''
if x == 0:
return 0
while a > 1:
p_a = prime_n(a)
(x, a, acc) = (x, a-1, legendre_phi(x/p_a, a-1) + acc)
return (x+1)/2 - acc
def legendre_pi(n):
'''Calculate the number of primes less than or equal to n using Legendre's
algorithm.'''
if n == 2:
return 1
elif n == 3:
return 2
else:
a = legendre_pi(int(sqrt(n)))
return legendre_phi(n, a) + a - 1
if __name__ == '__main__':
print legendre_pi(int(1e6))
```
#### File: praxis/ex538/magic1089.py
```python
import numpy as np
def digits_list(n):
'''Return a list of the digits of an integer.'''
ret = [(n / 10**i) % 10 for i in range(int(np.log10(n)) + 1)]
ret.reverse()
return ret
def from_digits_list(lst):
'''Return an integer from the digits list.'''
lst.reverse()
n = 0
for i, d in enumerate(lst):
n += d * 10**i
return n
def is_descending(n):
'''Return True if the digits of the number are descending, False
otherwise.'''
prev_i = np.inf
for i in digits_list(n):
if i >= prev_i:
return False
prev_i = i
return True
def magic1089(n):
'''Do the Magic 1089 trick.'''
if n < 100 or n >= 1000:
raise ValueError('magic1089(): input must be three digits number')
if not is_descending(n):
raise ValueError('magic1089(): digits must be descending')
digits = digits_list(n)
rev_digits = digits[::-1]
rev_n = from_digits_list(rev_digits)
diff = n - rev_n
rev_diff = from_digits_list(digits_list(diff)[::-1])
return diff + rev_diff
``` |
{
"source": "joe-antognini/rosalind",
"score": 4
} |
#### File: joe-antognini/rosalind/rna.py
```python
import sys
def rna_transcribe(s):
'''Given a string of DNA return the corresponding string of RNA by
replacing T with U.'''
outstring = ''
same_bases = ['A', 'C', 'G']
for char in s:
if char in same_bases:
outstring += char
elif char == 'T':
outstring += 'U'
else:
raise ValueError('Unacceptable character in string.')
return outstring
if __name__ == '__main__':
with open(sys.argv[1]) as INFILE:
for LINE in INFILE:
DATA = LINE.strip()
break
print rna_transcribe(DATA)
``` |
{
"source": "joe-antognini/tf-estimator-example",
"score": 3
} |
#### File: joe-antognini/tf-estimator-example/trainer.py
```python
import argparse
import logging
import os
import time
import tensorflow as tf
N_LABELS = 10
N_EVAL_EXAMPLES = 10000
N_TRAIN_EXAMPLES = 60000
def build_input_fn(fnames, hparams, is_training=True, use_tpu=True):
'''Build the input function.'''
def parse_fn(proto):
'''Parse a single Tensorflow example from a `TFRecord`.
Args:
proto: The serialized protobuf of the `tf.Example`
Returns:
A `Tensor` containing the image.
A one-hot `Tensor` containing the label.
'''
features = {
'im': tf.FixedLenFeature([28 * 28], tf.float32),
'label': tf.FixedLenFeature([], tf.int64),
}
parsed_features = tf.parse_single_example(proto, features)
im = tf.reshape(parsed_features['im'], [28, 28, 1])
label = tf.one_hot(parsed_features['label'], N_LABELS)
return im, label
def input_fn(params):
'''Feed input into the graph.'''
with tf.variable_scope('image_preprocessing'):
dataset = tf.data.TFRecordDataset(fnames)
dataset = dataset.shuffle(len(fnames))
dataset = dataset.map(parse_fn)
if is_training:
dataset = dataset.shuffle(args.shuffle_buffer_size)
dataset = dataset.repeat()
if use_tpu:
dataset = dataset.apply(
tf.contrib.data.batch_and_drop_remainder(params['batch_size']))
else:
dataset = dataset.batch(hparams.batch_size)
dataset = dataset.prefetch(buffer_size=1)
iterator = dataset.make_one_shot_iterator()
features, label = iterator.get_next()
return features, label
return input_fn
def model_body(features):
net = tf.identity(features)
net = tf.layers.conv2d(net, filters=32, kernel_size=5, activation=tf.nn.relu)
net = tf.layers.max_pooling2d(net, pool_size=2, strides=2)
net = tf.layers.conv2d(net, filters=64, kernel_size=5, activation=tf.nn.relu)
net = tf.layers.max_pooling2d(net, pool_size=2, strides=2)
net = tf.contrib.layers.flatten(net)
net = tf.layers.dense(net, 1024, activation=tf.nn.relu)
return net
def build_model_fn(hparams):
'''Build the model function.'''
def model_fn(features, labels, mode, params=None):
'''Define the model graph.'''
if params:
hparams.override_from_dict(params)
net = model_body(features)
logits = tf.layers.dense(net, units=N_LABELS)
xentropies = tf.nn.softmax_cross_entropy_with_logits(logits=logits,
labels=labels)
loss = tf.reduce_mean(xentropies)
if hparams.get('learning_rate_decay_scheme') == 'exponential':
learning_rate = tf.train.exponential_decay(hparams.learning_rate,
tf.train.get_global_step(),
hparams.decay_steps,
hparams.decay_rate)
else:
learning_rate = hparams.learning_rate
optimizer = tf.train.MomentumOptimizer(learning_rate,
hparams.momentum)
if hparams.use_tpu:
optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
def metric_fn(labels, logits):
predictions = tf.argmax(logits, axis=1)
accuracy = tf.metrics.accuracy(tf.argmax(labels, axis=1), predictions)
return {'accuracy': accuracy}
eval_metrics = (metric_fn, [labels, logits])
eval_metric_ops = metric_fn(labels, logits)
if hparams.use_tpu:
return tf.contrib.tpu.TPUEstimatorSpec(mode=mode,
loss=loss,
train_op=train_op,
eval_metrics=eval_metrics)
else:
return tf.estimator.EstimatorSpec(mode=mode,
loss=loss,
train_op=train_op,
eval_metric_ops=eval_metric_ops)
return model_fn
def main(args):
eval_batch_size = args.eval_batch_size
if args.mode == 'train':
eval_batch_size = None
hparams = tf.contrib.training.HParams(
learning_rate=args.learning_rate,
momentum=args.momentum,
batch_size=args.batch_size,
eval_batch_size=eval_batch_size,
use_tpu=False)
if hparams.use_tpu:
print 'Using TPU!'
run_config = tf.contrib.tpu.RunConfig(
master=args.tpu_master,
evaluation_master=args.tpu_master,
model_dir=args.model_dir,
save_checkpoints_steps=args.save_checkpoints_steps,
save_summary_steps=args.save_summary_steps,
keep_checkpoint_max=args.keep_checkpoint_max,
session_config=tf.ConfigProto(
allow_soft_placement=True, log_device_placement=True),
tpu_config=tf.contrib.tpu.TPUConfig(args.tpu_iterations_per_loop,
args.tpu_num_shards))
nn = tf.contrib.tpu.TPUEstimator(model_fn=build_model_fn(hparams),
config=run_config,
train_batch_size=hparams.batch_size,
eval_batch_size=hparams.eval_batch_size)
else:
run_config = tf.estimator.RunConfig(
model_dir=args.model_dir,
save_checkpoints_steps=args.save_checkpoints_steps,
save_summary_steps=args.save_summary_steps,
keep_checkpoint_max=args.keep_checkpoint_max)
nn = tf.estimator.Estimator(model_fn=build_model_fn(hparams),
config=run_config)
train_fnames = [args.train_file_pattern]
eval_fnames = [args.eval_file_pattern]
logging.info('mode: {}'.format(args.mode))
if args.mode == 'train':
logging.info('Starting training.')
input_fn = build_input_fn(train_fnames, hparams, is_training=True,
use_tpu=args.use_tpu)
nn.train(input_fn=input_fn, steps=args.train_steps)
elif args.mode == 'eval':
while not tf.train.checkpoint_exists(os.path.join(args.model_dir, 'model')):
logging.info(
'No checkpoint found. Waiting 60 seconds before trying again.')
time.sleep(60)
while True:
input_fn = build_input_fn(eval_fnames, hparams, is_training=False,
use_tpu=args.use_tpu)
nn.evaluate(input_fn=input_fn,
steps=int(N_EVAL_EXAMPLES / hparams.eval_batch_size))
elif args.mode == 'train_and_eval':
i_steps = 0
# Get steps at initialization
input_fn = build_input_fn(train_fnames, hparams, is_training=True,
use_tpu=args.use_tpu)
nn.evaluate(input_fn=input_fn,
steps=int(N_TRAIN_EXAMPLES / hparams.batch_size),
name='train')
input_fn = build_input_fn(eval_fnames, hparams, is_training=False,
use_tpu=args.use_tpu)
nn.evaluate(input_fn=input_fn,
steps=int(N_EVAL_EXAMPLES / hparams.batch_size),
name='test')
# Start training!
while i_steps < args.train_steps:
input_fn = build_input_fn(train_fnames, hparams, is_training=True,
use_tpu=args.use_tpu)
nn.train(input_fn=input_fn, steps=args.eval_freq)
nn.evaluate(input_fn=input_fn,
steps=int(N_TRAIN_EXAMPLES / hparams.batch_size),
name='train')
input_fn = build_input_fn(eval_fnames, hparams, is_training=False,
use_tpu=args.use_tpu)
nn.evaluate(input_fn=input_fn,
steps=int(N_EVAL_EXAMPLES / hparams.batch_size),
name='test')
i_steps += args.eval_freq
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Run an MNIST model.')
parser.add_argument('--batch_size', type=int, default=128,
help='Batch size.')
parser.add_argument('--eval_batch_size', type=int, default=128,
help='Batch size on eval.')
parser.add_argument('--train_file_pattern',
help='File pattern of the training data.')
parser.add_argument('--eval_file_pattern',
help='File pattern of the eval data.')
parser.add_argument('--eval_freq', type=int, default=500,
help='Number of steps between eval runs.')
parser.add_argument('--tpu_iterations_per_loop', type=int, default=500,
help='Number of iterations in a TPU cycle.')
parser.add_argument('--keep_checkpoint_max', type=int, default=2,
help='Maximum number of checkpoints to keep.')
parser.add_argument('--learning_rate', type=float, default=0.1,
help='Initial learning rate for the optimizer.')
parser.add_argument('--mode', choices=['train', 'eval', 'train_and_eval'],
help='Which mode to run in.')
parser.add_argument('--model_dir',
help='Directory to save model checkpoints.')
parser.add_argument('--momentum', type=float, default=0.9,
help='Momentum for the optimizer.')
parser.add_argument('--tpu_num_shards', type=int, default=8,
help='Number of TPU shards.')
parser.add_argument('--save_checkpoints_steps', type=int, default=100,
help='Number of steps between checkpoint saves.')
parser.add_argument('--save_summary_steps', type=int, default=100,
help='Number of steps between saving summaries.')
parser.add_argument('--train_steps', type=int, default=100000,
help='Number of steps to train.')
parser.add_argument('--use_tpu', type=bool, default=False,
help='Whether to train on TPU.')
parser.add_argument('--shuffle_buffer_size', type=int, default=1024,
help='Number of images to read into buffer before '
'shuffling.')
parser.add_argument('--tpu_master',
help='Location of TPU master.')
args = parser.parse_args()
main(args)
``` |
{
"source": "joe-antognini/tridentine_calendar",
"score": 3
} |
#### File: tridentine_calendar/tests/test_cli.py
```python
import argparse
import os
import tempfile
import unittest
from ..cli import _main
from ..cli import parse_args
class TestParseArgs(unittest.TestCase):
def test_parse_args_one_year(self):
args = parse_args(['--output', 'foo', '2000'])
self.assertEqual(args.output, 'foo')
self.assertEqual(args.years, [2000])
self.assertFalse(args.overwrite_existing)
def test_parse_args_multiple_years(self):
args = parse_args(['--output', 'foo', '2000', '2010'])
self.assertEqual(args.output, 'foo')
self.assertEqual(args.years, [2000, 2010])
self.assertFalse(args.overwrite_existing)
def test_parse_args_help(self):
with self.assertRaises(SystemExit):
parse_args(['-h'])
class TestMain(unittest.TestCase):
def test_main_new_calendar(self):
with tempfile.TemporaryDirectory() as tmp_dir:
args = argparse.Namespace(
output=os.path.join(tmp_dir, 'foo'),
years=[2018, 2019],
overwrite_existing=False,
use_html_formatting=False,
)
_main(args)
def test_main_existing_calendar(self):
with tempfile.TemporaryDirectory() as tmp_dir:
args = argparse.Namespace(
output=os.path.join(tmp_dir, 'foo'),
years=[2018],
overwrite_existing=False,
use_html_formatting=True,
)
_main(args)
args = argparse.Namespace(
output=os.path.join(tmp_dir, 'foo'),
years=[2019],
overwrite_existing=False,
use_html_formatting=True,
)
_main(args)
```
#### File: tridentine_calendar/tests/test_tridentine_calendar.py
```python
import datetime as dt
import tempfile
import unittest
from ..tridentine_calendar import LiturgicalCalendar
from ..tridentine_calendar import LiturgicalCalendarEvent
from ..tridentine_calendar import LiturgicalCalendarEventUrl
from ..tridentine_calendar import LiturgicalSeason
from ..tridentine_calendar import LiturgicalYear
from ..tridentine_calendar import _feast_sort_key
class TestLiturgicalCalendarEventUrl(unittest.TestCase):
def test_init(self):
feast_link = LiturgicalCalendarEventUrl(
'https://en.wikipedia.org/Saturnin', 'Saturnin')
self.assertEqual(feast_link.url, 'https://en.wikipedia.org/Saturnin')
self.assertEqual(feast_link.description, 'Saturnin')
def test_from_json(self):
json_obj = {
'url': 'https://en.wikipedia.org/Saturnin',
'description': 'Saturnin',
}
feast_link = LiturgicalCalendarEventUrl.from_json(json_obj)
self.assertEqual(feast_link.url, 'https://en.wikipedia.org/Saturnin')
self.assertEqual(feast_link.description, 'Saturnin (Wikipedia)')
json_obj = 'https://en.wikipedia.org/Saturnin'
feast_link = LiturgicalCalendarEventUrl.from_json(json_obj)
self.assertEqual(feast_link.url, 'https://en.wikipedia.org/Saturnin')
self.assertEqual(feast_link.description, 'Saturnin (Wikipedia)')
json_obj = 'http://www.newadvent.org/cathen/01471a.htm'
feast_link = LiturgicalCalendarEventUrl.from_json(
json_obj, default='Saturninus')
self.assertEqual(feast_link.url, 'http://www.newadvent.org/cathen/01471a.htm')
self.assertEqual(feast_link.description, 'Saturninus (New Advent)')
json_obj = 'https://fisheaters.com/customsadvent2a.html'
feast_link = LiturgicalCalendarEventUrl.from_json(
json_obj, default='St. Barbara')
self.assertEqual(feast_link.url, 'https://fisheaters.com/customsadvent2a.html')
self.assertEqual(feast_link.description, 'St. Barbara (Fish Eaters)')
json_obj = 'https://en.wikipedia.org/Saint_Nicholas'
feast_link = LiturgicalCalendarEventUrl.from_json(json_obj)
self.assertEqual(feast_link.url, 'https://en.wikipedia.org/Saint_Nicholas')
self.assertEqual(feast_link.description, 'Saint Nicholas (Wikipedia)')
json_obj = 'https://en.wikipedia.org/wiki/Saint_Sylvester%27s_Day'
feast_link = LiturgicalCalendarEventUrl.from_json(json_obj)
self.assertEqual(
feast_link.url, 'https://en.wikipedia.org/wiki/Saint_Sylvester%27s_Day')
self.assertEqual(feast_link.description, 'Saint Sylvester\'s Day (Wikipedia)')
def test_to_href(self):
feast_link = LiturgicalCalendarEventUrl(
'https://en.wikipedia.org/Saturnin', 'Saturnin (Wikipedia)')
self.assertEqual(
feast_link.to_href(),
'<a href=https://en.wikipedia.org/Saturnin>Saturnin (Wikipedia)</a>',
)
class TestLiturgicalCalendarSeason(unittest.TestCase):
def test_init(self):
season = LiturgicalSeason('Advent')
self.assertEqual(season.name, 'Advent')
def test_from_json_key(self):
season = LiturgicalSeason.from_json_key('Advent')
self.assertEqual(season.name, 'Advent')
self.assertEqual(season.color, 'Violet')
def test_from_date(self):
date = dt.date(2018, 12, 4)
season = LiturgicalSeason.from_date(date)
self.assertEqual(season.name, 'Advent')
self.assertEqual(season.color, 'Violet')
date = dt.date(2018, 12, 25)
season = LiturgicalSeason.from_date(date)
self.assertEqual(season.name, 'Christmastide')
self.assertEqual(season.color, 'White')
date = dt.date(2019, 1, 25)
season = LiturgicalSeason.from_date(date)
self.assertEqual(season.name, 'Time after Epiphany')
self.assertEqual(season.color, 'Green')
date = dt.date(2019, 2, 25)
season = LiturgicalSeason.from_date(date)
self.assertEqual(season.name, 'Septuagesima')
self.assertEqual(season.color, 'Violet')
date = dt.date(2019, 3, 25)
season = LiturgicalSeason.from_date(date)
self.assertEqual(season.name, 'Lent')
self.assertEqual(season.color, 'Violet')
date = dt.date(2019, 4, 8)
season = LiturgicalSeason.from_date(date)
self.assertEqual(season.name, 'Passiontide')
self.assertEqual(season.color, 'Violet')
date = dt.date(2019, 4, 15)
season = LiturgicalSeason.from_date(date)
self.assertEqual(season.name, 'Holy Week')
self.assertEqual(season.color, 'Violet')
date = dt.date(2019, 4, 25)
season = LiturgicalSeason.from_date(date)
self.assertEqual(season.name, 'Eastertide')
self.assertEqual(season.color, 'White')
date = dt.date(2019, 6, 25)
season = LiturgicalSeason.from_date(date)
self.assertEqual(season.name, 'Time after Pentecost')
self.assertEqual(season.color, 'Green')
date = dt.date(2019, 11, 2)
season = LiturgicalSeason.from_date(date)
self.assertEqual(season.name, 'Hallowtide')
def test_full_name(self):
season = LiturgicalSeason('Advent')
self.assertEqual(season.full_name(capitalize=True), 'Advent')
season = LiturgicalSeason('Time after Pentecost')
self.assertEqual(season.full_name(capitalize=True), 'The Time after Pentecost')
season = LiturgicalSeason('Time after Epiphany')
self.assertEqual(season.full_name(capitalize=False), 'the Time after Epiphany')
class TestLiturgicalCalendarEvent(unittest.TestCase):
def test_from_json_st_nicholas(self):
date = dt.date(2018, 12, 6)
json_obj = {
'name': '<NAME>',
'titles': ['Bishop', 'Confessor'],
'urls': [
'https://fisheaters.com/customsadvent3.html',
'https://en.wikipedia.org/wiki/Saint_Nicholas',
],
'obligation': False,
'class': 3,
'liturgical_event': True,
}
event = LiturgicalCalendarEvent.from_json(date, json_obj)
self.assertEqual(event.name, 'St. Nicholas')
self.assertEqual(event.rank, 3)
self.assertEqual(event.liturgical_event, True)
self.assertEqual(event.holy_day, False)
self.assertEqual(event.urls[0].description, 'St. Nicholas (Fish Eaters)')
self.assertEqual(event.urls[1].description, 'Saint Nicholas (Wikipedia)')
self.assertEqual(event.color, 'White')
self.assertEqual(event.feast, True)
def test_from_json_st_saturninus(self):
date = dt.date(2018, 11, 30)
json_obj = {
'name': 'St. Andrew',
'titles': ['Apostle'],
'urls': [
'https://en.wikipedia.org/wiki/Andrew_the_Apostle',
],
'obligation': False,
'class': 2,
'liturgical_event': True,
}
event = LiturgicalCalendarEvent.from_json(date, json_obj)
self.assertEqual(event.name, 'St. Andrew')
self.assertEqual(event.rank, 2)
self.assertEqual(event.liturgical_event, True)
self.assertEqual(event.feast, True)
self.assertEqual(event.holy_day, False)
self.assertEqual(event.urls[0].description, 'Andrew the Apostle (Wikipedia)')
self.assertEqual(event.color, 'Red')
def test_full_name(self):
date = dt.date(2018, 12, 6)
event = LiturgicalCalendarEvent(date, 'St. Nicholas', rank=3)
expected_output = 'The Feast of St. Nicholas'
self.assertEqual(event.full_name(capitalize=True), expected_output)
expected_output = 'the Feast of St. Nicholas'
self.assertEqual(event.full_name(capitalize=False), expected_output)
date = dt.date(2019, 10, 27)
event = LiturgicalCalendarEvent(date, 'Christ the King', rank=3)
expected_output = 'The Feast of Christ the King'
self.assertEqual(event.full_name(capitalize=True), expected_output)
date = dt.date(2019, 6, 28)
event = LiturgicalCalendarEvent(date, 'Vigil of SS. Peter & Paul', rank=2)
expected_output = 'The Vigil of the Feast of SS. Peter & Paul'
self.assertEqual(event.full_name(capitalize=True), expected_output)
date = dt.date(2019, 8, 14)
event = LiturgicalCalendarEvent(date, 'Vigil of the Assumption', rank=2)
expected_output = 'The Vigil of the Assumption'
self.assertEqual(event.full_name(capitalize=True), expected_output)
date = dt.date(2020, 1, 5)
event = LiturgicalCalendarEvent(date, 'Twelfth Night', rank=1)
expected_output = 'Twelfth Night'
self.assertEqual(event.full_name(capitalize=True), expected_output)
date = dt.date(2020, 1, 19)
event = LiturgicalCalendarEvent(date, 'Second Sunday after Epiphany', rank=2)
expected_output = 'The Second Sunday after Epiphany'
self.assertEqual(event.full_name(capitalize=True), expected_output)
def test_generate_description(self):
url = LiturgicalCalendarEventUrl(
'https://fisheaters.com/customsadvent5.html',
description='Feast of the Immaculate Conception',
)
event = LiturgicalCalendarEvent(
dt.date(2018, 12, 8),
'The Immaculate Conception',
liturgical_event=True,
holy_day=True,
urls=[url],
rank=1,
color='White',
feast=True,
)
expected_description = (
'The Feast of the Immaculate Conception is a Holy Day of Obligation. '
'Today is a Class I feast. '
'The liturgical color is white.\n\n'
'More information about the Feast of the Immaculate Conception:\n'
'• https://fisheaters.com/customsadvent5.html\n\n'
'More information about Advent:\n'
)
description = event.generate_description(html_formatting=False)
self.assertTrue(description.startswith(expected_description))
def test_is_fixed(self):
event = LiturgicalCalendarEvent(
dt.date(2018, 12, 8),
'The Immaculate Conception',
)
self.assertTrue(event.is_fixed())
event = LiturgicalCalendarEvent(dt.date(2019, 4, 21), 'Easter')
self.assertFalse(event.is_fixed())
class TestFeastComparison(unittest.TestCase):
def test_feast_comparison(self):
feast = LiturgicalCalendarEvent(
dt.date(2018, 4, 1), name='Easter', rank=1, liturgical_event=True)
self.assertEqual(_feast_sort_key(feast), 1)
feast = LiturgicalCalendarEvent(
dt.date(2018, 10, 31), name='Halloween', liturgical_event=False)
self.assertEqual(_feast_sort_key(feast), 4)
class TestLiturgicalYearSmoke(unittest.TestCase):
def test_liturgical_year(self):
self.assertIsNotNone(LiturgicalYear(2018))
class TestLiturgicalYearSundayDates(unittest.TestCase):
def test_liturgical_year_sunday_dates(self):
litcal_2018 = LiturgicalYear(2018)
self.assertEqual(
litcal_2018[dt.date(2018, 9, 2)][0].name,
'Fifteenth Sunday after Pentecost',
)
self.assertEqual(
litcal_2018[dt.date(2018, 11, 25)][0].name,
'Last Sunday after Pentecost',
)
class TestLiturgicalYearIcal(unittest.TestCase):
def test_to_ical_smoke(self):
ics_calendar = LiturgicalYear(2019).to_ical()
self.assertIsNotNone(ics_calendar)
class TestLiturgicalCalendar(unittest.TestCase):
def test_liturgical_calendar_init_single_year(self):
litcal = LiturgicalCalendar(2018)
self.assertIsNotNone(litcal)
def test_liturgical_calendar_init_multiple_years(self):
litcal = LiturgicalCalendar([2018, 2019])
self.assertIsNotNone(litcal)
def test_liturgical_calendar_getitem(self):
litcal = LiturgicalCalendar([2018, 2019])
event = litcal[dt.date(2018, 12, 25)][0]
self.assertEqual(event.name, 'Christmas')
event = litcal[dt.date(2019, 4, 21)][0]
self.assertEqual(event.name, 'Easter')
def test_liturgical_calendar_description(self):
litcal = LiturgicalCalendar(2019)
event = litcal[dt.date(2018, 12, 8)][0]
description = event.generate_description(
html_formatting=False, ranking_feast=True)
self.assertTrue(description.startswith(
'The Feast of the Immaculate Conception is a Holy Day of Obligation.'))
def test_liturgical_calendar_to_ics(self):
ics_calendar = LiturgicalYear(2019).to_ical()
self.assertIsNotNone(ics_calendar)
def test_extend_existing_ics(self):
litcal = LiturgicalCalendar(2018)
filename = tempfile.NamedTemporaryFile()
with open(filename.name, 'wb') as fp:
fp.write(litcal.to_ical())
new_litcal = LiturgicalCalendar(2019)
new_litcal.extend_existing_ical(filename.name)
filename.close()
``` |
{
"source": "joe-antognini/triplesec",
"score": 3
} |
#### File: joe-antognini/triplesec/ekm.py
```python
if __name__ == '__main__':
import __init__
# System packages
import argparse
import json
import random
import sys
import time
# Numerical packages
import numpy as np
from scipy.integrate import ode, quad
from scipy.optimize import brentq
from scipy.special import ellipk, ellipe
# Triplesec packages
from ts_constants import *
class Triple_octupole:
'''A hierachical triple where only the octupole term of the Hamiltonian is
considered. The quadrupole term is averaged over.
Parameters:
e1: Inner eccentricity
e2: Outer eccentricity
a1: Inner semi-major axis in AU
a2: OUter semi-major axis in AU
inc: Inclination in degrees
argperi: Argument of periastron in degrees
longascnode: Longitude of ascending node in degrees
epsoct: e2 / (1 - e2^2) * (a1 / a2)
phiq: The value of the quadrupole term of the Hamiltonian
chi: The other integral of motion of the octupole term
tstop: The time to integrate (units of t_KL)
cputstop: The number of CPU seconds to integrate for
outfreq: Print out state every n steps (-1 for no output)
outfile: Filename to write output to (None for stdout)
atol: Absolute tolerance of the integrator
rtol: Relative tolerance of the integrator
'''
def __init__(self, a1=1, a2=20, e1=.1, e2=.3, inc=80, longascnode=180,
argperi=0, epsoct=None, phiq=None, chi=None, tstop=1e3, cputstop=300,
outfreq=1, outfilename=None, atol=1e-9, rtol=1e-9,
integration_algo='vode'):
#
# Given parameters
#
self.a1 = float(a1)
self.a2 = float(a2)
self.e1 = e1
self.e2 = e2
self.inc = inc
self.Omega = longascnode * np.pi / 180
self.omega = argperi * np.pi / 180
#
# Derived parameters
#
self.cosi = np.cos(inc * np.pi / 180)
self.j = np.sqrt(1 - e1**2)
self.jz = self.j * self.cosi
# We don't use calc_CKL() at first because we need CKL to calculate chi.
self.CKL = (self.e1**2 * (1 - 5/2. * (1 - self.cosi**2) *
np.sin(self.omega)**2))
if phiq is None:
self.phiq = self.CKL + self.jz**2 / 2.
else:
self.phiq = phiq
self.jz = 0
self.CKL = self.phiq
if epsoct is None:
self.epsoct = self.e2 / (1 - self.e2**2) * (self.a1 / self.a2)
else:
self.epsoct = epsoct
if chi is None:
self.chi = F(self.CKL) - self.epsoct * np.cos(self.Omega)
else:
self.chi = chi
self.Omega = np.arccos((F(self.CKL) - self.chi) / self.epsoct)
self.set_x()
self.set_fj()
self.set_fOmega()
#
# Integration parameters
#
self.nstep = 0
self.t = 0
self.tstop = tstop
self.cputstop = cputstop
self.outfreq = outfreq
self.outfilename = outfilename
self.integration_algo = integration_algo
self.y = [self.jz, self.Omega]
self.tol = 1e-9
self.atol = atol
self.rtol = rtol
if self.outfilename is not None:
self.outfile = open(self.outfilename, 'w')
# Set up the integrator
self.solver = ode(self._deriv)
self.solver.set_integrator(self.integration_algo, nsteps=1,
atol=self.atol, rtol=self.rtol)
self.solver.set_initial_value(self.y, self.t).set_f_params(self.epsoct,
self.phiq)
self.solver._integrator.iwork[2] = -1 # Don't print FORTRAN errors
def _deriv(self, t, y, epsoct, phiq):
# Eqs. 11 of Katz (2011)
jz, Omega = y
CKL = phiq - jz**2 / 2.
x = (3 - 3 * CKL) / (3 + 2 * CKL)
fj = (15 * np.pi / (128 * np.sqrt(10)) / ellipk(x) * (4 - 11 * CKL)
* np.sqrt(6 + 4 * CKL))
fOmega = ((6 * ellipe(x) - 3 * ellipk(x)) / (4 * ellipk(x)))
jzdot = -epsoct * fj * np.sin(Omega)
Omegadot = jz * fOmega
return [jzdot, Omegadot]
def _step(self):
self.solver.integrate(self.tstop, step=True)
self.t = self.solver.t
self.jz, self.Omega = self.solver.y
# Update all the parameters
self.set_CKL()
self.set_x()
self.set_fj()
self.set_fOmega()
self.nstep += 1
def set_CKL(self):
self.CKL = self.calc_CKL()
def calc_CKL(self):
return self.phiq - self.jz**2 / 2.
def calc_x(self):
return (3 - 3 * self.CKL) / (3 + 2 * self.CKL)
def set_x(self):
self.x = self.calc_x()
def calc_fj(self):
return (15 * np.pi / (128 * np.sqrt(10)) / ellipk(self.x) *
(4 - 11 * self.CKL) * np.sqrt(6 + 4 * self.CKL))
def set_fj(self):
self.fj = self.calc_fj()
def calc_fOmega(self):
return ((6 * ellipe(self.x) - 3 * ellipk(self.x)) / (4 *
ellipk(self.x)))
def set_fOmega(self):
self.fOmega = self.calc_fOmega()
def integrate(self):
'''Integrate the triple in time.'''
self.printout()
self.tstart = time.time()
while ((self.t < self.tstop) and
((time.time() - self.tstart) < self.cputstop)):
self._step()
if self.nstep % self.outfreq == 0:
self.printout()
self.printout()
if self.outfilename is not None:
self.outfile.close()
def printout(self):
'''Print out the state of the system in the format:
time jz Omega <f_j> <f_Omega> x C_KL
'''
outstring = ' '.join(map(str, [self.t, self.jz, self.Omega, self.fj,
self.fOmega, self.x, self.CKL]))
if self.outfilename is None:
print outstring
else:
self.outfile.write(outstring + '\n')
def period(self):
'''Analytically calculate the period of EKM oscillations.'''
# First calculate the limits.
xcrit = brentq(lambda x: ellipk(x) - 2 * ellipe(x), 0, 1)
phicrit = 3 * (1 - xcrit) / (3 + 2 * xcrit)
if self.phiq < phicrit:
CKLmin = brentq(lambda CKL: self.chi - self.epsoct - F(CKL), self.tol, self.phiq)
else:
# Check if flips occur for Omega = Pi or 0
if (np.sign(self.chi - self.epsoct - F(self.tol)) !=
np.sign(self.chi - self.epsoct - F(self.phiq))):
CKLmin = brentq(lambda CKL: self.chi - self.epsoct - F(CKL), self.tol, self.phiq)
else:
CKLmin = brentq(lambda CKL: self.chi + self.epsoct - F(CKL), self.tol, self.phiq)
if self.doesflip():
CKLmax = self.phiq
else:
CKLmax = brentq(lambda CKL: self.chi + self.epsoct - F(CKL), 0, 1)
prefactor = 256 * np.sqrt(10) / (15 * np.pi) / self.epsoct
P = quad(lambda CKL: (prefactor * ellipk((3 - 3*CKL)/(3 + 2*CKL)) /
(4 - 11*CKL) / np.sqrt(6 + 4*CKL) / np.sqrt(1 - 1/self.epsoct**2 *
(F(CKL) - self.chi)**2) / np.sqrt(2* np.fabs(self.phiq - CKL))),
CKLmin, CKLmax, epsabs=1e-12, epsrel=1e-12, limit=100)
return P[0]
def numeric_period(self, n_flips=3):
'''Calculate the period of EKM oscillations by integrating the EOMs and
taking the average flip time for n_flips flips.'''
t_flip_prev = 0
sign_prev = np.sign(self.jz)
periods = []
while (len(periods) < n_flips) and (self.t < self.tstop):
self._step()
if np.sign(self.jz) != sign_prev:
if t_flip_prev != 0:
periods.append(self.t - t_flip_prev)
t_flip_prev = self.t
sign_prev = np.sign(self.jz)
return np.mean(periods)
def doesflip(self):
'''Return True if the triple flips, false otherwise. This is determined
using Eq. 16 of Katz (2011).
'''
#
# Calculate Delta F over many values of x. x can range from
#
# C_KL < x < C_KL + j_z^2 / 2
#
X = np.linspace(self.CKL, self.CKL + (self.jz)**2 / 2.)
DeltaF = np.fabs(np.array(map(F, X)) - F(self.CKL))
epsoct_crit = np.max(DeltaF) / 2.
if self.epsoct > epsoct_crit:
return True
else:
return False
def __exit__(self):
self.outfile.close()
def _F_integrand(x):
return (ellipk(x) - 2 * ellipe(x)) / (41*x - 21) / np.sqrt(2*x + 3)
def F(CKL):
x_low = (3 - 3 * CKL) / (3 + 2 * CKL)
integral = quad(_F_integrand, x_low, 1)[0]
return 32 * np.sqrt(3) / np.pi * integral
def process_command_line(argv):
'''Process the command line.'''
if argv is None:
argv = sys.argv[1:]
# Configure the command line options
parser = argparse.ArgumentParser()
def_trip = Triple_octupole()
parser.add_argument('-a', '--a1', dest='a1', type=float,
default=def_trip.a1, help =
'Inner semi-major axis in au [%g]' % def_trip.a1, metavar='\b')
parser.add_argument('-b', '--a2', dest='a2', type=float,
default=def_trip.a2, help =
'Outer semi-major axis in au [%g]' % def_trip.a2, metavar='\b')
parser.add_argument('-e', '--e1', dest='e1', type=float,
default=def_trip.e1, help =
'Inner eccentricity [%g]' % def_trip.e1, metavar='\b')
parser.add_argument('-f', '--e2', dest='e2', type=float,
default=def_trip.e2, help =
'Outer eccentricity [%g]' % def_trip.e2, metavar='\b')
parser.add_argument('-i', '--inc', dest='inc', type=float,
default=def_trip.inc, help =
'Inclination of the third body in degrees [%g]' % def_trip.inc,
metavar='\b')
parser.add_argument('-g', '--g1', dest='g1', type=float,
default=def_trip.omega, help =
'Inner argument of periapsis in degrees [%g]' % (def_trip.omega * 180
/ np.pi), metavar='\b')
parser.add_argument('-L', '--Omega', dest='Omega', type=float,
default=def_trip.Omega, help =
'Longitude of ascending node in degrees [%g]' % def_trip.Omega,
metavar='\b')
parser.add_argument('-t', '--end', dest='tstop', type=float,
default=def_trip.tstop, help = 'Total time of integration in years [%g]'
% def_trip.tstop, metavar='\b')
parser.add_argument('-C', '--cpu', dest='cputstop', type=float,
default=def_trip.cputstop, help =
'cpu time limit in seconds, if -1 then no limit [%g]' %
def_trip.cputstop, metavar='\b')
parser.add_argument('-F', '--freq', dest='outfreq', type=int,
default=def_trip.outfreq, help = 'Output frequency [%g]' %
def_trip.outfreq, metavar='\b')
parser.add_argument('-A', '--abstol', dest='atol', type=float,
default=def_trip.atol, help = 'Absolute accuracy [%g]' %
def_trip.atol, metavar='\b')
parser.add_argument('-R', '--reltol', dest='rtol', type=float,
default=def_trip.rtol, help = 'Relative accuracy [%g]' %
def_trip.rtol, metavar='\b')
parser.add_argument('--epsoct', dest='epsoct', type=float, help =
'Set epsilon_octupole parameter (override SMA and e2 settings)',
metavar='\b')
parser.add_argument('--phiq', dest='phiq', type=float, help =
'Set the constant phi_q (override e1, g1, and Omega)', metavar='\b')
parser.add_argument('--chi', dest='chi', type=float, help =
'Set the constant chi (override e1, g1, and Omega)', metavar='\b')
parser.add_argument('--algorithm', dest='algo', type=str,
default=def_trip.integration_algo, help = 'Integration algorithm [%s]'
% def_trip.integration_algo)
arguments = parser.parse_args()
return arguments
def main(argv=None):
args = process_command_line(argv)
to = Triple_octupole(a1=args.a1, a2=args.a2, e1=args.e1, e2=args.e2,
inc=args.inc, argperi=args.g1, longascnode=args.Omega,
epsoct=args.epsoct, phiq=args.phiq, chi=args.chi, tstop=args.tstop,
cputstop=args.cputstop, outfreq=args.outfreq, atol=args.atol,
rtol=args.rtol, integration_algo=args.algo)
to.integrate()
return 0
if __name__=='__main__':
status = main()
sys.exit(status)
```
#### File: triplesec/tests/test_triple.py
```python
import os
from numpy.testing import assert_allclose
from ..triplesec import Triple
###
### Object creation tests
###
def test_make_Triple():
'''Try to create a Triple class.'''
t = Triple()
def test_nooct():
'''Try to turn the octupole term off.'''
t = Triple(octupole=False)
def test_setoptions():
'''Try to set some options.'''
t = Triple(a1=1, a2=20, e1=.1, e2=.3, m1=1, m2=.5, m3=2, argperi1=90,
argperi2=25, r1=1, r2=2, inc=70)
###
### Integration tests
###
def test_integrate():
'''Try to integrate a triple.'''
t = Triple(tstop=10)
t.integrate()
def test_integrate_tofile():
'''See if we can integrate the triple and write to file.'''
t = Triple(tstop=10, outfilename='foo.dat')
t.integrate()
os.remove('foo.dat') # Clean up
def test_ecc_extrema():
'''See that we can use the eccmaxima function.'''
t = Triple(tstop=10)
t.ecc_extrema()
def test_ecc_extrema_tofile():
'''See that we can use the eccmaxima function and write to file.'''
t = Triple(tstop=10, outfilename='foo.dat')
t.ecc_extrema()
os.remove('foo.dat') # Clean up
def test_cputimeout():
'''Make sure that the integration halts after exceeding the maximum CPU
integration time.'''
large_time = 1e9
t = Triple(tstop=large_time, cputstop=.1)
t.integrate()
assert t.t < large_time
# todo test conservation of constants
``` |
{
"source": "joe-antognini/zoia",
"score": 2
} |
#### File: tests/backend/test_json.py
```python
import tempfile
import unittest
import unittest.mock
from pathlib import Path
from ..context import zoia
import zoia.backend.config
import zoia.backend.json
from ..fixtures.metadata import ZoiaUnitTest
class TestMetadata(unittest.TestCase):
def setUp(self):
self._tmpdir = tempfile.TemporaryDirectory()
self.tmpdir = Path(self._tmpdir.name)
library_root = self.tmpdir / 'library'
db_root = self.tmpdir / 'metadata'
library_root.mkdir()
db_root.mkdir()
self.zoia_config = zoia.backend.config.ZoiaConfig(
library_root=str(library_root),
db_root=str(db_root),
backend=zoia.backend.config.ZoiaBackend.JSON,
)
def tearDown(self):
self._tmpdir.cleanup()
def test_metadata_init(self):
metadata = zoia.backend.json.JSONMetadata(self.zoia_config)
self.assertIsNotNone(metadata)
self.assertEqual(metadata._metadata, {})
def test_write_load_metadata(self):
old_metadata = zoia.backend.json.JSONMetadata(self.zoia_config)
old_metadata._metadata = {'foo': 'bar'}
old_metadata.write()
new_metadata = zoia.backend.json.JSONMetadata(self.zoia_config)
self.assertEqual(old_metadata._metadata, new_metadata._metadata)
def test___contains__(self):
metadata = zoia.backend.json.JSONMetadata(self.zoia_config)
metadata._metadata = {'foo': 'bar'}
self.assertIn('foo', metadata)
self.assertNotIn('baz', metadata)
def test___getitem__(self):
metadata = zoia.backend.json.JSONMetadata(self.zoia_config)
metadata._metadata = {'foo': 'bar'}
self.assertEqual(metadata['foo'], 'bar')
def test___setitem__(self):
metadata = zoia.backend.json.JSONMetadata(self.zoia_config)
metadata._metadata = {'foo': 'bar'}
metadata['baz'] = 'qux'
self.assertEqual(metadata._metadata, {'foo': 'bar', 'baz': 'qux'})
def test_rename_key(self):
metadata = zoia.backend.json.JSONMetadata(self.zoia_config)
metadata._metadata = {'foo': 'bar', 'baz': 'qux'}
metadata.rename_key('foo', 'quux')
self.assertEqual(metadata._metadata, {'quux': 'bar', 'baz': 'qux'})
def test_rename_key_existing_key(self):
metadata = zoia.backend.json.JSONMetadata(self.zoia_config)
metadata._metadata = {'foo': 'bar', 'baz': 'qux'}
with self.assertRaises(KeyError):
metadata.rename_key('quuz', 'foo')
with self.assertRaises(KeyError):
metadata.rename_key('foo', 'baz')
class TestMetadataGetters(ZoiaUnitTest):
def setUp(self):
super().setUp()
self.metadata._metadata = {
'doe09-foo': {'arxiv_id': '0901.0123'},
'johnson13-qux': {'doi': '10.1000/foo'},
'roe19-baz': {'isbn': '9781499999990'},
'smith10-bar': {'arxiv_id': '1002.1001'},
'thompson11-quux': {'pdf_md5': '2aa5d113c95b2432dbdb7c6440115774'},
}
def test_get_arxiv_ids(self):
self.assertTrue(self.metadata.arxiv_id_exists('0901.0123'))
self.assertFalse(self.metadata.arxiv_id_exists('0901.0124'))
def test_get_isbns(self):
self.assertTrue(self.metadata.isbn_exists('9781499999990'))
self.assertFalse(self.metadata.isbn_exists('9781499999991'))
def test_get_dois(self):
self.assertTrue(self.metadata.doi_exists('10.1000/foo'))
self.assertFalse(self.metadata.doi_exists('10.1000/bar'))
def test_get_pdf_md5_hashes(self):
self.assertTrue(
self.metadata.pdf_md5_hash_exists(
'2aa5d113c95b2432dbdb7c6440115774'
)
)
self.assertFalse(self.metadata.pdf_md5_hash_exists('foo'))
```
#### File: tests/cli/test_config.py
```python
import os
import tempfile
import unittest
import unittest.mock
from click.testing import CliRunner
from ..context import zoia
import zoia.cli
import zoia.cli.config
class TestConfigValidator(unittest.TestCase):
def test__config_validator_good_obj(self):
good_obj = {
'library_root': '/tmp/foo',
'db_root': '/tmp/bar',
'backend': 'json',
}
self.assertIsNone(zoia.cli.config._config_validator(good_obj))
def test__config_validator_bad_obj(self):
bad_obj = {
'db_root': '/tmp/bar',
'backend': 'json',
}
with self.assertRaises(zoia.parse.yaml.ZoiaYamlValidationError):
zoia.cli.config._config_validator(bad_obj)
bad_obj = {
'library_root': '/tmp/foo',
'db_root': '/tmp/bar',
'backend': 'foo',
}
with self.assertRaises(zoia.parse.yaml.ZoiaYamlValidationError):
zoia.cli.config._config_validator(bad_obj)
class TestConfig(unittest.TestCase):
@unittest.mock.patch(
'zoia.cli.config.zoia.backend.config.get_config_filepath'
)
@unittest.mock.patch('zoia.cli.config.zoia.parse.yaml.edit_until_valid')
def test_config(self, mock_edit, mock_get_config_filepath):
with tempfile.TemporaryDirectory() as tmpdir:
config_filename = os.path.join(tmpdir, 'config.yaml')
mock_get_config_filepath.return_value = config_filename
config = zoia.backend.config.ZoiaConfig(
library_root='/tmp/foo', db_root='/tmp/bar', backend='sqlite'
)
zoia.backend.config.save_config(config, config_filename)
config_dict = config.to_dict()
config_dict['backend'] = 'json'
mock_edit.return_value = config_dict
runner = CliRunner()
result = runner.invoke(zoia.cli.zoia, ['config'])
self.assertEqual(result.exit_code, 0)
new_config = zoia.backend.config.load_config(config_filename)
self.assertEqual(
new_config.backend, zoia.backend.config.ZoiaBackend.JSON
)
```
#### File: tests/cli/test_edit.py
```python
import unittest
import unittest.mock
import json
from copy import copy
from click.testing import CliRunner
from ..context import zoia
from ..fixtures.metadata import ZoiaUnitTest
import zoia.cli
class TestEdit(ZoiaUnitTest):
@unittest.mock.patch('zoia.cli.note.zoia.backend.config.load_config')
@unittest.mock.patch('zoia.cli.note.click.edit')
def test_edit(self, mock_edit, mock_load_config):
mock_load_config.return_value = self.config
self.metadata._metadata = {
'doe+roe01-foo': {
'authors': [['John', 'Doe'], ['Jane', 'Roe']],
'title': 'Foo',
'year': 2001,
},
}
self.metadata.write()
new_metadata = copy(self.metadata._metadata['doe+roe01-foo'])
new_metadata['year'] = 2002
mock_edit.return_value = json.dumps(new_metadata)
runner = CliRunner()
result = runner.invoke(
zoia.cli.zoia, ['edit', 'doe+roe01-foo', '--syntax', 'json']
)
self.assertEqual(result.exit_code, 0)
metadata = zoia.backend.metadata.get_metadata(self.config)
self.assertEqual(metadata['doe+roe01-foo']['year'], 2002)
```
#### File: tests/cli/test_init.py
```python
import os
import tempfile
import unittest
import unittest.mock
from pathlib import Path
from ..context import zoia
import zoia.cli.init
class TestIsValidInitDir(unittest.TestCase):
def test__is_valid_init_dir_none(self):
self.assertFalse(zoia.cli.init._is_valid_init_dir(None))
def test__is_valid_init_dir_no_exists(self):
with tempfile.TemporaryDirectory() as tmpdir:
directory = os.path.join(tmpdir, 'foo')
self.assertTrue(zoia.cli.init._is_valid_init_dir(directory))
def test__is_valid_init_dir_exists_and_empty(self):
with tempfile.TemporaryDirectory() as tmpdir:
self.assertTrue(zoia.cli.init._is_valid_init_dir(tmpdir))
def test__is_valid_init_dir_exists_not_empty(self):
with tempfile.TemporaryDirectory() as tmpdir:
(Path(tmpdir) / 'foo').touch()
self.assertFalse(zoia.cli.init._is_valid_init_dir(tmpdir))
@unittest.mock.patch('zoia.cli.init._is_valid_init_dir')
@unittest.mock.patch('zoia.cli.init.os.getcwd')
class TestGetDefaultDirectory(unittest.TestCase):
def test__get_default_directory_cwd(
self, mock_getcwd, mock_is_valid_init_dir
):
mock_getcwd.return_value = '/home/foo'
mock_is_valid_init_dir.side_effect = lambda x: x == '/home/foo'
observed_default_directory = zoia.cli.init._get_default_library_root()
expected_default_directory = '/home/foo'
self.assertEqual(
observed_default_directory, expected_default_directory
)
def test__get_default_directory_subdir(
self, mock_getcwd, mock_is_valid_init_dir
):
mock_getcwd.return_value = '/home/foo'
mock_is_valid_init_dir.side_effect = lambda x: x == '/home/foo/zoia'
observed_default_directory = zoia.cli.init._get_default_library_root()
expected_default_directory = '/home/foo/zoia'
self.assertEqual(
observed_default_directory, expected_default_directory
)
def test__get_default_directory_none(
self, mock_getcwd, mock_is_valid_init_dir
):
mock_getcwd.return_value = '/home/foo'
mock_is_valid_init_dir.side_effect = lambda x: False
observed_default_directory = zoia.cli.init._get_default_library_root()
self.assertIsNone(observed_default_directory)
```
#### File: tests/parse/test_classification.py
```python
import os
import tempfile
import unittest
from ..context import zoia # noqa: F401
from zoia.parse.classification import IdType
from zoia.parse.classification import classify_identifier
from zoia.parse.classification import classify_and_normalize_identifier
class TestClassifyIdentifier(unittest.TestCase):
def test_classify_identifier_pdf(self):
with tempfile.TemporaryDirectory() as tmpdir:
filename = os.path.join(tmpdir, 'foo.pdf')
with open(filename, 'wb') as fp:
fp.write(b'%PDF')
observed_id_type = classify_identifier(filename)
expected_id_type = IdType.PDF
self.assertEqual(observed_id_type, expected_id_type)
def test_classify_identifier_arxiv(self):
identifier = '2001.00001'
observed_id_type = classify_identifier(identifier)
expected_id_type = IdType.ARXIV
self.assertEqual(observed_id_type, expected_id_type)
def test_classify_identifier_isbn(self):
identifier = '9780691159027'
observed_id_type = classify_identifier(identifier)
expected_id_type = IdType.ISBN
self.assertEqual(observed_id_type, expected_id_type)
def test_classify_identifier_doi(self):
identifier = '10.1000/foo'
observed_id_type = classify_identifier(identifier)
expected_id_type = IdType.DOI
self.assertEqual(observed_id_type, expected_id_type)
class TestClassifyAndNormalizeIdentifier(unittest.TestCase):
def test_classify_and_normalize_identifier_pdf(self):
with tempfile.TemporaryDirectory() as tmpdir:
filename = os.path.join(tmpdir, 'foo.pdf')
with open(filename, 'wb') as fp:
fp.write(b'%PDF')
(
observed_id_type,
normalized_identifier,
) = classify_and_normalize_identifier(filename)
expected_id_type = IdType.PDF
self.assertEqual(observed_id_type, expected_id_type)
self.assertEqual(normalized_identifier, filename)
def test_classify_and_normalize_identifier_arxiv(self):
identifier = 'arxiv:2001.00001v2'
(
observed_id_type,
normalized_identifier,
) = classify_and_normalize_identifier(identifier)
expected_id_type = IdType.ARXIV
self.assertEqual(observed_id_type, expected_id_type)
self.assertEqual(normalized_identifier, '2001.00001')
def test_classify_and_normalize_identifier_isbn(self):
identifier = '978-0-691159-02-7'
(
observed_id_type,
normalized_identifier,
) = classify_and_normalize_identifier(identifier)
expected_id_type = IdType.ISBN
self.assertEqual(observed_id_type, expected_id_type)
self.assertEqual(normalized_identifier, '9780691159027')
def test_classify_and_normalize_identifier_doi(self):
identifier = 'doi:10.1000/foo'
(
observed_id_type,
normalized_identifier,
) = classify_and_normalize_identifier(identifier)
expected_id_type = IdType.DOI
self.assertEqual(observed_id_type, expected_id_type)
self.assertEqual(normalized_identifier, '10.1000/foo')
```
#### File: tests/parse/test_doi.py
```python
import unittest
from ..context import zoia
import zoia.parse.doi
class TestDoi(unittest.TestCase):
def test_is_doi(self):
self.assertFalse(zoia.parse.doi.is_doi('foo'))
self.assertFalse(zoia.parse.doi.is_doi('11.23915/distill.00005'))
self.assertFalse(zoia.parse.doi.is_doi('10.1/distill.00005'))
self.assertFalse(zoia.parse.doi.is_doi('10.23915'))
self.assertFalse(zoia.parse.doi.is_doi('10.23915/'))
self.assertTrue(zoia.parse.doi.is_doi('10.23915/distill.00005'))
self.assertTrue(zoia.parse.doi.is_doi('doi:10.23915/distill.00005'))
def test_normalize(self):
self.assertEqual(
zoia.parse.doi.normalize('10.23915/distill.00005'),
'10.23915/distill.00005',
)
self.assertEqual(
zoia.parse.doi.normalize('doi:10.23915/distill.00005'),
'10.23915/distill.00005',
)
self.assertEqual(
zoia.parse.doi.normalize('http://doi.org/10.23915/distill.00005'),
'10.23915/distill.00005',
)
self.assertEqual(
zoia.parse.doi.normalize(
'https://dx.doi.org/10.23915/distill.00005'
),
'10.23915/distill.00005',
)
self.assertEqual(
zoia.parse.doi.normalize(
'https://arxiv.org/10.23915/distill.00005'
),
'https://arxiv.org/10.23915/distill.00005',
)
```
#### File: tests/parse/test_normalization.py
```python
import unittest
from ..context import zoia
import zoia.parse.normalization
class TestNormalization(unittest.TestCase):
def test_strip_diacritics(self):
self.assertEqual(
zoia.parse.normalization.strip_diacritics('foo'), 'foo'
)
self.assertEqual(
zoia.parse.normalization.strip_diacritics('Foo'), 'Foo'
)
self.assertEqual(
zoia.parse.normalization.strip_diacritics('Fóò'), 'Foo'
)
def test_normalize_string(self):
self.assertEqual(zoia.parse.normalization.normalize_name('foo'), 'foo')
self.assertEqual(zoia.parse.normalization.normalize_name('Foo'), 'foo')
self.assertEqual(zoia.parse.normalization.normalize_name('Fóò'), 'foo')
def test_split_name(self):
self.assertEqual(
zoia.parse.normalization.split_name('Doe'), ['', 'Doe']
)
self.assertEqual(
zoia.parse.normalization.split_name('<NAME>'), ['John', 'Doe']
)
self.assertEqual(
zoia.parse.normalization.split_name('<NAME>'),
['John', '<NAME>'],
)
self.assertEqual(
zoia.parse.normalization.split_name('John Q. Public'),
['<NAME>.', 'Public'],
)
def test_normalize_title_word(self):
self.assertEqual(
zoia.parse.normalization.normalize_title_word('The'), 'the'
)
self.assertEqual(
zoia.parse.normalization.normalize_title_word('"Why"'), 'why'
)
self.assertEqual(
zoia.parse.normalization.normalize_title_word(r'$\eta_3$'), 'eta3'
)
```
#### File: zoia/cli/init.py
```python
import os
from pathlib import Path
import click
import zoia
import zoia.backend.metadata
def _is_valid_init_dir(directory):
"""Determine whether a given directory is a valid root directory for zoia.
A valid directory must either not exist or be empty.
"""
if directory is None:
return False
return not Path(directory).exists() or len(os.listdir(directory)) == 0
def _get_default_library_root():
"""Return a default directory for the zoia library root.
The default library root will be set by trying the following directories in
order until a valid directory is found:
1. The user's current working directory.
2. A subdirectory of the user's current working directory called `zoia`.
If no valid directory is found from that list no default will be provided.
"""
default_directories = [os.getcwd(), os.path.join(os.getcwd(), 'zoia')]
for default_directory in default_directories:
if _is_valid_init_dir(default_directory):
return default_directory
return None
@click.command()
def init():
"""Initialize the `zoia` library."""
while True:
library_root = click.prompt(
'Please provide a directory for your library',
default=_get_default_library_root(),
)
library_root = os.path.expanduser(library_root)
if _is_valid_init_dir(library_root):
break
if library_root is not None:
click.secho(
f'Error: Directory {library_root} exists and is not empty.',
fg='red',
)
os.makedirs(library_root, exist_ok=True)
config = zoia.backend.config.ZoiaConfig(library_root=library_root)
zoia.backend.config.save_config(config)
os.makedirs(config.db_root, exist_ok=True)
# Start with an empty dictionary in the metadata file.
metadata = zoia.backend.metadata.get_metadata(config)
metadata.write()
click.secho(
f'Your zoia library was successfully initialized at {library_root}!',
fg='blue',
)
```
#### File: zoia/cli/note.py
```python
import os
import sys
import yaml
import click
import zoia.backend.config
import zoia.parse.yaml as zoia_yaml
def _create_header(metadatum):
"""Create a header string for a paper."""
header = {}
if 'title' in metadatum:
header['title'] = metadatum['title']
if 'authors' in metadatum:
authors = metadatum['authors']
if len(authors) <= 4:
header['authors'] = [' '.join(author) for author in authors]
else:
header['authors'] = [' '.join(author) for author in authors[:3]]
header['authors'].append('et al.')
if 'year' in metadatum:
header['year'] = metadatum['year']
if 'tags' in metadatum:
header['tags'] = ', '.join(metadatum['tags'])
return '---\n' + zoia_yaml.dump(header, indent=4) + '---\n'
@click.command()
@click.argument('citekey', required=True)
def note(citekey):
"""Write a note for a document."""
config = zoia.backend.config.load_config()
metadata = zoia.backend.metadata.get_metadata(config)
if citekey not in metadata:
click.secho(f'Citekey {citekey} does not exist in library.', fg='red')
sys.exit(1)
note_path = os.path.join(config.library_root, citekey, 'notes.md')
metadatum = metadata[citekey]
header = _create_header(metadatum)
body = ''
if os.path.isfile(note_path):
with open(note_path) as fp:
body = fp.read()
text = header + body
while True:
text = click.edit(text=text, extension='.md')
if text is not None:
try:
note_docs = yaml.safe_load_all(text)
header = next(note_docs)
body = zoia_yaml.remove_header(text)
with open(note_path, 'w') as fp:
fp.write(body)
except StopIteration:
# We reach here if the user provided only one document. (Maybe
# they deleted the header.) Save the whole thing.
with open(note_path, 'w') as fp:
fp.write(text)
except (yaml.scanner.ScannerError, yaml.parser.ParserError):
if click.confirm(
'Error parsing header. Continue editing? If no, the file'
'will be saved as is.'
):
continue
else:
with open(note_path, 'w') as fp:
fp.write(text)
else:
click.secho('No input recorded. Nothing saved.', fg='red')
break
```
#### File: zoia/parse/doi.py
```python
import re
def is_doi(identifier):
"""Determine whether the given identifier has a valid DOI format."""
if not isinstance(identifier, str):
return False
identifier = normalize(identifier)
identifier = identifier.split('/')
if len(identifier) < 2:
return False
if not identifier[0] or not identifier[1]:
return False
prefix = identifier[0]
prefix = prefix.split('.')
if len(prefix) < 2:
return False
if any(map(lambda x: not x.isnumeric(), prefix)):
return False
if prefix[0] != '10':
return False
return int(prefix[1]) >= 1000
def normalize(identifier):
"""Normalize a DOI."""
identifier = identifier.lower()
prefix = 'doi:'
if identifier.startswith(prefix):
identifier = identifier[len(prefix) :]
else:
pattern = re.compile(r'^(https?://)?(www\.)?(dx\.)?doi\.org/')
if pattern.match(identifier) is not None:
identifier = pattern.split(identifier)[-1]
return identifier
``` |
{
"source": "joeaortiz/clevr-dataset-gen-1",
"score": 3
} |
#### File: clevr-dataset-gen-1/image_generation/look_at.py
```python
import numpy as np
def normalize(x: np.ndarray) -> np.ndarray:
assert x.ndim == 1, 'x must be a vector (ndim: 1)'
return x / np.linalg.norm(x)
def look_at(
eye,
target,
up,
) -> np.ndarray:
"""Returns transformation matrix with eye, at and up.
Parameters
----------
eye: (3,) float
Camera position.
target: (3,) float
Camera look_at position.
up: (3,) float
Vector that defines y-axis of camera (z-axis is vector from eye to at).
Returns
-------
T_cam2world: (4, 4) float (if return_homography is True)
Homography transformation matrix from camera to world.
Points are transformed like below:
# x: camera coordinate, y: world coordinate
y = trimesh.transforms.transform_points(x, T_cam2world)
x = trimesh.transforms.transform_points(
y, np.linalg.inv(T_cam2world)
)
"""
eye = np.asarray(eye, dtype=float)
if target is None:
target = np.array([0, 0, 0], dtype=float)
else:
target = np.asarray(target, dtype=float)
if up is None:
up = np.array([0, 0, -1], dtype=float)
else:
up = np.asarray(up, dtype=float)
assert eye.shape == (3,), 'eye must be (3,) float'
assert target.shape == (3,), 'target must be (3,) float'
assert up.shape == (3,), 'up must be (3,) float'
# create new axes
z_axis = normalize(target - eye)
x_axis = normalize(np.cross(up, z_axis))
y_axis = normalize(np.cross(z_axis, x_axis))
# create rotation matrix: [bs, 3, 3]
R = np.vstack((x_axis, y_axis, z_axis))
t = eye
T_cam2world = np.zeros([4,4])
T_cam2world[:3,:3] = R.T
T_cam2world[:3, 3] = t
T_cam2world[3,3] = 1.
return T_cam2world
``` |
{
"source": "joeaortiz/gbp",
"score": 3
} |
#### File: gbp/utils/derivatives.py
```python
import numpy as np
from utils import lie_algebra
"""
Standard useful derivatives.
"""
def jac_fd(inp, meas_fn, *args, delta=1e-8):
"""
Compute Jacobian of meas_fn at inp using finite difference method.
"""
z = meas_fn(inp, *args)
if isinstance(z, float):
jac = np.zeros([1, len(inp)])
else:
jac = np.zeros([len(z), len(inp)])
for i in range(len(inp)):
d_inp = np.copy(inp)
d_inp[i] += delta
jac[:, i] = (meas_fn(d_inp, *args) - meas_fn(inp, *args)) / delta
return jac
def check_jac(jac_fn, inp, meas_fn, *args, threshold=1e-3):
jac = jac_fn(inp, *args)
jacfd = jac_fd(inp, meas_fn, *args)
if np.max(jac - jacfd) < threshold:
print(f"Passed! Jacobian correct to within {threshold}")
else:
print(f"Failed: Jacobian difference to finite difference Jacobian not within threshold ({threshold})"
f"\nMaximum discrepancy between Jacobian and finite diff Jacobian: {np.max(jac - jacfd)}")
def dR_wx_dw(w, x):
"""
:param w: Minimal SO(3) rep
:param x: 3D point / vector
:return: derivative of R(w)x wrt w
"""
R = lie_algebra.so3exp(w)
dR_wx_dw = -np.dot(np.dot(R, lie_algebra.S03_hat_operator(x)),
(np.outer(w, w) + np.dot(R.T - np.eye(3), lie_algebra.S03_hat_operator(w))) / np.dot(w, w))
return dR_wx_dw
def proj_derivative(x):
if x.ndim == 1:
return np.hstack((np.eye(len(x) - 1) / x[-1], np.array([- x[:-1] / x[-1]**2]).T))
```
#### File: gbp/utils/lie_algebra.py
```python
import numpy as np
import scipy.linalg
"""
Lie algebra functions to move between group and tangent space.
"""
_EPS = np.finfo(float).eps
def S03_hat_operator(x):
"""
Hat operator for SO(3) Lie Group
"""
return np.array([[0., -x[2], x[1]],
[x[2], 0., -x[0]],
[-x[1], x[0], 0.]])
def SE3_hat_operator(x):
"""
Hat operator for SE(3) Lie Group.
First 3 elements of the minimal representation x are to do with the translation part while the
latter 3 elements are to do with the rotation part.
"""
return np.array([[0., -x[5], x[4], x[0]],
[x[5], 0., -x[3], x[1]],
[-x[4], x[3], 0., x[2]],
[0., 0., 0., 0.]])
def so3exp(w):
"""
Maps so(3) --> SO(3) group with closed form expression.
"""
theta = np.linalg.norm(w)
if theta < _EPS * 3:
return np.eye(3)
else:
w_hat = S03_hat_operator(w)
R = np.eye(3) + (np.sin(theta) / theta) * w_hat + ((1 - np.cos(theta)) / theta**2) * np.dot(w_hat, w_hat)
return R
def se3exp(x):
"""
Maps se(3) --> SE(3) group.
Uses closed form expression if rotation is not identity.
"""
if (x[3:6] == np.zeros(3)).all():
T = np.hstack((np.eye(3), np.array([x[0:3]]).T))
T = np.vstack((T, np.array([0.0, 0.0, 0.0, 1.0])))
return T
else:
# Use closed form expression.
T = np.zeros([4, 4])
T[3, 3] = 1.0
T[0:3, 0:3] = so3exp(x[3:6])
w_hat = S03_hat_operator(x[3:6])
theta = np.linalg.norm(x[3:6])
V = np.eye(3) + ((1-np.cos(theta)) / theta**2) * w_hat + ((theta - np.sin(theta)) / theta**3) * np.dot(w_hat, w_hat)
T[0:3, 3] = np.dot(V, x[0:3])
return T
def so3log(R):
"""
Maps SO(3) --> so(3) group. Holds for d between -1 and 1
"""
if (R == np.eye(3)).all():
return np.array([0.0, 0.0, 0.0])
else:
d = 0.5 * (np.trace(R) - 1)
lnR = (np.arccos(d) / (2 * np.sqrt(1 - d**2))) * (R - R.T)
w = np.array([0.0, 0.0, 0.0])
w[0] = lnR[2, 1]
w[1] = lnR[0, 2]
w[2] = lnR[1, 0]
return w
def se3log(T):
"""
Maps SO(3) --> so(3) group.
"""
R = T[0:3, 0:3]
t = T[0:3, 3]
if (R == np.eye(3)).all():
return np.concatenate((t, np.array([0.0, 0.0, 0.0])))
else:
w = so3log(R)
w_hat = S03_hat_operator(w)
theta = np.linalg.norm(w)
V = np.eye(3) + ((1-np.cos(theta)) / theta**2) * w_hat + ((theta - np.sin(theta)) / theta**3) * np.dot(w_hat, w_hat)
Vinv = scipy.linalg.inv(V)
u = np.dot(Vinv, t)
x = np.concatenate((u, w))
return x
```
#### File: gbp/utils/read_balfile.py
```python
import numpy as np
def read_balfile(balfile):
with open(balfile, 'r') as f:
while True:
line = f.readline()
if len(line.split()) != 0:
if line.split()[0] != '#':
break
n_keyframes, n_points, n_edges = [int(x) for x in line.split()]
K = np.zeros([3, 3])
K[0, 0], K[1, 1], K[0, 2], K[1, 2] = [float(x) for x in f.readline().split()]
K[2, 2] = 1.
measurements_camIDs, measurements_lIDs, measurements = [], [], []
for i in range(n_edges):
split = f.readline().split()
measurements_camIDs.append(int(split[0]))
measurements_lIDs.append(int(split[1]))
measurements.append(float(split[2]))
measurements.append(float(split[3]))
cam_mean, lmk_mean = [], []
for i in range(n_keyframes * 6):
cam_mean.append(float(f.readline().split()[0]))
for i in range(n_points * 3):
lmk_mean.append(float(f.readline().split()[0]))
cam_means = np.reshape(cam_mean, [-1, 6])
lmk_means = np.reshape(lmk_mean, [-1, 3])
measurements = np.reshape(measurements, [-1, 2])
return n_keyframes, n_points, n_edges, cam_means, lmk_means, measurements, measurements_camIDs, measurements_lIDs, K
```
#### File: gbp/utils/transformations.py
```python
import numpy as np
from utils import lie_algebra
def proj(x):
if x.ndim == 1:
return x[:-1] / x[-1]
elif x.ndim == 2:
return np.divide(x[:, :-1].T, x[:, -1]).T
# ----------------------------- get transformation functions -----------------------------
def getT_axisangle(x):
"""
Get the transformation matrix from the minimal representation where the angle parameters are in axis angle form.
"""
T = np.zeros([4, 4])
T[3, 3] = 1.0
T[0:3, 0:3] = lie_algebra.so3exp(x[3:6])
T[0:3, 3] = x[0:3]
return T
def getT_qt(x):
"""
Get the transformation matrix from the camera position and quaternion parameters.
"""
T = np.zeros([4, 4])
T[3, 3] = 1.0
q = Quaternion(x[3:])
T[0:3, 0:3] = q.rot_matrix()
T[0:3, 3] = x[0:3]
return T
# ---------------------------------- Quaternions -----------------------------------------------
def normalize(v, tolerance=1e-4):
mag2 = sum(n * n for n in v)
if abs(mag2 - 1.0) > tolerance:
mag = np.sqrt(mag2)
v = tuple(n / mag for n in v)
return np.array(v)
class Quaternion:
def __init__(self, q=None, axis=None, angle=None):
axis = normalize(axis) # Normalize the axis vector so we have a unit quaternion
if q is None:
self.w = np.cos(angle / 2)
self.x = np.sin(angle / 2) * axis[0]
self.y = np.sin(angle / 2) * axis[1]
self.z = np.sin(angle / 2) * axis[2]
self.q = np.array([self.w, self.x, self.y, self.z])
if q is not None:
self.q = q
def rotate(self, v):
point = np.array([0, v[0], v[1], v[2]])
return q_multiply(q_multiply(self.q, point), self.conjugate)[1:]
def conjugate(self):
return np.array([self.q[0], -self.q[1], -self.q[2], -self.q[3]])
def rot_matrix(self):
q = self.q
R = [[1 - 2 * (q[2] ** 2 + q[3] ** 2), 2 * (q[1] * q[2] - q[3] * q[0]), 2 * (q[1] * q[3] + q[2] * q[0])],
[2 * (q[1] * q[2] + q[3] * q[0]), 1 - 2 * (q[1] ** 2 + q[3] ** 2), 2 * (q[2] * q[3] - q[1] * q[0])],
[2 * (q[1] * q[3] - q[2] * q[0]), 2 * (q[2] * q[3] + q[1] * q[0]), 1 - 2 * (q[1] ** 2 + q[2] ** 2)]]
return np.array(R)
def q_multiply(q1, q2):
"""
Multiply together two quaternions
:return: product of two quaternions
"""
w1, x1, y1, z1 = q1
w2, x2, y2, z2 = q2
w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2
z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2
return np.array([w, x, y, z])
# ---------------------------------------- Euler -----------------------------------------------
def eulerAnglesToRotationMatrix(theta):
"""
Calculates Rotation Matrix given euler angles.
"""
R_x = np.array([[1, 0, 0],
[0, np.cos(theta[0]), -np.sin(theta[0])],
[0, np.sin(theta[0]), np.cos(theta[0])]
])
R_y = np.array([[np.cos(theta[1]), 0, np.sin(theta[1])],
[0, 1, 0],
[-np.sin(theta[1]), 0, np.cos(theta[1])]
])
R_z = np.array([[np.cos(theta[2]), -np.sin(theta[2]), 0],
[np.sin(theta[2]), np.cos(theta[2]), 0],
[0, 0, 1]
])
R = np.dot(R_z, np.dot(R_y, R_x))
return R
# -------------------------------------- Rotation matrices -----------------------------------------
def x_rotation_mat(angle):
# angle in radians
return np.array([[1, 0, 0], [0, np.cos(angle), -np.sin(angle)], [0, np.sin(angle), np.cos(angle)]])
def y_rotation_mat(angle):
# angle in radians
return np.array([[np.cos(angle), 0, np.sin(angle)], [0, 1, 0], [-np.sin(angle), 0, np.cos(angle)]])
def z_rotation_mat(angle):
# angle in radians
return np.array([[np.cos(angle), -np.sin(angle), 0], [np.sin(angle), np.cos(angle), 0], [0, 0, 1]])
def angle_between(v1, v2):
"""
Angle between 2 vectors.
"""
return np.arccos(np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
# ------------------------------------ Specific ------------------------------------------------
_EPS = np.finfo(float).eps * 4.0
def transform44(l):
"""
From evaluate_rpe.py from ORBSLAM
Generate a 4x4 homogeneous transformation matrix from a 3D point and unit quaternion.
Input:
l -- tuple consisting of (stamp,tx,ty,tz,qx,qy,qz,qw) where
(tx,ty,tz) is the 3D position and (qx,qy,qz,qw) is the unit quaternion.
Output:
matrix -- 4x4 homogeneous transformation matrix
"""
t = l[1:4]
q = np.array(l[4:8], dtype=np.float64, copy=True)
nq = np.dot(q, q)
if nq < _EPS:
return np.array((
(1.0, 0.0, 0.0, t[0])
(0.0, 1.0, 0.0, t[1])
(0.0, 0.0, 1.0, t[2])
(0.0, 0.0, 0.0, 1.0)
), dtype=np.float64)
q *= np.sqrt(2.0 / nq)
q = np.outer(q, q)
return np.array((
(1.0 - q[1, 1] - q[2, 2], q[0, 1] - q[2, 3], q[0, 2] + q[1, 3], t[0]),
(q[0, 1] + q[2, 3], 1.0 - q[0, 0] - q[2, 2], q[1, 2] - q[0, 3], t[1]),
(q[0, 2] - q[1, 3], q[1, 2] + q[0, 3], 1.0 - q[0, 0] - q[1, 1], t[2]),
(0.0, 0.0, 0.0, 1.0)
), dtype=np.float64)
``` |
{
"source": "joearnet/automatic-ripping-machine",
"score": 3
} |
#### File: joearnet/automatic-ripping-machine/getmovietitle.py
```python
import argparse
import urllib
import os
import datetime
import pydvdid
import unicodedata
import xmltodict
import sys
import re
def entry():
""" Entry to program, parses arguments"""
parser = argparse.ArgumentParser(description='Get Movie Title from DVD or Blu-Ray')
parser.add_argument('-p', '--path', help='Mount path to disc', required=True)
return parser.parse_args()
def getdvdtitle():
""" Calculates CRC64 for the DVD and calls Windows Media
Metaservices and returns the Title and year of DVD """
crc64 = pydvdid.compute(args.path)
# print (crc64)
dvd_info_xml = urllib.request.urlopen(
"http://metaservices.windowsmedia.com/pas_dvd_B/template/GetMDRDVDByCRC.xml?CRC={0}".
format(crc64)).read()
doc = xmltodict.parse(dvd_info_xml)
dvd_title = doc['METADATA']['MDR-DVD']['dvdTitle']
dvd_release_date = doc['METADATA']['MDR-DVD']['releaseDate']
# title + release year
return dvd_title + " (" + dvd_release_date.split()[0] + ")"
def getbluraytitle():
""" Get's Blu-Ray title by parsing XML in bdmt_eng.xml """
with open(args.path + '/BDMV/META/DL/bdmt_eng.xml', "rb") as xml_file:
doc = xmltodict.parse(xml_file.read())
bluray_title = doc['disclib']['di:discinfo']['di:title']['di:name']
bluray_modified_timestamp = os.path.getmtime(args.path + '/BDMV/META/DL/bdmt_eng.xml')
bluray_year = (datetime.datetime.fromtimestamp(bluray_modified_timestamp).strftime('%Y'))
bluray_title = unicodedata.normalize('NFKD', bluray_title).encode('ascii', 'ignore').decode()
bluray_title = bluray_title.replace(' - Blu-rayTM', '')
bluray_title = bluray_title.replace(' - BLU-RAYTM', '')
bluray_title = bluray_title.replace(' - BLU-RAY', '')
bluray_title = bluray_title.replace(' - Blu-ray', '')
return bluray_title + " (" + bluray_year + ")"
def clean_for_filename(string):
""" Cleans up string for use in filename """
string = re.sub('\[(.*?)\]', '', string)
string = re.sub( '\s+', ' ', string)
string = string.replace(' : ',' - ')
string = string.replace(': ',' - ')
return re.sub('[^\w\-_\.\(\) ]', '', string)
#pylint: disable=C0103
args = entry()
try:
disc_title = clean_for_filename(getdvdtitle())
except:
disc_title = clean_for_filename(getbluraytitle())
print(disc_title)
else:
print(disc_title)
``` |
{
"source": "joeatbayes/mds",
"score": 3
} |
#### File: mds/client/produce_es_mds_query_list.py
```python
import Queue
#import Timer
import socket
#from util import *
import os.path
import time
import sys
import glob
import json
def elapRun(msg, begin1):
curr = time.time()
print "\n", msg, "elap1=%0.3f sec " % (curr - begin1)
class MDSIDHarvest:
def __init__(self):
self.unique_id = {}
# the es bulk load files have format
# of "index metadata\nrecord" so we will read them
# in pairs and get the object type and id
# from the meta line and create a bulk insert line
# for MDS. Accumulate those lines until we have
# enough data and the post to MDS.
def processFile(self, fiName):
begFi = time.time()
headers = {"Content-type": "text/txt"}
f = open(fiName)
while True:
l1 = f.readline()
l2 = f.readline()
if not l1:
break
if not l2:
break
o1 = json.loads(l1)
objType = o1["index"]["_type"]
objId = o1["index"]["_id"]
mdsKey = str(objId) + "/000/" + objType
self.unique_id[mdsKey] = ""
f.close()
elapRun("read File" + fiName, begFi)
def flushAndSave(self):
if len(self.unique_id) > 0:
begt = time.time()
print "begin Save ", len(self.unique_id), " keys"
allkey = self.unique_id.keys()
elapRun("obtained keys", begt)
begt = time.time()
self.acumItems = {}
keysstr = "\n".join(allkey)
elapRun("made save Str", begt)
begt = time.time()
allkey = ""
f = open("../tmp/mds_keys.txt", "w")
f.write(keysstr)
f.close()
elapRun("finished save", begt)
def produceKeySet(self, dirIn):
self.begRun = time.time()
print "produceKeySet ", dirIn
globPath =dirIn + "/*.json.txt"
fnames = glob.glob(globPath) #[:10]
print "found ", len(fnames), " files "
fnames.sort()
for fname in fnames:
self.processFile(fname)
elapRun("Finished Read", self.begRun)
self.flushAndSave()
elapRun("produceKeySet", self.begRun)
tObj = MDSIDHarvest()
#tObj.produceKeySet("/...../tmp/report")
tObj.produceKeySet("/....../el-bulk")
```
#### File: mds/client/send_es_to_mds.py
```python
import Queue
#import Timer
import socket
#from util import *
import os.path
import os
import time
import sys
import glob
import httplib
import json
def elapRun(msg, begin1):
curr = time.time()
print "\n", msg, "elap1=%0.3f sec " % (curr - begin1)
class MDSSend:
def __init__(self, serverName, serverPort):
self.serverName = serverName
self.serverPort = serverPort
self.acumItems = []
self.acumBytes = 0
def esHTTP(self, verb, uri, postStr="", headers = {}):
begPos = time.time()
r1 = ""
print "verb=", verb, " uri=", uri, "len(postStr)=", len(postStr) #, " postStr=", postStr
try:
conn = httplib.HTTPConnection(self.serverName, self.serverPort, timeout=30)
if len(postStr) > 1:
conn.request(verb, uri, postStr, headers)
else:
conn.request(verb, uri)
r1 = conn.getresponse()
data1 = ""
print "resp.status=", r1.status
if r1.status != 200:
print "status code error from server = ", r1.status, r1.msg, r1.reason
else:
data1 = r1.read()
#print "L140: data1=", data1
conn.close()
elapRun(verb + " " + uri + " sent=" + str(len(postStr)) + " returnBytes=" + str(len(data1)), begPos)
return data1
except httplib.HTTPException,e:
print "httpException", e #// " status=", r1.status, " msg=", r1.msg, " reason=", r1.reason
time.sleep(15)
return "-1"
except socket.error,e:
print "failed http fetch ", e
time.sleep(15)
return "-1"
# the es bulk load files have format
# of "index metadata\nrecord" so we will read them
# in pairs and get the object type and id
# from the meta line and create a bulk insert line
# for MDS. Accumulate those lines until we have
# enough data and the post to MDS.
def processFile(self, fiName):
headers = {"Content-type": "text/txt"}
f = open(fiName)
while True:
l1 = f.readline()
l2 = f.readline()
if not l1:
break
if not l2:
break
o1 = json.loads(l1)
objType = o1["index"]["_type"]
objId = o1["index"]["_id"]
mdsStr = str(objId) + "/000/" + objType + "=" + l2
self.acumItems.append(mdsStr)
self.acumBytes += len(mdsStr)
if self.acumBytes > 2000000:
self.flushAndSend()
f.close()
def flushAndSend(self):
if len(self.acumItems) > 0:
headers = {"Content-type": "text/txt"}
respStr = "-1"
postStr = "\n".join(self.acumItems)
tryCnt = 0
while respStr == "-1":
tryCnt += 1
respStr = self.esHTTP("POST", "/add", postStr, headers)
print "respStr[:100]=", respStr[:100]
if respStr.find("\"errors\":true") != -1:
print "Error BulkUpdate ", respStr
self.acumItems = []
self.acumBytes = 0
if respStr == "-1" and tryCnt > 15:
print "giving up"
break
return ""
def sendUpdatesFromDir(self, dirIn):
print "SendUpdatesFrom ", dirIn
globPath =dirIn + "/*.json.txt"
fnames = glob.glob(globPath)
print "found ", len(fnames), " files "
fnames.sort()
self.finishedParse = False
for fname in fnames:
self.processFile(fname)
self.begSend = time.time()
self.flushAndSend()
elapRun("Finished All Send", self.begSend)
tObj = MDSSend("127.0.0.1", 9839)
#tObj.sendUpdatesFromDir("/ag/tmp/reports")
tObj.sendUpdatesFromDir("/cores/consult/el-bulk")
``` |
{
"source": "joeatbayes/oid-mapper",
"score": 2
} |
#### File: joeatbayes/oid-mapper/generateInQueries.py
```python
import sys
import os
def quote(str):
return "\'" + str + "\'"
MaxInItems = 500
# Process input file reading line by line.
# Break it up into chunks and generate
# a psql file with separate insert statements
# for each chunk
def processFile(fname, fout):
fin = open(fname)
hdr = fin.readline()
buf = []
insStr = "INSERT INTO omap(chiloid, chiltbl, paroid, partbl) VALUES"
while True:
dline = fin.readline().strip()
if dline:
flds = dline.split(",")
#print("flds=", flds)
partbl = flds[0]
paroid = flds[1]
chiltbl = flds[2]
chiloid = flds[3]
buf.append(quote(chiloid))
if (len(buf) > MaxInItems) or (not dline):
if len(buf) > 0:
fout.write("SELECT DISTINCT paroid, partbl FROM omap WHERE omap.chiloid IN ( ");
sout = ", ".join(buf)
fout.write(sout)
fout.write(" );\n")
buf = []
else:
break
def printMsg():
print("Usage: python generateInQueries.py inFiName outFiName")
# MAIN
if len(sys.argv) < 3:
raise ValueError('not enough parameters')
foutName = sys.argv[2]
fout = open(foutName, "w")
fout.write("\\c oidmap\n\o data/log/in_query.RESULTS.txt\n")
fnameIn = sys.argv[1]
print ("fnameIn=", fnameIn, "foutName=", foutName)
if not os.path.isfile(fnameIn):
printMsg()
raise ValueError("Could not find file " + str(fnameIn))
processFile(fnameIn, fout)
```
#### File: joeatbayes/oid-mapper/make_sort_seg.py
```python
import sys
import os
MaxBufLen = 15000000
MaxBufBytes = 1000000000
def quote(str):
return "\'" + str + "\'"
def flush(buf, fiName):
if len(buf) == 0:
return
buf.sort()
with open(fiName, 'w') as fi:
fi.writelines(buf)
fi.close()
MaxBuffBytes = 999999999
# Process input file reading line by line.
# convert it into the proper field order
# sort and save to disk in segments
def processFile(fname, foutName):
fin = open(fname)
hdr = fin.readline()
buf = []
segCnt = 0
bytesBuff = 0
while True:
dline = fin.readline().strip()
# Process single line
if dline:
flds = dline.split(",")
#print("flds=", flds)
partbl = flds[0]
paroid = flds[1]
chiltbl = flds[2]
chiloid = flds[3]
tstr = chiloid + "," + paroid + "," + chiltbl + "," + partbl + "\n"
bytesBuff += len(tstr)
buf.append(tstr)
if bytesBuff > MaxBuffBytes:
flush(buf, foutName + str(segCnt).zfill(5) + ".pseg" )
segCnt += 1
bytesBuff = 0
buf = []
else:
break
# Flush any left over at end of run
flush(buff, foutName + str(segCnt) + ".pseg")
def printMsg():
print("Usage: python make_sortSeg.py inFiName outFiName")
# MAIN
if len(sys.argv) < 2:
printMsg()
raise ValueError('Please provide source file name')
fnameIn = sys.argv[1]
fnameOut = sys.argv[2]
print ("fnameIn=", fnameIn, " fnameOut=", fnameOut)
if not os.path.isfile(fnameIn):
printMsg()
raise ValueError("Could not find file " + str(fnameIn))
processFile(fnameIn, fnameOut)
``` |
{
"source": "JoeAtEgypt/recipe-app-API",
"score": 2
} |
#### File: recipe-app-API/core/models.py
```python
# creates anything that is shared between 1 or more apps so things like the migrations and the database. (All in One Place)
# A universally unique identifier (UUID) is a 128-bit "Encrypted" label used for information in computer systems.
# this is the python 'uuid' package that lets us generate the 'uid'
import uuid
# this is used for 'os.path' to create a valid path for our file destination.
import os
from django.db import models
# these ar all things that are required to extend the Django user model while making use of some of the features that come with the django user model out of the box.
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.conf import settings
def recipe_image_file_path(instance, filename):
""" Generate file path for new recipe image """
# Slice the list and return the last item.(extension)
ext = filename.split('.')[-1]
filename = f'{uuid.uuid4()}.{ext}'
# we can simply join this up to the destination path that
# we want to store the file so we want to return.
return os.path.join('uploads/recipe/', filename)
## User Manager Class:
# A class that provides the helper functions for creating a user or a super user
class UserManager(BaseUserManager):
# Overridden Functions
# "password=<PASSWORD>" = in case, you want to create a user that is not active, that does not have a password
# "**extra_fields" = says: take any of the extra functions that are passed in,
# when you call the "create_user" and pass them into extra fields
# so that we can then just add any additional fields that we create without user model.
# Not Required
# Little more flexible bec. every time we add new fields to our user, it means we don't have to add them in here.
def create_user(self, email, password=<PASSWORD>, **extra_fields):
""" Creates and Saves a new User """
# the manager can access the model.
# "self.model" = creating a new user model
# "normalize_email" is a helper function that comes with the "BaseUserManager"
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
# "using=self._db" - supporting multiple databases (Good Practice)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
""" Creates and Saves a new super user """
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
""" Custom User Model that supports using email instead of username """
# fields of our database model
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
class Tag(models.Model):
""" Tag to be used for a recipe """
name = models.CharField(max_length=255)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True,
)
def __str__(self):
return self.name
class Ingredient(models.Model):
""" Ingredient to be used in a recipe """
name = models.CharField(max_length=255)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
def __str__(self):
return self.name
class Recipe(models.Model):
""" Recipe object """
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
time_minutes = models.IntegerField()
price = models.DecimalField(max_digits=5, decimal_places=2)
link = models.CharField(max_length=255, blank=True)
# this string here, you can actually remove the quotes and just pass i the class directly.
# The issue with this is you would have to then have your classes in a correct order.
# So the Django has this useful feature where you can just provide the name of the class in a string
# and then it doesn't matter which order you place your models in.
ingredients = models.ManyToManyField('Ingredient')
tags = models.ManyToManyField('Tag')
# we don't need to make '()' bec. we don't wanna actually call the function.
# we just wanna pass a reference to the function so it can be every time we upload.
# and it gets called in the background by Django by the image filled feature.
# we'll save the file.
image = models.FileField(null=True, upload_to=recipe_image_file_path)
def __str__(self):
return self.title
```
#### File: core/tests/test_commands.py
```python
# it basically simulate the database being available and not being available for when we test our command.
from unittest.mock import patch
# Call Command Function:
# allows us to call the command in our source code.
from django.core.management import call_command
# Operational Error: that Django throws when tha database is unavailable.
# simulates the database being available or not when we run our command.
from django.db.utils import OperationalError
from django.test import TestCase
class CommandTests(TestCase):
# test what happens when we call our command and the database is already available.
def test_wait_for_db_ready(self):
""" Test waiting for db when db is available """
# to setup our test, we need to simulate the behaviour of Django when the database is available.
# Our Management command is gonna basically try and retrieve the database connection from Django.
# and it's gonna check if when we try and retrieve it, it retrieves an Operational Error or not.
# to setup our test, we're gonna override the behaviour of the "ConnectionHandler"
# and make it return true and not throw any exception and then Our Management commands should continue and allows us to continue with the execution flow.
# let's use the "patch" to mock the "ConnectionHandler" to just return true every time it's called.
with patch('django.db.utils.ConnectionHandler.__getitem__') as gi:
# the way that we tested the database is available in Django is
# we just try and retrieve the default database via "ConnectionHandler" function '__getitem__'.
# So we're gonna mock the behaviour of this "__getitem__" Using "patch" which is assigned as a variable "gi".
# whenever "getitem" is called during our test execution instead of actually before performing whatever behaviour of this function does in Django,
# it will override it and replace it with a mock object which does 2 things:
# 1. specify "return_value"
# 2. allow us to monitor how many times it was called and the different calls that were made to it.
gi.return_value = True
# test our call_command
# "wait_for_db" is gonna be the name of management command that we create.
call_command('wait_for_db')
# all we're gonna check is that "__getitem__" was called once.
self.assertEqual(gi.call_count, 1)
# what this does: it replaces the behaviour of "time.sleep" and replaces it with a mock function that returns true.
# the reason with this is to speed up the test when you run them.
# bec. if we're checking the database 5 times, then that is 5 extra seconds that it would take to run our tests.
# "ts" = "gi" (Mock Object), it must be passed in as an extra argument; Otherwise it will show a test error.
@patch('time.sleep', return_value=True)
def test_wait_for_db(self, ts): # Test if "wait_for_db" command will try database 5 times and then on the 6th time, it'll be successful and it will continue.
""" Test waiting for db """
with patch('django.db.utils.ConnectionHandler.__getitem__') as gi:
# Adding a SideEffect
# The Python Unit Tests Mock Module has a really useful option where you can set a side effect to
# the function that you're mocking.
# SideEffect: Raise The Operational Error 5 times, and then on 6th time, it's not gonna raise the error and then the call should complete.
# "[OperationalError] * 5": means you call this "__getitem__", Raise the Operational Error
# "+ [True]": means that in the additional 6th time, it won't raise the error, it will just return.
gi.side_effect = [OperationalError] * 5 + [True]
call_command('wait_for_db')
self.assertEqual(gi.call_count, 6)
``` |
{
"source": "joeavanzato/QuickScan",
"score": 3
} |
#### File: configs/network_connections/qwinsta.py
```python
import logging
import datetime
import os
import configuration_data
import configs.network_connections.qwinsta
import helpers.execute
import helpers.csv_parse
import helpers.write_detection
def launch():
logging.info("Starting 'startup' Config")
print("STARTING STARTUP SCAN")
print(os.getcwd())
command = 'qwinsta'
result = helpers.execute.execute(command)
if not result == "ERROR":
process_result(result)
def process_result(result):
#fields = ['Name', 'Reason','File Path','Registry Path','MITRE Tactic','MITRE Technique','Risk','Details']
results = result.split("\n")
helpers.write_detection.write_detection(configuration_data.detection_csv, configuration_data.fields, detection_list)
```
#### File: configs/process/start.py
```python
import logging
import datetime
import os
import sys
import re
import yaml
import configuration_data
import helpers.execute
import helpers.csv_parse
import helpers.write_detection
def launch():
logging.info("Starting 'process' Config")
print("STARTING PROCESS SCAN")
command = 'powershell -Command Get-CimInstance Win32_Process | Select-Object * | Export-CSV -NoTypeInformation -Path .\evidence\\processes.csv"'
result = helpers.execute.execute(command)
with open('configs\\evtx\\security\\malicious_commandline_regex.yml') as f:
try:
command_regex = yaml.safe_load(f)
except yaml.YAMLError as e:
print(e)
logging.exception("Error Reading configs\\evtx\\security\\malicious_commandline_regex.yml")
sys.exit(1)
with open('configs\\files\\suspicious_names.yml') as f:
try:
name_data = yaml.safe_load(f)
except yaml.YAMLError as e:
print(e)
logging.exception("Error Reading configs\\files\\suspicious_names.yml")
sys.exit(1)
re_list = []
re_dict = {}
for item in command_regex['keys']:
re_item = command_regex['keys'][item]['command']
#print(re_item)
re_list.append(re_item)
re_dict[command_regex['keys'][item]['command']] = item #For reverse lookup in YAML
if not result == "ERROR":
process("evidence\processes.csv", re_list, command_regex, name_data, re_dict)
def process(file, re_list, command_regex, name_data, re_dict):
detection_list = []
data = helpers.csv_parse.parse(file)
for d in data:
name = d['ProcessName']
command_line = d['CommandLine']
path = d['Path']
matches = {}
for r in re_list:
matches[r] = re.findall(r, command_line, flags=re.IGNORECASE | re.MULTILINE)
for k, v in matches.items():
if len(v) != 0:
detection_base = {}
print(f"Regex Detection on Active Process {command_regex['keys'][re_dict[k]]['name']}")
detection_base['Name'] = command_regex['keys'][re_dict[k]]['name']
detection_base['Reason'] = command_regex['keys'][re_dict[k]]['description']
detection_base['File Path'] = "NA"
detection_base['Registry Path'] = "NA"
detection_base['MITRE Tactic'] = command_regex['keys'][re_dict[k]]['tactic']
detection_base['MITRE Technique'] = command_regex['keys'][re_dict[k]]['technique']
detection_base['Risk'] = command_regex['keys'][re_dict[k]]['risk']
detection_base['Details'] = str(d)
detection_list.append(detection_base)
#TODO - Hash File at Path for Known Matches
#TODO - Known Suspicious Name Match
helpers.write_detection.write_detection(configuration_data.detection_csv, configuration_data.fields, detection_list)
```
#### File: configs/tasks/start.py
```python
import logging
import datetime
import os
import configuration_data
import helpers.execute
import helpers.csv_parse
import helpers.write_detection
# Field Output
# PSComputerName Name Status ExitCode DesktopInteract ErrorControl PathName ServiceType StartMode
# __GENUS __CLASS __SUPERCLASS __DYNASTY __RELPATH __PROPERTY_COUNT __DERIVATION __SERVER __NAMESPACE
# __PATH AcceptPause AcceptStop Caption CheckPoint CreationClassName DelayedAutoStart Description DisplayName
# InstallDate ProcessId ServiceSpecificExitCode Started StartName State SystemCreationClassName SystemName TagId
# WaitHint Scope Path Options ClassPath Properties SystemProperties Qualifiers Site Container
#detection_base = {}
#detection_base['Name'] = "Abnormally Short Service Name"
#detection_base['Reason'] = "Malware and Threat Actors often use short/randomized executables"
#detection_base['File Path'] = image_path
#detection_base['Registry Path'] = "NA"
#detection_base['MITRE Tactic'] = "Execution, Persistence, Privilege Escalation"
#detection_base['MITRE Technique'] = "NA"
#detection_base['Risk'] = "Medium"
#detection_base['Details'] = str(d)
def launch():
logging.info("Starting 'tasks' Config")
print("STARTING SCHEDULED TASK SCAN")
print(os.getcwd())
command = 'powershell schtasks /query /v /fo csv | ConvertFrom-CSV | Export-CSV -NoTypeInformation -Path ".\\evidence\\tasks.csv"'
result = helpers.execute.execute(command)
if not result == "ERROR":
process_services("evidence\\tasks.csv")
def process_services(file):
#fields = ['Name', 'Reason','File Path','Registry Path','MITRE Tactic','MITRE Technique','Risk','Details']
data = helpers.csv_parse.parse(file)
detection_list = []
for d in data:
if not d['HostName'] == 'HostName': #Sometimes we are seeing the headers row repeat multiple times - not sure why.
task_name = d['TaskName']
task_to_run = d['Task To Run']
try:
base_task, arguments = task_to_run.split(" ", 1)
except ValueError:
base_task = task_to_run
try:
file, extension = base_task.rsplit('.', 1)
except ValueError:
file = base_task
extension = "NA"
if len(task_name) < 5:
detection_base = {}
print(f'Abnormally Short Task Name: {task_name}')
detection_base['Name'] = "Abnormally Short Task Name"
detection_base['Reason'] = "Malware and Threat Actors often use short/randomized naming conventions"
detection_base['File Path'] = task_to_run
detection_base['Registry Path'] = "NA"
detection_base['MITRE Tactic'] = "Execution, Persistence, Privilege Escalation"
detection_base['MITRE Technique'] = "NA"
detection_base['Risk'] = "Medium"
detection_base['Details'] = str(d)
detection_list.append(detection_base)
if extension.strip().lower() in configuration_data.bad_extensions:
detection_base = {}
print(f'Potentially Dangerous Scheduled Task Extension: {task_to_run}')
detection_base['Name'] = "Potentially Dangerous Scheduled Task Extension"
detection_base['Reason'] = "Malware and Threat Actors often use common extensions that allow dangerous capabilities"
detection_base['File Path'] = task_to_run
detection_base['Registry Path'] = "NA"
detection_base['MITRE Tactic'] = "Execution, Persistence, Privilege Escalation"
detection_base['MITRE Technique'] = "NA"
detection_base['Risk'] = "Medium"
detection_base['Details'] = str(d)
detection_list.append(detection_base)
helpers.write_detection.write_detection(configuration_data.detection_csv, configuration_data.fields, detection_list)
```
#### File: QuickScan/helpers/ip_updater.py
```python
import requests
import sys
import os
import re
def launch(url_list):
"""
Receive dictionary containing file_name reference and URL as k,v pair - pass each K,V to update_list function if a file
reference doesn't already exist.
:param url_list:
:return:
"""
if not os.path.isdir('iocs'):
try:
os.mkdir('iocs')
except PermissionError:
print("PermissionError Creating Directory 'iocs'")
sys.exit(1)
#ip_pattern = '^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
ip_pattern = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
ip_compiled = re.compile(ip_pattern)
for name, url in url_list.items():
if not os.path.isfile("iocs/"+name+"_ips.txt"):
update_list(url, name, ip_compiled)
else:
print(f'Skipping IP Update for {url}')
i = 0
# TODO - Deduplication of IP Addresses
with open('iocs\\primary_ip_list.txt') as f:
for line in f:
i += 1
print(f"{i} IPs updated for usage")
def update_list(url, filename, ip_compiled):
"""
Receive a URL, Filename and basic compiled regex for IP addresses - download the relevant data and push it to the primary IOC file for IPs.
:param url:
:param filename:
:param ip_compiled:
:return:
"""
try:
list = requests.get(url)
except:
print(f"Error Contacting {url}")
return
with open(f'iocs/{filename}_ips.txt', 'w') as f:
f.write(list.text)
with open('iocs/primary_ip_list.txt', 'a') as dest:
with open(f'iocs/{filename}_ips.txt', 'r') as src:
lines = src.readlines()
for line in lines:
line = line.strip()
matches = ip_compiled.findall(line)
for match in matches:
dest.write(match+"\n")
print(f"Updated IPs from {url}")
```
#### File: joeavanzato/QuickScan/main.py
```python
import os
import traceback
import sys
import argparse
import logging
import datetime
import csv
import configuration_data
import configs.files.start
import configs.services.start
import configs.tasks.start
import configs.false_extensions.start
import configs.network_connections.start
import configs.startup.start
import configs.prefetch.start
import configs.hash_scan.start
import configs.evtx.security.start
import configs.evtx.powershell_operational.start
import configs.powershell.start
import configs.process.start
import helpers.ip_updater
import helpers.update_loki
def parse_args():
arguments = {}
parser = argparse.ArgumentParser(usage='''
### QuickScan ###
Rapidly Triage Windows Hosts for Suspicious Activity and Artifacts.
Usage Examples:
quickscan.exe
quickscan.exe -c prefetch,network_connections,services,startup
''')
parser.add_argument("-c", "--configs", help="Which Configurations to Run - if left blank, will run all.",
required=False, nargs=1, type=str)
args = parser.parse_args()
available_configs = os.listdir('configs')
if args.configs:
try:
config_list = args.configs[0].split(',')
except:
configs = args.configs[0]
config_list[0] = configs
for c in config_list:
if c not in available_configs:
print(f"Error: Could not find config - {c}")
sys.exit(1)
else:
pass
arguments['configs'] = config_list
else:
arguments['configs'] = available_configs
print(f"Using Configs: {arguments['configs']}")
return arguments
def launch_configs(args):
"""
Launch relevant configuration based on what is contained in input arguments.
:param args:
:return:
"""
if 'files' in args['configs']:
configs.files.start.launch()
if 'services' in args['configs']:
configs.services.start.launch()
if 'tasks' in args['configs']:
configs.tasks.start.launch()
if 'false_extensions' in args['configs']:
configs.false_extensions.start.launch()
if 'network_connections' in args['configs']:
configs.network_connections.start.launch()
if 'startup' in args['configs']:
configs.startup.start.launch()
if 'prefetch' in args['configs']:
configs.prefetch.start.launch()
#if 'hash_scan' in args['configs']:
# configs.hash_scan.start.launch()
if 'evtx' in args['configs']:
configs.evtx.security.start.launch()
configs.evtx.powershell_operational.start.launch()
if 'powershell' in args['configs']:
configs.powershell.start.launch()
if 'process' in args['configs']:
configs.process.start.launch()
def start_detections(file, fields):
"""
Start the CSV containing 'detections' generated by QuickScan
:param file:
:param fields:
:return:
"""
with open(file, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=fields)
writer.writeheader()
def build_ips():
# TODO - Add More Threat Feeds / Improve Fidelity
# Primarily sourced from http://www.covert.io/threat-intelligence/
"""
Provide a dictionary with file_name reference and URL to ip_updater.launch()
- typically a line-delimited text-based source for malicious IP addresses.
:return:
"""
url_list = {}
url_list['greensnow'] = 'http://blocklist.greensnow.co/greensnow.txt'
url_list['ci_badguys'] = 'http://cinsscore.com/list/ci-badguys.txt'
url_list['the_haleys_ssh'] = 'http://charles.the-haleys.org/ssh_dico_attack_hdeny_format.php/hostsdeny.txt'
url_list['mirai_scanner'] = 'http://data.netlab.360.com/feeds/mirai-scanner/scanner.list'
url_list['dshield_top10'] = 'https://feeds.dshield.org/top10-2.txt'
url_list['blocklist_de'] = 'http://lists.blocklist.de/lists/all.txt'
url_list['malcode'] = 'http://malc0de.com/bl/IP_Blacklist.txt'
url_list['rutgers'] = 'http://report.rutgers.edu/DROP/attackers'
url_list['emergingthreats_ciarmy'] = 'http://rules.emergingthreats.net/blockrules/emerging-ciarmy.rules'
url_list['emergingthreats_compromised'] = 'http://rules.emergingthreats.net/blockrules/emerging-compromised.rules'
url_list['emergingthreats_fwrules'] = 'http://rules.emergingthreats.net/fwrules/emerging-PF-CC.rules'
url_list['emergingthreats_bots'] = 'http://rules.emergingthreats.net/open/suricata/rules/botcc.rules'
url_list['emergingthreats_compromised2'] = 'http://rules.emergingthreats.net/open/suricata/rules/compromised-ips.txt'
url_list['sblam_blacklist'] = 'https://sblam.com/blacklist.txt'
url_list['tor_exits'] = 'https://raw.githubusercontent.com/SecOps-Institute/Tor-IP-Addresses/master/tor-exit-nodes.lst'
url_list['tor_nodes'] = 'https://raw.githubusercontent.com/SecOps-Institute/Tor-IP-Addresses/master/tor-nodes.lst'
url_list['binary_defense'] = 'https://www.binarydefense.com/banlist.txt'
url_list['maxmind_highrisk'] = 'https://www.maxmind.com/en/high-risk-ip-sample-list'
url_list['myip_blacklist'] = 'https://myip.ms/files/blacklist/htaccess/latest_blacklist.txt'
url_list['firehol_proxies'] = 'https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/proxyspy_1d.ipset'
url_list['scriptzteam_badips'] = 'https://raw.githubusercontent.com/scriptzteam/badIPS/main/ips.txt'
url_list['talos_intel'] = 'https://www.talosintelligence.com/documents/ip-blacklist'
url_list['torproject'] = 'https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=1.1.1.1'
url_list['urlhaus_urls'] = 'https://urlhaus.abuse.ch/downloads/text/'
url_list['loki_signatures'] = 'https://raw.githubusercontent.com/Neo23x0/signature-base/master/iocs/c2-iocs.txt'
helpers.ip_updater.launch(url_list)
def build_hashset():
"""
Update malicious hashes from high-fidelity sources.
:return:
"""
if not os.path.isfile('iocs\\loki_hashlist.txt'):
print("Updating Hash Set from Loki Signature Repository...")
helpers.update_loki.launch()
def main():
logo = '''
___ _ _ ___
/ _ \ _ _(_)__| |__/ __| __ __ _ _ _
| (_) | || | / _| / /\__ \/ _/ _` | ' \
\__\_\\_,_|_\__|_\_\|___/\__\__,_|_||_|
'''
logo2 = '''
░██████╗░██╗░░░██╗██╗░█████╗░██╗░░██╗░██████╗░█████╗░░█████╗░███╗░░██╗
██╔═══██╗██║░░░██║██║██╔══██╗██║░██╔╝██╔════╝██╔══██╗██╔══██╗████╗░██║
██║██╗██║██║░░░██║██║██║░░╚═╝█████═╝░╚█████╗░██║░░╚═╝███████║██╔██╗██║
╚██████╔╝██║░░░██║██║██║░░██╗██╔═██╗░░╚═══██╗██║░░██╗██╔══██║██║╚████║
░╚═██╔═╝░╚██████╔╝██║╚█████╔╝██║░╚██╗██████╔╝╚█████╔╝██║░░██║██║░╚███║
░░░╚═╝░░░░╚═════╝░╚═╝░╚════╝░╚═╝░░╚═╝╚═════╝░░╚════╝░╚═╝░░╚═╝╚═╝░░╚══╝
'''
print(logo2)
print("https://github.com/joeavanzato/QuickScan")
print("Run As Administrator!") #TODO - Check Admin - PyUAC works for elevation or other
args = parse_args()
log_file = "quickscan_log.log"
logging.basicConfig(filename=log_file, level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logging.info("New Logger Initialized")
try:
os.mkdir('evidence')
except OSError as e:
pass
configuration_data.fields = ['Name', 'Reason','File Path','Registry Path','MITRE Tactic','MITRE Technique','Risk','Details']
configuration_data.detection_csv = 'detection_output.csv'
start_detections(configuration_data.detection_csv, configuration_data.fields)
build_hashset()
build_ips()
launch_configs(args)
main()
``` |
{
"source": "joeavanzato/WARD",
"score": 2
} |
#### File: joeavanzato/WARD/connector.py
```python
import subprocess, traceback, sys, wmi, subprocess, win32api, winreg, os, config, fs_interaction
class connector(): #Create, Execute, Destroy.
def __init__(self, target, credential, password, user, domain):
print("Connector Initiated..\n")
self.execution_label = target+"["+user+"]"
self.target = target
self.credential = credential
self.password = password
self.user = user
self.domain = domain
self.root = " "
self.envroot = " "
self.log_buddy = fs_interaction.log_writer()
if config.elevated_password:
self.provided = 1
else:
self.provided = 0
def create_session(self): #Establish WMI Connection - will play with WinRM in future..
print("Target Device : "+self.target)
print("User Target : "+self.user)
print("Using Credential : "+self.credential)
#session = winrm.Session(target, auth=(credential, password), transport='kerberos') #WinRM would be easier but would require setup on remote machine.
self.session = wmi.WMI(computer=self.target, user=self.credential, password=<PASSWORD>)
self.log_buddy.write_log("Execution", "WMI SESSION CREATED ON "+self.target+" WITH USER "+self.credential)
def get_sid(self): #Trying a few different ways to get SID before settling on the method below as most reliable
#for group in self.session.Win32_Group():
# print(group.Caption)
# for user in group.associators(wmi_result_class="Win32_UserAccount"):
# print(user.Caption)
# if self.domain+"\\"+self.user == user.Caption:
# print("Found User, Checking SID..")
# print(user.Caption)
# print(user.SID)
# break
#for item in self.session.Win32_UserAccount():
# #print(item)
# print(item.Caption)
# sid = item.sid
# print(sid)
# if (item.Caption == self.domain+"\\"+self.user) or (item.Caption == self.target+"\\"+self.user):
# break
print("Examining Computer Profiles..")
profiles = []
for user in self.session.Win32_UserProfile():#Check WMI UserProfile data
if (self.user in user.LocalPath) and ("_alt" not in user.LocalPath):#Detect primary account
print("User Target Found..")
target_sid = user.SID
user_path = user.LocalPath
self.user_path = user.LocalPath
print("User Path : "+user.LocalPath)
print("User SID : "+target_sid)
profiles.append((user.LastUseTime, user.SID, user.LocalPath))
try:
profiles.sort(reverse=True) #Will fail on NoneType collections
print("Listing All Detected Profiles for Reference..")
for profile in profiles:
print(profile)
except:
print("SOFT ERROR Listing All User Profiles..")
self.log_buddy.write_log("Error","SOFT ERROR Listing All User Profiles..")
tb = traceback.format_exc()
self.log_buddy.write_log("Error", str(tb))
return(target_sid, user_path)
def get_windir(self): #Gets default Windows Directory and by extension environment root
with open(config.cur_dir+"\\"+config.execution_label+r"-data\files\Win32_OS.txt", "w+") as f:
for item in self.session.Win32_OperatingSystem():
f.write(str(item))
#print(item)
self.root = item.WindowsDirectory
self.envroot = item.WindowsDirectory[0]
return item.WindowsDirectory
def make_dir(self, dir): #Prepare folder for copying/writing/exporting artifacts
command = "mkdir "+dir #Try to use envroot
#print("Running : "+command)
process_id, return_value = self.session.Win32_Process.Create(CommandLine="cmd.exe /c "+command)
if (return_value != 0) and ("TEMPARTIFACTS" in dir):
print("Failed to create "+dir+" Directory..")
print("Halting Execution..")
self.log_buddy.write_log("Error","CRITICAL ERROR CREATING DIRECTORY: "+dir)
tb = traceback.format_exc()
self.log_buddy.write_log("Error", str(tb))
exit(0)
elif return_value !=0:
print("Failed to create " + dir + " Directory..")
self.log_buddy.write_log("Error", "SOFT ERROR CREATING DIRECTORY: " + dir)
tb = traceback.format_exc()
self.log_buddy.write_log("Error", str(tb))
return 1
elif return_value == 0:
#print("Created Directory :"+dir)
self.log_buddy.write_log("Execution", "CREATED DIRECTORY: " + dir)
return 0
#Passwords - Either you don't provide it initially via -p XXX then provide it to connect via WMI then either DONT pass to each WMIC and individually enter or DO pass to each WMI
#Alternative is provide initially via -p XXX then DO or DONT provide to each WMIC -> although likely in this case you wouldn't care and would provide it regardless
def execute(self, command, artifact_name, category, type, iteration):#Run Command on Remote Host
show_window = 0
process_startup = self.session.Win32_ProcessStartup.new()
process_startup.ShowWindow = show_window #Hide Window
if "wmic" in command:
command = command.replace("wmic","")
if self.provided == 0:
command = "wmic /node:\""+self.target+"\" /user:"+self.credential+" "+command+" > "+self.execution_label+"-data\WMI\\"+artifact_name+".txt"
command_censored = command.replace(self.password, "****").replace("wmic", "echo wmic")
result_filt = subprocess.getoutput(command_censored)
result = subprocess.getoutput(command)
print("Enter Password for "+self.credential+":")
elif self.provided == 1:
#command = "wmic /node:\""+self.target+"\" /user:"+self.credential+" /password:"+self.password+" "+command+" > "+self.execution_label+"-data\\"+artifact_name+".txt" #STDOUT to File
command = "wmic /output:\""+self.execution_label+"-data\WMI\\"+artifact_name+".txt\" /node:\""+self.target+"\" /user:"+self.credential+" /password:"+self.password+" "+command #/output flag in WMIC testing
command_censored = command.replace(self.password, "****").replace("wmic", "echo wmic")
result_filt = subprocess.getoutput(command_censored)
result = subprocess.getoutput(command)#With PW
else:#Everything except WMIC commands
dir = self.envroot + ":\\Users\\" + self.credential + "\TEMPARTIFACTS\\" + category+artifact_name+"\\"+type
val = self.make_dir(dir)
if val == 0:
dir = dir + "\\" + artifact_name + ".txt"
else:
dir = self.envroot + ":\\Users\\" + self.credential + "\TEMPARTIFACTS\\"+artifact_name+".txt"
#process_id, return_value = self.session.Win32_Process.Create(CommandLine=("cmd.exe /c echo "+command+" >> "+self.envroot+":\\Users\\"+self.credential+"\TEMPARTIFACTS\\"+artifact_name+".txt"), ProcessStartupInformation=process_startup)
#process_id, return_value = self.session.Win32_Process.Create(CommandLine=("cmd.exe /c "+command+" >> "+self.envroot+":\\Users\\"+self.credential+"\TEMPARTIFACTS\\"+artifact_name+".txt"), ProcessStartupInformation=process_startup)
process_id, return_value = self.session.Win32_Process.Create(CommandLine=("cmd.exe /c echo "+command+" >> "+dir), ProcessStartupInformation=process_startup)
process_id, return_value = self.session.Win32_Process.Create(CommandLine=("cmd.exe /c "+command+" >> "+dir), ProcessStartupInformation=process_startup)
#print("Process Executed: cmd.exe /c "+command+" > "+self.envroot+":\\Users\\"+self.credential+"\TEMPARTIFACTS\\"+artifact_name+str(iteration)+".txt")
#print("Process ID: "+str(process_id)+" , Return Value (0 = Success): "+str(return_value)+"\n")
def connect_drive(self):
x = 0
y = 0
try:
command = "net view"
cmd_result = subprocess.getoutput(command)
if self.target.lower() in cmd_result.lower():
print("DRIVE ALREADY MAPPED")
self.log_buddy.write_log('Execution', "DRIVE DETECTED IN RESULT OF 'NET VIEW' COMMAND")
x = 1
return cmd_result
except:
y = 1
print("SOFT ERROR running net view, need admin priveliges?")
self.log_buddy.write_log('Error', "SOFT ERROR RUNNING 'NET VIEW'")
print(traceback.print_exc(sys.exc_info()))
tb = traceback.format_exc()
log_buddy.write_log("Error",str(tb))
if (x == 0) or (y==1):
try:
print("Trying to Map Target Drive..")
if self.domain == "":
print("EXECUTING : net use \\\\"+self.target+"\\"+config.system_root+" /u:"+self.credential)
command = "net use \\\\"+self.target+"\\"+config.system_root+" /u:"+self.credential
self.log_buddy.write_log('Execution', command)
cmd_result = subprocess.getoutput(command)
else:
print("EXECUTING : net use \\\\"+self.target+"\\"+config.system_root+"$ /u:"+self.domain+"\\"+self.credential)
self.log_buddy.write_log('Execution', 'EXECUTED net use \\\\'+self.target+"\\"+config.system_root+"$ /u:"+self.domain+"\\"+self.credential) #why $ vs no $
command = ['net', 'use', "\\\\"+self.target+"\\"+config.system_root+"$", "/u:"+self.domain+"\\"+self.credential]
#cmd_result = subprocess.run("net use \\\\\""+self.target+"\\"+config.system_root+"$\" /u:"+self.domain+"\\"+self.credential, shell=True
cmd_result = subprocess.run(command, shell=True)
self.log_buddy.write_log('Execution', "TARGET DRIVE SUCCESSFULLY MAPPED")
print("Mapped Target Drive..")
return cmd_result
except:
print("CRITICAL ERROR Failed to Map Drive, Last Ran Command Logged to Execution Log..")
tb = traceback.format_exc()
self.log_buddy.write_log("Error", str(tb))
print(traceback.print_exc(sys.exc_info()))
exit(0)
def disconnect_drive(self):
try:
print("Trying to Remove Mapped Target Drive")
cmd_result = subprocess.getoutput(r'net use \\\\'+self.target+"\\"+config.system_root+" /delete", shell=True)
print("UnMapped Target Drive..")
except:
print("Failed to Close Connection")
print(traceback.print_exc(sys.exc_info()))
exit(0)
``` |
{
"source": "joeavanzato/WinGraph",
"score": 3
} |
#### File: parsers/remconmanager/rdp_connection_established.py
```python
import networkx
import re
def add_node(network, node_name, node_properties):
network.add_node(node_name)
for k,v in node_properties.items():
network.nodes[node_name][k] = v
def add_edge(network, node1, node2, edge_properties):
network.add_edge(node1, node2)
for k,v in edge_properties.items():
network.edges[node1,node2][k] = v
def parse(network, d, user_props, properties, mode):
user_ = d['UserName']
try:
domain, user = user_.split('\\', 1)
except:
domain = "NA"
user = user_
target_pc = d['Computer']
try:
target_pc, domain = target_pc.split('.', 1)
except:
pass
src_pc = d['RemoteHost']
user = user.lower().strip()
src_pc = src_pc.lower().strip()
target_pc = target_pc.lower().strip()
properties['title'] = d['MapDescription'] + f": User {user} authenticated as {user} from {src_pc} to {target_pc} using Domain {domain}"
properties['user'] = user
if mode == 'user':
add_node(network, user, user_props)
add_edge(network, src_pc, user, properties)
add_edge(network, user, target_pc, properties)
elif mode == 'host':
add_edge(network, src_pc, target_pc, properties)
``` |
{
"source": "joeb15/202Problems",
"score": 3
} |
#### File: queues/linked_list_queue/queue_test.py
```python
import unittest
from queue import *
class Test_Linked_Queue(unittest.TestCase):
def test_complete(self):
queue = Linked_Queue(3)
self.assertTrue(queue.enqueue(5))
self.assertFalse(queue.is_full())
self.assertTrue(queue.enqueue(4))
self.assertTrue(queue.enqueue(6))
self.assertFalse(queue.enqueue(3))
self.assertEqual(queue.as_list(), [4, 5, 6])
self.assertTrue(queue.is_full())
self.assertEqual(queue.dequeue(), 4)
self.assertEqual(queue.dequeue(), 5)
self.assertEqual(queue.dequeue(), 6)
with self.assertRaises(IndexError):
queue.dequeue()
def test_enqueue(self):
queue = Linked_Queue(3)
self.assertTrue(queue.enqueue(4))
self.assertTrue(queue.enqueue(5))
self.assertTrue(queue.enqueue(2))
self.assertFalse(queue.enqueue(6))
def test_dequeue(self):
queue = Linked_Queue(2)
with self.assertRaises(IndexError):
queue.dequeue()
queue.enqueue(5)
queue.enqueue(3)
self.assertEqual(queue.dequeue(), 3)
self.assertEqual(queue.dequeue(), 5)
def test_list(self):
queue = Linked_Queue(5)
queue.enqueue(5)
self.assertEqual(queue.as_list(), [5])
queue.enqueue(3)
self.assertEqual(queue.as_list(), [3, 5])
queue.enqueue(6)
self.assertEqual(queue.as_list(), [3, 5, 6])
if __name__ == "__main__":
unittest.main()
```
#### File: queues/list_queue/queue.py
```python
class List_Queue:
"""
Creates a List Queue
"""
def __init__(self, size):
self.size = size
self.num_items = 0
self.front = 0
self.end = 0
self.list = [None for i in range(self.size)]
"""
returns whether the queue is full or not
"""
def is_full(self):
"""
Method will add a new items to the end of the queue
return True if successful
return False if not enough space in queue
"""
def enqueue(self, item):
"""
Method will remove the first item from the queue and return it
Raises an IndexError if no items are in the queue
"""
def dequeue(self):
``` |
{
"source": "JoeBaker/naughts-and-crosses",
"score": 3
} |
#### File: JoeBaker/naughts-and-crosses/naughts-and-crosses.pyw
```python
import tkinter
import tkinter.messagebox
import os
import sys
import random
class naughtsAndCrosses:
root = tkinter.Tk()
def buttonPressed(place):
self = naughtsAndCrosses
if self.grid[place]:
return
self.grid[place] = self.gridNumber(self.turn)
if self.images["images"]:
self.buttons[place].config(image=self.images[self.turn])
else:
self.buttons[place].config(text=self.turnChar(self.turn))
hasWon = int(self.hasWon(self.grid))
if hasWon:
self.text.config(text="naughts score: "+str(self.score[0])+
"\ncrosses score: "+str(self.score[1])+"\n")
self.message(self.pluralTurn(self.turn)+" has won", self.pluralTurn(self.turn)+" has won")
self.grid = [0]*9
self.score[self.scoreIndex(self.turn)] += 1
self.turn = self.randomTurn()
for i in range(9):
if self.images["images"]:
self.buttons[i].config(image=self.images["none"])
else:
self.buttons[i].config(text=" ")
else:
if 0 not in self.grid:
self.text.config(text="naughts score: "+str(self.score[0])+
"\ncrosses score: "+str(self.score[1])+"\n")
self.message("No one has won", "No one has won")
self.grid = [0]*9
for i in range(9):
if self.images["images"]:
self.buttons[i].config(image=self.images["none"])
else:
self.buttons[i].config(text=" ")
else:
self.turn = self.nextTurn(self.turn)
self.text.config(text="naughts score: "+str(self.score[0])+
"\ncrosses score: "+str(self.score[1])+"\n"+self.pluralTurn(self.turn)+" turn")
def hasWon(grid):
for i in range(3):
tmp = grid[(i*3)] + grid[(i*3)+1] + grid[(i*3)+2]
if tmp in [-3, 3]:
return tmp/3
tmp = grid[i] + grid[3+i] + grid[6+i]
if tmp in [-3, 3]:
return tmp/3
for i in range(0,3,2):
tmp = grid[0+i] + grid[4] + grid[8-i]
if tmp in [-3, 3]:
return tmp/3
return 0
def path(relativePath):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relativePath)
return os.path.join(os.path.abspath("."), relativePath)
turnChar = lambda turn: {"naught":"O", "cross":"X"}[turn]
pluralTurn = lambda turn: {"naught":"naughts", "cross":"crosses"}[turn]
scoreIndex = lambda turn: {"naught":0, "cross":1}[turn]
nextTurn = lambda turn: {"naught":"cross", "cross":"naught"}[turn]
randomTurn = lambda: random.choice(["cross", "naught"])
gridNumber = lambda turn: {"naught":-1, "cross":1}[turn]
message = lambda title, message: tkinter.messagebox.showinfo(title=title, message=message)
try:
images = {"naught":tkinter.PhotoImage(file=path("assets/naught.gif")),
"cross":tkinter.PhotoImage(file=path("assets/cross.gif")),
"none":tkinter.PhotoImage(), "images":True}
except Exception as e:
images = {"none":tkinter.PhotoImage(), "images":False}
print(e, "\nAn error has occoured loading the image files.\nText will be used instead.")
try:
root.iconbitmap(path("assets/icon.ico"))
except Exception as e:
print(e)
root.title("Naughts and Crosses")
root.resizable(False, False)
root.geometry("330x<PASSWORD>")
turn = randomTurn()
score = [0]*2
grid = [0]*9
text = tkinter.Label(text="naughts score: "+str(score[0])+"\ncrosses score: "+str(score[1])+"\n"+pluralTurn(turn)+" turn")
mainGrid = tkinter.Frame()
text.pack()
mainGrid.pack()
buttons = []
for column in range(3):
for row in range(3):
buttons.append(tkinter.Button(mainGrid, image=images["none"],
command=lambda arg=(column*3)+row: naughtsAndCrosses.buttonPressed(arg)))
if images["images"]:
buttons[(column*3)+row].config(height=100, width=100)
else:
buttons[(column*3)+row].config(text=" ", height=98, width=98, compound="center")
buttons[(column*3)+row].grid(column=column, row=row)
naughtsAndCrosses.root.mainloop()
``` |
{
"source": "joebalt/hl52",
"score": 3
} |
#### File: joebalt/hl52/hl52.py
```python
import argparse
import sys
from yahoo_finance import Share
def init_argparse():
parser = argparse.ArgumentParser(description="hl52")
parser.add_argument("--symfile", dest="symFile",
help="Path to the symbols file to analyze.")
return parser.parse_args()
def load_symbols(filename):
with open(filename, 'rb') as f:
symbol_list = [line.rstrip() for line in f]
return symbol_list
def calc_marker_loc(bid, low, high, markerWidth=10):
markerLoc = 0
# find out how far above the low price the current bid price is
if bid >= low:
bidAboveLow = bid - low
else:
return 0
hlRange = high - low
markerLoc = int(round(bidAboveLow * markerWidth / hlRange, 0))
# ensure we don't return anything invalid...just in case.
if markerLoc > markerWidth - 1:
markerLoc = markerWidth - 1
return markerLoc
def print_52_week_hl_marker(bid, low, high, symbol, length=10):
markerTemplate = list('=' * length)
markerLoc = calc_marker_loc(bid, low, high, length)
markerTemplate[markerLoc] = 'X'
# If bid has crossed below 52-week low, I want the
# percentage printed at the end of the line here
# The way I did this feels very 'brute force'...
if (bid / low) < 1.0:
print('{:5}@{:6.2f} : {:6.2f}[{}]{:6.2f} {:6.2f}%'
.format(symbol,
bid,
low,
''.join(markerTemplate),
high,
(bid / low) * 100.0))
else:
print('{:5}@{:6.2f} : {:6.2f}[{}]{:6.2f}'
.format(symbol,
bid,
low,
''.join(markerTemplate),
high))
def main(argv):
print('Begin run...')
args = init_argparse()
print('Loading symbols from {}'.format(args.symFile))
symbols = load_symbols(args.symFile)
d = {}
for s in symbols:
print('fetching {}...'.format(s))
share = Share(s)
bid = float(share.get_price())
year_low = float(share.get_year_low())
year_high = float(share.get_year_high())
d[s] = [bid, year_low, year_high]
# v is a list of ticker information:
# v[0] - bid
# v[1] - 52-week low
# v[2] - 52-week high
for k, v in sorted(d.iteritems()):
print_52_week_hl_marker(float(v[0]), float(v[1]), float(v[2]), k, 50)
print('End run.')
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
``` |
{
"source": "JoeBarney1/floodlevelmonitor131",
"score": 2
} |
#### File: JoeBarney1/floodlevelmonitor131/Task1C.py
```python
from distutils.command.build import build
from sympy import N
from floodsystem.geo import stations_within_radius
from floodsystem.stationdata import build_station_list
def run():
"""Requirements for Task 1C"""
cam = (52.2053, 0.1218)
print(stations_within_radius(build_station_list(),cam, 10))
if __name__ == "__main__":
run()
```
#### File: JoeBarney1/floodlevelmonitor131/Task2C.py
```python
from floodsystem.stationdata import build_station_list
from floodsystem.station import MonitoringStation, inconsistent_typical_range_stations
from floodsystem.flood import stations_highest_rel_level
from floodsystem.utils import sorted_by_key
def run():
"""Requirements for Task 2C"""
stations= build_station_list()
for s in stations_highest_rel_level(stations,10):
relative_level=s.latest_level-s.typical_range[1]
print(s.name, relative_level)
if __name__ == "__main__":
print("*** Task 2C: CUED Part IA Flood Warning System ***")
run()
```
#### File: JoeBarney1/floodlevelmonitor131/Task2G.py
```python
from floodsystem.flood import highest_risk
from floodsystem.stationdata import build_station_list
def run():
"""Requirements for Task 2G"""
stations= build_station_list()
for s in highest_risk(stations,dt=3,N=10,y=3):
print(s)
#works with whole list but takes v. long time
if __name__ == "__main__":
print("*** Task 2G: CUED Part IA Flood Warning System ***")
run()
``` |
{
"source": "joebartusek/graf",
"score": 2
} |
#### File: gan_training/metrics/kid_score.py
```python
import os
import torch
from torch import nn
import torch.utils.data
from tqdm import tqdm
from torchvision.models.inception import inception_v3
import numpy as np
from sklearn.metrics.pairwise import polynomial_kernel
from scipy import linalg
import sys
from .inception import InceptionV3
class Identity(nn.Module):
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
return x
def get_activations(data_loader, model, device=None, batch_size=32, resize=False, n_samples=None):
"""Computes the activation of the given images
Args:
imgs: Torch dataset of (3xHxW) numpy images normalized in the
range [-1, 1]
cuda: whether or not to run on GPU
batch_size: batch size for feeding into Inception v3
splits: number of splits
"""
try:
n_batches = len(data_loader)
except TypeError: # data_loader can also be a generator object
n_batches = float('inf')
assert batch_size > 0
if n_samples is not None:
assert n_samples <= n_batches * batch_size
n_batches = int(np.ceil(n_samples / batch_size))
model = model.to(device)
model.eval()
up = nn.Upsample(size=(299, 299), mode='bilinear', align_corners=False).to(device)
def get_feat(x):
with torch.no_grad():
x = x.to(device)
if resize:
x = up(x)
_, out = model(x)
out = out[0].flatten(1, 3)
return out.cpu().numpy()
# Get predictions
feat = []
for batch in tqdm(data_loader, 'Compute activations', total=n_batches):
if len(feat) >= n_batches:
break
if isinstance(batch, tuple) or isinstance(batch, list): # img, label
batch = batch[0]
batch = batch.to(device)
feat_i = get_feat(batch[:, :3]) # rgb only
feat.append(feat_i)
feat = np.concatenate(feat)
if n_samples is not None:
feat = feat[:n_samples]
return feat
def polynomial_mmd_averages(codes_g, codes_r, n_subsets=50, subset_size=1000,
ret_var=True, output=sys.stdout, **kernel_args):
m = min(codes_g.shape[0], codes_r.shape[0])
mmds = np.zeros(n_subsets)
if ret_var:
vars = np.zeros(n_subsets)
choice = np.random.choice
with tqdm(range(n_subsets), desc='MMD', file=output) as bar:
for i in bar:
g = codes_g[choice(len(codes_g), min(m, subset_size), replace=False)]
r = codes_r[choice(len(codes_r), min(m, subset_size), replace=False)]
o = polynomial_mmd(g, r, **kernel_args, var_at_m=m, ret_var=ret_var)
if ret_var:
mmds[i], vars[i] = o
else:
mmds[i] = o
bar.set_postfix({'mean': mmds[:i + 1].mean()})
return (mmds, vars) if ret_var else mmds
def polynomial_mmd(codes_g, codes_r, degree=3, gamma=None, coef0=1,
var_at_m=None, ret_var=True):
# use k(x, y) = (gamma <x, y> + coef0)^degree
# default gamma is 1 / dim
X = codes_g
Y = codes_r
K_XX = polynomial_kernel(X, degree=degree, gamma=gamma, coef0=coef0)
K_YY = polynomial_kernel(Y, degree=degree, gamma=gamma, coef0=coef0)
K_XY = polynomial_kernel(X, Y, degree=degree, gamma=gamma, coef0=coef0)
return _mmd2_and_variance(K_XX, K_XY, K_YY,
var_at_m=var_at_m, ret_var=ret_var)
def _mmd2_and_variance(K_XX, K_XY, K_YY, unit_diagonal=False,
mmd_est='unbiased', block_size=1024,
var_at_m=None, ret_var=True):
# based on
# https://github.com/dougalsutherland/opt-mmd/blob/master/two_sample/mmd.py
# but changed to not compute the full kernel matrix at once
m = K_XX.shape[0]
print(m, K_XX.shape, K_YY.shape, K_XY.shape)
assert K_XX.shape == (m, m)
assert K_XY.shape == (m, m)
assert K_YY.shape == (m, m)
if var_at_m is None:
var_at_m = m
# Get the various sums of kernels that we'll use
# Kts drop the diagonal, but we don't need to compute them explicitly
if unit_diagonal:
diag_X = diag_Y = 1
sum_diag_X = sum_diag_Y = m
sum_diag2_X = sum_diag2_Y = m
else:
diag_X = np.diagonal(K_XX)
diag_Y = np.diagonal(K_YY)
sum_diag_X = diag_X.sum()
sum_diag_Y = diag_Y.sum()
sum_diag2_X = _sqn(diag_X)
sum_diag2_Y = _sqn(diag_Y)
Kt_XX_sums = K_XX.sum(axis=1) - diag_X
Kt_YY_sums = K_YY.sum(axis=1) - diag_Y
K_XY_sums_0 = K_XY.sum(axis=0)
K_XY_sums_1 = K_XY.sum(axis=1)
Kt_XX_sum = Kt_XX_sums.sum()
Kt_YY_sum = Kt_YY_sums.sum()
K_XY_sum = K_XY_sums_0.sum()
if mmd_est == 'biased':
mmd2 = ((Kt_XX_sum + sum_diag_X) / (m * m)
+ (Kt_YY_sum + sum_diag_Y) / (m * m)
- 2 * K_XY_sum / (m * m))
else:
assert mmd_est in {'unbiased', 'u-statistic'}
mmd2 = (Kt_XX_sum + Kt_YY_sum) / (m * (m - 1))
if mmd_est == 'unbiased':
mmd2 -= 2 * K_XY_sum / (m * m)
else:
mmd2 -= 2 * (K_XY_sum - np.trace(K_XY)) / (m * (m - 1))
if not ret_var:
return mmd2
Kt_XX_2_sum = _sqn(K_XX) - sum_diag2_X
Kt_YY_2_sum = _sqn(K_YY) - sum_diag2_Y
K_XY_2_sum = _sqn(K_XY)
dot_XX_XY = Kt_XX_sums.dot(K_XY_sums_1)
dot_YY_YX = Kt_YY_sums.dot(K_XY_sums_0)
m1 = m - 1
m2 = m - 2
zeta1_est = (
1 / (m * m1 * m2) * (
_sqn(Kt_XX_sums) - Kt_XX_2_sum + _sqn(Kt_YY_sums) - Kt_YY_2_sum)
- 1 / (m * m1) ** 2 * (Kt_XX_sum ** 2 + Kt_YY_sum ** 2)
+ 1 / (m * m * m1) * (
_sqn(K_XY_sums_1) + _sqn(K_XY_sums_0) - 2 * K_XY_2_sum)
- 2 / m ** 4 * K_XY_sum ** 2
- 2 / (m * m * m1) * (dot_XX_XY + dot_YY_YX)
+ 2 / (m ** 3 * m1) * (Kt_XX_sum + Kt_YY_sum) * K_XY_sum
)
zeta2_est = (
1 / (m * m1) * (Kt_XX_2_sum + Kt_YY_2_sum)
- 1 / (m * m1) ** 2 * (Kt_XX_sum ** 2 + Kt_YY_sum ** 2)
+ 2 / (m * m) * K_XY_2_sum
- 2 / m ** 4 * K_XY_sum ** 2
- 4 / (m * m * m1) * (dot_XX_XY + dot_YY_YX)
+ 4 / (m ** 3 * m1) * (Kt_XX_sum + Kt_YY_sum) * K_XY_sum
)
var_est = (4 * (var_at_m - 2) / (var_at_m * (var_at_m - 1)) * zeta1_est
+ 2 / (var_at_m * (var_at_m - 1)) * zeta2_est)
return mmd2, var_est
def _sqn(arr):
flat = np.ravel(arr)
return flat.dot(flat)
class KIDEvaluator(object):
def __init__(self, device=None, batch_size=32, resize=False, n_samples=None, subset_size=1000):
self.device = device
self.batch_size = batch_size
self.resize = resize
self.n_samples = n_samples
self.subset_size = subset_size
self.init_model()
self.act_target = None
def init_model(self):
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
self.model = InceptionV3([block_idx]).to(self.device)
# model = inception_v3(pretrained=True, transform_input=False)
# # replace fc layer by identity mapping to obtain features
# model.fc = Identity()
# return model
def get_activations(self, data_loader):
return get_activations(data_loader, self.model, device=self.device, batch_size=self.batch_size,
resize=self.resize, n_samples=self.n_samples)
def initialize_target(self, target_loader, cache_file=None):
if cache_file is not None:
if os.path.isfile(cache_file):
cache = np.load(cache_file)
self.act_target = cache['act']
else:
self.act_target = self.get_activations(target_loader)
np.savez(cache_file, act=self.act_target)
else:
self.act_target = self.get_activations(target_loader)
if self.n_samples is None:
self.n_samples = len(self.act_target)
def is_initialized(self):
return self.act_target is not None
def get_kid(self, data_loader):
assert self.is_initialized()
act = self.get_activations(data_loader)
return polynomial_mmd_averages(self.act_target, act, n_subsets=100, subset_size=self.subset_size)
```
#### File: GAN_stability/gan_training/utils.py
```python
import torch
import torch.utils.data
import torch.utils.data.distributed
import torchvision
def save_images(imgs, outfile, nrow=8):
imgs = imgs / 2 + 0.5 # unnormalize
torchvision.utils.save_image(imgs, outfile, nrow=nrow)
def get_nsamples(data_loader, N):
x = []
y = []
n = 0
while n < N:
x_next, y_next = next(iter(data_loader))
x.append(x_next)
y.append(y_next)
n += x_next.size(0)
x = torch.cat(x, dim=0)[:N]
y = torch.cat(y, dim=0)[:N]
return x, y
def update_average(model_tgt, model_src, beta):
param_dict_src = dict(model_src.named_parameters())
for p_name, p_tgt in model_tgt.named_parameters():
p_src = param_dict_src[p_name]
assert(p_src is not p_tgt)
p_tgt.copy_(beta*p_tgt + (1. - beta)*p_src)
```
#### File: notebooks/diracgan/subplots.py
```python
import numpy as np
from matplotlib import pyplot as plt
def arrow_plot(x, y, color='C1'):
plt.quiver(x[:-1], y[:-1], x[1:]-x[:-1], y[1:]-y[:-1],
color=color, scale_units='xy', angles='xy', scale=1)
def vector_field_plot(theta, psi, v1, v2, trajectory=None, clip_y=None, marker='b^'):
plt.quiver(theta, psi, v1, v2)
if clip_y is not None:
plt.axhspan(np.min(psi), -clip_y, facecolor='0.2', alpha=0.5)
plt.plot([np.min(theta), np.max(theta)], [-clip_y, -clip_y], 'k-')
plt.axhspan(clip_y, np.max(psi), facecolor='0.2', alpha=0.5)
plt.plot([np.min(theta), np.max(theta)], [clip_y, clip_y], 'k-')
if trajectory is not None:
psis, thetas = trajectory
plt.plot(psis, thetas, marker, markerfacecolor='None')
plt.plot(psis[0], thetas[0], 'ro')
plt.xlim(np.min(theta), np.max(theta))
plt.ylim(np.min(psi), np.max(psi))
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\psi$')
plt.xticks(np.linspace(np.min(theta), np.max(theta), 5))
plt.yticks(np.linspace(np.min(psi), np.max(psi), 5))
``` |
{
"source": "joebartusek/nerf_atlas",
"score": 2
} |
#### File: nerf_atlas/src/nerf.py
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from .neural_blocks import (
SkipConnMLP, UpdateOperator, FourierEncoder, PositionalEncoder, NNEncoder
)
from .utils import (
dir_to_elev_azim, autograd, sample_random_hemisphere, laplace_cdf, load_sigmoid,
)
import src.refl as refl
from .renderers import ( load_occlusion_kind, direct )
import src.march as march
@torch.jit.script
def cumuprod_exclusive(t):
cp = torch.cumprod(t, dim=0)
cp = torch.roll(cp, 1, dims=0)
cp[0, ...] = 1.0
return cp
<EMAIL> # cannot jit script cause of tensordot :)
def compute_pts_ts(
rays, near, far, steps, lindisp=False,
perturb: float = 0,
):
r_o, r_d = rays.split([3,3], dim=-1)
device = r_o.device
if lindisp:
t_vals = torch.linspace(0, 1, steps, device=device, dtype=r_o.dtype)
ts = 1/(1/max(near, 1e-10) * (1-t_vals) + 1/far * (t_vals))
else:
ts = torch.linspace(near, far, steps=steps, device=device, dtype=r_o.dtype)
if perturb > 0:
mids = 0.5 * (ts[:-1] + ts[1:])
lower = torch.cat([mids, ts[-1:]])
upper = torch.cat([ts[:1], mids])
rand = torch.rand_like(lower) * perturb
ts = lower + (upper - lower) * rand
pts = r_o.unsqueeze(0) + torch.tensordot(ts, r_d, dims = 0)
return pts, ts, r_o, r_d
# given a set of densities, and distances between the densities,
# compute alphas from them.
<EMAIL>
def alpha_from_density(
density, ts, r_d,
softplus: bool = True,
):
device=density.device
if softplus: sigma_a = F.softplus(density-1)
else: sigma_a = F.relu(density)
end_val = torch.full_like(ts[..., :1], 1e10)
dists = torch.cat([ts[..., 1:] - ts[..., :-1], end_val], dim=-1)
while len(dists.shape) < 4: dists = dists[..., None]
dists = dists * torch.linalg.norm(r_d, dim=-1)
alpha = 1 - torch.exp(-sigma_a * dists)
weights = alpha * cumuprod_exclusive(1.0 - alpha + 1e-10)
return alpha, weights
# TODO delete these for utils
# sigmoids which shrink or expand the total range to prevent gradient vanishing,
# or prevent it from representing full density items.
# fat sigmoid has no vanishing gradient, but thin sigmoid leads to better outlines.
def fat_sigmoid(v, eps: float = 1e-3): return v.sigmoid() * (1+2*eps) - eps
def thin_sigmoid(v, eps: float = 1e-2): return fat_sigmoid(v, -eps)
def cyclic_sigmoid(v, eps:float=-1e-2,period:int=5):
return ((v/period).sin()+1)/2 * (1+2*eps) - eps
# perform volumetric integration of density with some other quantity
# returns the integrated 2nd value over density at timesteps.
@torch.jit.script
def volumetric_integrate(weights, other):
return torch.sum(weights[..., None] * other, dim=0)
# perform volumetric integration but only using some of other's values where the weights
# are big enough.
#
# TODO the computation of `other` itself should be sparse, so that it doesn't need to be
# computed in the first place.
@torch.jit.script
def sparse_volumetric_integrate(weights, other, eps:float=1e-3):
vals = torch.full_like(other, 1e-3)
mask = weights > 1e-3
vals[mask] = other[mask]
return torch.sum(weights[..., None] * vals, dim=0)
# bg functions, need to be here for pickling
def black(_elaz_r_d, _weights): return 0
def white(_, weights): 1-weights.sum(dim=0).unsqueeze(-1)
# having a random color will probably help prevent any background
def random_color(_elaz_r_d, weights):
# TODO need to think this through more
# This will make it so that there never is a background.
summed = (1-weights.sum(dim=0).unsqueeze(-1))
return torch.rand_like(summed) * summed
class CommonNeRF(nn.Module):
def __init__(
self,
steps: int = 64,
#out_features: int = 3, # 3 is for RGB
t_near: float = 0,
t_far: float = 1,
density_std: float = 0.01,
noise_std: int = 1e-2,
mip = None,
instance_latent_size: int = 0,
per_pixel_latent_size: int = 0,
per_point_latent_size: int = 0,
sigmoid_kind: str = "thin",
bg: str = "black",
record_depth: bool = False,
device="cuda",
):
super().__init__()
self.empty_latent = torch.zeros(1,1,1,1,0, device=device, dtype=torch.float)
self.t_near = t_near
self.t_far = t_far
self.steps = steps
self.mip = mip
self.per_pixel_latent_size = per_pixel_latent_size
self.per_pixel_latent = None
self.instance_latent_size = instance_latent_size
self.instance_latent = None
self.per_pt_latent_size = per_point_latent_size
self.per_pt_latent = None
self.alpha = None
self.noise_std = 0.2
# TODO add activation for using sigmoid or fat sigmoid
self.set_bg(bg)
self.set_sigmoid(sigmoid_kind)
self.record_depth = record_depth
self.depth = None
def forward(self, _x): raise NotImplementedError()
def set_bg(self, bg="black"):
if bg == "black":
self.sky_color = black
elif bg == "white":
self.sky_color = white
elif bg == "mlp":
self.sky_mlp = SkipConnMLP(
in_size=2, out=3, enc=NNEncoder(in_size=2,out=3),
num_layers=3, hidden_size=32, device=device, xavier_init=True,
)
self.sky_color = self.sky_from_mlp
elif bg == "random":
self.sky_color = random_color
else:
raise NotImplementedError(f"Unexpected bg: {bg}")
def set_sigmoid(self, kind="thin"): self.feat_act = load_sigmoid(kind)
def sky_from_mlp(self, elaz_r_d, weights):
return (1-weights.sum(dim=0)).unsqueeze(-1) * fat_sigmoid(self.sky_mlp(elaz_r_d))
def total_latent_size(self) -> int:
return self.mip_size() + \
self.per_pixel_latent_size + \
self.instance_latent_size + \
self.per_pt_latent_size
def set_per_pt_latent(self, latent):
assert(latent.shape[-1] == self.per_pt_latent_size), \
f"expected latent in [T, B, H, W, L={self.per_pixel_latent_size}], got {latent.shape}"
assert(len(latent.shape) == 5), \
f"expected latent in [T, B, H, W, L], got {latent.shape}"
self.per_pt_latent = latent
def set_per_pixel_latent(self, latent):
assert(latent.shape[-1] == self.per_pixel_latent_size), \
f"expected latent in [B, H, W, L={self.per_pixel_latent_size}], got {latent.shape}"
assert(len(latent.shape) == 4), \
f"expected latent in [B, H, W, L], got {latent.shape}"
self.per_pixel_latent = latent
def set_instance_latent(self, latent):
assert(latent.shape[-1] == self.instance_latent_size), "expected latent in [B, L]"
assert(len(latent.shape) == 2), "expected latent in [B, L]"
self.instance_latent = latent
# produces a segmentation mask of sorts, using the alpha for occupancy.
def acc(self): return self.alpha.max(dim=0)[0]
def acc_smooth(self): return self.weights.sum(dim=0).unsqueeze(-1)
def set_refl(self, refl):
if hasattr(self, "refl"): self.refl = refl
def depths(self, depths):
with torch.no_grad():
return volumetric_integrate(self.alpha, depths[..., None, None, None])
@property
def nerf(self): return self
def mip_size(self): return 0 if self.mip is None else self.mip.size() * 6
def mip_encoding(self, r_o, r_d, ts):
if self.mip is None: return None
end_val = torch.tensor([1e10], device=ts.device, dtype=ts.dtype)
ts = torch.cat([ts, end_val], dim=-1)
return self.mip(r_o, r_d, ts[..., :-1], ts[..., 1:])
# gets the current latent vector for this NeRF instance
def curr_latent(self, pts_shape) -> ["T", "B", "H", "W", "L_pp + L_inst"]:
curr = self.empty_latent.expand(pts_shape[:-1] + (0,)) if self.per_pt_latent is None \
else self.per_pt_latent
if self.per_pixel_latent is not None:
ppl = self.per_pixel_latent[None, ...].expand(pts.shape[:-1] + (-1,))
curr = torch.cat([curr, ppl], dim=-1)
if self.instance_latent is not None:
il = self.instance_latent[None, :, None, None, :].expand_as(pts.shape[:-1] + (-1,))
curr = torch.cat([curr, il], dim=-1)
return curr
class TinyNeRF(CommonNeRF):
# No frills, single MLP NeRF
def __init__(
self,
out_features: int = 3,
device="cuda",
**kwargs,
):
super().__init__(**kwargs, device=device)
self.estim = SkipConnMLP(
in_size=3, out=1 + out_features,
latent_size = self.total_latent_size(),
num_layers=6, hidden_size=128,
xavier_init=True,
)
def forward(self, rays):
pts, ts, r_o, r_d = compute_pts_ts(
rays, self.t_near, self.t_far, self.steps,
perturb = 1 if self.training else 0,
)
self.ts = ts
return self.from_pts(pts, ts, r_o, r_d)
def from_pts(self, pts, ts, r_o, r_d):
latent = self.curr_latent(pts.shape)
mip_enc = self.mip_encoding(r_o, r_d, ts)
if mip_enc is not None: latent = torch.cat([latent, mip_enc], dim=-1)
density, feats = self.estim(pts, latent).split([1, 3], dim=-1)
self.alpha, self.weights = alpha_from_density(density, ts, r_d)
return volumetric_integrate(self.weights, self.feat_act(feats)) + \
self.sky_color(None, self.weights)
# A plain old nerf
class PlainNeRF(CommonNeRF):
def __init__(
self,
intermediate_size: int = 32,
out_features: int = 3,
device: torch.device = "cuda",
**kwargs,
):
super().__init__(**kwargs, device=device)
self.latent_size = self.total_latent_size()
self.first = SkipConnMLP(
in_size=3, out=1 + intermediate_size, latent_size=self.latent_size,
enc=FourierEncoder(input_dims=3, device=device),
num_layers = 6, hidden_size = 128, xavier_init=True,
)
self.refl = refl.View(
out_features=out_features,
latent_size=self.latent_size+intermediate_size,
)
def forward(self, rays):
pts, ts, r_o, r_d = compute_pts_ts(
rays, self.t_near, self.t_far, self.steps, perturb = 1 if self.training else 0,
)
self.ts = ts
return self.from_pts(pts, ts, r_o, r_d)
def from_pts(self, pts, ts, r_o, r_d):
latent = self.curr_latent(pts.shape)
mip_enc = self.mip_encoding(r_o, r_d, ts)
# If there is a mip encoding, stack it with the latent encoding.
if mip_enc is not None: latent = torch.cat([latent, mip_enc], dim=-1)
first_out = self.first(pts, latent if latent.shape[-1] != 0 else None)
density = first_out[..., 0]
if self.training and self.noise_std > 0:
density = density + torch.randn_like(density) * self.noise_std
intermediate = first_out[..., 1:]
#n = None
#if self.refl.can_use_normal: n = autograd(pts, density)
view = r_d[None, ...].expand_as(pts)
rgb = self.refl(
x=pts, view=view,
latent=torch.cat([latent, intermediate], dim=-1),
)
self.alpha, self.weights = alpha_from_density(density, ts, r_d)
return volumetric_integrate(self.weights, rgb) + self.sky_color(view, self.weights)
# NeRF with a thin middle layer, for encoding information
class NeRFAE(CommonNeRF):
def __init__(
self,
intermediate_size: int = 32,
out_features: int = 3,
encoding_size: int = 32,
normalize_latent: bool = True,
device="cuda",
**kwargs,
):
super().__init__(**kwargs, device=device)
self.latent_size = self.total_latent_size()
self.encode = SkipConnMLP(
in_size=3, out=encoding_size,
latent_size=self.latent_size,
num_layers=5, hidden_size=128,
enc=FourierEncoder(input_dims=3, device=device),
xavier_init=True,
)
self.density_tform = SkipConnMLP(
in_size=encoding_size, out=1+intermediate_size, latent_size=0,
num_layers=5, hidden_size=64, xavier_init=True,
)
self.refl = refl.View(
out_features=out_features,
latent_size=encoding_size+intermediate_size,
)
self.encoding_size = encoding_size
self.regularize_latent = False
self.normalize_latent = normalize_latent
def set_regularize_latent(self):
self.regularize_latent = True
self.latent_l2_loss = 0
def forward(self, rays):
pts, ts, r_o, r_d = compute_pts_ts(
rays, self.t_near, self.t_far, self.steps,
perturb = 1 if self.training else 0,
)
self.ts = ts
return self.from_pts(pts, ts, r_o, r_d)
def from_pts(self, pts, ts, r_o, r_d):
encoded = self.compute_encoded(pts, ts, r_o, r_d)
if self.regularize_latent:
self.latent_l2_loss = torch.linalg.norm(encoded, dim=-1).square().mean()
return self.from_encoded(encoded, ts, r_d, pts)
def compute_encoded(self, pts, ts, r_o, r_d):
latent = self.curr_latent(pts.shape)
mip_enc = self.mip_encoding(r_o, r_d, ts)
# If there is a mip encoding, stack it with the latent encoding.
if mip_enc is not None: latent = torch.cat([latent, mip_enc], dim=-1)
return self.encode(pts, latent if latent.shape[-1] != 0 else None)
def from_encoded(self, encoded, ts, r_d, pts):
if self.normalize_latent: encoded = F.normalize(encoded, dim=-1)
first_out = self.density_tform(encoded)
density = first_out[..., 0]
intermediate = first_out[..., 1:]
if self.training and self.noise_std > 0:
density = density + torch.randn_like(density) * self.noise_std
rgb = self.refl(
x=pts, view=r_d[None,...].expand_as(pts),
latent=torch.cat([encoded,intermediate],dim=-1),
)
self.alpha, self.weights = alpha_from_density(density, ts, r_d)
color = volumetric_integrate(self.weights, rgb)
sky = self.sky_color(None, self.weights)
return color + sky
def identity(x): return x
# https://arxiv.org/pdf/2106.12052.pdf
class VolSDF(CommonNeRF):
def __init__(
self, sdf,
# how many features to pass from density to RGB
intermediate_size: int = 32, out_features: int = 3,
device: torch.device = "cuda",
occ_kind=None,
w_missing:bool = False,
integrator_kind="direct",
scale_softplus=True,
**kwargs,
):
super().__init__(**kwargs, device=device)
self.sdf = sdf
# the reflectance model is in the SDF, so don't encode it here.
self.scale = nn.Parameter(torch.tensor(0.1, requires_grad=True, device=device))
self.secondary = None
self.out_features = out_features
self.scale_act = identity if not scale_softplus else nn.Softplus()
if occ_kind is not None:
assert(isinstance(self.sdf.refl, refl.LightAndRefl)), \
f"Must have light w/ volsdf integration {type(self.sdf.refl)}"
self.occ = load_occlusion_kind(occ_kind, self.sdf.latent_size)
if integrator_kind == "direct": self.secondary = self.direct
elif integrator_kind == "path": self.convert_to_path(w_missing)
else: raise NotImplementedError(f"unknown integrator kind {integrator_kind}")
def convert_to_path(self, w_missing: bool):
if self.secondary == self.path: return
self.secondary = self.path
self.path_n = N = 3
missing_cmpts = 3 * (N + 1) + 6
# this is a function of the seen pts and the sampled lighting dir
self.missing = None
if w_missing:
self.missing = SkipConnMLP(
in_size=missing_cmpts, out=self.out_features, enc=FourierEncoder(input_dims=missing_cmpts),
# here we care about the aggregate set of all point, so bundle them all up.
latent_size = self.sdf.latent_size * (N + 1),
hidden_size=512,
)
self.transfer_fn = SkipConnMLP(
in_size=6, out=1, enc=FourierEncoder(input_dims=6),
# multiply by two here ince it's the pair of latent values at sets of point
latent_size = self.sdf.latent_size * 2,
hidden_size=512,
)
def direct(self, r_o, weights, pts, view, n, latent):
out = torch.zeros_like(pts)
for light in self.sdf.refl.light.iter():
light_dir, light_val = self.occ(pts, light, self.sdf.intersect_mask, latent=latent)
bsdf_val = self.sdf.refl(x=pts, view=view, normal=n, light=light_dir, latent=latent)
out = out + bsdf_val * light_val
return out
def path(self, r_o, weights, pts, view, n, latent):
out = torch.zeros_like(pts)
N = self.path_n # number of samples for 1st order bounces
# for each point sample some number of directions
dirs = sample_random_hemisphere(n, num_samples=N)
# compute intersection of random directions with surface
ext_pts, ext_hits, dists, _ = march.bisect(
self.sdf.underlying, pts[None,...].expand_as(dirs), dirs, iters=64, near=5e-3, far=10,
)
decays = 1/dists.square().clamp(min=1e-8)
ext_sdf_vals, ext_latent = self.sdf.from_pts(ext_pts)
ext_view = F.normalize(ext_pts - r_o[None,None,...], eps=1e-6, dim=-1)
ext_n = F.normalize(self.sdf.normals(ext_pts), dim=-1).detach()
fit = lambda x: x.unsqueeze(0).expand(N,-1,-1,-1,-1,-1)
# reflection at the intersection points from light incoming from the random directions
first_step_bsdf = self.sdf.refl(
x=fit(pts), view=ext_view, normal=fit(n), light=-dirs, latent=fit(latent),
)
# compute transfer function (G) between ext_pts and pts
tf = self.transfer_fn(
torch.cat([ext_pts, pts.unsqueeze(0).expand_as(ext_pts)],dim=-1),
torch.cat([ext_latent, latent.unsqueeze(0).expand_as(ext_latent)], dim=-1),
).sigmoid()
# bsdf = light decay * transfer function * transfer fn
first_step_bsdf = first_step_bsdf * decays * tf
for light in self.sdf.refl.light.iter():
# compute direct lighting at each point (identical to direct)
light_dir, light_val = self.occ(pts, light, self.sdf.intersect_mask, latent=latent)
bsdf_val = self.sdf.refl(x=pts, view=view, normal=n, light=light_dir, latent=latent)
out = out + bsdf_val * light_val
# compute light contribution and bsdf at 2ndary points from this light
ext_light_dir, ext_light_val = \
self.occ(ext_pts, light, self.sdf.intersect_mask, latent=ext_latent)
path_bsdf = self.sdf.refl(
x=ext_pts, view=dirs, normal=ext_n, light=ext_light_dir, latent=ext_latent,
)
second_step = ext_light_val * path_bsdf
# TODO add missing to second step as a multiplication of each component?
#print(first_step.shape, second_step.shape)
# sum over the contributions at each point adding with each secondary contribution
secondary = (first_step_bsdf * second_step).sum(dim=0)
out = out + secondary
# because we have high sampling variance, add in a secondary component which accounts for
# unsampled values by taking the points sampled and the current set of points.
# This makes it possible to learn outside of the scope of what is possible, but should
# converge faster?
# we explicitly allow it to be negative in case the points we pick are all sampled with
# super high value.
if self.missing is None: continue
missing = self.missing(
torch.cat([
ext_pts.reshape((*ext_pts.shape[1:-1], 3 * N)), pts, light_dir, view,
], dim=-1),
torch.cat([
ext_latent.reshape((*ext_latent.shape[1:-1], self.sdf.latent_size * N)), latent,
], dim=-1),
)
missing = self.feat_act(missing)
out = out + missing
return out
def forward(self, rays):
pts, ts, r_o, r_d = compute_pts_ts(
rays, self.t_near, self.t_far, self.steps, perturb = 1 if self.training else 0,
)
self.ts = ts
return self.from_pts(pts, ts, r_o, r_d)
def total_latent_size(self): return self.sdf.latent_size
def set_refl(self, refl): self.sdf.refl = refl
@property
def refl(self): return self.sdf.refl
def from_pts(self, pts, ts, r_o, r_d):
latent = self.curr_latent(pts.shape)
mip_enc = self.mip_encoding(r_o, r_d, ts)
if mip_enc is not None: latent = torch.cat([latent, mip_enc], dim=-1)
sdf_vals, latent = self.sdf.from_pts(pts)
# turn this line on if things are broken due to not having a scale_act.
#if not hasattr(self, "scale_act"): self.scale_act = identity
scale = self.scale_act(self.scale) if self.training else 5e-3
density = 1/scale * laplace_cdf(-sdf_vals, scale)
self.alpha, self.weights = alpha_from_density(density, ts, r_d, softplus=False)
n = None
if self.sdf.refl.can_use_normal or self.secondary is not None:
self.n = n = F.normalize(self.sdf.normals(pts), dim=-1)
view = r_d.unsqueeze(0).expand_as(pts)
if self.secondary is None: rgb = self.sdf.refl(x=pts, view=view, normal=n, latent=latent)
else: rgb = self.secondary(r_o, self.weights, pts, view, n, latent)
return volumetric_integrate(self.weights, rgb)
def set_sigmoid(self, kind="thin"):
if not hasattr(self, "sdf"): return
self.sdf.refl.act = load_sigmoid(kind)
def alternating_volsdf_loss(model, nerf_loss, sdf_loss):
def aux(x, ref): return nerf_loss(x, ref[..., :3]) if model.vol_render else sdf_loss(x, ref)
return aux
# An odd module which alternates between volume rendering and SDF rendering
class AlternatingVolSDF(nn.Module):
def __init__(
self,
volsdf: VolSDF,
# run_len is how many iterations of volume/SDF rendering it will perform.
# it performs run_len/2 volume, and run_len/2 SDF
run_len:int = 4096,
):
super().__init__()
assert(isinstance(volsdf, VolSDF))
self.volsdf = volsdf
self.i = 0
self.force_volume = False
self.force_sdf = False
self.run_len = run_len
# TODO add some count for doing only sdfs first?
# forward a few properties to sdf
@property
def sdf(self): return self.volsdf.sdf
@property
def nerf(self): return self.volsdf
@property
def n(self): return self.volsdf.n
@property
def total_latent_size(self): return self.volsdf.total_latent_size
@property
def refl(self): return self.volsdf.refl
def set_refl(self, refl): return self.volsdf.set_refl(refl)
def forward(self, rays):
if not self.training: return self.volsdf(rays)
self.i = (self.i + 1) % self.run_len
self.vol_render = (self.i < self.run_len//2 or self.force_volume) and not self.force_sdf
if self.vol_render:
return self.volsdf(rays)
else:
return direct(self.volsdf.sdf, self.volsdf.refl, self.volsdf.occ, rays, self.training)
# Dynamic NeRF for multiple frams
class DynamicNeRF(nn.Module):
def __init__(self, canonical: CommonNeRF, gru_flow:bool=False, device="cuda"):
super().__init__()
self.canonical = canonical
if gru_flow:
self.delta_estim = UpdateOperator(in_size=4, out_size=3, hidden_size=32)
else:
self.delta_estim = SkipConnMLP(
# x,y,z,t -> dx, dy, dz
in_size=4, out=3,
num_layers = 5, hidden_size = 128,
enc=NNEncoder(input_dims=4),
activation=nn.Softplus(),
zero_init=True,
)
self.time_noise_std = 1e-2
self.smooth_delta = False
self.delta_smoothness = 0
@property
def nerf(self): return self.canonical
@property
def sdf(self): return getattr(self.canonical, "sdf", None)
def set_smooth_delta(self): setattr(self, "smooth_delta", True)
def forward(self, rays_t):
rays, t = rays_t
device=rays.device
pts, ts, r_o, r_d = compute_pts_ts(
rays, self.canonical.t_near, self.canonical.t_far, self.canonical.steps,
perturb = 1 if self.training else 0,
)
self.ts = ts
# small deviation for regularization
if self.training and self.time_noise_std > 0:
t = t + self.time_noise_std * torch.randn_like(t)
t = t[None, :, None, None, None].expand(pts.shape[:-1] + (1,))
pts_t = torch.cat([pts, t], dim=-1)
dp = self.delta_estim(pts_t)
dp = torch.where(t.abs() < 1e-6, torch.zeros_like(pts), dp)
#if self.training and self.smooth_delta:
# self.delta_smoothness = self.delta_estim.l2_smoothness(pts_t, dp)
pts = pts + dp
return self.canonical.from_pts(pts, ts, r_o, r_d)
# Dynamic NeRFAE for multiple framss with changing materials
class DynamicNeRFAE(nn.Module):
def __init__(self, canonical: NeRFAE, gru_flow: bool=False, device="cuda"):
super().__init__()
assert(isinstance(canonical, NeRFAE)), "Must use NeRFAE for DynamicNeRFAE"
self.canon = canonical.to(device)
self.delta_estim = SkipConnMLP(
# x,y,z,t -> dx, dy, dz
in_size=4, out=3 + canonical.encoding_size,
num_layers = 6, hidden_size = 128,
enc=NNEncoder(input_dims=4, device=device),
activation=nn.Softplus(), zero_init=True,
)
self.smooth_delta = False
self.tf_smoothness = 0
self.time_noise_std = 1e-3
@property
def nerf(self): return self.canon
def set_smooth_delta(self): setattr(self, "smooth_delta", True)
def forward(self, rays_t):
rays, t = rays_t
device=rays.device
pts, ts, r_o, r_d = compute_pts_ts(
rays, self.canon.t_near, self.canon.t_far, self.canon.steps,
)
self.ts = ts
# small deviation for regularization
if self.training and self.time_noise_std > 0: t = t + self.time_noise_std * torch.randn_like(t)
t = t[None, :, None, None, None].expand(pts.shape[:-1] + (1,))
# compute encoding using delta positions at a given time
pts_t = torch.cat([pts, t], dim=-1)
delta = self.delta_estim(pts_t)
#delta = torch.where(t.abs() < 1e-6, torch.zeros_like(delta), delta)
dp, d_enc = delta.split([3, self.canon.encoding_size], dim=-1)
encoded = self.canon.compute_encoded(pts + dp, ts, r_o, r_d)
# TODO is this best as a sum, or is some other kind of tform better?
return self.canon.from_encoded(encoded + d_enc, ts, r_d, pts)
class SinglePixelNeRF(nn.Module):
def __init__(
self,
canon: CommonNeRF,
encoder,
img,
device: torch.device = "cuda",
):
super().__init__()
self.canon = canon
self.encoder = encoder
# encode image
self.encoder(img)
self.device = device
@property
def nerf(self): return self.canon
def forward(self, rays_uvs):
rays, uvs = rays_uvs
latent = self.encoder.sample(uvs)
self.canon.set_per_pixel_latent(latent)
return self.canon(rays)
class MPI(nn.Module):
# Multi Plane Imaging.
def __init__(
self,
canonical: CommonNeRF,
position = [0,0,0],
normal = [0,0,-1],
delta=0.1,
n_planes: int = 6,
device="cuda",
):
super().__init__()
self.n_planes = torch.linspace(canon.t_near, canon.t_far, steps=n_planes, device=device)
self.position = torch.tensor(position, device=device, dtype=torch.float)
self.normal = torch.tensor(normal, device=device, dtype=torch.float)
self.delta = delta
self.canonical = canonical.to(device)
def forward(self, rays):
r_o, r_d = rays.split([3,3], dim=-1)
device = r_o.device
n = self.normal.expand_as(r_d)
denom = (n * r_d).sum(dim=-1, keepdim=True)
centers = self.position.unsqueeze(0) + torch.tensordot(
self.delta * torch.arange(self.n_planes, device=device, dtype=torch.float),
-self.normal, dims=0,
)
ts = ((centers - r_o) * n).sum(dim=-1, keepdim=True)/denom
# if denom is too small it will have numerical instability because it's near parallel.
hits = torch.where(denom.abs() > 1e-3, ts, torch.zeros_like(denom))
pts = r_o.unsqueeze(0) + r_d.unsqueeze(0) * hits
return self.canonical.from_pts(pts, ts, r_o, r_d)
@property
def nerf(self): return self.canon
def from_pts(self, pts, ts, r_o, r_d):
density, feats = self.estim(pts).split([1, 3], dim=-1)
alpha, weights = alpha_from_density(density, ts, r_d)
return volumetric_integrate(weights, self.feat_act(feats))
# TODO test this as well
def metropolis_sampling(
density_estimator,
ts_init, r_o, r_d,
iters: int = 6,
):
# need to make this the shape of r_d exit with last dim 1
curr = ts_init
print(r_o.shape)
exit()
with torch.no_grad():
candidates = torch.rand_like(curr) + curr
curr_density = density_estimator(candidates)
for i in range(iters):
candidates = torch.randn_like(curr) + curr
density = density_estimator(candidates)
acceptance = density/curr_density
alphas = torch.rand_like(density)
mask = acceptance <= alphas
curr = torch.where(mask, candidates, curr)
curr_density = torch.where(mask, density, curr_density)
return curr, r_o + curr * r_d
# TODO need to test this more, doesn't seem to work that well
def inverse_sample(
density_estimator,
pts, ts, r_o, r_d,
):
with torch.no_grad():
_, weights = alpha_from_density(density_estimator(pts.squeeze(-1)), ts, r_d)
weights = weights.clamp(min=1e-10)
pdf = weights/weights.sum(dim=0,keepdim=True)
cdf = torch.cumsum(pdf, dim=0)
N = ts.shape[0]
# XXX this only works because we assume that the number of samples (N) is the same.
#u = torch.rand_like(cdf)
u = torch.linspace(0, 1, N, device=cdf.device)\
[..., None, None, None].expand_as(cdf)
# XXX this operates on innermost dimension, so need to do this transpose
inds = torch.searchsorted(
cdf.transpose(0, -1).contiguous(), u.transpose(0, -1).contiguous(), right=True
).transpose(0, -1)
below = (inds - 1).clamp(min=0)
above = inds.clamp(max=N-1)
inds_g = torch.stack([below, above], dim=-1)
# TODO what is the right dimension to add here?
cdf_g = torch.gather(cdf.unsqueeze(1).expand_as(inds_g), 0, inds_g)
bins_g = torch.gather(ts[:, None, None, None, None].expand_as(inds_g), 0, inds_g)
denom = cdf_g[..., 1] - cdf_g[..., 0]
denom = torch.where(denom < 1e-5, torch.ones_like(denom), denom)
t = (u - cdf_g[..., 0]) / denom
samples = bins_g[..., 0] + t * (bins_g[..., 1] - bins_g[..., 0])
new_pts = r_o + samples.unsqueeze(-1) * r_d
return samples, new_pts
``` |
{
"source": "joebasirico/django-DefectDojo",
"score": 2
} |
#### File: api_v2/schema/utils.py
```python
from drf_yasg2.openapi import SchemaRef, Schema
class LazySchemaRef:
"""Utility class to support SchemaRef definition without knowing the resolver.
The reference can be evaluated later in the context of a swagger generator
"""
def __init__(self, schema_name, ignore_unresolved=False):
# Bind curried version of the SchemaRef init
self.schema_ref = lambda resolver: SchemaRef(resolver, schema_name, ignore_unresolved)
def apply(self, resolver):
"""Resolve the LazySchemaRef with the given resolver
Args:
resolver (ReferenceResolver): resolver containing the schema refs
Returns:
SchemaRef: the corresponding SchemaRef
"""
return self.schema_ref(resolver)
def try_apply(obj, resolver):
"""Try to resolve a LazySchemaRef
Args:
obj (object): the object to resolve
resolver (resolver): the resolver to use
Returns:
object: the original object if it was not resolve otherwise the resolved LazySchemaRef
"""
if type(obj) is LazySchemaRef:
return obj.apply(resolver)
else:
return obj
def resolve_lazy_ref(schema, resolver):
"""Recursively evaluate the schema to unbox LazySchemaRef based on the underlying resolvers.
Args:
schema (object): the schema to evaluate
Returns:
object: the schema without LazySchemaRef
"""
if type(schema) is not Schema:
return try_apply(schema, resolver)
if "properties" in schema:
for prop_name, prop in schema["properties"].items():
schema["properties"][prop_name] = resolve_lazy_ref(prop, resolver)
if "additionalProperties" in schema:
schema["additionalProperties"] = resolve_lazy_ref(schema["additionalProperties"], resolver)
return schema
```
#### File: tools/semgrep/parser.py
```python
import json
from dojo.models import Finding
from dojo.tools.semgrep.models import SemgrepJSONResult
class SemgrepParser(object):
def get_scan_types(self):
return ["Semgrep JSON Report"]
def get_label_for_scan_types(self, scan_type):
return scan_type # no custom label for now
def get_description_for_scan_types(self, scan_type):
return "Import Semgrep output (--json)"
def get_findings(self, filehandle, test):
tree = json.load(filehandle)
items = []
results = tree.get('results')
for item in results:
title = item['check_id']
semgrep_result = SemgrepJSONResult(item['extra'], item['path'], item['start'], item['end'])
findingItem = Finding(
title=semgrep_result.title,
severity=semgrep_result.severity,
numerical_severity=Finding.get_numerical_severity(semgrep_result.severity),
description=semgrep_result.message,
mitigation='N/A',
file_path=item['path'],
cwe=semgrep_result.cwe,
line=semgrep_result.start,
url='N/A',
impact='N/A',
static_finding=True,
test=test
)
items.append(findingItem)
return items
```
#### File: tools/spotbugs/parser.py
```python
__author__ = 'bakalor'
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
import re
from defusedxml import ElementTree as ET
from dojo.models import Finding
class SpotbugsParser(object):
def get_scan_types(self):
return ["SpotBugs Scan"]
def get_label_for_scan_types(self, scan_type):
return scan_type # no custom label for now
def get_description_for_scan_types(self, scan_type):
return "XML report of textui cli."
def get_findings(self, filename, test):
bug_patterns = dict()
dupes = dict()
SEVERITY = {
'1': 'High',
'2': 'Medium',
'3': 'Low'
}
tree = ET.parse(filename)
root = tree.getroot()
for pattern in root.findall('BugPattern'):
plain_pattern = re.sub(r'<[b-z/]*?>|<a|</a>|href=', '', ET.tostring(pattern.find('Details'), method='text').decode('utf-8'))
bug_patterns[pattern.get('type')] = plain_pattern
for bug in root.findall('BugInstance'):
desc = ''
for message in bug.itertext():
desc += message
dupe_key = bug.get('instanceHash')
title = bug.find('ShortMessage').text
cwe = bug.get('cweid', default=0)
severity = SEVERITY[bug.get('priority')]
description = desc
mitigation = bug_patterns[bug.get('type')]
impact = 'N/A'
references = 'N/A'
if dupe_key in dupes:
finding = dupes[dupe_key]
else:
finding = Finding(
title=title,
cwe=cwe,
severity=severity,
description=description,
mitigation=mitigation,
impact=impact,
references=references,
test=test,
active=False,
verified=False,
numerical_severity=Finding.get_numerical_severity(severity),
static_finding=True
)
dupes[dupe_key] = finding
self.items = list(dupes.values())
```
#### File: tools/sslyze/parser.py
```python
from .parser_json import SSLyzeJSONParser
from .parser_xml import SSLyzeXMLParser
class SslyzeParser(object):
"""SSLYze support JSON and XML"""
def get_scan_types(self):
return ["SSLyze 3 Scan (JSON)", "Sslyze Scan"]
def get_label_for_scan_types(self, scan_type):
return scan_type # no custom label for now
def get_description_for_scan_types(self, scan_type):
if scan_type == "SSLyze 3 Scan (JSON)":
return "Import JSON report of SSLyze version 3 scan."
return "Import XML report of SSLyze version 2 scan."
def get_findings(self, filename, test):
if filename is None:
return list()
content = filename.read()
if filename.name.lower().endswith('.xml'):
return SSLyzeXMLParser().get_findings(filename, test)
elif filename.name.lower().endswith('.json'):
return SSLyzeJSONParser().get_findings(filename, test)
else:
raise Exception('Unknown File Format')
```
#### File: dojo/unittests/test_deduplication_logic.py
```python
from django.test import TestCase
from dojo.models import Finding, User, Product, Endpoint, Endpoint_Status, Test, Engagement
from dojo.models import System_Settings
from crum import impersonate
import logging
logger = logging.getLogger(__name__)
deduplicationLogger = logging.getLogger("dojo.specific-loggers.deduplication")
# things to consider:
# - cross scanner deduplication is still flaky as if some scanners don't provide severity, but another doesn, the hashcode will be different so no deduplication happens.
# so I couldn't create any good tests
# - hash_code is only calculated once and never changed. should we add a feature to run dedupe when somebody modifies a finding? bulk edit action to trigger dedupe?
# - deduplication is using the default ordering for findings, so most of the time this means a new finding will be marked as duplicate of the most recent existing finding
# that matches the criteria. I thinkg it would be better to consider the oldest existing findings first? Otherwise we have the chance that an old finding becomes
# marked as duplicate of a newer one at some point.
# - legacy: if file_path and line or both empty and there are no endpoints, no dedupe will happen. Is this desirable or a BUG?
# - DEDUPE_ALGO_UNIQUE_ID_FROM_TOOL_OR_HASH_CODE should:
# - try to match on uniquer_id first before falling back to hash_Code. Currently it just takes the first finding it can find
# that mathces either the hash_code or unique id.
# - If the unique_id does NOT match, the finding is still considered for dedupe if the hash_code matches. We may need to forbid as the unique_id should be leading for the same test_type
# false positive history observations:
# - doesn't respect dedupe_on_engagement
# - if endpoints are mismatching, it falls back to comparing just the title + test_type or cwe + test_type. this leads to false positive false positives (pung intended)
# - I think this feature should be resdesigned and use the dedupe algo to find "identical/similar findings" to copy false_p status from
# test data summary
# product 1: Python How-to
# engagement 2: April monthly engagement (dedupe_inside: True)
# test 13: ZAP Scan (algo=hash_code, dynamic=True)
# no findings
# endpoints
# 2: ftp://localhost/
# 1: http://127.0.0.1/endpoint/420/edit/
# 3: ssh:127.0.1
# endpoint statuses
# 1: dojo.Endpoint.None dojo.Finding.None 1 2020-07-01 00:00:00+00:00 2020-07-01 17:45:39.791907+00:00 False None None False False False ftp://localhost/ High Impact Test Finding
# product 2: Security How-to
# engagement 1: 1st Quarter Engagement (dedupe_inside: True)
# test 3: ZAP Scan (algo=hash_code, dynamic=True)
# findings:
# 2 : "High Impact Test Fin": High : act: True : ver: True : mit: False: dup: False: dup_id: None: hash_code: 8cba854f0b70f8a25064952402fbe30c728c0017b83c245d786366956044e0bf: eps: 0: notes: []: uid: None
# 3 : "High Impact Test Fin": High : act: True : ver: True : mit: False: dup: True : dup_id: 2 : hash_code: 8cba854f0b70f8a25064952402fbe30c728c0017b83c245d786366956044e0bf: eps: 0: notes: []: uid: None
# 4 : "High Impact Test Fin": High : act: True : ver: True : mit: False: dup: True : dup_id: 2 : hash_code: 8cba854f0b70f8a25064952402fbe30c728c0017b83c245d786366956044e0bf: eps: 0: notes: []: uid: None
# 5 : "High Impact Test Fin": High : act: True : ver: True : mit: False: dup: True : dup_id: 2 : hash_code: 8cba854f0b70f8a25064952402fbe30c728c0017b83c245d786366956044e0bf: eps: 0: notes: []: uid: None
# 6 : "High Impact Test Fin": High : act: True : ver: True : mit: False: dup: True : dup_id: 2 : hash_code: 8cba854f0b70f8a25064952402fbe30c728c0017b83c245d786366956044e0bf: eps: 0: notes: []: uid: None
# 7 : "DUMMY FINDING ": High : act: False: ver: False: mit: False: dup: False: dup_id: None: hash_code: c89d25e445b088ba339908f68e15e3177b78d22f3039d1bfea51c4be251bf4e0: eps: 0: notes: [1]: uid: None
# endpoints
# 2: ftp://localhost/
# 1: http://127.0.0.1/endpoint/420/edit/
# 3: ssh:127.0.1
# endpoint statuses
# 1: dojo.Endpoint.None dojo.Finding.None 1 2020-07-01 00:00:00+00:00 2020-07-01 17:45:39.791907+00:00 False None None False False False ftp://localhost/ High Impact Test Finding
# test 14: ZAP Scan (algo=hash_code, dynamic=True)
# no findings
# endpoints
# 2: ftp://localhost/
# 1: http://127.0.0.1/endpoint/420/edit/
# 3: ssh:127.0.1
# endpoint statuses
# 1: dojo.Endpoint.None dojo.Finding.None 1 2020-07-01 00:00:00+00:00 2020-07-01 17:45:39.791907+00:00 False None None False False False ftp://localhost/ High Impact Test Finding
# engagement 4: April monthly engagement (dedupe_inside: True)
# test 4: ZAP Scan (algo=hash_code, dynamic=True)
# no findings
# endpoints
# 2: ftp://localhost/
# 1: http://127.0.0.1/endpoint/420/edit/
# 3: ssh:127.0.1
# endpoint statuses
# 1: dojo.Endpoint.None dojo.Finding.None 1 2020-07-01 00:00:00+00:00 2020-07-01 17:45:39.791907+00:00 False None None False False False ftp://localhost/ High Impact Test Finding
# engagement 5: April monthly engagement (dedupe_inside: True)
# test 55: Checkmarx Scan detailed (algo=unique_id_from_tool, dynamic=False)
# findings:
# 124 : "Low Impact Test Find": Low : act: True : ver: True : mit: False: dup: False: dup_id: None: hash_code: 5f272ec29b29d56ca08eba26435bdb225ae4956812c10fce872a6143b73474ba: eps: 0: notes: []: uid: 12345
# 125 : "Low Impact Test Find": Low : act: True : ver: True : mit: False: dup: True : dup_id: None: hash_code: 5f272ec29b29d56ca08eba26435bdb225ae4956812c10fce872a6143b73474ba: eps: 0: notes: []: uid: 12345
# endpoints
# 2: ftp://localhost/
# 1: http://127.0.0.1/endpoint/420/edit/
# 3: ssh:127.0.1
# endpoint statuses
# 1: dojo.Endpoint.None dojo.Finding.None 1 2020-07-01 00:00:00+00:00 2020-07-01 17:45:39.791907+00:00 False None None False False False ftp://localhost/ High Impact Test Finding
# test 66: Checkmarx Scan detailed (algo=unique_id_from_tool, dynamic=False)
# no findings
# endpoints
# 2: ftp://localhost/
# 1: http://127.0.0.1/endpoint/420/edit/
# 3: ssh:127.0.1
# endpoint statuses
# 1: dojo.Endpoint.None dojo.Finding.None 1 2020-07-01 00:00:00+00:00 2020-07-01 17:45:39.791907+00:00 False None None False False False ftp://localhost/ High Impact Test Finding
# test 77: Veracode Scan (algo=unique_id_from_tool_or_hash_code, dynamic=False)
# findings:
# 224 : "UID Impact Test Find": Low : act: True : ver: True : mit: False: dup: False: dup_id: None: hash_code: 3c5e9d1ec77aea19dd2bbf3aa51f585fc0da876174be8cac885966db1271f147: eps: 0: notes: []: uid: 6789
# 225 : "UID Impact Test Find": Low : act: True : ver: True : mit: False: dup: True : dup_id: 224 : hash_code: 3c5e9d1ec77aea19dd2bbf3aa51f585fc0da876174be8cac885966db1271f147: eps: 0: notes: []: uid: 6789
# endpoints
# 2: ftp://localhost/
# 1: http://127.0.0.1/endpoint/420/edit/
# 3: ssh:127.0.1
# endpoint statuses
# 1: dojo.Endpoint.None dojo.Finding.None 1 2020-07-01 00:00:00+00:00 2020-07-01 17:45:39.791907+00:00 False None None False False False ftp://localhost/ High Impact Test Finding
# test 88: Veracode Scan (algo=unique_id_from_tool_or_hash_code, dynamic=False)
# no findings
# endpoints
# 2: ftp://localhost/
# 1: http://127.0.0.1/endpoint/420/edit/
# 3: ssh:127.0.1
# endpoint statuses
# 1: dojo.Endpoint.None dojo.Finding.None 1 2020-07-01 00:00:00+00:00 2020-07-01 17:45:39.791907+00:00 False None None False False False ftp://localhost/ High Impact Test Finding
# engagement 6: April monthly engagement (dedupe_inside: True)
# engagement 3: weekly engagement (dedupe_inside: True)
# test 33: Generic Findings Import (algo=legacy, dynamic=False)
# findings:
# 22 : "Low Impact Test Find": Low : act: True : ver: True : mit: False: dup: False: dup_id: None: hash_code: 5f272ec29b29d56ca08eba26435bdb225ae4956812c10fce872a6143b73474ba: eps: 0: notes: []: uid: None
# 23 : "Low Impact Test Find": Low : act: True : ver: True : mit: False: dup: True : dup_id: 22 : hash_code: 5f272ec29b29d56ca08eba26435bdb225ae4956812c10fce872a6143b73474ba: eps: 0: notes: []: uid: None
# 24 : "Low Impact Test Find": Low : act: True : ver: True : mit: False: dup: True : dup_id: 22 : hash_code: 5f272ec29b29d56ca08eba26435bdb225ae4956812c10fce872a6143b73474ba: eps: 0: notes: []: uid: None
# endpoints
# 2: ftp://localhost/
# 1: http://127.0.0.1/endpoint/420/edit/
# 3: ssh:127.0.1
# endpoint statuses
# 1: dojo.Endpoint.None dojo.Finding.None 1 2020-07-01 00:00:00+00:00 2020-07-01 17:45:39.791907+00:00 False None None False False False ftp://localhost/ High Impact Test Finding
# product 3: Security Podcast
class TestDuplicationLogic(TestCase):
fixtures = ['dojo_testdata.json']
def run(self, result=None):
testuser = User.objects.get(username='admin')
testuser.usercontactinfo.block_execution = True
testuser.save()
# unit tests are running without any user, which will result in actions like dedupe happening in the celery process
# this doesn't work in unittests as unittests are using an in memory sqlite database and celery can't see the data
# so we're running the test under the admin user context and set block_execution to True
with impersonate(testuser):
super().run(result)
def setUp(self):
logger.debug('enabling deduplication')
self.enable_dedupe()
self.log_summary()
def tearDown(self):
# some test disable dedupe, always reenable
self.enable_dedupe()
self.log_summary()
# self.log_summary(test=33)
# self.log_summary(product=2)
# all engagements in the test data have deduplication_on_engagement set to true
# legacy algo: findings 23, 24, 25 in test 33 are scan_Type Generic Findings Import which uses the legacy algo
def test_identical_legacy(self):
# 24 is already a duplicate of 22 let's see what happens if we create an identical finding (but reset status)
# expect: marked as duplicate
finding_new, finding_24 = self.copy_and_reset_finding(id=24)
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=24, duplicate=True, duplicate_finding_id=finding_24.duplicate_finding.id, hash_code=finding_24.hash_code)
def test_identical_ordering_legacy(self):
finding_22 = Finding.objects.get(id=22)
# 23 is already a duplicate of 22, but let's reset it's status. then update 24 and see if it gets marked as duplicate of 22 or 23
# expect: marked as duplicate of 23 as 23 is older (date field on finding)
# but feature or BUG? it will get marked as duplicate of 22 as it becomes earlier in the findings list (or ordering is by date desc)
finding_23 = Finding.objects.get(id=23)
finding_23.duplicate = False
finding_23.duplicate_finding = None
finding_23.active = True
finding_23.save(dedupe_option=False)
self.assert_finding(finding_23, duplicate=False, hash_code=finding_22.hash_code)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.save()
self.assert_finding(finding_new, not_pk=22, duplicate=True, duplicate_finding_id=finding_22.id, hash_code=finding_22.hash_code)
# self.assert_finding(finding_new, not_pk=22, duplicate=True, duplicate_finding_id=finding_23.id, hash_code=finding_22.hash_code)
def test_identical_except_title_legacy(self):
# 24 is already a duplicate of 22, let's see what happens if we create an identical finding with different title (and reset status)
# expect: NOT marked as duplicate as title is part of hash_code calculation
finding_new, finding_4 = self.copy_and_reset_finding(id=4)
finding_new.title = 'the best title'
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=24, duplicate=False, not_hash_code=finding_4.hash_code)
def test_identical_except_description_legacy(self):
# 24 is already a duplicate of 22, let's see what happens if we create an identical finding with different description (and reset status)
# expect: not marked as duplicate as legacy sees description as leading for hash_code
finding_new, finding_24 = self.copy_and_reset_finding(id=24)
finding_new.description = 'useless finding'
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=24, duplicate=False, not_hash_code=finding_24.hash_code)
def test_identical_except_line_legacy(self):
# 24 is already a duplicate of 22, let's see what happens if we create an identical finding with different line (and reset status)
# expect: not marked as duplicate
finding_new, finding_24 = self.copy_and_reset_finding(id=24)
finding_new.line = 666
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=24, duplicate=False, not_hash_code=finding_24.hash_code)
def test_identical_except_filepath_legacy(self):
# 24 is already a duplicate of 22, let's see what happens if we create an identical finding with different file_path (and reset status)
# expect: not marked as duplicate
finding_new, finding_24 = self.copy_and_reset_finding(id=24)
finding_new.file_path = '/dev/null'
finding_22 = Finding.objects.get(id=22)
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=24, duplicate=False, not_hash_code=finding_24.hash_code)
def test_dedupe_inside_engagement_legacy(self):
# finding 2 in engagement 1
# make a copy and store it in engagement 2, test 4
# should not result in being marked as duplicate as it crosses engagement boundaries
# both test 3 and 4 are ZAP scans (cross scanner dedupe is still not working very well)
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
# create new engagment + test in same product
test_new, eng_new = self.create_new_test_and_engagment_from_finding(finding_22)
finding_new.test = test_new
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=22, duplicate=False, hash_code=finding_22.hash_code)
def test_dedupe_not_inside_engagement_legacy(self):
# finding 2 in engagement 1
# make a copy and store it in engagement 2, test 4
# should result in being marked as duplicate as dedupe inside engagement is set to False
# both test 3 and 4 are ZAP scans (cross scanner dedupe is still not working very well)
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
# dedupe_inside_engagment must be false before cloning engagement
self.set_dedupe_inside_engagement(False)
# create new engagment + test in same product
test_new, eng_new = self.create_new_test_and_engagment_from_finding(finding_22)
finding_new.test = test_new
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=22, duplicate=True, duplicate_finding_id=22, hash_code=finding_22.hash_code)
# legacy: if file_path and line or both empty and there are no endpoints, no dedupe will happen. Is this desirable or a BUG?
def test_identical_no_filepath_no_line_no_endpoints_legacy(self):
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.file_path = None
finding_new.line = None
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=22, duplicate=False)
def test_identical_legacy_with_identical_endpoints_static(self):
finding_new, finding_24 = self.copy_and_reset_finding_add_endpoints(id=24, static=True, dynamic=False) # has myhost.com, myhost2.com
finding_new.save()
# create an identical copy of the new finding with the same endpoints. it should be marked as duplicate
finding_new2, finding_new = self.copy_and_reset_finding(id=finding_new.id)
finding_new2.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new2.test.engagement.product, finding=finding_new2, host="myhost.com", protocol="https")
ep1.save()
ep2 = Endpoint(product=finding_new2.test.engagement.product, finding=finding_new2, host="myhost2.com", protocol="https")
ep2.save()
finding_new2.endpoints.add(ep1)
finding_new2.endpoints.add(ep2)
finding_new2.save()
self.assert_finding(finding_new2, not_pk=finding_new.pk, duplicate=True, duplicate_finding_id=finding_new.id, hash_code=finding_new.hash_code, not_hash_code=finding_24.hash_code)
def test_identical_legacy_extra_endpoints_static(self):
finding_new, finding_24 = self.copy_and_reset_finding_add_endpoints(id=24, static=True, dynamic=False) # has myhost.com, myhost2.com
finding_new.save()
# create a new finding with 3 endpoints (so 1 extra)
finding_new3, finding_new = self.copy_and_reset_finding(id=finding_new.id)
finding_new3.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost.com", protocol="https")
ep1.save()
ep2 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost2.com", protocol="https")
ep2.save()
ep3 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost3.com", protocol="https")
ep3.save()
finding_new3.endpoints.add(ep1)
finding_new3.endpoints.add(ep2)
finding_new3.endpoints.add(ep3)
finding_new3.save()
# expect: marked as duplicate as the requirement for static findings is that the new finding has to contain all the endpoints of the existing finding (extra is no problem)
# hash_code not affected by endpoints
self.assert_finding(finding_new3, not_pk=finding_new.pk, duplicate=True, duplicate_finding_id=finding_new.id, hash_code=finding_new.hash_code, not_hash_code=finding_24.hash_code)
def test_identical_legacy_different_endpoints_static(self):
finding_new, finding_24 = self.copy_and_reset_finding_add_endpoints(id=24, static=True, dynamic=False) # has myhost.com, myhost2.com
finding_new.save()
# create an identical copy of the new finding, but with different endpoints
finding_new3, finding_new = self.copy_and_reset_finding(id=finding_new.id)
finding_new3.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost4.com", protocol="https")
ep1.save()
ep2 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost2.com", protocol="https")
ep2.save()
finding_new3.endpoints.add(ep1)
finding_new3.endpoints.add(ep2)
finding_new3.save()
# expect: not marked as duplicate as the requirement for static findings is that the new finding has to contain all the endpoints of the existing finding and this is not met
# hash_code not affected by endpoints
self.assert_finding(finding_new3, not_pk=finding_new.pk, duplicate=False, hash_code=finding_new.hash_code, not_hash_code=finding_24.hash_code)
def test_identical_legacy_no_endpoints_static(self):
finding_new, finding_24 = self.copy_and_reset_finding_add_endpoints(id=24, static=True, dynamic=False) # has myhost.com, myhost2.com
finding_new.save()
# create an identical copy of the new finding, but with 1 extra endpoint. should not be marked as duplicate
finding_new3, finding_new = self.copy_and_reset_finding(id=finding_new.id)
finding_new3.save(dedupe_option=False)
finding_new3.save()
# expect not marked as duplicate as the new finding doesn't have endpoints and we don't have filepath/line
self.assert_finding(finding_new3, not_pk=finding_new.pk, duplicate=False, hash_code=finding_new.hash_code, not_hash_code=finding_24.hash_code)
def test_identical_legacy_with_identical_endpoints_dynamic(self):
finding_new, finding_24 = self.copy_and_reset_finding_add_endpoints(id=24, static=True, dynamic=False) # has myhost.com, myhost2.com
finding_new.save()
# create an identical copy of the new finding. it should be marked as duplicate
finding_new2, finding_new = self.copy_and_reset_finding(id=finding_new.id)
finding_new2.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new2.test.engagement.product, finding=finding_new2, host="myhost.com", protocol="https")
ep1.save()
ep2 = Endpoint(product=finding_new2.test.engagement.product, finding=finding_new2, host="myhost2.com", protocol="https")
ep2.save()
finding_new2.endpoints.add(ep1)
finding_new2.endpoints.add(ep2)
finding_new2.save()
self.assert_finding(finding_new2, not_pk=finding_new.pk, duplicate=True, duplicate_finding_id=finding_new.id, hash_code=finding_new.hash_code, not_hash_code=finding_24.hash_code)
def test_identical_legacy_extra_endpoints_dynamic(self):
finding_new, finding_24 = self.copy_and_reset_finding_add_endpoints(id=24)
finding_new.save()
# create an identical copy of the new finding, but with 1 extra endpoint.
finding_new3, finding_new = self.copy_and_reset_finding(id=finding_new.id)
finding_new3.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost.com", protocol="https")
ep1.save()
ep2 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost2.com", protocol="https")
ep2.save()
ep3 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost3.com", protocol="https")
ep3.save()
finding_new3.endpoints.add(ep1)
finding_new3.endpoints.add(ep2)
finding_new3.endpoints.add(ep3)
finding_new3.save()
# expect: not marked as duplicate, hash_code affected by endpoints
self.assert_finding(finding_new3, not_pk=finding_new.pk, duplicate=False, not_hash_code=finding_new.hash_code)
def test_identical_legacy_different_endpoints_dynamic(self):
# this test is using the pattern currently in use in the import / serializers.py.
# - save finding first with dedupe-false
# - add endpoints
# - safe finding again with endpoints attached, dedupe=True (default) -> hash_code gets computed
# create a new finding with 3 endpoints (so 1 extra)
# expect: not marked as duplicate as endpoints need to be 100% equal for dynamic findings (host+port)
# hash_code not affected by endpoints
finding_new, finding_24 = self.copy_and_reset_finding_add_endpoints(id=24)
finding_new.save()
# create an identical copy of the new finding, but with 1 extra endpoint. should not be marked as duplicate
finding_new3, finding_new = self.copy_and_reset_finding(id=finding_new.id)
finding_new3.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost4.com", protocol="https")
ep1.save()
ep2 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost2.com", protocol="https")
ep2.save()
finding_new3.endpoints.add(ep1)
finding_new3.endpoints.add(ep2)
finding_new3.save()
# expect: not marked as duplicate, hash_code affected by endpoints
self.assert_finding(finding_new3, not_pk=finding_new.pk, duplicate=False, not_hash_code=finding_new.hash_code)
def test_identical_legacy_no_endpoints_dynamic(self):
finding_new, finding_24 = self.copy_and_reset_finding_add_endpoints(id=24)
finding_new.save()
# create an identical copy of the new finding, but with no endpoints
finding_new3, finding_new = self.copy_and_reset_finding(id=finding_new.id)
finding_new3.save(dedupe_option=False)
finding_new3.save()
# expect: not marked as duplicate, hash_code affected by endpoints
self.assert_finding(finding_new3, not_pk=finding_new.pk, duplicate=False, not_hash_code=finding_new.hash_code)
# hash_code based algorithm tests
# existing findings in test 3 are from ZAP scanner, which uses hash_code algorithm with ['title', 'cwe', 'endpoints', 'severity']
def test_identical_hash_code(self):
# 4 is already a duplicate of 2, let's see what happens if we create an identical finding (but reset status)
# expect: marked as duplicate
finding_new, finding_4 = self.copy_and_reset_finding(id=4)
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=4, duplicate=True, duplicate_finding_id=finding_4.duplicate_finding.id, hash_code=finding_4.hash_code)
def test_identical_ordering_hash_code(self):
finding_2 = Finding.objects.get(id=2)
# 3 is already a duplicate of 2, but let's reset it's status. then update 24 and see if it gets marked as duplicate of 22 or 23
# expect: marked as duplicate of 3 as 3 is older (date field on finding)
# but feature or BUG? it will get marked as duplicate of 2 as it becomes earlier in the findings list (or ordering is by date desc)
finding_3 = Finding.objects.get(id=3)
finding_3.duplicate = False
finding_3.duplicate_finding = None
finding_3.active = True
finding_3.save(dedupe_option=False)
self.assert_finding(finding_3, duplicate=False, hash_code=finding_2.hash_code)
# create a copy of 2
finding_new, finding_2 = self.copy_and_reset_finding(id=2)
finding_new.save()
self.assert_finding(finding_new, not_pk=2, duplicate=True, duplicate_finding_id=finding_2.id, hash_code=finding_2.hash_code)
# self.assert_finding(finding_new, not_pk=2, duplicate=True, duplicate_finding_id=finding_3.id, hash_code=finding_2.hash_code)
def test_identical_except_title_hash_code(self):
# 4 is already a duplicate of 2, let's see what happens if we create an identical finding with different title (and reset status)
# expect: NOT marked as duplicate as title is part of hash_code calculation
finding_new, finding_4 = self.copy_and_reset_finding(id=4)
finding_new.title = 'the best title'
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=4, duplicate=False, not_hash_code=finding_4.hash_code)
def test_identical_except_description_hash_code(self):
# 4 is already a duplicate of 2, let's see what happens if we create an identical finding with different description (and reset status)
# expect: marked as duplicate
finding_new, finding_4 = self.copy_and_reset_finding(id=4)
finding_new.description = 'useless finding'
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=4, duplicate=True, duplicate_finding_id=finding_4.duplicate_finding.id, hash_code=finding_4.hash_code)
# TODO not usefile with ZAP?
def test_identical_except_line_hash_code(self):
# 4 is already a duplicate of 2, let's see what happens if we create an identical finding with different line (and reset status)
# expect: marked as duplicate
finding_new, finding_4 = self.copy_and_reset_finding(id=4)
finding_new.line = 666
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=4, duplicate=True, duplicate_finding_id=finding_4.duplicate_finding.id, hash_code=finding_4.hash_code)
# TODO not usefile with ZAP?
def test_identical_except_filepath_hash_code(self):
# 4 is already a duplicate of 2, let's see what happens if we create an identical finding with different file_path (and reset status)
# expect: marked as duplicate
finding_new, finding_4 = self.copy_and_reset_finding(id=4)
finding_new.file_path = '/dev/null'
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=4, duplicate=True, duplicate_finding_id=finding_4.duplicate_finding.id, hash_code=finding_4.hash_code)
def test_dedupe_inside_engagement_hash_code(self):
# finding 2 in engagement 1
# make a copy and store it in engagement 2, test 4
# should not result in being marked as duplicate as it crosses engagement boundaries
# both test 3 and 4 are ZAP scans (cross scanner dedupe is still not working very well)
finding_new, finding_2 = self.copy_and_reset_finding(id=2)
finding_new.test = Test.objects.get(id=4)
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=2, duplicate=False, hash_code=finding_2.hash_code)
def test_dedupe_not_inside_engagement_hash_code(self):
# finding 2 in engagement 1
# make a copy and store it in engagement 2, test 4
# should result in being marked as duplicate as dedupe inside engagement is set to False
# both test 3 and 4 are ZAP scans (cross scanner dedupe is still not working very well)
self.set_dedupe_inside_engagement(False)
finding_new, finding_2 = self.copy_and_reset_finding(id=2)
finding_new.test = Test.objects.get(id=4)
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=2, duplicate=True, duplicate_finding_id=2, hash_code=finding_2.hash_code)
# hash_code: if file_path and line or both empty and there are no endpoints, dedupe should happen (as opposed to legacy dedupe)
def test_identical_no_filepath_no_line_no_endpoints_hash_code(self):
finding_new, finding_2 = self.copy_and_reset_finding(id=2)
finding_new.file_path = None
finding_new.line = None
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=2, duplicate=True, duplicate_finding_id=2, hash_code=finding_2.hash_code)
def test_identical_hash_code_with_identical_endpoints(self):
finding_new, finding_4 = self.copy_and_reset_finding_add_endpoints(id=4) # has myhost.com, myhost2.com
finding_new.save()
# create an identical copy of the new finding, with the same endpoints
finding_new2, finding_new = self.copy_and_reset_finding(id=finding_new.id)
finding_new2.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new2.test.engagement.product, finding=finding_new2, host="myhost.com", protocol="https")
ep1.save()
ep2 = Endpoint(product=finding_new2.test.engagement.product, finding=finding_new2, host="myhost2.com", protocol="https")
ep2.save()
finding_new2.endpoints.add(ep1)
finding_new2.endpoints.add(ep2)
finding_new2.save()
# expect: not marked as duplicate, hash_code affected by endpoints
self.assert_finding(finding_new2, not_pk=finding_new.pk, duplicate=True, duplicate_finding_id=finding_new.id, hash_code=finding_new.hash_code, not_hash_code=finding_4.hash_code)
def test_identical_hash_code_with_different_endpoints(self):
finding_new, finding_4 = self.copy_and_reset_finding_add_endpoints(id=4)
# save with dedupe so hash_code contains endpoints
finding_new.save()
# create an identical copy of the new finding, but with 1 extra endpoint. should not be marked as duplicate
finding_new3, finding_new = self.copy_and_reset_finding(id=finding_new.id)
finding_new3.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost4.com", protocol="https")
ep1.save()
ep2 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost2.com", protocol="https")
ep2.save()
ep3 = Endpoint(product=finding_new3.test.engagement.product, finding=finding_new3, host="myhost3.com", protocol="https")
ep3.save()
finding_new3.endpoints.add(ep1)
finding_new3.endpoints.add(ep2)
finding_new3.endpoints.add(ep3)
finding_new3.save()
# expect: not marked as duplicate, hash_code affected by endpoints
self.assert_finding(finding_new3, not_pk=finding_new.pk, duplicate=False, not_hash_code=finding_4.hash_code)
# # unique_id algo uses id from tool. hash_code is still calculated, according to legacy field config Checkmarx detailed scan
def test_identical_unique_id(self):
# create identical copy
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
finding_new.save()
# expect duplicate
self.assert_finding(finding_new, not_pk=124, duplicate=True, duplicate_finding_id=124, hash_code=finding_124.hash_code)
def test_different_unique_id_unique_id(self):
# create identical copy
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
finding_new.unique_id_from_tool = '9999'
finding_new.save()
# expect not duplicate, but same hash_code
self.assert_finding(finding_new, not_pk=124, duplicate=False, hash_code=finding_124.hash_code)
def test_identical_ordering_unique_id(self):
# create identical copy
finding_new, finding_125 = self.copy_and_reset_finding(id=125)
finding_new.save()
# expect duplicate, but of 124 as that is first in the list, but it's newer then 125. feature or BUG?
self.assert_finding(finding_new, not_pk=124, duplicate=True, duplicate_finding_id=124, hash_code=finding_125.hash_code)
def test_title_description_line_filepath_different_unique_id(self):
# create identical copy, change some fields
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
finding_new.title = 'another title'
finding_new.cve = 'CVE-2020-12345'
finding_new.cwe = '456'
finding_new.description = 'useless finding'
finding_new.save()
# expect duplicate as we only match on unique id, hash_code also different
self.assert_finding(finding_new, not_pk=124, duplicate=True, duplicate_finding_id=124, not_hash_code=finding_124.hash_code)
def test_title_description_line_filepath_different_and_id_different_unique_id(self):
# create identical copy, change some fields
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
finding_new.title = 'another title'
finding_new.cve = 'CVE-2020-12345'
finding_new.cwe = '456'
finding_new.description = 'useless finding'
finding_new.unique_id_from_tool = '9999'
finding_new.save()
# expect not duplicate as we match on unique id, hash_code also different because fields changed
self.assert_finding(finding_new, not_pk=124, duplicate=False, not_hash_code=finding_124.hash_code)
def test_dedupe_not_inside_engagement_unique_id(self):
# create identical copy
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
# first setup some finding with same unique_id in different engagement, but same test_type
finding_22 = Finding.objects.get(id=22)
finding_22.test.test_type = finding_124.test.test_type
finding_22.test.save()
finding_22.unique_id_from_tool = '888'
finding_22.save(dedupe_option=False)
finding_new.unique_id_from_tool = '888'
finding_new.save()
# expect not duplicate as dedupe_inside_engagement is True
self.assert_finding(finding_new, not_pk=124, duplicate=False, hash_code=finding_124.hash_code)
def test_dedupe_inside_engagement_unique_id(self):
# create identical copy
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
# first setup some finding with same unique_id in same engagement, but different test (same test_type)
finding_new.test = Test.objects.get(id=66)
finding_new.save()
print(finding_new.pk)
print(finding_new.hash_code)
print(finding_new.duplicate)
# expect duplicate as dedupe_inside_engagement is True and the other test is in the same engagement
self.assert_finding(finding_new, not_pk=124, duplicate=True, duplicate_finding_id=124, hash_code=finding_124.hash_code)
def test_dedupe_inside_engagement_unique_id2(self):
# create identical copy
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
# first setup some finding with same unique_id in different engagement, but same test_type
self.set_dedupe_inside_engagement(False)
finding_22 = Finding.objects.get(id=22)
finding_22.test.test_type = finding_124.test.test_type
finding_22.test.save()
finding_22.unique_id_from_tool = '888'
finding_22.save(dedupe_option=False)
finding_new.unique_id_from_tool = '888'
finding_new.save()
# expect duplicate as dedupe_inside_engagement is false
self.assert_finding(finding_new, not_pk=124, duplicate=True, duplicate_finding_id=finding_22.id, hash_code=finding_124.hash_code)
def test_dedupe_same_id_different_test_type_unique_id(self):
# create identical copy
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
# first setup some finding from a different test_Type, but with the same unique_id_from_tool
finding_22 = Finding.objects.get(id=22)
finding_22.unique_id_from_tool = '888'
finding_new.unique_id_from_tool = '888'
# and we need to look in another engagement this time for finding_22
self.set_dedupe_inside_engagement(False)
finding_22.save(dedupe_option=False)
finding_new.save()
# expect not duplicate as the mathcing finding is from another test_type, hash_code is the same as original
self.assert_finding(finding_new, not_pk=124, duplicate=False, hash_code=finding_124.hash_code)
def test_identical_different_endpoints_unique_id(self):
# create identical copy
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
finding_new.endpoints.add(ep1)
finding_new.save()
# expect duplicate, as endpoints shouldn't affect dedupe and hash_code due to unique_id
self.assert_finding(finding_new, not_pk=124, duplicate=True, duplicate_finding_id=124, hash_code=finding_124.hash_code)
# algo unique_id_or_hash_code Veracode scan
def test_identical_unique_id_or_hash_code(self):
# create identical copy
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
finding_new.save()
# expect duplicate as uid matches
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=224, hash_code=finding_224.hash_code)
# existing BUG? finding gets matched on hash code, while there is also an existing finding with matching unique_id_from_tool
def test_identical_unique_id_or_hash_code_bug(self):
# create identical copy
finding_124 = Finding.objects.get(id=124)
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
finding_new.title = finding_124.title # use title from 124 to get matching hashcode
finding_new.save()
# it should match finding 224 as uid matches, but dd currently matches against 124 as that has the same hashcode and is earlier in the list of findings
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=124, hash_code=finding_124.hash_code)
def test_different_unique_id_unique_id_or_hash_code(self):
# create identical copy
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
finding_new.unique_id_from_tool = '9999'
finding_new.save()
# expect duplicate, uid mismatch, but same hash_code
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=finding_224.id, hash_code=finding_224.hash_code)
# but if we change title and thus hash_code, it should no longer matchs
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
finding_new.unique_id_from_tool = '9999'
finding_new.title = 'no no no no no no'
finding_new.save()
# expect duplicate, uid mismatch, but same hash_code
self.assert_finding(finding_new, not_pk=224, duplicate=False, not_hash_code=finding_224.hash_code)
def test_identical_ordering_unique_id_or_hash_code(self):
# create identical copy
finding_new, finding_225 = self.copy_and_reset_finding(id=225)
finding_new.save()
# expect duplicate, but of 124 as that is first in the list, but it's newer then 225. feature or BUG?
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=224, hash_code=finding_225.hash_code)
def test_title_description_line_filepath_different_unique_id_or_hash_code(self):
# create identical copy, change some fields
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
finding_new.title = 'another title'
finding_new.cve = 'CVE-2020-12345'
finding_new.cwe = '456'
finding_new.description = 'useless finding'
finding_new.save()
# expect duplicate as we only match on unique id, hash_code also different
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=224, not_hash_code=finding_224.hash_code)
def test_title_description_line_filepath_different_and_id_different_unique_id_or_hash_code(self):
# create identical copy, change some fields
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
finding_new.title = 'another title'
finding_new.cve = 'CVE-2020-12345'
finding_new.cwe = '456'
finding_new.description = 'useless finding'
finding_new.unique_id_from_tool = '9999'
finding_new.save()
# expect not duplicate as we match on unique id, hash_code also different because fields changed
self.assert_finding(finding_new, not_pk=224, duplicate=False, not_hash_code=finding_224.hash_code)
def test_dedupe_not_inside_engagement_same_hash_unique_id_or_hash_code(self):
# create identical copy
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
# first setup some finding with same unique_id in different engagement, but same test_type, same hash
finding_22 = Finding.objects.get(id=22)
finding_22.test.test_type = finding_224.test.test_type
finding_22.test.save()
finding_22.unique_id_from_tool = '888'
finding_22.save(dedupe_option=False)
finding_new.unique_id_from_tool = '888'
finding_new.save()
# should become duplicate of finding 22 because of the uid match, but existing BUG makes it duplicate of 224 due to hashcode match
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=224, hash_code=finding_224.hash_code)
def test_dedupe_not_inside_engagement_same_hash_unique_id_or_hash_code2(self):
# create identical copy
# create identical copy
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
# first setup some finding with same unique_id in different engagement, different test_type, same hash_code
finding_22 = Finding.objects.get(id=22)
finding_22.test.test_type = finding_224.test.test_type
finding_22.test.save()
finding_22.unique_id_from_tool = '333'
finding_22.save(dedupe_option=False)
finding_new.hash_code = finding_22.hash_code # sneaky copy of hash_code to be able to test this case icm with the bug in previous test case above
finding_new.unique_id_from_tool = '333'
finding_new.save()
# expect not duplicate as dedupe_inside_engagement is True and 22 is in another engagement
# but existing BUG? it is marked as duplicate of 124 which has the same hash and same engagement, but different unique_id_from_tool at same test_type
self.assert_finding(finding_new, not_pk=22, duplicate=True, duplicate_finding_id=124, hash_code=finding_22.hash_code)
def test_dedupe_inside_engagement_unique_id_or_hash_code(self):
# create identical copy
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
# first setup some finding with same unique_id in same engagement, but different test (same test_type)
finding_new.test = Test.objects.get(id=66)
finding_new.save()
# expect duplicate as dedupe_inside_engagement is True and the other test is in the same engagement
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=224, hash_code=finding_224.hash_code)
def test_dedupe_inside_engagement_unique_id_or_hash_code2(self):
# create identical copy
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
# first setup some finding with same unique_id in different engagement, but same test_type
self.set_dedupe_inside_engagement(False)
finding_22 = Finding.objects.get(id=22)
finding_22.test.test_type = finding_224.test.test_type
finding_22.test.save()
finding_22.unique_id_from_tool = '888'
finding_22.save(dedupe_option=False)
finding_new.unique_id_from_tool = '888'
finding_new.title = 'hack to work around bug that matches on hash_code first' # arrange different hash_code
finding_new.save()
# expect duplicate as dedupe_inside_engagement is false
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=finding_22.id, not_hash_code=finding_22.hash_code)
def test_dedupe_same_id_different_test_type_unique_id_or_hash_code(self):
# create identical copy
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
# first setup some finding from a different test_Type, but with the same unique_id_from_tool
finding_22 = Finding.objects.get(id=22)
finding_22.unique_id_from_tool = '888'
finding_new.unique_id_from_tool = '888'
# and we need to look in another engagement this time for finding_22
self.set_dedupe_inside_engagement(False)
finding_22.save(dedupe_option=False)
finding_new.title = 'title to change hash_code'
finding_new.save()
# expect not duplicate as the mathcing finding is from another test_type, hash_code is also different
self.assert_finding(finding_new, not_pk=224, duplicate=False, not_hash_code=finding_224.hash_code)
# same scenario but with idencital hash_code as 224 leads to being marked as duplicate of 224
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
# first setup some finding from a different test_Type, but with the same unique_id_from_tool
finding_22 = Finding.objects.get(id=22)
finding_22.unique_id_from_tool = '888'
finding_new.unique_id_from_tool = '888'
# and we need to look in another engagement this time for finding_22
self.set_dedupe_inside_engagement(False)
finding_22.save(dedupe_option=False)
finding_new.save()
# expect not duplicate as the mathcing finding is from another test_type, hash_code is also different
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=224, hash_code=finding_224.hash_code)
def test_identical_different_endpoints_unique_id_or_hash_code(self):
# create identical copy, so unique id is the same
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
finding_new.endpoints.add(ep1)
finding_new.save()
# expect duplicate, as endpoints shouldn't affect dedupe and hash_code due to unique_id
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=224, hash_code=finding_224.hash_code)
# same scenario, now with different uid. and different endpoints, but hash will be different due the endpoints because we set dynamic_finding to True
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
finding_new.endpoints.add(ep1)
finding_new.unique_id_from_tool = 1
finding_new.dynamic_finding = True
finding_new.save()
# different uid. and different endpoints, so different hash, so no duplicate
self.assert_finding(finding_new, not_pk=224, duplicate=False, not_hash_code=finding_224.hash_code)
# same scenario, now with different uid. and different endpoints, but hash will not be affected by endpoints because dynamic_finding is set to False
finding_new, finding_224 = self.copy_and_reset_finding(id=224)
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
finding_new.endpoints.add(ep1)
finding_new.unique_id_from_tool = 1
finding_new.dynamic_finding = False
finding_new.save()
# different uid. and different endpoints, but hash will not be affected by endpoints because dynamic_finding is set to False
self.assert_finding(finding_new, not_pk=224, duplicate=True, duplicate_finding_id=224, hash_code=finding_224.hash_code)
# sync false positive history tests
def test_false_positive_history_with_dedupe_no_endpoints_identical(self):
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
finding_22.false_p = True
finding_22.save(dedupe_option=False)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.false_p = False
finding_new.save()
# dedupe is enabled, hash_code matches, so new finding marked as duplicate AND copies false positive True from original
# feature or BUG? finding already marked as duplicate, should it als be marked as false positive?
# should we do the same for out_of_scope? risk accepted?
# should this be part of the dedupe process? or seperate as in false_p history?
self.assert_finding(finding_new, not_pk=22, duplicate=True, duplicate_finding_id=finding_22.id, hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, True)
def test_false_positive_history_with_dedupe_no_endpoints_title_matches_but_not_hash_code(self):
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
finding_22.false_p = True
finding_22.save(dedupe_option=False)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.cwe = 432
finding_new.false_p = False
finding_new.save()
# dedupe is enabled, hash_code doesn't matches, so new finding not marked as duplicate and also not recognized by false positive history
self.assert_finding(finding_new, not_pk=22, duplicate=False, not_hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, False)
def test_false_positive_history_with_dedupe_no_endpoints_cwe_matches_but_not_hash_code(self):
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
finding_22.false_p = True
finding_22.save(dedupe_option=False)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.title = 'same same but different'
finding_new.false_p = False
finding_new.save()
# dedupe is enabled, hash_code doesn't matches, so new finding not marked as duplicate and also not recognized by false positive history
self.assert_finding(finding_new, not_pk=22, duplicate=False, not_hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, False)
def test_false_positive_history_without_dedupe_no_endpoints_identical(self):
self.enable_dedupe(enable=False)
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
finding_22.false_p = True
finding_22.save(dedupe_option=False)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.false_p = False
finding_new.save()
# dedupe is disabled, hash_code matches, so marked as false positive
self.assert_finding(finding_new, not_pk=22, duplicate=False, hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, True)
def test_false_positive_history_without_dedupe_no_endpoints_title_matches_but_not_hash_code(self):
self.enable_dedupe(enable=False)
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
finding_22.false_p = True
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.cwe = 432
finding_new.false_p = False
finding_new.save()
# dedupe is disabled, hash_code doesn't matches, so not marked as false positive
self.assert_finding(finding_new, not_pk=22, duplicate=False, not_hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, False)
def test_false_positive_history_without_dedupe_no_endpoints_cwe_matches_but_not_hash_code(self):
self.enable_dedupe(enable=False)
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
finding_22.false_p = True
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.title = 'same same but different'
finding_new.false_p = False
finding_new.save()
# dedupe is enabled, hash_code doesn't matches, so new finding not marked as duplicate and also not recognized by false positive history
self.assert_finding(finding_new, not_pk=22, duplicate=False, not_hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, False)
# false positive history with endpoints
def test_false_positive_history_with_dedupe_with_endpoints_identical(self):
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
finding_22.false_p = True
ep1 = Endpoint(product=finding_22.test.engagement.product, finding=finding_22, host="myhostxxx.com", protocol="https")
ep1.save()
finding_22.endpoints.add(ep1)
finding_22.save(dedupe_option=False)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.false_p = False
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
finding_new.endpoints.add(ep1)
finding_new.save(false_history=True)
# dedupe is enabled, hash_code mismatche due to endpoints, so new finding not marked as duplicate AND copies false positive True from original even with mismatching endpoints
# feature or BUG? false positive status is copied when dedupe says it's not a dupe and endpoints are mismatching
self.assert_finding(finding_new, not_pk=22, duplicate=False, hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, True)
def test_false_positive_history_with_dedupe_with_endpoints_title_matches_but_not_hash_code(self):
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
finding_22.false_p = True
ep1 = Endpoint(product=finding_22.test.engagement.product, finding=finding_22, host="myhostxxx.com", protocol="https")
ep1.save()
finding_22.endpoints.add(ep1)
finding_22.save(dedupe_option=False)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.false_p = False
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
finding_new.endpoints.add(ep1)
finding_new.cwe = 432
finding_new.save(false_history=True)
# dedupe is enabled, hash_code doesn't matches, so new finding not marked as duplicate but it IS recognized by false positive history because of the title matching
# feature or BUG? false positive status is copied when dedupe says it's not a dupe and endpoints are mismatching
self.assert_finding(finding_new, not_pk=22, duplicate=False, not_hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, True)
def test_false_positive_history_with_dedupe_with_endpoints_cwe_matches_but_not_hash_code(self):
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
ep1 = Endpoint(product=finding_22.test.engagement.product, finding=finding_22, host="myhostxxx.com", protocol="https")
ep1.save()
finding_22.endpoints.add(ep1)
finding_22.false_p = True
finding_22.cwe = 123 # testdate has no CWE
finding_22.save(dedupe_option=False)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
finding_new.endpoints.add(ep1)
finding_new.title = 'same same but different'
finding_new.false_p = False
finding_new.save(false_history=True)
# dedupe is enabled, hash_code doesn't matches, so new finding not marked as duplicate but it IS recognized by false positive history because of the cwe matching
# feature or BUG? false positive status is copied when dedupe says it's not a dupe and endpoints are mismatching
self.assert_finding(finding_new, not_pk=22, duplicate=False, not_hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, True)
def test_false_positive_history_without_dedupe_with_endpoints_identical(self):
self.enable_dedupe(enable=False)
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
ep1 = Endpoint(product=finding_22.test.engagement.product, finding=finding_22, host="myhostxxx.com", protocol="https")
ep1.save()
finding_22.endpoints.add(ep1)
finding_22.false_p = True
finding_22.save(dedupe_option=False)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
finding_new.endpoints.add(ep1)
finding_new.false_p = False
finding_new.save(false_history=True)
# dedupe is disabled, hash_code matches, so marked as false positive
self.assert_finding(finding_new, not_pk=22, duplicate=False, hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, True)
def test_false_positive_history_without_dedupe_with_endpoints_title_matches_but_not_hash_code(self):
self.enable_dedupe(enable=False)
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
ep1 = Endpoint(product=finding_22.test.engagement.product, finding=finding_22, host="myhostxxx.com", protocol="https")
ep1.save()
finding_22.endpoints.add(ep1)
finding_22.false_p = True
finding_22.save(dedupe_option=False)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
finding_new.endpoints.add(ep1)
finding_new.cwe = 432
finding_new.false_p = False
finding_new.save(false_history=True)
# dedupe is disabled, hash_code doesn't matches, but it IS recognized by false positive history because of the title matching
# feature or BUG? false positive status is copied when dedupe says it's not a dupe and endpoints are mismatching
self.assert_finding(finding_new, not_pk=22, duplicate=False, not_hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, True)
def test_false_positive_history_without_dedupe_with_endpoints_cwe_matches_but_not_hash_code(self):
self.enable_dedupe(enable=False)
self.enable_false_positive_history()
finding_22 = Finding.objects.get(id=22)
ep1 = Endpoint(product=finding_22.test.engagement.product, finding=finding_22, host="myhostxxx.com", protocol="https")
ep1.save()
finding_22.endpoints.add(ep1)
finding_22.cwe = 123 # test data has now CWE here
finding_22.false_p = True
finding_22.save(dedupe_option=False)
# create a copy of 22
finding_new, finding_22 = self.copy_and_reset_finding(id=22)
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
finding_new.endpoints.add(ep1)
finding_new.title = 'same same but different'
finding_new.false_p = False
finding_new.save(false_history=True)
# dedupe is disabled, hash_code doesn't matches, so new finding not marked as duplicate but it IS recognized by false positive history because of the cwe matching
# feature or BUG? false positive status is copied when dedupe says it's not a dupe and endpoints are mismatching
self.assert_finding(finding_new, not_pk=22, duplicate=False, not_hash_code=finding_22.hash_code)
self.assertEquals(finding_new.false_p, True)
# # some extra tests
# # hash_code currently is only created on finding creation and after that never changed. feature or BUG?
def test_hash_code_onetime(self):
finding_new, finding_2 = self.copy_and_reset_finding(id=2)
self.assertEqual(finding_new.hash_code, None)
finding_new.save()
self.assertTrue(finding_new.hash_code) # True -> not None
hash_code_at_creation = finding_new.hash_code
finding_new.title = 'new_title'
finding_new.cve = 999
# both title and cve affect hash_code for ZAP scans, but not here because hash_code was already calculated
finding_new.save()
self.assertEqual(finding_new.hash_code, hash_code_at_creation)
finding_new.save(dedupe_option=False)
self.assertEqual(finding_new.hash_code, hash_code_at_creation)
finding_new.save(dedupe_option=True)
self.assertEqual(finding_new.hash_code, hash_code_at_creation)
def test_identical_legacy_dedupe_option_true_false(self):
# 24 is already a duplicate of 22 let's see what happens if we create an identical finding (but reset status)
# expect: not marked as duplicate with dedupe_option-False
finding_new, finding_24 = self.copy_and_reset_finding(id=24)
finding_new.save(dedupe_option=False)
self.assert_finding(finding_new, not_pk=24, duplicate=False, hash_code=None)
# expect duplicate when saving with dedupe_option=True
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=24, duplicate=True, duplicate_finding_id=finding_24.duplicate_finding.id, hash_code=finding_24.hash_code)
def test_duplicate_after_modification(self):
# we copy a finding but change some important fields so it's no longer a duplicate
# expect: not marked as duplicate with dedupe_option-False
finding_new, finding_24 = self.copy_and_reset_finding(id=24)
finding_new.title = 'new_title'
finding_new.cve = 999
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=24, duplicate=False, not_hash_code=None)
# now when we change the title and cve back the same as finding_24, it should be marked as duplicate
# howwever defect dojo does NOT recalculate the hash_code, so it will not mark this finding as duplicate. feature or BUG?
finding_new.title = finding_24.title
finding_new.cve = finding_24.cve
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=24, duplicate=False, not_hash_code=None)
def test_case_sensitiveness_hash_code_computation(self):
# hash_code calculation is case sensitive. feature or BUG?
finding_new, finding_24 = self.copy_and_reset_finding(id=24)
finding_new.title = finding_24.title.upper()
finding_new.save(dedupe_option=True)
self.assert_finding(finding_new, not_pk=24, duplicate=False, not_hash_code=finding_24.hash_code)
def test_title_case(self):
# currentlt the finding.save method applies title casing to the title
# 'absolutely great title' becomes 'Absolutely Great Title'
# as this affects deduplication (hash_code computation) we provide a test case here
# it will fail if someone removes title casing and force them to think about the implications
# ideally we will switch to case-in-sensitive hash_code computation.
# this could be a relatively small impact change as saving findings (currently) doesn't recompute the hash_code
finding_new, finding_24 = self.copy_and_reset_finding(id=24)
finding_new.title = 'the quick brown fox jumps over the lazy dog'
finding_new.save(dedupe_option=True)
self.assertEqual(finding_new.title, 'The Quick Brown Fox Jumps Over the Lazy Dog')
def test_hash_code_without_dedupe(self):
# if dedupe is disabled, hash_code should still be calculated
self.enable_dedupe(enable=False)
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
finding_new.save(dedupe_option=False)
# save skips hash_code generation if dedupe_option==False
self.assertFalse(finding_new.hash_code)
finding_new.save(dedupe_option=True)
self.assertTrue(finding_new.hash_code)
finding_new, finding_124 = self.copy_and_reset_finding(id=124)
finding_new.save()
# by default hash_code should be generated
self.assertTrue(finding_new.hash_code)
# # utility methods
def log_product(self, product):
if isinstance(product, int):
product = Product.objects.get(pk=product)
logger.debug('product %i: %s', product.id, product.name)
for eng in product.engagement_set.all():
self.log_engagement(eng)
for test in eng.test_set.all():
self.log_test(test)
def log_engagement(self, eng):
if isinstance(eng, int):
eng = Engagement.objects.get(pk=eng)
logger.debug('\t' + 'engagement %i: %s (dedupe_inside: %s)', eng.id, eng.name, eng.deduplication_on_engagement)
def log_test(self, test):
if isinstance(test, int):
test = Test.objects.get(pk=test)
logger.debug('\t\t' + 'test %i: %s (algo=%s, dynamic=%s)', test.id, test, test.dedupe_algo, test.test_type.dynamic_tool)
self.log_findings(test.finding_set.all())
def log_all_products(self):
for product in Product.objects.all():
self.log_summary(product=product)
def log_findings(self, findings):
if not findings:
logger.debug('\t\t' + 'no findings')
else:
logger.debug('\t\t' + 'findings:')
for finding in findings:
logger.debug('\t\t\t{:4.4}'.format(str(finding.id)) + ': "' + '{:20.20}'.format(finding.title) + '": ' + '{:5.5}'.format(finding.severity) + ': act: ' + '{:5.5}'.format(str(finding.active)) +
': ver: ' + '{:5.5}'.format(str(finding.verified)) + ': mit: ' + '{:5.5}'.format(str(finding.is_Mitigated)) +
': dup: ' + '{:5.5}'.format(str(finding.duplicate)) + ': dup_id: ' +
('{:4.4}'.format(str(finding.duplicate_finding.id)) if finding.duplicate_finding else 'None') + ': hash_code: ' + str(finding.hash_code) +
': eps: ' + str(finding.endpoints.count()) + ": notes: " + str([n.id for n in finding.notes.all()]) +
': uid: ' + '{:5.5}'.format(str(finding.unique_id_from_tool)) + (' fp' if finding.false_p else '')
)
logger.debug('\t\tendpoints')
for ep in Endpoint.objects.all():
logger.debug('\t\t\t' + str(ep.id) + ': ' + str(ep))
logger.debug('\t\t' + 'endpoint statuses')
for eps in Endpoint_Status.objects.all():
logger.debug('\t\t\t' + str(eps.id) + ': ' + str(eps))
def log_summary(self, product=None, engagement=None, test=None):
if product:
self.log_product(product)
if engagement:
self.log_engagement(engagement)
if test:
self.log_test(test)
if not product and not engagement and not test:
self.log_all_products()
def copy_and_reset_finding(self, id):
org = Finding.objects.get(id=id)
new = org
new.pk = None
new.duplicate = False
new.duplicate_finding = None
new.active = True
new.hash_code = None
# return unsaved new finding and reloaded existing finding
return new, Finding.objects.get(id=id)
def copy_and_reset_finding_add_endpoints(self, id, static=False, dynamic=True):
finding_new, finding_org = self.copy_and_reset_finding(id=id)
# remove file_path and line as we now have endpoints
finding_new.file_path = None
finding_new.line = None
finding_new.static_finding = static
finding_new.dynamic_finding = dynamic
# first save without dedupe to avoid hash_code calculation to happen without endpoints
finding_new.save(dedupe_option=False)
ep1 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost.com", protocol="https")
ep1.save()
ep2 = Endpoint(product=finding_new.test.engagement.product, finding=finding_new, host="myhost2.com", protocol="https")
ep2.save()
finding_new.endpoints.add(ep1)
finding_new.endpoints.add(ep2)
return finding_new, finding_org
def copy_and_reset_test(self, id):
org = Test.objects.get(id=id)
new = org
new.pk = None
# return unsaved new finding and reloaded existing finding
return new, Test.objects.get(id=id)
def copy_and_reset_engagement(self, id):
org = Engagement.objects.get(id=id)
new = org
new.pk = None
# return unsaved new finding and reloaded existing finding
return new, Engagement.objects.get(id=id)
def assert_finding(self, finding, not_pk=None, duplicate=False, duplicate_finding_id=None, hash_code=None, not_hash_code=None):
if not_pk:
self.assertNotEqual(finding.pk, not_pk)
self.assertEqual(finding.duplicate, duplicate)
if not duplicate:
self.assertFalse(finding.duplicate_finding) # False -> None
if duplicate_finding_id:
logger.debug('asserting that finding %i is a duplicate of %i', finding.id, duplicate_finding_id)
self.assertTrue(finding.duplicate_finding) # True -> not None
self.assertEqual(finding.duplicate_finding.id, duplicate_finding_id)
if hash_code:
self.assertEqual(finding.hash_code, hash_code)
if not_hash_code:
self.assertNotEqual(finding.hash_code, not_hash_code)
def set_dedupe_inside_engagement(self, deduplication_on_engagement):
for eng in Engagement.objects.all():
logger.debug('setting deduplication_on_engagment to %s for %i', str(deduplication_on_engagement), eng.id)
eng.deduplication_on_engagement = deduplication_on_engagement
eng.save()
def create_new_test_and_engagment_from_finding(self, finding):
eng_new, eng = self.copy_and_reset_engagement(id=finding.test.engagement.id)
eng_new.save()
test_new, test = self.copy_and_reset_test(id=finding.test.id)
test_new.engagement = eng_new
test_new.save()
return test_new, eng_new
def enable_dedupe(self, enable=True):
system_settings = System_Settings.objects.get()
system_settings.enable_deduplication = enable
system_settings.save()
def enable_false_positive_history(self, enable=True):
system_settings = System_Settings.objects.get()
system_settings.false_positive_history = enable
system_settings.save()
```
#### File: unittests/tools/test_qualys_infrascan_webgui_parser.py
```python
from django.test import TestCase
from dojo.models import Test
from dojo.tools.qualys_infrascan_webgui.parser import QualysInfrascanWebguiParser
class TestQualysInfrascanWebguiParser(TestCase):
def test_parse_file_with_no_vuln_has_no_findings(self):
testfile = open(
"dojo/unittests/scans/qualys_infrascan_webgui/qualys_infrascan_webgui_0.xml"
)
parser = QualysInfrascanWebguiParser()
findings = parser.get_findings(testfile, Test())
self.assertEqual(0, len(findings))
# Sample with One Test
# + also verify data with one test
def test_parse_file_with_one_vuln_has_one_findings(self):
testfile = open(
"dojo/unittests/scans/qualys_infrascan_webgui/qualys_infrascan_webgui_1.xml"
)
parser = QualysInfrascanWebguiParser()
findings = parser.get_findings(testfile, Test())
self.assertEqual(1, len(findings))
findings = findings[0]
self.assertEqual(
findings.title, "Oracle Java SE Critical Patch Update - January 2015"
)
self.assertEqual(
findings.severity, "Critical"
) # Negligible is translated to Informational
# Sample with Multiple Test
def test_parse_file_with_multiple_vuln_has_multiple_findings(self):
testfile = open(
"dojo/unittests/scans/qualys_infrascan_webgui/qualys_infrascan_webgui_multiple.xml"
)
parser = QualysInfrascanWebguiParser()
findings = parser.get_findings(testfile, Test())
self.assertEqual(6, len(findings))
``` |
{
"source": "joebass85/GSH",
"score": 2
} |
#### File: joebass85/GSH/gsh.py
```python
import tkinter as tki
from subprocess import Popen
import pyautogui as pyag
from time import sleep
#variable creation
name = ''
ip = ''
port = ''
key = ''
term = ''
xf = ''
#environment variables
master = tki.Tk()
master.title("GSH Program - GUI ssh in Python")
master.resizable(False,False)
master.geometry('1010x165')
#username entry-box
ent = tki.Entry(master, font=("Arial",16))
ent.grid(row=0, column=1)
def name_get():
global name
name = ent.get()
#username label
username = tki.Label(master, text="Username:", font=("Arial",16))
username.grid(row=0, column=0)
#Destination IP label
dest = tki.Label(master, text="Destination:",font=("Arial",16))
dest.grid(row=0, column=3)
#Destination IP entry-box
destEnt = tki.Entry(master, font=("Arial",16))
destEnt.grid(row=0, column=4)
def IP_get():
global ip
ip = destEnt.get()
#Port nuber label
ports = tki.Label(master, text="Port:", font=("Arial",16))
ports.grid(row=1, column=3)
#Port number entry-box
portEnt = tki.Entry(master, font=("Arial",16))
portEnt.grid(row=1, column=4)
def port_get():
global port
port = portEnt.get()
#ssh key location textbox
key = tki.Label(master, text="Key Location:", font=("Arial",16))
key.grid(row=1,column=0)
#ssh key entry-box
keyEnt = tki.Entry(master, font=("Arial",16))
keyEnt.grid(row=1,column=1)
def key_get():
global key
key = keyEnt.get()
#terminal name textbox
term = tki.Label(master, text="Terminal Name:", font=("Arial",16))
term.grid(row=2,column=0)
#terminal name entry-box
termEnt = tki.Entry(master, font=("Arial",16))
termEnt.grid(row=2,column=1)
def term_get():
global term
term = termEnt.get()
#X forwarding label
xford = tki.Label(master,text="X Forwarding:",font=("Arial",16))
xford.grid(row=2,column=3)
#X forwarding widget thingy
xfEnt = tki.Entry(master, font=("Arial",16))
xfEnt.grid(row=2,column=4)
def xf_get():
global xf
xf = xfEnt.get()
#Main funtion
def mainfunc ():
if xf != '':
if key != '' and port != '':
Popen([term])
sleep(3)
pyag.typewrite("ssh " + name + "@" + ip + " -p " + port + " -i " + key + " -Y")
pyag.press("return")
if key != '' and port == '':
Popen([term])
sleep(3)
pyag.typewrite("ssh " + name + "@" + ip + " -i " + key + " -Y")
pyag.press("return")
if port != '' and key == '':
Popen([term])
sleep(3)
pyag.typewrite("ssh " + name + "@" + ip + " -p " + port + " -Y")
pyag.press("return")
if port == '' and key == '':
Popen([term])
sleep(3)
pyag.typewrite("ssh " + name + "@" + ip + " -Y")
pyag.press("return")
else:
if key != '' and port != '':
Popen([term])
sleep(3)
pyag.typewrite("ssh " + name + "@" + ip + " -p " + port + " -i " + key + " -x")
pyag.press("return")
if key != '' and port == '':
Popen([term])
sleep(3)
pyag.typewrite("ssh " + name + "@" + ip + " -i " + key + " -x")
pyag.press("return")
if port != '' and key == '':
Popen([term])
sleep(3)
pyag.typewrite("ssh " + name + "@" + ip + " -p " + port + " -x")
pyag.press("return")
if port == '' and key == '':
Popen([term])
sleep(3)
pyag.typewrite("ssh " + name + "@" + ip + " -x")
pyag.press("return")
#Buttons to launch or cancel ssh command
def yes ():
name_get()
IP_get()
port_get()
key_get()
term_get()
xf_get()
master.destroy()
mainfunc()
def no ():
ent.delete(0,"end")
destEnt.delete(0,"end")
portEnt.delete(0,"end")
keyEnt.delete(0,"end")
termEnt.delete(0,"end")
xfEnt.delete(0,"end")
def exit_button():
master.destroy()
launch = tki.Button(master,text="Launch ssh",command=yes, font=("Arial",16))
launch.grid(row=3,column=0)
cancel = tki.Button(master,text="Cancel",command=no, font=("Arial",16))
cancel.grid(row=3, column=2)
exit_butt = tki.Button(master,text="Exit",command=exit_button, font=("Arial",16))
exit_butt.grid(row=3,column=4)
#Run everything with the below:
master.mainloop()
``` |
{
"source": "joebebel/toughsat",
"score": 2
} |
#### File: joebebel/toughsat/circuit_ops.py
```python
def project(x,y,z,v): return tuple(v[i] for i in x), tuple(v[i] for i in y), tuple(v[i] for i in z)
def adder(cin, x,y,z, cout, v, op):
x,y,z = project(x, y, z, v)
return adders[len(x)](v[cin], x, y, z, v[cout])
def subtractor(cin, x, y, z, cout, v, op):
x,y,z = project(x, y, z, v)
return adders[len(x)](v[cin], x, tuple(-i for i in y), z, v[cout])
def multiplier(x, y, z, v, op):
x,y,z = project(x, y, z, v)
return multipliers[len(x)](x, y, z)
def and_gates(x, y, z, v, op):
return tuple(clause for cnf in (and_1bit(v[x_i], v[y_i], v[z_i]) for (x_i, y_i, z_i) in zip(x,y,z)) for clause in cnf)
def xor_gates(x, y, z, v, op):
return tuple(clause for cnf in (xor_1bit(v[x_i], v[y_i], v[z_i]) for (x_i, y_i, z_i) in zip(x,y,z)) for clause in cnf)
def or_gates(x, y, z, v, op):
return tuple(clause for cnf in (or_1bit(v[x_i], v[y_i], v[z_i]) for (x_i, y_i, z_i) in zip(x,y,z)) for clause in cnf)
def atleastoneof(x, v, op):
return ( tuple(v[i] for i in x), )
####################
def adder_1bit(cin, x, y, z, cout): # cin plus x plus y = z + cout*2
x,y,z=x[0],y[0],z[0]
return [ (-z, x, y, cin),
(-z, -x, -y, cin),
(-z, -x, y, -cin),
(-z, x, -y, -cin),
(z, -x, -y, -cin),
(z, x, y, -cin),
(z, x, -y, cin),
(z, -x, y, cin),
(-x, -y, cout),
(-x, -cin, cout),
(-y, -cin, cout),
(x, y, -cout),
(x, cin, -cout),
(y, cin, -cout) ]
def half_adder_1bit(x,y,z,cout): #x plus y = z plus cout*2
return [(-z, x, y), (-z, -x, -y), (z, x, -y), (z, -x, y), (-x, -y, cout), (x, y, -cout), (x, -cout), (y, -cout)]
def xor_1bit(x,y,z): # x xor y = z
return [(-z, -x, -y), (-z, x, y), (z, -x, y), (z, x, -y)]
def and_1bit(x,y,z): # x andd y = z
return [(z, -x, -y), (-z, x), (-z, y)]
def or_1bit(x,y,z): # x or y = z
return [(-z, x, y), (z, -x), (z, -y)]
def adder_2bit(cin, x,y,z, cout): # cin plus (2 bit x) plus (2 bit y) = (2 bit z) plus cout
return [(-x[0],-y[0],-cin,z[0],), # -0-0-01-
(x[0],y[0],cin,-z[0],), # -1-1-10-
(cout,-y[1],z[1],), # 1---0--1
(-cout,y[1],-z[1],), # 0---1--0
(-cout,x[0],x[1],y[0],), # 0111----
(cout,-x[0],-x[1],-y[0],), # 1000----
(-x[0],y[0],cin,z[0],), # -0-1-11-
(x[0],-y[0],cin,z[0],), # -1-0-11-
(cout,-x[1],-cin,z[0],), # 1-0--01-
(-cout,x[1],cin,-z[0],), # 0-1--10-
(-x[0],y[0],-cin,-z[0],), # -0-1-00-
(x[0],-y[0],-cin,-z[0],), # -1-0-00-
(x[0],-x[1],y[0],y[1],z[1],), # -1011--1
(-x[0],x[1],-y[0],y[1],z[1],), # -0101--1
(-x[0],-x[1],-y[0],-y[1],z[1],), # -0000--1
(x[1],y[1],-cin,z[0],z[1],), # --1-1011
(-x[1],-y[1],-cin,z[0],z[1],), # --0-0011
(-x[1],y[1],cin,-z[0],z[1],), # --0-1101
(x[0],x[1],y[0],y[1],-z[1],), # -1111--0
(x[0],-x[1],y[0],-y[1],-z[1],), # -1010--0
(-x[0],x[1],-y[0],-y[1],-z[1],), # -0100--0
(x[1],-y[1],-cin,z[0],-z[1],), # --1-0010
(x[1],y[1],cin,-z[0],-z[1],), # --1-1100
(-x[1],-y[1],cin,-z[0],-z[1],), # --0-0100
]
def mult_2x2(x,y,z): #2 bit x times 2 bit y = 4 bit z
return [(x[1],-z[2],), # 1----0--
(y[1],-z[2],), # --1--0--
(x[0],-z[0],), # -1-----0
(y[0],-z[0],), # ---1---0
(x[1],y[1],-z[1],), # 1-1---0-
(x[0],y[0],-z[1],), # -1-1--0-
(-x[0],-y[0],z[0],), # -0-0---1
(x[1],-z[3],), # 1---0---
(y[1],-z[3],), # --1-0---
(-z[3],-z[2],), # ----00--
(-x[0],-y[1],z[3],z[1],), # -00-1-1-
(-x[1],-y[0],z[3],z[1],), # 0--01-1-
(-x[1],-y[1],z[2],z[0],), # 0-0--1-1
(-x[1],-x[0],-y[1],-y[0],-z[1],), # 0000--0-
(-x[1],-x[0],z[2],-z[1],z[0],), # 00---101
(-y[1],-y[0],z[2],-z[1],z[0],), # --00-101
]
def adder_3bit(cin, x, y, z, cout): # cin plus (2 bit x) plus (2 bit y) = (2 bit z) plus cout
return [(-x[0],-x[2],-y[2],z[0],z[1],z[2],), # -0-0--0-111
(-x[2],-y[0],-y[2],-cin,z[1],z[2],), # ---00-00-11
(x[1],x[2],y[2],-z[1],-z[2],), # --11--1--00
(x[2],y[1],y[2],-z[1],-z[2],), # ---1-11--00
(-x[0],x[2],-y[2],z[0],z[1],-z[2],), # -0-1--0-110
(-x[0],-x[2],y[2],z[0],z[1],-z[2],), # -0-0--1-110
(x[2],-y[0],-y[2],-cin,z[1],-z[2],), # ---10-00-10
(-x[2],-y[0],y[2],-cin,z[1],-z[2],), # ---00-10-10
(x[1],x[2],y[1],y[2],-z[2],), # --11-11---0
(-x[1],-x[2],-y[1],-y[2],z[2],), # --00-00---1
(x[1],x[2],-y[2],-z[1],z[2],), # --11--0--01
(x[2],y[1],-y[2],-z[1],z[2],), # ---1-10--01
(x[1],-x[2],y[2],-z[1],z[2],), # --10--1--01
(-x[2],y[1],y[2],-z[1],z[2],), # ---0-11--01
(x[0],-y[0],-cin,-z[0],), # -1--0--00--
(-x[0],y[0],cin,z[0],), # -0--1--11--
(cout,-x[0],z[0],z[1],z[2],), # 10------111
(cout,-y[0],-cin,z[1],z[2],), # 1---0--0-11
(x[0],x[1],-y[1],-z[0],z[1],), # -11--0--01-
(x[0],-x[1],y[1],-z[0],z[1],), # -10--1--01-
(x[1],y[0],-y[1],cin,z[1],), # --1-10-1-1-
(-x[1],y[0],y[1],cin,z[1],), # --0-11-1-1-
(x[1],x[2],y[1],-y[2],z[2],), # --11-10---1
(x[1],-x[2],y[1],y[2],z[2],), # --10-11---1
(x[0],x[1],y[1],-z[0],-z[1],), # -11--1--00-
(x[1],y[0],y[1],cin,-z[1],), # --1-11-1-0-
(-x[1],x[2],-y[1],-y[2],-z[2],), # --01-00---0
(-x[1],-x[2],-y[1],y[2],-z[2],), # --00-01---0
(x[0],-x[1],-y[1],-z[0],-z[1],), # -10--0--00-
(-x[1],y[0],-y[1],cin,-z[1],), # --0-10-1-0-
(-x[0],-x[1],-y[1],z[0],z[1],), # -00--0--11-
(-x[1],-y[0],-y[1],-cin,z[1],), # --0-00-0-1-
(-cout,x[1],-z[1],-z[2],), # 0-1------00
(-cout,y[1],-z[1],-z[2],), # 0----1---00
(x[1],-y[0],-y[1],z[0],-z[1],), # --1-00--10-
(-x[1],-y[0],y[1],z[0],-z[1],), # --0-01--10-
(-x[0],x[1],-y[1],-cin,-z[1],), # -01--0-0-0-
(-x[0],-x[1],y[1],-cin,-z[1],), # -00--1-0-0-
(-x[0],y[0],-cin,-z[0],), # -0--1--00--
(-x[0],-y[0],cin,-z[0],), # -0--0--10--
(x[0],y[0],-cin,z[0],), # -1--1--01--
(x[0],-y[0],cin,z[0],), # -1--0--11--
(-cout,x[1],y[1],-z[2],), # 0-1--1----0
(cout,-x[1],-y[1],z[2],), # 1-0--0----1
(cout,-x[2],-y[2],), # 1--0--0----
(-cout,x[2],y[2],), # 0--1--1----
(x[0],y[0],cin,-z[0],), # -1--1--10--
(-x[0],-y[0],-cin,z[0],), # -0--0--01--
]
def mult_3x3(x,y,z): #3 bit x times 3 bit y = 6 bit z
return [(-x[2],-y[1],z[3],-z[2],-z[1],), # 0---0---100-
(-x[0],y[2],-z[2],z[1],z[0],), # --01-----011
(x[2],x[0],y[1],-z[2],), # 1-1-1----0--
(-y[0],-z[4],z[2],z[1],z[0],), # -----0-0-111
(-x[2],x[0],-y[2],y[0],-z[3],-z[2],), # 0-10-1--00--
(x[1],y[1],-z[3],z[0],), # -1--1---0--1
(x[2],y[2],-z[3],z[0],), # 1--1----0--1
(x[0],-y[1],z[4],z[3],z[2],-z[1],), # --1-0--1110-
(x[2],x[1],x[0],-z[2],), # 111------0--
(x[1],y[2],y[0],-z[2],), # -1-1-1---0--
(-x[1],-y[1],z[2],z[1],z[0],), # -0--0----111
(x[2],y[2],-z[2],-z[0],), # 1--1-----0-0
(z[5],-z[4],z[3],z[2],-z[0],), # ------1011-0
(-x[2],x[0],-y[1],-z[2],-z[1],), # 0-1-0----00-
(x[0],y[1],y[0],-z[2],), # --1-11---0--
(x[2],y[2],-z[4],), # 1--1---0----
(y[1],y[0],-z[1],), # ----11----0-
(x[1],y[1],-z[5],), # -1--1-0-----
(-x[1],y[1],z[1],-z[0],), # -0--1-----10
(-x[2],-x[1],-z[3],-z[0],), # 00------0--0
(x[1],-y[1],z[1],-z[0],), # -1--0-----10
(-y[2],-y[1],-z[3],-z[0],), # ---00---0--0
(-x[2],-x[0],-z[4],z[2],z[0],), # 0-0----0-1-1
(-x[2],-y[2],-z[2],-z[0],), # 0--0-----0-0
(y[1],-z[5],z[0],), # ----1-0----1
(-x[1],-y[1],z[4],z[3],z[2],), # -0--0--111--
(x[1],-z[5],z[0],), # -1----0----1
(-x[1],-x[0],-y[2],-y[1],-z[2],-z[1],), # -0000----00-
(-x[1],-y[1],z[5],-z[3],z[2],-z[1],), # -0--0-1-010-
(-x[0],-y[2],z[5],z[4],z[2],), # --00--11-1--
(-x[2],-y[1],z[5],z[4],z[3],), # 0---0-111---
(-x[1],-y[2],z[5],z[4],z[3],), # -0-0--111---
(x[1],-y[1],-z[4],z[3],), # -1--0--01---
(-y[2],-y[0],-z[4],z[2],-z[1],), # ---0-0-0-10-
(-x[1],-y[0],z[1],z[0],), # -0---0----11
(-x[0],-y[1],z[1],z[0],), # --0-0-----11
(-x[1],y[1],-z[4],z[3],), # -0--1--01---
(x[2],y[1],-z[4],), # 1---1--0----
(-x[2],-y[0],z[5],z[4],z[2],), # 0----011-1--
(-x[1],-y[1],-z[4],-z[2],z[0],), # -0--0--0-0-1
(-x[2],-y[2],z[5],z[4],), # 0--0--11----
(x[2],x[1],-z[3],), # 11------0---
(y[2],y[1],-z[3],), # ---11---0---
(x[1],y[2],-z[4],), # -1-1---0----
(x[2],-z[5],), # 1-----0-----
(y[2],-z[5],), # ---1--0-----
(-x[0],-y[0],z[0],), # --0--0-----1
(x[0],y[0],-z[1],), # --1--1----0-
(x[0],-z[0],), # --1--------0
(y[0],-z[0],), # -----1-----0
(x[1],y[1],-z[1],), # -1--1-----0-
]
def mult_4x4(x,y,z): #4 bit x times 4 bit y = 8 bit z
return [(x[3],x[1],y[3],y[1],z[4],-z[3],), # 1-1-1-1----10---
(x[2],x[0],-y[1],z[4],-z[3],z[2],), # -1-1--0----101--
(-x[1],y[2],y[0],z[4],-z[3],z[2],), # --0--1-1---101--
(x[1],y[1],y[0],-z[7],z[4],), # --1---110--1----
(-x[3],-x[2],-x[1],z[7],z[3],-z[0],), # 000-----1---1--0
(-x[1],-y[2],-y[1],z[5],z[2],-z[0],), # --0--00---1--1-0
(-x[2],-y[2],-z[7],z[6],z[5],z[3],-z[2],), # -0---0--011-10--
(-y[1],y[0],-z[7],-z[4],z[1],), # ------010--0--1-
(-x[1],-y[1],-z[7],z[4],-z[1],), # --0---0-0--1--0-
(x[3],-x[1],y[2],z[4],-z[3],-z[1],-z[0],), # 1-0--1-----10-00
(y[3],-y[1],-z[6],z[4],-z[1],-z[0],), # ----1-0--0-1--00
(-x[3],-x[1],-y[2],-y[1],z[6],-z[3],-z[0],), # 0-0--00--1--0--0
(z[6],-z[5],z[4],z[3],-z[1],z[0],), # ---------1011-01
(x[3],-x[1],y[3],-y[1],-z[3],-z[2],-z[0],), # 1-0-1-0-----00-0
(-x[3],z[6],z[3],z[2],-z[1],-z[0],), # 0--------1--1100
(-x[1],-y[1],z[6],-z[5],z[3],-z[1],), # --0---0--10-1-0-
(x[3],-y[1],-y[0],z[3],-z[2],z[1],z[0],), # 1-----00----1011
(y[2],z[6],-z[4],z[2],z[1],-z[0],), # -----1---1-0-110
(-x[3],x[1],-y[2],y[0],-z[4],-z[3],z[2],), # 0-1--0-1---001--
(-y[1],-z[6],-z[5],-z[2],-z[0],), # ------0--00--0-0
(-x[1],-y[2],y[0],z[3],z[2],z[1],), # --0--0-1----111-
(-x[2],y[1],z[2],-z[1],z[0],), # -0----1------101
(-x[2],y[3],-y[1],z[5],z[3],-z[2],-z[1],), # -0--1-0---1-100-
(x[3],-x[1],y[3],-y[1],-z[4],-z[2],z[0],), # 1-0-1-0----0-0-1
(x[1],-y[3],z[7],z[6],z[4],z[3],-z[0],), # --1-0---11-11--0
(x[2],-x[0],y[3],-z[3],-z[1],z[0],), # -1-01-------0-01
(-x[1],-y[1],-z[7],z[6],z[4],z[3],z[0],), # --0---0-01-11--1
(-x[2],-y[2],y[1],z[4],z[3],z[1],z[0],), # -0---01----11-11
(-x[1],x[0],z[6],-z[5],z[4],-z[3],-z[2],), # --01-----10100--
(-x[3],-y[1],-y[0],-z[3],-z[2],z[1],z[0],), # 0-----00----0011
(-y[2],z[5],-z[4],z[3],z[2],-z[0],), # -----0----1011-0
(-x[2],-y[2],z[7],z[5],z[3],z[2],-z[1],), # -0---0--1-1-110-
(x[1],y[2],-z[7],z[3],-z[0],), # --1--1--0---1--0
(-x[2],x[1],y[2],-z[6],-z[1],), # -01--1---0----0-
(x[2],y[1],-z[7],z[3],-z[0],), # -1----1-0---1--0
(-x[2],-y[1],y[0],z[3],z[2],z[1],), # -0----01----111-
(y[2],y[0],-z[7],-z[4],z[2],), # -----1-10--0-1--
(-y[0],-z[7],-z[6],-z[2],), # -------000---0--
(x[1],y[3],y[1],y[0],-z[3],), # --1-1-11----0---
(y[2],-y[1],-y[0],-z[6],-z[3],z[2],-z[1],), # -----100-0--010-
(x[3],-x[0],-y[3],-y[2],-y[1],-z[4],), # 1--0000----0----
(-z[7],-z[3],-z[2],-z[1],z[0],), # --------0---0001
(-x[2],x[0],-y[3],y[1],-z[4],-z[3],z[2],), # -0-10-1----001--
(x[3],-y[3],y[2],y[1],z[3],-z[0],), # 1---011-----1--0
(-x[2],-y[1],y[0],z[7],z[6],z[5],z[3],), # -0----01111-1---
(-x[3],x[0],y[2],z[3],-z[1],), # 0--1-1------1-0-
(x[3],x[0],-y[2],z[3],-z[1],), # 1--1-0------1-0-
(-x[3],-x[2],-y[2],-y[1],z[7],-z[5],-z[2],), # 00---00-1-0--0--
(x[3],x[0],y[2],-z[3],-z[1],), # 1--1-1------0-0-
(-x[1],-y[2],z[7],z[6],-z[4],z[3],z[1],z[0],), # --0--0--11-01-11
(-x[2],-y[2],z[7],z[6],z[4],-z[3],z[1],), # -0---0--11-10-1-
(-y[1],z[7],-z[6],z[3],z[1],-z[0],), # ------0-10--1-10
(z[5],-z[4],-z[2],-z[1],-z[0],), # ----------10-000
(x[3],x[2],y[3],y[1],-z[4],), # 11--1-1----0----
(-x[2],y[1],-z[7],z[5],z[4],z[1],), # -0----1-0-11--1-
(x[3],x[1],y[2],-z[4],-z[3],), # 1-1--1-----00---
(x[0],y[0],-z[6],-z[5],z[4],-z[3],), # ---1---1-0010---
(y[1],-z[6],-z[3],z[1],-z[0],), # ------1--0--0-10
(-x[3],x[1],y[2],z[6],-z[5],-z[3],), # 0-1--1---10-0---
(x[3],y[3],-z[5],-z[4],z[0],), # 1---1-----00---1
(x[2],-x[1],y[3],-y[2],z[6],z[4],z[3],), # -10-10---1-11---
(x[1],-y[2],y[0],z[2],-z[1],), # --1--0-1-----10-
(-x[3],-y[3],-z[6],z[5],-z[3],-z[0],), # 0---0----01-0--0
(x[3],x[1],x[0],y[1],-z[3],), # 1-11--1-----0---
(-x[3],-y[2],y[1],-z[5],z[4],-z[1],), # 0----01---01--0-
(x[2],x[0],y[1],-z[2],), # -1-1--1------0--
(-z[7],-z[5],z[4],-z[2],z[0],), # --------0-01-0-1
(x[2],y[3],y[1],-z[6],), # -1--1-1--0------
(x[2],-x[0],y[3],-y[1],z[4],-z[3],-z[1],), # -1-01-0----10-0-
(-x[3],x[1],-y[3],y[1],-z[5],-z[4],z[0],), # 0-1-0-1---00---1
(-x[1],-y[1],z[5],z[4],z[3],-z[0],), # --0---0---111--0
(-x[3],-y[3],y[1],-y[0],z[4],z[3],z[1],), # 0---0-10---11-1-
(x[3],-x[1],-y[3],-y[1],-z[5],z[3],-z[2],), # 1-0-0-0---0-10--
(x[3],-x[0],y[2],-y[1],-z[5],-z[3],), # 1--0-10---0-0---
(z[7],z[6],-z[5],-z[3],z[2],-z[0],), # --------110-01-0
(-y[3],y[0],z[7],-z[5],-z[4],z[3],-z[2],), # ----0--11-0010--
(x[3],y[2],-z[6],z[1],z[0],), # 1----1---0----11
(x[1],y[2],y[1],-z[4],z[0],), # --1--11----0---1
(-x[2],-y[3],y[0],-z[3],-z[1],), # -0--0--1----0-0-
(-x[3],x[0],-y[2],-z[3],-z[1],), # 0--1-0------0-0-
(y[3],y[1],-z[6],z[1],z[0],), # ----1-1--0----11
(-x[3],-x[2],-x[1],-y[3],-z[3],-z[0],), # 000-0-------0--0
(x[3],x[2],x[1],-z[4],), # 111--------0----
(-x[2],-x[0],-z[6],-z[5],-z[3],-z[1],), # -0-0-----00-0-0-
(x[2],x[1],-z[7],-z[3],), # -11-----0---0---
(x[2],-x[1],-z[5],-z[4],-z[3],-z[1],), # -10-------000-0-
(x[2],x[0],y[2],y[0],-z[3],), # -1-1-1-1----0---
(-x[2],y[2],z[2],-z[0],), # -0---1-------1-0
(y[1],-y[0],-z[7],-z[4],z[2],), # ------100--0-1--
(x[3],y[3],y[2],-z[5],), # 1---11----0-----
(x[3],-x[1],-y[2],y[1],-z[5],-z[3],), # 1-0--01---0-0---
(-x[2],x[0],-y[1],-z[6],-z[3],-z[2],), # -0-1--0--0--00--
(x[0],y[1],y[0],-z[2],), # ---1--11-----0--
(-x[2],-x[1],-y[1],z[6],z[4],z[3],z[2],), # -00---0--1-111--
(x[2],x[1],-x[0],-y[3],z[3],z[0],), # -1100-------1--1
(x[2],y[3],y[1],-z[4],z[1],), # -1--1-1----0--1-
(-x[2],x[1],-y[3],-y[2],-z[6],z[1],z[0],), # -01-00---0----11
(-x[2],z[7],-z[6],z[4],z[3],-z[2],z[1],), # -0------10-1101-
(-x[3],-x[0],-z[6],z[3],-z[2],z[0],), # 0--0-----0--10-1
(-x[3],x[2],-y[2],-y[1],-z[5],z[4],z[0],), # 01---00---01---1
(y[2],y[1],y[0],-z[2],), # -----111-----0--
(-x[1],-y[2],y[0],-z[2],-z[1],), # --0--0-1-----00-
(-x[1],-y[1],y[0],z[2],z[1],), # --0---01-----11-
(-x[3],-y[3],y[2],-y[1],z[4],z[2],z[1],), # 0---010----1-11-
(-x[1],y[2],y[0],z[2],-z[1],), # --0--1-1-----10-
(-x[0],y[1],-z[5],z[3],z[2],z[1],), # ---0--1---0-111-
(-x[1],-y[3],-y[0],z[4],-z[3],z[2],-z[1],), # --0-0--0---1010-
(-x[3],-x[2],-x[1],-x[0],-y[1],z[4],-z[1],), # 0000--0----1--0-
(x[2],y[3],-z[6],z[1],z[0],), # -1--1----0----11
(-x[3],-x[2],-x[1],y[3],-y[0],-z[4],), # 000-1--0---0----
(-x[1],y[1],z[1],-z[0],), # --0---1-------10
(x[3],x[2],x[1],-z[5],), # 111-------0-----
(-x[2],-y[2],z[6],-z[4],z[2],-z[1],), # -0---0---1-0-10-
(x[0],y[2],-z[6],z[5],-z[2],), # ---1-1---01--0--
(-y[2],-y[1],-z[5],z[4],-z[2],-z[1],), # -----00---01-00-
(x[2],-z[7],z[2],z[1],), # -1------0----11-
(x[1],x[0],y[0],-z[2],), # --11---1-----0--
(-x[2],-x[1],y[2],y[1],-z[5],z[4],), # -00--11---01----
(-z[6],z[5],-z[4],-z[3],-z[2],), # ---------01000--
(x[2],y[2],-z[2],-z[0],), # -1---1-------0-0
(x[2],-y[2],z[2],-z[0],), # -1---0-------1-0
(x[2],-y[1],-y[0],-z[5],-z[4],z[3],), # -1----00--001---
(y[3],y[2],y[1],-z[4],), # ----111----0----
(x[1],y[2],y[0],-z[2],), # --1--1-1-----0--
(-x[1],-y[3],-y[2],-y[1],-z[5],-z[4],), # --0-000---00----
(-x[3],-y[2],z[7],z[6],z[5],), # 0----0--111-----
(-x[2],-y[2],-z[2],-z[0],), # -0---0-------0-0
(-x[3],y[2],y[1],z[6],-z[4],), # 0----11--1-0----
(y[3],y[2],-z[6],), # ----11---0------
(-x[2],-y[3],z[7],z[6],z[5],), # -0--0---111-----
(-x[2],-y[3],-y[0],-z[5],z[2],-z[1],), # -0--0--0--0--10-
(x[3],x[2],-z[6],), # 11-------0------
(-x[0],-y[2],y[1],z[2],z[0],), # ---0-01------1-1
(x[2],-x[1],-x[0],-y[3],-z[4],z[3],), # -1000------01---
(-x[1],-y[3],y[1],-z[3],-z[2],z[1],), # --0-0-1-----001-
(x[2],-x[1],-y[1],-y[0],z[2],-z[1],), # -10---00-----10-
(x[1],-y[1],z[1],-z[0],), # --1---0-------10
(y[3],y[2],y[0],-z[5],), # ----11-1--0-----
(x[1],x[0],-z[1],), # --11----------0-
(-x[3],y[2],-y[1],-y[0],-z[4],z[3],), # 0----100---01---
(x[2],-y[0],-z[2],z[1],z[0],), # -1-----0-----011
(-x[3],y[1],-y[0],z[6],z[3],z[1],), # 0-----10-1--1-1-
(x[2],-x[1],-y[3],z[7],z[5],z[4],), # -10-0---1-11----
(x[2],y[2],-z[5],z[2],z[0],), # -1---1----0--1-1
(-x[3],-x[2],-y[3],z[7],z[5],), # 00--0---1-1-----
(-x[3],y[2],-y[1],z[7],z[5],z[4],), # 0----10-1-11----
(-x[2],-y[0],z[2],z[1],z[0],), # -0-----0-----111
(-x[1],-y[0],z[1],z[0],), # --0----0------11
(x[2],-y[3],-y[2],-z[6],z[5],), # -1--00---01-----
(-x[2],-y[2],z[6],z[5],z[4],), # -0---0---111----
(z[7],-z[6],-z[4],z[3],-z[1],), # --------10-01-0-
(-x[0],-y[1],z[1],z[0],), # ---0--0-------11
(x[3],y[3],-z[6],), # 1---1----0------
(-x[3],-y[3],z[7],z[6],), # 0---0---11------
(x[3],-z[7],), # 1-------0-------
(y[3],-z[7],), # ----1---0-------
(-x[0],-y[0],z[0],), # ---0---0-------1
(x[0],y[0],-z[1],), # ---1---1------0-
(x[0],-z[0],), # ---1-----------0
(y[0],-z[0],), # -------1-------0
(x[1],y[1],-z[1],), # --1---1-------0-
]
def adder_4bit(cin, x, y, z, cout):
return [(-x[0],-x[3],-y[3],z[0],z[1],z[2],z[3],), # -0--0---0-1111
(-x[3],-y[0],-y[3],-cin,z[1],z[2],z[3],), # ----00--00-111
(x[2],x[3],y[3],-z[2],-z[3],), # ---11---1---00
(x[3],y[2],y[3],-z[2],-z[3],), # ----1--11---00
(-x[1],-x[3],-y[1],-y[3],z[2],z[3],), # --0-0-0-0---11
(-x[0],x[3],-y[3],z[0],z[1],z[2],-z[3],), # -0--1---0-1110
(-x[0],-x[3],y[3],z[0],z[1],z[2],-z[3],), # -0--0---1-1110
(x[3],-y[0],-y[3],-cin,z[1],z[2],-z[3],), # ----10--00-110
(-x[3],-y[0],y[3],-cin,z[1],z[2],-z[3],), # ----00--10-110
(x[2],x[3],y[2],y[3],-z[3],), # ---11--11----0
(-x[2],-x[3],-y[2],-y[3],z[3],), # ---00--00----1
(cout,-x[0],z[0],z[1],z[2],z[3],), # 10--------1111
(cout,-y[0],-cin,z[1],z[2],z[3],), # 1----0---0-111
(-x[1],x[3],-y[1],-y[3],z[2],-z[3],), # --0-1-0-0---10
(-x[1],-x[3],-y[1],y[3],z[2],-z[3],), # --0-0-0-1---10
(x[2],x[3],-y[3],-z[2],z[3],), # ---11---0---01
(x[3],y[2],-y[3],-z[2],z[3],), # ----1--10---01
(x[2],-x[3],y[3],-z[2],z[3],), # ---10---1---01
(-x[3],y[2],y[3],-z[2],z[3],), # ----0--11---01
(-x[0],x[1],y[1],z[0],z[1],), # -01---1---11--
(x[1],-y[0],y[1],-cin,z[1],), # --1--01--0-1--
(-x[0],-x[2],-y[2],z[0],z[1],z[2],), # -0-0---0--111-
(-x[2],-y[0],-y[2],-cin,z[1],z[2],), # ---0-0-0-0-11-
(x[1],x[2],y[2],-z[1],-z[2],), # --11---1---00-
(x[1],x[2],-y[2],-z[1],z[2],), # --11---0---01-
(x[1],-x[2],y[2],-z[1],z[2],), # --10---1---01-
(x[1],x[2],y[1],y[2],-z[2],), # --11--11----0-
(x[1],-x[2],-y[2],-z[1],-z[2],), # --10---0---00-
(-x[1],x[2],-y[2],z[1],-z[2],), # --01---0---10-
(-x[1],-x[2],y[2],z[1],-z[2],), # --00---1---10-
(x[1],x[2],y[1],-y[2],z[2],), # --11--10----1-
(x[1],-x[2],y[1],y[2],z[2],), # --10--11----1-
(x[2],-y[1],-y[2],z[1],-z[2],), # ---1--00---10-
(x[1],-x[2],y[1],-y[2],-z[2],), # --10--10----0-
(-x[2],-y[1],y[2],z[1],-z[2],), # ---0--01---10-
(x[0],-y[0],-cin,-z[0],), # -1---0---00---
(-x[0],y[0],cin,z[0],), # -0---1---11---
(x[0],x[1],y[1],-z[0],-z[1],), # -11---1---00--
(x[1],y[0],y[1],cin,-z[1],), # --1--11--1-0--
(x[0],-x[1],-y[1],-z[0],-z[1],), # -10---0---00--
(-x[1],y[0],-y[1],cin,-z[1],), # --0--10--1-0--
(x[2],x[3],y[2],-y[3],z[3],), # ---11--10----1
(x[2],-x[3],y[2],y[3],z[3],), # ---10--11----1
(x[0],-x[1],y[1],-z[0],z[1],), # -10---1---01--
(-x[1],y[0],y[1],cin,z[1],), # --0--11--1-1--
(-x[2],x[3],-y[2],-y[3],-z[3],), # ---01--00----0
(-x[2],-x[3],-y[2],y[3],-z[3],), # ---00--01----0
(-x[1],-y[0],y[1],z[0],-z[1],), # --0--01---10--
(-x[0],-x[1],y[1],-cin,-z[1],), # -00---1--0-0--
(x[0],x[1],-y[1],-z[0],z[1],), # -11---0---01--
(x[1],y[0],-y[1],cin,z[1],), # --1--10--1-1--
(-cout,x[2],-z[2],-z[3],), # 0--1--------00
(-cout,y[2],-z[2],-z[3],), # 0------1----00
(cout,-x[1],-y[1],z[2],z[3],), # 1-0---0-----11
(x[1],-y[0],-y[1],z[0],-z[1],), # --1--00---10--
(-x[0],x[1],-y[1],-cin,-z[1],), # -01---0--0-0--
(-x[0],-x[1],-y[1],z[0],z[1],), # -00---0---11--
(-x[1],-y[0],-y[1],-cin,z[1],), # --0--00--0-1--
(x[2],y[1],y[2],-z[1],-z[2],), # ---1--11---00-
(x[2],y[1],-y[2],-z[1],z[2],), # ---1--10---01-
(-x[2],y[1],y[2],-z[1],z[2],), # ---0--11---01-
(-x[1],x[2],-y[1],-y[2],-z[2],), # --01--00----0-
(-x[1],-x[2],-y[1],y[2],-z[2],), # --00--01----0-
(-x[2],y[1],-y[2],-z[1],-z[2],), # ---0--10---00-
(-x[1],-x[2],-y[1],-y[2],z[2],), # --00--00----1-
(-x[0],y[0],-cin,-z[0],), # -0---1---00---
(-x[0],-y[0],cin,-z[0],), # -0---0---10---
(x[0],y[0],-cin,z[0],), # -1---1---01---
(x[0],-y[0],cin,z[0],), # -1---0---11---
(-cout,x[2],y[2],-z[3],), # 0--1---1-----0
(cout,-x[2],-y[2],z[3],), # 1--0---0-----1
(-cout,x[3],y[3],), # 0---1---1-----
(cout,-x[3],-y[3],), # 1---0---0-----
(x[0],y[0],cin,-z[0],), # -1---1---10---
(-x[0],-y[0],-cin,z[0],), # -0---0---01---
]
def mult_5x5(x,y,z): # 5 bit x times 5 bit y = 10 bit z
return [(-x[4],x[1],-y[3],-y[2],z[9],z[5],z[2],-z[1],), # 0--1--00--1---1--10-
(x[4],-x[2],y[3],y[2],z[4],z[3],z[2],-z[1],), # 1-0---11-------1110-
(-x[1],-y[4],-y[3],-y[2],z[9],z[8],z[6],z[5],), # ---0-000--11-11-----
(x[2],y[2],y[1],-z[9],-z[7],-z[4],), # --1----11-0-0--0----
(-x[2],x[1],y[3],-z[9],z[6],-z[3],z[1],), # --01--1---0--1--0-1-
(-x[4],-y[4],y[2],-y[0],-z[6],-z[3],z[2],-z[1],z[0],), # 0----0-1-0---0--0101
(-x[3],x[1],y[4],-y[3],z[8],-z[4],-z[1],-z[0],), # -0-1-10----1---0--00
(x[2],y[4],y[2],y[0],-z[6],z[5],-z[2],), # --1--1-1-1---01--0--
(x[4],-x[3],-x[1],z[8],z[7],z[5],z[2],z[1],-z[0],), # 10-0-------11-1--110
(-x[3],x[1],y[3],-y[2],y[0],z[9],z[8],-z[4],-z[3],), # -0-1--10-111---00---
(x[4],x[0],-y[3],y[1],y[0],z[7],-z[5],z[4],-z[3],), # 1---1-0-11--1-010---
(-x[3],x[2],y[4],-y[3],-y[0],z[7],z[5],z[4],-z[1],), # -01--10--0--1-11--0-
(x[2],x[1],y[4],y[3],z[5],-z[3],-z[2],), # --11-11-------1-00--
(x[4],y[4],-y[3],y[1],z[7],z[4],-z[3],-z[1],-z[0],), # 1----10-1---1--10-00
(-y[4],-y[3],y[2],y[1],z[9],-z[7],z[6],z[2],-z[1],), # -----0011-1-01---10-
(x[4],-x[3],y[4],-y[3],y[1],z[4],z[3],z[1],-z[0],), # 10---10-1------11-10
(x[3],-x[2],y[4],y[2],z[5],-z[4],z[2],z[1],), # -10--1-1------10-11-
(x[1],-z[9],-z[8],z[5],-z[2],z[1],), # ---1------00--1--01-
(-x[1],-y[3],-y[2],-z[9],z[6],z[2],z[1],), # ---0--00--0--1---11-
(-y[4],y[3],-y[2],y[1],z[9],-z[4],z[3],-z[2],-z[1],), # -----0101-1----0100-
(x[4],y[4],y[2],y[1],z[6],-z[4],z[1],-z[0],), # 1----1-11----1-0--10
(x[0],-y[3],-y[2],y[1],-z[9],z[6],-z[5],-z[1],), # ----1-001-0--10---0-
(x[4],x[2],-x[1],-x[0],y[4],-y[1],z[6],-z[5],-z[4],), # 1-1001--0----100----
(x[3],y[3],-z[8],-z[7],z[4],z[1],-z[0],), # -1----1----00--1--10
(x[3],y[3],y[1],-z[7],-z[6],z[3],z[0],), # -1----1-1---00--1--1
(-x[4],-x[3],-y[4],y[2],y[0],-z[5],z[4],z[2],-z[1],), # 00---0-1-1----01-10-
(x[0],-y[3],z[9],z[8],z[7],z[6],z[4],-z[1],), # ----1-0---1111-1--0-
(-x[4],-x[2],-x[0],y[2],z[9],z[8],-z[5],-z[4],z[3],), # 0-0-0--1--11--001---
(x[3],x[2],-y[0],-z[5],z[4],z[1],z[0],), # -11------0----01--11
(-x[3],y[3],-y[2],-y[1],z[3],-z[0],), # -0----100-------1--0
(-x[3],y[0],z[9],z[8],z[7],z[6],z[4],-z[1],), # -0-------11111-1--0-
(x[4],-x[3],x[1],-y[4],z[5],z[4],z[2],-z[1],), # 10-1-0--------11-10-
(-x[4],-x[3],-y[3],y[1],z[9],-z[4],z[3],z[1],-z[0],), # 00----0-1-1----01-10
(x[3],x[1],y[4],-y[3],z[7],-z[6],-z[4],), # -1-1-10-----10-0----
(-x[4],-y[3],-y[2],-y[1],-z[5],z[1],-z[0],), # 0-----000-----0---10
(-x[3],-y[4],-y[3],-y[2],y[0],-z[4],-z[1],), # -0---000-1-----0--0-
(-x[3],x[1],-y[4],z[5],z[4],-z[3],z[2],-z[1],-z[0],), # -0-1-0--------110100
(y[2],y[0],-z[9],z[5],z[3],-z[2],z[1],), # -------1-10---1-101-
(x[3],x[2],-x[1],y[3],-y[1],z[3],z[2],-z[0],), # -110--1-0-------11-0
(x[3],-x[1],y[2],z[7],z[5],-z[4],-z[3],-z[2],z[1],), # -1-0---1----1-10001-
(x[0],-y[3],-z[9],-z[4],-z[3],z[2],-z[1],), # ----1-0---0----0010-
(x[4],x[3],y[4],y[3],-z[4],-z[1],-z[0],), # 11---11--------0--00
(y[1],-z[9],-z[7],z[4],z[1],-z[0],), # --------1-0-0--1--10
(x[3],x[1],y[2],y[1],-z[9],-z[5],), # -1-1---11-0---0-----
(x[1],-y[4],z[8],z[6],z[4],z[2],z[1],-z[0],), # ---1-0-----1-1-1-110
(x[3],-y[3],y[2],-y[1],-z[3],-z[2],-z[1],-z[0],), # -1----010-------0000
(-x[3],y[3],-y[2],y[1],-z[3],-z[2],-z[1],), # -0----101-------000-
(-x[1],-y[3],-y[2],-z[9],z[6],-z[5],z[1],), # ---0--00--0--10---1-
(-x[2],x[0],-y[3],y[1],-z[8],-z[7],z[6],-z[5],), # --0-1-0-1--0010-----
(y[2],y[0],-z[8],-z[7],-z[5],-z[2],z[1],), # -------1-1-00-0--01-
(x[4],-y[2],z[8],z[7],z[5],-z[4],z[3],z[2],-z[0],), # 1------0---11-1011-0
(-x[3],y[4],y[2],-z[6],z[4],-z[2],-z[0],), # -0---1-1-----0-1-0-0
(x[3],y[4],-y[1],z[7],z[5],-z[4],-z[1],-z[0],), # -1---1--0---1-10--00
(x[3],x[2],y[4],y[3],y[2],-y[1],z[5],-z[4],), # -11--1110-----10----
(x[3],-x[1],y[4],y[2],-y[0],-z[6],-z[5],z[4],), # -1-0-1-1-0---001----
(x[2],y[4],y[1],-z[4],-z[2],z[0],), # --1--1--1------0-0-1
(x[4],-x[3],-y[4],y[3],-y[1],-z[4],-z[3],-z[1],-z[0],), # 10---01-0------00-00
(-x[3],y[4],-y[2],-y[1],z[7],z[4],-z[1],-z[0],), # -0---1-00---1--1--00
(-x[4],y[1],z[9],z[8],z[6],z[4],z[1],-z[0],), # 0-------1-11-1-1--10
(x[2],-y[3],-y[2],y[0],z[4],-z[3],z[2],z[1],), # --1---00-1-----1011-
(x[3],-x[2],y[4],-y[3],-y[2],y[1],-z[5],z[4],-z[2],), # -10--1001-----01-0--
(-x[2],-y[4],-y[3],-y[2],y[0],z[8],z[4],-z[1],), # --0--000-1-1---1--0-
(-x[3],-x[1],-y[3],-y[2],z[3],-z[2],-z[1],-z[0],), # -0-0--00--------1000
(-x[3],x[2],y[4],-y[2],y[0],z[4],-z[2],-z[1],), # -01--1-0-1-----1-00-
(-x[3],-y[4],y[0],z[9],z[8],-z[5],-z[3],z[2],z[1],), # -0---0---111--0-011-
(x[4],-x[3],-x[2],x[1],-y[3],y[2],z[8],-z[4],-z[1],), # 1001--01---1---0--0-
(-x[2],-x[1],y[3],-y[2],-y[1],-z[8],-z[7],z[6],), # --00--100--001------
(x[0],-y[4],-y[3],y[2],y[1],z[9],z[8],z[4],-z[1],), # ----10011-11---1--0-
(-x[2],-x[1],-x[0],-y[4],y[2],z[9],z[8],z[5],z[0],), # --0000-1--11--1----1
(x[2],y[2],-z[9],-z[7],z[3],z[2],z[1],), # --1----1--0-0---111-
(x[2],-x[1],-y[4],y[1],z[5],z[3],z[2],z[1],), # --10-0--1-----1-111-
(x[1],-y[4],z[9],z[8],z[7],z[6],-z[5],), # ---1-0----11110-----
(-x[3],-y[4],-y[3],-y[2],-z[5],z[4],-z[0],), # -0---000------01---0
(x[3],x[0],-y[2],-y[1],z[4],-z[3],z[2],z[1],), # -1--1--00------1011-
(-x[3],-x[2],y[3],y[2],-y[1],-z[3],-z[1],-z[0],), # -00---110-------0-00
(-x[3],x[0],y[2],-y[1],y[0],z[4],z[2],), # -0--1--101-----1-1--
(-x[0],y[3],y[2],-y[1],-z[8],-z[7],-z[5],-z[3],), # ----0-110--00-0-0---
(-x[4],x[3],-y[4],y[3],y[1],z[8],), # 01---01-1--1--------
(x[3],-x[1],-y[4],z[6],z[5],-z[3],z[2],z[1],), # -1-0-0-------11-011-
(-x[3],-x[2],-y[3],-y[1],z[3],-z[2],-z[1],-z[0],), # -00---0-0-------1000
(x[4],x[1],y[3],y[0],z[7],-z[5],-z[3],z[2],), # 1--1--1--1--1-0-01--
(-x[3],y[3],-y[2],y[1],-z[3],z[2],z[1],-z[0],), # -0----101-------0110
(-x[4],x[2],x[1],y[2],-y[1],z[5],-z[4],z[1],), # 0-11---10-----10--1-
(x[4],x[1],y[3],y[2],-y[1],z[5],z[3],-z[2],), # 1--1--110-----1-10--
(-x[4],-x[3],-y[4],-y[1],-z[4],-z[2],z[1],-z[0],), # 00---0--0------0-010
(-x[4],-x[3],-y[4],-y[2],-z[4],z[2],z[1],-z[0],), # 00---0-0-------0-110
(-x[3],x[0],y[4],y[1],y[0],z[5],-z[3],), # -0--11--11----1-0---
(-x[4],-y[4],-y[3],y[2],y[1],z[4],-z[3],-z[1],-z[0],), # 0----0011------10-00
(x[4],x[1],x[0],y[3],z[7],-z[6],-z[5],), # 1--11-1-----100-----
(x[3],y[4],y[3],y[2],y[0],-z[4],), # -1---111-1-----0----
(-x[3],x[2],-x[1],-x[0],y[4],-z[8],z[7],z[6],-z[4],), # -01001-----011-0----
(x[0],y[1],z[7],-z[6],z[4],z[2],-z[1],), # ----1---1---10-1-10-
(-x[3],-x[2],x[1],-y[4],y[3],y[0],-z[5],z[4],-z[2],), # -001-01--1----01-0--
(x[3],-x[2],x[0],-z[7],-z[6],-z[5],-z[3],z[1],), # -10-1-------000-0-1-
(-x[1],-x[0],y[4],y[1],z[4],-z[3],z[2],z[0],), # ---001--1------101-1
(x[2],y[2],z[8],z[6],z[4],-z[3],-z[2],), # --1----1---1-1-100--
(x[1],-y[2],z[9],-z[5],z[3],z[2],z[1],-z[0],), # ---1---0--1---0-1110
(x[3],-x[1],x[0],y[3],-z[4],-z[2],z[1],), # -1-01-1--------0-01-
(-x[3],x[2],-x[0],y[4],z[8],z[5],-z[3],-z[2],z[0],), # -01-01-----1--1-00-1
(x[0],-y[4],-y[3],-y[2],-y[1],z[9],-z[8],z[5],), # ----10000-10--1-----
(-x[4],-x[3],x[2],y[4],y[3],-y[1],-z[4],-z[3],-z[1],), # 001--11-0------00-0-
(x[3],x[2],-y[1],z[8],-z[7],z[6],z[5],z[0],), # -11-----0--1011----1
(x[1],y[4],y[2],y[1],y[0],-z[4],), # ---1-1-111-----0----
(x[3],-x[2],-x[1],-y[3],-y[1],-y[0],z[7],z[6],), # -100--0-00--11------
(x[4],-x[2],-y[3],-y[2],z[7],-z[4],-z[2],-z[1],), # 1-0---00----1--0-00-
(-x[4],x[3],x[1],y[4],z[5],z[4],-z[1],), # 01-1-1--------11--0-
(-x[4],-x[3],-x[2],x[0],-y[3],-z[4],-z[1],), # 000-1-0--------0--0-
(x[4],-x[3],-y[3],y[1],z[8],-z[4],-z[1],-z[0],), # 10----0-1--1---0--00
(x[3],-y[3],-y[2],-z[8],-z[5],z[2],-z[1],z[0],), # -1----00---0--0--101
(x[4],-x[2],x[1],-y[3],y[1],-z[7],-z[5],z[0],), # 1-01--0-1---0-0----1
(x[4],-x[3],-y[2],z[8],z[5],-z[4],z[1],-z[0],), # 10-----0---1--10--10
(-x[4],-x[3],y[4],y[3],y[0],-z[6],z[5],), # 00---11--1---01-----
(-x[3],-x[2],-x[1],-y[1],-z[5],-z[4],-z[0],), # -000----0-----00---0
(-x[3],-z[8],z[7],-z[5],-z[4],z[3],z[2],), # -0---------01-0011--
(x[1],x[0],y[2],y[1],y[0],-z[4],), # ---11--111-----0----
(-x[2],y[3],y[1],y[0],z[4],-z[3],z[2],), # --0---1-11-----101--
(-x[2],x[1],-y[2],y[1],y[0],z[4],z[2],), # --01---011-----1-1--
(-x[4],-x[2],x[0],-y[4],y[0],-z[7],-z[5],-z[4],z[3],), # 0-0-10---1--0-001---
(x[3],x[2],y[3],-z[7],z[2],z[1],), # -11---1-----0----11-
(-x[3],x[1],-y[2],y[0],-z[4],-z[3],z[2],), # -0-1---0-1-----001--
(x[1],-y[1],-z[9],z[6],-z[5],-z[4],z[0],), # ---1----0-0--100---1
(x[4],x[3],x[2],x[0],y[3],-z[4],), # 111-1-1--------0----
(-x[2],-y[3],-y[1],z[7],-z[5],z[4],-z[1],-z[0],), # --0---0-0---1-01--00
(-x[4],x[3],-y[3],-y[2],y[1],z[4],-z[3],-z[2],-z[1],), # 01----001------1000-
(-x[4],y[4],y[1],z[7],-z[5],z[3],-z[2],-z[0],), # 0----1--1---1-0-10-0
(x[4],-x[3],y[4],y[3],y[1],z[5],-z[4],), # 10---11-1-----10----
(-x[4],-x[2],-y[2],-y[0],z[7],z[5],z[3],-z[1],), # 0-0----0-0--1-1-1-0-
(-x[2],-y[3],z[9],-z[8],z[4],-z[3],z[1],-z[0],), # --0---0---10---10-10
(-x[3],-y[4],y[2],y[1],z[7],z[6],z[1],-z[0],), # -0---0-11---11----10
(-x[2],x[1],y[4],-y[3],y[2],z[8],z[7],z[5],), # --01-101---11-1-----
(-x[4],x[2],x[1],-y[3],y[1],-z[6],-z[5],z[0],), # 0-11--0-1----00----1
(-y[2],z[9],z[6],z[5],z[4],z[2],-z[0],), # -------0--1--111-1-0
(-x[3],-x[2],-x[1],x[0],-z[9],-z[5],z[1],), # -0001-----0---0---1-
(-x[4],-x[2],-y[3],y[1],z[8],-z[7],z[6],z[4],-z[1],), # 0-0---0-1--101-1--0-
(y[4],-y[2],-y[1],z[7],-z[5],z[4],-z[3],-z[2],-z[1],), # -----1-00---1-01000-
(x[3],x[2],-y[4],-y[1],-z[5],-z[1],-z[0],), # -11--0--0-----0---00
(x[4],-y[1],-y[0],-z[7],z[4],-z[3],z[1],), # 1-------00--0--10-1-
(x[3],-x[2],x[1],-y[3],y[1],z[5],-z[4],z[0],), # -101--0-1-----10---1
(-x[4],-y[3],-y[2],z[6],z[4],z[1],-z[0],), # 0-----00-----1-1--10
(-x[4],-y[3],-y[2],z[8],-z[5],-z[3],z[1],-z[0],), # 0-----00---1--0-0-10
(x[4],x[2],x[1],x[0],y[1],-z[4],), # 1-111---1------0----
(x[3],y[4],y[2],y[1],-z[6],z[1],), # -1---1-11----0----1-
(-x[4],x[2],y[4],-y[3],-y[2],y[1],-z[7],z[6],), # 0-1--1001---01------
(x[2],y[2],z[9],z[7],-z[6],-z[5],-z[4],z[0],), # --1----1--1-1000---1
(-x[2],-x[1],-y[4],-y[3],z[8],z[5],-z[2],-z[0],), # --00-00----1--1--0-0
(x[3],-y[4],-y[3],y[2],z[9],-z[4],-z[3],-z[2],-z[1],), # -1---001--1----0000-
(x[4],x[2],x[0],-y[4],y[2],-z[6],-z[2],), # 1-1-10-1-----0---0--
(x[1],z[9],z[8],-z[5],-z[4],z[2],z[1],-z[0],), # ---1------11--00-110
(x[3],y[4],y[3],y[1],z[6],-z[5],z[0],), # -1---11-1----10----1
(x[4],-x[0],-y[2],-y[1],-z[7],-z[5],z[4],-z[1],), # 1---0--00---0-01--0-
(x[4],x[1],x[0],y[2],-z[4],-z[2],), # 1--11--1-------0-0--
(-x[4],-x[1],-y[3],z[9],z[8],z[5],z[2],-z[1],), # 0--0--0---11--1--10-
(-x[3],y[4],y[1],z[6],-z[5],z[4],-z[1],), # -0---1--1----101--0-
(-x[4],-x[1],y[4],y[3],z[4],-z[3],-z[0],), # 0--0-11--------10--0
(-x[2],x[0],y[2],y[0],z[3],-z[2],), # --0-1--1-1------10--
(x[3],-x[2],y[4],-y[3],y[2],-y[0],z[5],-z[4],-z[1],), # -10--101-0----10--0-
(-x[4],-y[4],-y[1],z[6],-z[3],z[1],-z[0],), # 0----0--0----1--0-10
(-x[4],x[3],-x[1],y[3],-y[1],-y[0],z[9],-z[4],z[3],z[2],), # 01-0--1-001----011--
(-x[2],y[4],-y[3],z[8],-z[7],z[5],z[1],-z[0],), # --0--10----10-1---10
(-x[4],y[3],y[2],y[1],-z[5],-z[1],-z[0],), # 0-----111-----0---00
(x[4],x[1],x[0],-y[2],z[4],-z[2],), # 1--11--0-------1-0--
(-x[4],-x[3],-x[2],x[0],y[3],z[4],-z[1],), # 000-1-1--------1--0-
(x[3],x[1],-y[1],z[3],-z[2],z[1],), # -1-1----0-------101-
(x[4],x[3],x[0],-y[4],-y[2],-z[6],z[4],), # 11--10-0-----0-1----
(-x[4],x[3],y[4],y[1],y[0],z[7],-z[5],), # 01---1--11--1-0-----
(-x[4],-x[1],-y[4],-y[2],y[1],z[9],z[3],z[0],), # 0--0-0-01-1-----1--1
(-x[3],-x[2],y[4],y[3],-y[0],-z[5],-z[4],-z[1],), # -00--11--0----00--0-
(-x[3],y[4],-y[3],y[2],-z[6],z[5],-z[2],z[0],), # -0---101-----01--0-1
(-y[4],y[1],z[9],z[8],z[4],-z[2],z[1],-z[0],), # -----0--1-11---1-010
(x[4],-x[2],x[1],-y[4],-y[3],-z[5],-z[1],), # 1-01-00-------0---0-
(-x[4],-x[3],y[3],-y[1],-y[0],z[9],z[7],z[6],), # 00----1-001-11------
(-x[4],x[1],-y[4],y[2],-y[1],z[9],z[3],-z[2],), # 0--1-0-10-1-----10--
(x[4],-x[2],-x[1],-y[4],-y[3],z[7],z[6],), # 1-00-00-----11------
(x[4],x[0],-y[4],-y[3],z[5],z[2],-z[1],), # 1---100-------1--10-
(-x[0],-y[4],y[3],z[4],z[2],z[1],z[0],), # ----001--------1-111
(x[4],x[0],y[3],-y[2],-y[1],-z[4],-z[1],), # 1---1-100------0--0-
(-x[2],y[4],y[1],y[0],z[4],-z[2],), # --0--1--11-----1-0--
(x[2],-y[3],-y[1],z[9],z[5],z[4],z[1],-z[0],), # --1---0-0-1---11--10
(-x[4],-x[3],y[4],y[0],z[5],z[2],-z[1],), # 00---1---1----1--10-
(x[3],x[2],x[1],-y[4],z[4],-z[1],z[0],), # -111-0---------1--01
(-x[4],y[3],y[2],y[1],z[4],-z[1],z[0],), # 0-----111------1--01
(x[3],-x[2],-x[1],y[4],y[0],-z[4],-z[1],), # -100-1---1-----0--0-
(x[4],-x[3],-x[2],x[0],-y[3],z[4],-z[1],), # 100-1-0--------1--0-
(-x[2],x[1],-z[9],-z[6],z[5],z[3],z[2],), # --01------0--01-11--
(-x[3],-x[2],-x[1],-y[4],-y[2],y[0],z[9],-z[6],z[1],), # -000-0-0-11--0----1-
(x[2],x[1],y[2],y[1],-z[8],-z[6],), # --11---11--0-0------
(x[3],y[3],-z[7],-z[5],-z[3],-z[2],), # -1----1-----0-0-00--
(-x[4],x[3],-x[2],-x[1],-y[3],-y[2],z[9],-z[6],z[1],z[0],), # 0100--00--1--0----11
(-y[2],-z[7],-z[6],z[5],-z[4],-z[1],-z[0],), # -------0----0010--00
(-x[3],x[2],z[8],-z[6],z[5],z[4],z[3],-z[0],), # -01--------1-0111--0
(-x[1],-y[1],-z[9],z[8],z[7],-z[5],z[3],), # ---0----0-011-0-1---
(y[3],y[2],-z[9],-z[6],-z[1],), # ------11--0--0----0-
(-x[3],-x[2],-x[1],y[0],z[9],z[8],z[4],-z[1],), # -000-----111---1--0-
(x[0],-y[3],-y[2],-y[1],z[9],z[8],z[4],-z[1],), # ----1-000-11---1--0-
(-x[4],-x[0],-y[3],-z[7],z[6],-z[5],z[3],-z[2],), # 0---0-0-----010-10--
(x[4],x[3],y[4],y[3],y[2],-z[5],), # 11---111------0-----
(x[4],x[2],y[4],y[2],z[6],-z[5],-z[4],), # 1-1--1-1-----100----
(-x[2],x[0],-y[3],y[1],-z[4],-z[3],z[2],), # --0-1-0-1------001--
(x[3],-x[2],y[1],-z[7],-z[5],-z[4],-z[1],), # -10-----1---0-00--0-
(x[1],-x[0],-y[4],-y[3],y[2],z[8],z[5],-z[4],z[3],z[2],), # ---10001---1--1011--
(-x[2],-y[2],y[1],-z[8],-z[7],-z[6],-z[4],), # --0----01--000-0----
(x[2],x[1],x[0],-y[2],z[5],-z[3],), # --111--0------1-0---
(-x[3],x[2],-y[1],y[0],z[4],z[2],z[1],), # -01-----01-----1-11-
(-x[4],-x[3],x[2],-y[3],y[1],z[7],z[6],z[5],z[0],), # 001---0-1---111----1
(-x[3],x[1],y[2],-z[8],z[7],-z[6],-z[3],z[1],), # -0-1---1---010--0-1-
(x[4],-x[2],x[1],y[3],-y[1],z[7],-z[5],-z[4],-z[2],), # 1-01--1-0---1-00-0--
(x[4],-x[0],y[3],-y[2],-z[6],-z[4],z[3],-z[2],), # 1---0-10-----0-010--
(-x[3],x[2],-x[1],y[0],-z[7],-z[5],-z[3],z[1],), # -010-----1--0-0-0-1-
(-x[3],x[1],-y[4],-y[3],-z[5],-z[2],-z[0],), # -0-1-00-------0--0-0
(-x[1],x[0],-y[3],y[2],z[4],z[2],z[1],), # ---01-01-------1-11-
(-x[3],x[0],y[3],y[0],z[4],-z[2],), # -0--1-1--1-----1-0--
(x[3],-y[4],y[0],z[4],-z[3],z[2],-z[1],), # -1---0---1-----1010-
(x[4],-x[3],x[2],y[4],-y[1],z[4],-z[3],z[2],), # 101--1--0------101--
(x[3],x[0],-y[3],y[0],z[4],-z[2],), # -1--1-0--1-----1-0--
(-x[2],-x[1],-y[1],-y[0],-z[9],z[6],z[5],z[4],), # --00----000--111----
(x[1],-y[4],y[1],y[0],z[4],-z[3],z[2],), # ---1-0--11-----101--
(x[3],x[2],y[4],y[3],-y[2],z[6],-z[5],), # -11--110-----10-----
(x[4],x[2],y[3],y[2],-z[6],z[2],-z[1],), # 1-1---11-----0---10-
(-x[3],-y[3],-z[9],-z[4],-z[1],-z[0],), # -0----0---0----0--00
(-x[4],x[3],-x[1],-y[4],y[3],z[7],-z[2],-z[0],), # 01-0-01-----1----0-0
(-x[1],y[3],y[1],z[3],-z[2],z[1],), # ---0--1-1-------101-
(-x[4],-y[4],y[3],-y[2],z[6],-z[5],z[4],-z[0],), # 0----010-----101---0
(x[3],x[2],-y[4],y[0],-z[6],-z[4],z[3],z[2],), # -11--0---1---0-011--
(-x[4],-y[4],-y[2],-z[6],z[5],-z[1],-z[0],), # 0----0-0-----01---00
(x[3],-x[2],x[1],-y[4],y[3],z[8],z[6],), # -101-01----1-1------
(-x[1],y[4],-y[3],-y[1],-y[0],-z[7],z[6],z[3],z[2],), # ---0-10-00--01--11--
(-x[4],-x[3],-y[4],y[1],-z[4],-z[3],-z[0],), # 00---0--1------00--0
(-x[4],y[1],-y[0],z[4],z[2],z[1],z[0],), # 0-------10-----1-111
(-x[4],x[3],y[2],-y[0],z[9],z[7],z[4],-z[2],-z[1],), # 01-----1-01-1--1-00-
(x[1],-y[3],y[0],z[3],-z[2],z[1],), # ---1--0--1------101-
(x[4],x[0],-y[3],y[2],-y[1],-z[7],-z[5],-z[4],), # 1---1-010---0-00----
(-x[3],-y[4],y[0],-z[4],-z[3],z[2],-z[1],), # -0---0---1-----0010-
(x[3],x[1],x[0],y[2],y[0],-z[4],), # -1-11--1-1-----0----
(x[4],x[3],x[1],-y[4],-y[3],-z[6],z[5],), # 11-1-00------01-----
(-x[3],-y[3],-y[1],y[0],-z[4],-z[2],z[1],), # -0----0-01-----0-01-
(x[2],-y[3],-y[1],z[9],z[6],-z[5],z[4],z[3],-z[1],), # --1---0-0-1--1011-0-
(-x[2],-y[2],-y[1],-z[9],z[7],z[6],z[0],), # --0----00-0-11-----1
(x[0],-y[4],y[1],-z[8],z[7],-z[5],-z[4],z[1],), # ----10--1--01-00--1-
(x[3],-x[2],x[0],-y[4],y[1],z[8],z[5],-z[3],), # -10-10--1--1--1-0---
(x[2],y[4],y[1],z[6],-z[4],-z[2],z[1],), # --1--1--1----1-0-01-
(-y[3],-y[2],z[8],-z[5],z[2],-z[1],-z[0],), # ------00---1--0--100
(-x[4],x[1],x[0],y[2],z[4],-z[2],), # 0--11--1-------1-0--
(-x[4],-x[0],-y[3],-y[2],z[9],-z[7],z[4],z[3],-z[1],), # 0---0-00--1-0--11-0-
(-x[2],-x[1],-x[0],-y[1],z[9],z[7],z[6],z[4],z[3],), # --000---0-1-11-11---
(x[4],x[1],y[3],y[2],-z[5],-z[4],z[1],), # 1--1--11------00--1-
(x[2],-x[1],-y[4],y[0],z[9],-z[7],z[5],-z[4],z[2],), # --10-0---11-0-10-1--
(x[2],-y[4],y[1],y[0],z[4],-z[2],), # --1--0--11-----1-0--
(x[2],x[1],y[2],y[1],-z[5],z[0],), # --11---11-----0----1
(-x[4],y[4],y[1],-z[5],-z[4],-z[3],-z[1],), # 0----1--1-----000-0-
(-x[1],-y[3],y[1],-z[3],-z[2],z[1],), # ---0--0-1-------001-
(-x[3],-x[1],-y[4],-z[5],z[3],z[1],-z[0],), # -0-0-0--------0-1-10
(x[4],-x[1],-x[0],-y[2],-z[8],z[6],z[5],), # 1--00--0---0-11-----
(-x[3],x[1],y[3],-y[2],y[1],z[5],-z[4],z[0],), # -0-1--101-----10---1
(-x[4],-x[3],-y[2],y[1],-y[0],z[9],-z[7],-z[6],-z[2],), # 00-----0101-00---0--
(-x[4],x[3],x[2],x[1],y[4],z[4],-z[0],), # 0111-1---------1---0
(x[2],-y[4],y[3],y[1],z[8],-z[6],-z[5],z[0],), # --1--01-1--1-00----1
(x[4],-x[3],-x[2],-x[1],-y[2],y[1],-z[6],-z[5],), # 1000---01----00-----
(-x[4],-x[3],-x[2],y[1],-z[5],-z[1],-z[0],), # 000-----1-----0---00
(-x[3],-x[2],-y[4],-y[2],y[1],-z[6],z[5],-z[1],), # -00--0-01----01---0-
(-x[4],-x[3],-y[0],z[9],z[8],z[7],-z[5],z[4],), # 00-------0111-01----
(-x[3],-y[4],-y[2],-y[1],z[9],z[8],z[5],z[2],), # -0---0-00-11--1--1--
(-x[3],x[1],-y[4],y[2],y[1],-z[6],-z[5],z[0],), # -0-1-0-11----00----1
(-x[4],x[1],x[0],-y[2],-z[4],-z[2],), # 0--11--0-------0-0--
(x[4],x[0],y[3],y[2],y[1],-z[4],), # 1---1-111------0----
(-x[3],x[2],x[1],-y[4],z[9],z[7],z[2],), # -011-0----1-1----1--
(-x[4],x[2],-x[1],y[4],y[2],y[0],-z[6],-z[5],), # 0-10-1-1-1---00-----
(-x[4],x[3],-x[2],-x[0],-y[2],z[9],z[5],-z[4],-z[3],-z[1],), # 010-0--0--1---100-0-
(-x[2],-y[4],y[1],y[0],-z[4],-z[2],), # --0--0--11-----0-0--
(x[4],x[1],-y[3],-y[1],-z[5],z[4],z[3],z[0],), # 1--1--0-0-----011--1
(x[4],-x[3],-x[2],-x[1],y[4],-y[1],-z[5],-z[4],), # 1000-1--0-----00----
(-x[4],x[0],y[3],-y[2],-y[1],z[4],-z[1],), # 0---1-100------1--0-
(-x[4],-x[1],-y[4],y[0],z[5],z[4],-z[1],), # 0--0-0---1----11--0-
(x[4],-x[1],y[4],-y[3],-y[2],-y[1],-z[5],-z[4],), # 1--0-1000-----00----
(-x[2],-x[1],-y[4],-y[3],-y[2],z[8],z[7],z[5],), # --00-000---11-1-----
(-x[3],-x[1],-y[3],-y[2],z[8],z[7],z[4],), # -0-0--00---11--1----
(x[4],x[3],-x[1],-x[0],-y[3],-y[2],z[6],-z[4],), # 11-00-00-----1-0----
(-x[4],y[4],-y[1],y[0],z[8],z[7],z[5],), # 0----1--01-11-1-----
(-x[1],-y[4],y[3],z[9],z[8],z[4],-z[3],-z[0],), # ---0-01---11---10--0
(-x[3],-x[1],y[4],-y[3],y[1],-z[5],z[4],-z[2],), # -0-0-10-1-----01-0--
(-x[3],-y[4],-y[3],z[9],z[4],-z[1],-z[0],), # -0---00---1----1--00
(-x[2],-y[4],y[3],y[2],z[9],z[8],z[6],z[0],), # --0--011--11-1-----1
(x[2],-x[1],y[3],y[1],-z[8],z[5],z[0],), # --10--1-1--0--1----1
(-x[4],x[2],-y[2],-y[1],y[0],z[9],z[6],-z[5],-z[4],), # 0-1----0011--100----
(-x[3],-x[2],y[3],y[2],-z[8],z[6],z[1],z[0],), # -00---11---0-1----11
(-x[3],-x[2],-x[1],-y[4],y[0],-z[4],-z[1],), # -000-0---1-----0--0-
(x[4],-x[3],-x[2],-x[1],-y[1],-y[0],z[8],z[7],z[5],), # 1000----00-11-1-----
(-x[4],-x[3],y[4],-y[2],y[1],-z[7],-z[4],z[1],z[0],), # 00---1-01---0--0--11
(z[8],-z[7],z[6],-z[4],z[3],-z[2],-z[0],), # -----------101-010-0
(-x[3],-x[1],-x[0],-y[4],-y[3],y[2],-y[1],z[9],-z[6],), # -0-000010-1--0------
(-x[3],-x[2],x[1],-y[4],-y[3],-y[2],z[9],z[6],z[1],), # -001-000--1--1----1-
(x[3],-x[1],-x[0],y[4],-y[3],-y[2],-y[1],z[8],z[5],), # -1-001000--1--1-----
(-x[4],-x[3],x[2],-x[1],-y[3],-y[1],-y[0],z[9],-z[6],), # 0010--0-001--0------
(-x[3],-x[2],-x[1],y[4],-y[3],y[1],z[5],-z[4],z[0],), # -000-10-1-----10---1
(-x[4],-y[3],-y[2],-y[1],z[9],z[5],-z[2],z[1],z[0],), # 0-----000-1---1--011
(-x[4],-x[3],-x[2],-y[3],-y[2],y[1],z[9],z[6],z[1],), # 000---001-1--1----1-
(-x[3],-x[2],-x[1],-y[4],z[9],z[5],-z[2],z[1],z[0],), # -000-0----1---1--011
(x[2],-x[0],-z[9],-z[6],z[4],z[2],), # --1-0-----0--0-1-1--
(x[1],-y[4],y[2],-y[1],-z[8],z[6],z[5],z[2],), # ---1-0-10--0-11--1--
(x[1],-y[3],z[7],z[5],-z[4],z[3],-z[2],z[1],), # ---1--0-----1-10101-
(-x[4],-y[3],-y[2],z[9],z[8],-z[4],-z[1],z[0],), # 0-----00--11---0--01
(x[2],x[0],y[3],y[1],y[0],-z[4],), # --1-1-1-11-----0----
(-x[3],-x[2],-x[1],-y[4],y[3],-y[1],z[9],-z[5],-z[1],), # -000-01-0-1---0---0-
(x[1],-y[3],-y[2],y[0],-z[8],z[7],-z[5],-z[4],), # ---1--00-1-01-00----
(x[2],-y[3],-y[2],z[6],-z[4],z[3],z[2],), # --1---00-----1-011--
(x[2],-y[3],y[2],-z[8],z[7],-z[5],z[0],), # --1---01---01-0----1
(x[2],-x[0],-y[4],y[3],z[8],z[7],-z[6],-z[2],-z[1],), # --1-001----110---00-
(x[2],x[0],-y[2],z[3],-z[2],z[1],), # --1-1--0--------101-
(x[3],x[2],y[3],-z[7],-z[6],), # -11---1-----00------
(-x[4],-x[1],-y[2],y[1],z[8],-z[6],z[5],z[3],), # 0--0---01--1-01-1---
(-x[4],-x[3],-x[1],y[3],y[1],z[8],-z[4],z[3],z[2],), # 00-0--1-1--1---011--
(-x[1],x[0],-y[2],z[3],z[2],z[1],), # ---01--0--------111-
(x[4],-x[1],-y[2],y[1],-z[6],-z[5],-z[4],z[3],), # 1--0---01----0001---
(-x[4],x[1],x[0],-y[3],y[0],-z[5],-z[3],), # 0--11-0--1----0-0---
(-x[4],x[1],-y[4],y[3],-z[4],z[3],-z[0],), # 0--1-01--------01--0
(-x[3],-x[2],-x[1],y[3],z[3],-z[0],), # -000--1---------1--0
(x[2],y[2],-z[9],z[7],z[6],z[0],), # --1----1--0-11-----1
(-x[2],x[0],-y[2],y[0],-z[3],-z[2],), # --0-1--0-1------00--
(x[3],-x[2],-x[1],-y[3],y[2],y[1],z[7],-z[6],), # -100--011---10------
(x[3],-y[4],y[3],z[8],z[4],-z[1],-z[0],), # -1---01----1---1--00
(x[4],y[4],y[2],-z[7],-z[6],), # 1----1-1----00------
(-x[0],-y[3],y[2],z[3],z[1],z[0],), # ----0-01--------1-11
(-x[4],-x[0],y[4],-z[6],-z[5],z[4],z[2],-z[1],), # 0---01-------001-10-
(x[3],y[4],y[2],z[7],-z[6],-z[5],), # -1---1-1----100-----
(-x[4],x[3],-y[4],y[3],-z[4],-z[1],-z[0],), # 01---01--------0--00
(-x[4],-x[2],-y[4],-y[2],-z[7],z[6],-z[3],-z[2],), # 0-0--0-0----01--00--
(-x[2],-x[1],-y[4],z[8],-z[6],z[5],-z[3],-z[2],z[0],), # --00-0-----1-01-00-1
(-x[2],-y[3],y[0],z[8],-z[5],z[4],-z[2],z[1],), # --0---0--1-1--01-01-
(x[3],-x[1],-y[4],-y[3],-z[5],z[2],-z[0],), # -1-0-00-------0--1-0
(-x[1],-x[0],-y[4],-y[2],z[8],-z[7],z[6],-z[4],z[1],), # ---000-0---101-0--1-
(x[2],x[1],-y[3],-y[2],-y[1],z[6],-z[5],), # --11--000----10-----
(-x[4],-x[2],-y[3],-y[1],-z[6],z[5],z[4],-z[2],z[0],), # 0-0---0-0----011-0-1
(-x[3],-x[1],y[3],y[2],-z[3],z[2],z[1],), # -0-0--11--------011-
(-x[4],x[2],y[3],y[1],z[8],z[6],-z[5],z[1],), # 0-1---1-1--1-10---1-
(-x[3],y[3],-y[2],-z[8],-z[7],z[6],), # -0----10---001------
(-x[4],z[9],z[6],z[5],z[4],z[2],-z[0],), # 0---------1--111-1-0
(-x[4],x[1],-y[4],y[1],z[7],-z[6],-z[5],z[0],), # 0--1-0--1---100----1
(x[4],-x[0],-y[4],y[2],-y[1],-z[5],z[4],-z[2],), # 1---00-10-----01-0--
(x[4],x[1],-x[0],-y[4],-y[2],z[7],-z[6],z[5],), # 1--100-0----101-----
(-x[3],x[2],-y[2],z[9],z[8],z[7],z[5],-z[4],), # -01----0--111-10----
(-x[3],-x[1],-y[3],-y[2],-z[9],z[8],z[4],), # -0-0--00--01---1----
(-x[3],-x[1],y[3],-y[1],-y[0],-z[7],z[5],-z[2],), # -0-0--1-00--0-1--0--
(-x[3],y[3],y[2],y[1],z[3],-z[0],), # -0----111-------1--0
(x[3],x[2],x[1],y[4],y[0],-z[4],), # -111-1---1-----0----
(-x[2],x[1],x[0],-y[4],-y[3],-y[2],-z[7],), # --011000----0-------
(-x[4],x[3],-y[4],-y[3],-z[4],z[1],-z[0],), # 01---00--------0--10
(-x[4],x[2],-y[4],-y[3],z[5],-z[2],-z[1],z[0],), # 0-1--00-------1--001
(-x[3],-y[3],-z[3],z[2],-z[1],-z[0],), # -0----0---------0100
(x[3],x[2],y[4],y[1],-z[5],-z[4],z[0],), # -11--1--1-----00---1
(-x[4],x[3],-x[2],-x[1],-y[4],y[2],y[1],-z[7],z[0],), # 0100-0-11---0------1
(-x[4],-x[3],x[2],x[1],-y[2],-y[1],-z[5],-z[4],z[0],), # 0011---00-----00---1
(x[3],-x[2],-x[1],y[3],-z[3],-z[0],), # -100--1---------0--0
(-x[3],-x[2],-x[1],z[9],-z[8],z[4],-z[0],), # -000------10---1---0
(x[3],y[3],-y[2],-y[1],-z[3],-z[0],), # -1----100-------0--0
(x[3],x[2],-y[3],-y[1],-z[3],z[2],z[1],), # -11---0-0-------011-
(x[3],x[2],-y[2],y[1],-z[8],z[6],z[0],), # -11----01--0-1-----1
(-x[2],-x[1],-y[4],-y[3],y[2],y[1],-z[5],-z[4],z[0],), # --00-0011-----00---1
(-x[4],-y[4],z[9],z[5],z[1],-z[0],), # 0----0----1---1---10
(x[3],y[1],-y[0],-z[3],z[1],z[0],), # -1------10------0-11
(-x[4],-x[2],y[4],-y[2],y[1],-y[0],-z[6],z[5],), # 0-0--1-010---01-----
(-x[3],-x[2],-y[4],y[2],-y[0],z[9],z[6],-z[2],-z[1],), # -00--0-1-01--1---00-
(-x[2],-x[1],-x[0],-y[4],z[9],-z[6],-z[5],-z[2],z[1],), # --0000----1--00--01-
(x[3],-y[3],-y[2],-y[1],z[3],-z[0],), # -1----000-------1--0
(-x[1],-x[0],-y[4],-y[2],-y[1],z[9],z[7],-z[5],), # ---000-00-1-1-0-----
(x[3],-y[4],-y[3],-y[2],-y[0],-z[8],-z[1],), # -1---000-0-0------0-
(-x[3],-x[2],x[1],-y[3],-y[2],z[8],-z[6],z[0],), # -001--00---1-0-----1
(-x[4],-x[2],-x[1],-y[1],-y[0],z[9],z[7],z[6],), # 0-00----001-11------
(-x[3],-x[2],x[1],-y[4],y[3],-y[2],-y[1],z[9],-z[6],), # -001-0100-1--0------
(-x[3],-y[3],-z[7],z[6],-z[5],z[4],-z[3],-z[1],), # -0----0-----01010-0-
(-z[9],z[8],z[6],z[5],z[3],-z[1],), # ----------01-11-1-0-
(-y[4],y[3],-y[2],y[1],-z[7],z[5],z[4],z[3],), # -----0101---0-111---
(-x[2],-y[2],z[7],z[6],z[5],z[4],-z[1],), # --0----0----1111--0-
(-x[4],x[3],-y[2],z[9],z[8],z[6],-z[5],z[0],), # 01-----0--11-10----1
(-x[1],-y[4],y[2],z[7],z[5],-z[4],-z[3],z[2],), # ---0-0-1----1-1001--
(x[2],y[2],-z[8],-z[6],-z[5],z[2],z[0],), # --1----1---0-00--1-1
(x[2],-y[4],-y[2],y[1],z[7],-z[6],z[5],-z[3],), # --1--0-01---101-0---
(x[2],x[0],y[2],y[0],-z[3],), # --1-1--1-1------0---
(-x[2],x[1],y[2],-z[9],z[7],-z[6],), # --01---1--0-10------
(-x[4],-y[3],-y[1],z[5],-z[4],-z[3],z[2],-z[1],), # 0-----0-0-----10010-
(x[2],-x[0],-y[4],y[2],z[7],z[6],z[4],-z[1],), # --1-00-1----11-1--0-
(x[3],x[2],x[1],-y[3],z[3],-z[0],), # -111--0---------1--0
(x[3],x[1],-y[3],-y[2],y[1],-z[3],z[2],), # -1-1--001-------01--
(x[4],x[3],y[4],y[3],-z[6],), # 11---11------0------
(-x[4],x[2],-y[3],-y[2],z[6],-z[4],-z[2],-z[1],), # 0-1---00-----1-0-00-
(x[3],-y[3],y[2],y[1],z[3],-z[0],), # -1----011-------1--0
(-y[3],-y[1],z[8],z[6],z[5],-z[4],z[2],z[1],), # ------0-0--1-110-11-
(x[4],x[2],y[3],z[7],-z[6],-z[5],), # 1-1---1-----100-----
(-x[4],x[2],y[2],-y[1],-y[0],-z[6],-z[5],-z[4],), # 0-1----100---000----
(-x[4],x[2],-y[3],-y[2],y[1],z[7],-z[6],-z[5],), # 0-1---001---100-----
(-x[4],x[2],-x[1],-y[4],y[2],-y[1],-z[8],z[6],), # 0-10-0-10--0-1------
(-x[4],-x[2],-y[3],-y[2],y[1],-z[8],-z[7],z[1],), # 0-0---001--00-----1-
(x[3],-x[2],-x[1],y[3],-y[2],-y[1],-z[6],z[5],), # -100--100----01-----
(-x[3],x[1],-y[1],-z[3],-z[2],z[1],), # -0-1----0-------001-
(x[2],y[3],y[0],-z[3],-z[1],), # --1---1--1------0-0-
(x[3],x[0],y[2],-z[3],-z[1],), # -1--1--1--------0-0-
(-x[2],x[1],-y[1],y[0],z[3],z[1],), # --01----01------1-1-
(-x[3],-y[3],-z[3],-z[2],z[1],-z[0],), # -0----0---------0010
(-x[3],x[2],x[1],-y[3],-z[3],-z[0],), # -011--0---------0--0
(-x[2],-y[2],y[1],z[8],z[7],z[6],z[4],z[1],), # --0----01--111-1--1-
(-x[4],-y[2],-y[1],z[8],z[7],z[3],-z[2],z[1],), # 0------00--11---101-
(-x[2],-y[2],-z[9],-z[7],-z[6],z[0],), # --0----0--0-00-----1
(x[2],x[0],y[1],-z[2],), # --1-1---1--------0--
(-x[4],x[3],x[2],y[2],z[8],-z[6],z[2],z[0],), # 011----1---1-0---1-1
(-x[3],-x[2],-x[0],-y[2],-y[1],z[7],z[3],z[2],), # -00-0--00---1---11--
(x[2],y[2],-z[7],-z[4],z[3],-z[1],z[0],), # --1----1----0--01-01
(-x[3],x[2],-y[3],-y[1],-y[0],z[3],z[2],z[1],), # -01---0-00------111-
(x[3],y[3],y[2],y[1],-z[3],), # -1----111-------0---
(x[3],-x[2],-x[1],-y[3],z[3],-z[0],), # -100--0---------1--0
(x[3],x[0],-y[2],z[3],-z[1],), # -1--1--0--------1-0-
(-x[2],y[3],y[0],z[3],-z[1],), # --0---1--1------1-0-
(-x[4],-x[2],-y[4],y[2],-y[1],-z[6],z[4],-z[1],), # 0-0--0-10----0-1--0-
(-x[4],-x[2],y[2],-y[1],z[8],-z[7],z[6],), # 0-0----10--101------
(-x[3],x[0],y[2],z[3],-z[1],), # -0--1--1--------1-0-
(x[4],x[2],-y[4],z[7],-z[6],-z[5],), # 1-1--0------100-----
(x[2],-y[3],y[0],z[3],-z[1],), # --1---0--1------1-0-
(-x[3],y[1],-y[0],z[3],z[1],z[0],), # -0------10------1-11
(x[4],x[2],x[1],-y[3],z[6],-z[5],), # 1-11--0------10-----
(-x[3],x[2],-y[4],y[2],-y[1],-y[0],z[7],-z[4],), # -01--0-100--1--0----
(-x[4],x[2],-y[4],y[3],z[8],-z[7],), # 0-1--01----10-------
(-x[4],-x[2],y[3],-y[1],-y[0],z[8],-z[6],-z[5],), # 0-0---1-00-1-00-----
(x[1],-y[2],y[0],z[2],-z[1],), # ---1---0-1-------10-
(-x[4],-x[3],x[1],-y[3],-y[1],-y[0],-z[6],z[5],), # 00-1--0-00---01-----
(-x[2],x[0],y[1],z[2],-z[1],), # --0-1---1--------10-
(-x[2],-y[3],-y[1],z[9],z[7],z[6],z[5],-z[2],), # --0---0-0-1-111--0--
(-x[3],-x[1],-x[0],-y[4],-y[3],y[1],-z[6],z[5],), # -0-0000-1----01-----
(-x[3],-x[2],-x[1],-y[3],-z[3],-z[0],), # -000--0---------0--0
(-x[2],x[1],-y[4],-y[3],z[9],-z[7],-z[6],z[5],), # --01-00---1-001-----
(-x[3],x[0],-y[2],-z[3],-z[1],), # -0--1--0--------0-0-
(-x[4],-x[2],x[1],-y[2],-y[0],z[8],z[6],-z[5],), # 0-01---0-0-1-10-----
(-x[3],y[4],-y[2],-y[1],z[7],z[6],z[4],), # -0---1-00---11-1----
(-x[2],-y[3],y[0],-z[3],-z[1],), # --0---0--1------0-0-
(-x[3],x[2],x[1],-y[2],y[1],z[5],z[0],), # -011---01-----1----1
(x[2],-x[1],-y[4],z[9],z[8],z[6],z[5],), # --10-0----11-11-----
(-x[2],x[1],-y[3],y[2],y[1],z[5],z[0],), # --01--011-----1----1
(-x[2],x[1],-y[4],y[2],z[9],-z[7],z[6],z[1],), # --01-0-1--1-01----1-
(-x[3],-x[2],-y[3],-y[2],y[1],z[8],-z[6],z[1],), # -00---001--1-0----1-
(-x[4],x[3],y[3],-y[1],z[9],z[5],-z[4],z[1],), # 01----1-0-1---10--1-
(-x[4],-x[1],-y[4],-y[1],z[7],-z[6],-z[5],z[0],), # 0--0-0--0---100----1
(-x[4],-y[4],-y[3],-y[2],z[5],z[3],-z[1],z[0],), # 0----000------1-1-01
(-x[2],-x[1],-y[4],y[3],y[2],z[9],-z[6],z[5],), # --00-011--1--01-----
(-x[1],x[0],-y[4],-y[3],-y[2],-y[1],-z[6],), # ---010000----0------
(-x[4],-x[3],-x[2],y[4],-y[1],-z[6],-z[5],), # 000--1--0----00-----
(-x[3],-x[2],-y[3],y[2],z[9],z[8],-z[6],z[5],), # -00---01--11-01-----
(-x[3],-y[4],-y[2],z[9],z[8],z[6],-z[1],), # -0---0-0--11-1----0-
(-x[1],-y[4],-y[3],-y[1],z[8],-z[6],-z[5],z[0],), # ---0-00-0--1-00----1
(-x[4],x[2],x[1],-y[4],-y[3],-y[2],z[7],z[0],), # 0-11-000----1------1
(-x[4],-x[3],-x[2],-y[4],y[2],y[1],z[7],z[0],), # 000--0-11---1------1
(-x[4],-x[3],x[2],y[3],-y[2],-y[1],z[9],-z[6],), # 001---100-1--0------
(-x[3],-x[2],-x[1],-y[4],y[1],z[8],z[6],z[0],), # -000-0--1--1-1-----1
(-x[4],x[3],x[2],x[1],-y[1],z[5],z[0],), # 0111----0-----1----1
(x[2],-y[4],-y[3],-y[2],z[9],z[8],z[4],-z[1],), # --1--000--11---1--0-
(-x[3],-x[2],-y[2],-y[1],z[9],z[8],z[6],z[5],), # -00----00-11-11-----
(-x[2],-y[4],y[3],z[9],z[8],z[6],-z[5],z[0],), # --0--01---11-10----1
(-x[4],-x[2],x[1],-y[3],-y[2],-y[1],z[9],-z[6],), # 0-01--000-1--0------
(-x[1],-y[2],z[7],z[6],z[5],z[4],z[3],), # ---0---0----11111---
(x[3],-y[4],y[2],z[8],-z[7],-z[6],), # -1---0-1---100------
(-x[4],-x[2],-y[3],y[2],-y[1],-z[8],-z[7],), # 0-0---010--00-------
(-x[4],y[3],-y[2],-y[1],z[7],z[5],-z[3],), # 0-----100---1-1-0---
(x[1],y[3],y[1],y[0],-z[3],), # ---1--1-11------0---
(x[4],y[3],-z[8],-z[7],), # 1-----1----00-------
(x[3],x[2],x[1],y[3],-z[3],), # -111--1---------0---
(x[3],y[4],-z[8],-z[7],), # -1---1-----00-------
(x[2],x[1],-y[4],y[3],z[8],-z[6],z[1],), # --11-01----1-0----1-
(x[4],-x[3],y[3],y[2],z[7],-z[6],), # 10----11----10------
(x[4],y[4],y[3],-z[7],), # 1----11-----0-------
(x[3],x[2],y[4],-y[3],z[7],-z[6],), # -11--10-----10------
(-x[1],x[0],-y[1],z[2],z[1],), # ---01---0--------11-
(x[2],x[0],-y[1],z[2],-z[1],), # --1-1---0--------10-
(-x[3],x[2],y[4],-y[2],-z[7],-z[6],), # -01--1-0----00------
(-x[1],y[2],y[0],z[2],-z[1],), # ---0---1-1-------10-
(x[3],y[3],z[8],-z[7],-z[6],), # -1----1----100------
(y[2],y[1],y[0],-z[2],), # -------111-------0--
(-x[3],y[4],y[2],y[1],z[6],-z[5],), # -0---1-11----10-----
(-x[4],y[4],y[2],y[1],z[7],-z[6],), # 0----1-11---10------
(-x[2],x[0],-y[1],-z[2],-z[1],), # --0-1---0--------00-
(-x[3],x[2],-y[3],y[2],z[9],-z[7],z[6],), # -01---01--1-01------
(-x[1],-y[2],y[0],-z[2],-z[1],), # ---0---0-1-------00-
(-x[4],x[3],-y[2],y[1],z[9],z[8],z[6],), # 01-----01-11-1------
(-x[4],-x[2],-y[4],-y[1],z[9],z[5],z[2],), # 0-0--0--0-1---1--1--
(-x[4],-x[2],-y[4],-y[2],z[9],z[7],), # 0-0--0-0--1-1-------
(-x[3],-y[3],y[2],y[1],-z[8],-z[7],), # -0----011--00-------
(y[3],-z[9],-z[8],), # ------1---00--------
(-x[3],x[2],-y[4],-y[3],-z[8],-z[7],), # -01--00----00-------
(x[2],y[2],-z[2],-z[0],), # --1----1---------0-0
(-x[3],x[2],x[1],y[3],-y[0],z[3],), # -011--1--0------1---
(x[0],y[1],y[0],-z[2],), # ----1---11-------0--
(x[4],x[3],y[4],-z[7],), # 11---1------0-------
(x[2],y[2],-z[5],-z[3],z[1],z[0],), # --1----1------0-0-11
(x[2],x[1],x[0],-z[2],), # --111------------0--
(x[2],-y[2],z[2],-z[0],), # --1----0---------1-0
(-x[2],y[2],z[2],-z[0],), # --0----1---------1-0
(-x[2],-y[2],-z[2],-z[0],), # --0----0---------0-0
(-x[2],x[1],-y[0],z[2],z[0],), # --01-----0-------1-1
(x[1],-y[1],z[1],-z[0],), # ---1----0---------10
(-x[1],-y[1],-z[1],-z[0],), # ---0----0---------00
(-x[1],y[1],z[1],-z[0],), # ---0----1---------10
(-x[0],-y[2],y[1],z[2],z[0],), # ----0--01--------1-1
(-x[4],y[3],-y[2],z[9],z[7],z[6],), # 0-----10--1-11------
(x[3],-x[2],-y[4],z[9],z[7],z[6],), # -10--0----1-11------
(-x[3],x[2],-y[4],y[3],z[9],z[7],), # -01--01---1-1-------
(-x[4],x[3],-y[3],y[2],z[9],z[7],), # 01----01--1-1-------
(-x[4],x[3],-y[4],y[3],z[8],z[0],), # 01---01----1-------1
(x[3],-z[9],-z[8],), # -1--------00--------
(-x[4],y[3],y[2],z[8],-z[7],), # 0-----11---10-------
(x[3],x[2],-y[4],z[8],-z[7],), # -11--0-----10-------
(x[1],y[2],y[0],-z[2],), # ---1---1-1-------0--
(-x[3],-y[3],z[8],z[7],z[6],), # -0----0----111------
(x[4],x[3],-z[8],), # 11---------0--------
(y[4],y[3],-z[8],), # -----11----0--------
(-x[1],-y[0],z[1],z[0],), # ---0-----0--------11
(-x[0],-y[1],z[1],z[0],), # ----0---0---------11
(-x[4],-x[3],-y[4],-y[3],z[9],), # 00---00---1---------
(x[4],y[4],-z[8],), # 1----1-----0--------
(y[4],-z[9],), # -----1----0---------
(x[4],-z[9],), # 1---------0---------
(-x[0],-y[0],z[0],), # ----0----0---------1
(x[0],y[0],-z[1],), # ----1----1--------0-
(x[1],y[1],-z[1],), # ---1----1---------0-
(x[0],-z[0],), # ----1--------------0
(y[0],-z[0],), # ---------1---------0
]
def mult_6x6(x,y,z): #6 bit x times 6 bit y = 12 bit z
return [(-x[5],-x[3],-x[2],-x[0],-y[5],y[3],-y[1],z[11],-z[7],z[1],), # 0-00-00-1-0-1---0-----1-
(-x[4],-x[3],-x[2],-x[1],-y[5],-y[0],z[10],z[7],z[1],), # -0000-0----0-1--1-----1-
(x[4],x[3],x[0],y[4],-y[2],z[5],z[4],z[3],-z[2],), # -11--1-1-0--------1110--
(-x[3],-x[1],x[0],-y[4],-y[2],y[1],z[10],z[9],-z[6],-z[5],), # --0-01-0-01--11--00-----
(x[5],-x[3],y[4],-y[3],y[1],z[7],z[6],z[2],-z[1],-z[0],), # 1-0----10-1-----11---100
(x[4],x[3],-x[2],-x[1],-y[4],-y[3],-z[4],-z[1],-z[0],), # -1100--00----------0--00
(-x[3],-x[2],-x[1],-y[5],y[3],y[1],z[11],z[10],z[7],z[2],z[1],), # --000-0-1-1-11--1----11-
(-x[4],-x[3],x[2],-y[3],-y[2],y[1],z[11],z[10],-z[6],-z[5],z[2],z[1],), # -001----001-11---00--11-
(x[4],x[3],y[5],y[4],-y[2],y[0],z[5],-z[3],z[2],-z[1],), # -11---11-0-1------1-010-
(x[3],y[5],y[2],y[1],z[8],-z[7],-z[5],-z[2],-z[1],z[0],), # --1---1--11----10-0--001
(-x[4],-x[3],x[2],-y[4],-y[2],-y[1],z[10],-z[7],z[6],), # -001---0-00--1--01------
(x[4],x[0],y[5],y[4],y[3],-z[6],-z[3],z[2],-z[1],), # -1---1111--------0--010-
(x[5],x[4],-x[3],x[0],y[3],z[5],z[4],z[3],-z[2],z[1],), # 110--1--1---------11101-
(-x[4],x[0],y[4],-y[2],-y[1],z[11],z[8],z[5],-z[4],-z[2],-z[1],), # -0---1-1-00-1--1--10-00-
(-x[5],x[4],-x[3],y[4],-y[3],-y[1],y[0],-z[6],-z[4],z[1],), # 010----10-01-----0-0--1-
(-x[4],-x[2],y[5],-y[3],-y[2],-y[1],z[9],-z[6],-z[2],), # -0-0--1-000---1--0---0--
(-x[5],-x[4],-x[2],-y[3],-y[2],-y[1],z[11],z[10],z[6],-z[2],-z[1],), # 00-0----000-11---1---00-
(x[5],y[5],y[4],y[3],y[2],-z[5],z[4],z[2],-z[1],-z[0],), # 1-----1111--------01-100
(x[5],x[2],x[1],y[5],-y[3],z[7],-z[5],-z[3],-z[0],), # 1--11-1-0-------1-0-0--0
(-x[5],-x[2],-y[4],-y[1],z[11],z[10],z[8],-z[6],-z[3],), # 0--0---0--0-11-1-0--0---
(x[5],x[4],x[3],x[1],y[5],y[3],y[2],-z[5],), # 111-1-1-11--------0-----
(-x[5],-x[3],-x[2],x[1],-y[5],y[4],-y[1],z[9],z[6],z[2],z[1],), # 0-001-01--0---1--1---11-
(-x[5],-x[3],-x[2],x[1],-x[0],-y[5],y[4],z[10],-z[6],z[5],z[0],), # 0-001001-----1---01----1
(x[5],x[2],x[1],y[5],y[4],y[3],z[5],-z[3],-z[2],), # 1--11-111---------1-00--
(-x[5],-x[3],-x[2],-y[5],-y[4],y[3],-y[2],y[1],-z[9],), # 0-00--00101---0---------
(-x[3],y[4],y[2],-z[9],-z[6],z[5],z[3],-z[0],), # --0----1-1----0--01-1--0
(x[2],x[1],-y[5],y[4],-y[3],-z[7],-z[6],z[3],-z[2],), # ---11-010-------00--10--
(x[4],-x[3],y[3],y[1],z[4],z[3],z[2],-z[1],), # -10-----1-1--------1110-
(-x[4],x[3],-y[5],-y[3],y[0],z[9],-z[6],-z[5],-z[3],z[2],), # -01---0-0--1--1--00-01--
(-x[4],-x[1],-y[5],-y[4],-y[2],y[1],z[11],z[6],z[2],-z[0],), # -0--0-00-01-1----1---1-0
(-x[4],-x[3],-x[2],y[5],y[4],y[1],-z[6],-z[1],), # -000--11--1------0----0-
(-x[4],x[3],-x[0],y[5],y[4],-y[2],-z[5],z[4],z[2],z[0],), # -01--011-0--------01-1-1
(x[5],-x[3],x[1],x[0],-y[3],-y[2],y[1],-z[5],-z[4],-z[2],), # 1-0-11--001-------00-0--
(-x[4],-x[3],y[5],y[4],-y[3],-y[2],y[0],-z[5],-z[2],-z[1],), # -00---1100-1------0--00-
(-x[3],x[1],y[5],y[4],-y[3],y[1],y[0],-z[5],-z[4],), # --0-1-110-11------00----
(x[4],-x[1],y[5],-y[4],y[0],z[5],-z[4],z[3],-z[2],-z[1],), # -1--0-10---1------10100-
(-x[5],-x[4],x[3],-x[1],y[5],y[3],z[10],-z[5],z[2],z[1],-z[0],), # 001-0-1-1----1----0--110
(x[5],x[4],y[5],z[7],-z[6],-z[5],z[4],-z[2],-z[0],), # 11----1---------1001-0-0
(x[5],-x[4],x[3],x[2],x[0],-y[4],z[8],-z[6],z[3],), # 1011-1-0-------1-0--1---
(x[2],y[4],-y[3],-y[1],-z[11],z[7],z[6],z[3],-z[0],), # ---1---10-0-0---11--1--0
(-x[5],x[0],y[1],y[0],-z[8],z[6],-z[5],z[4],-z[3],), # 0----1----11---0-1010---
(y[5],-y[3],y[1],-z[10],z[7],z[6],z[5],-z[2],-z[0],), # ------1-0-1--0--111--0-0
(-x[5],-x[2],-y[5],-y[3],y[2],z[11],z[7],-z[6],z[5],z[3],), # 0--0--0-01--1---101-1---
(x[4],x[2],x[1],-y[3],-y[2],y[1],-z[6],z[5],z[2],), # -1-11---001------01--1--
(-x[4],-y[4],y[3],-y[2],-y[1],z[5],-z[4],-z[3],z[1],), # -0-----0100-------100-1-
(-x[4],y[5],-y[2],-y[1],-z[10],z[9],z[8],z[6],-z[3],z[2],z[1],), # -0----1--00--011-1--011-
(-x[2],-y[3],y[1],z[11],-z[8],-z[7],z[5],z[4],z[1],-z[0],), # ---0----0-1-1--00-11--10
(x[4],x[0],y[1],-z[9],-z[8],z[6],z[5],z[3],-z[2],-z[1],), # -1---1----1---00-11-100-
(-x[4],-x[2],-x[1],y[5],-y[3],-y[1],-y[0],z[9],z[7],z[6],), # -0-00-1-0-00--1-11------
(-x[4],x[2],y[4],-y[3],y[2],-z[5],z[4],-z[2],z[1],), # -0-1---101--------01-01-
(x[4],x[3],-x[2],-x[1],x[0],-y[4],-y[3],y[2],-z[5],z[1],), # -11001-001--------0---1-
(-x[3],x[1],-y[3],y[0],-z[11],z[7],-z[6],-z[5],-z[1],), # --0-1---0--10---100---0-
(-x[2],y[5],-y[4],-y[3],z[10],-z[6],z[5],-z[3],-z[2],z[1],-z[0],), # ---0--100----1---01-0010
(-x[4],-x[3],x[2],y[4],y[3],-y[1],-z[4],-z[1],-z[0],), # -001---11-0--------0--00
(-x[5],x[4],-x[3],x[2],-y[2],z[10],-z[9],z[8],-z[7],z[0],), # 0101-----0---1010------1
(-x[5],x[4],x[3],x[2],-y[5],-y[4],-y[0],-z[6],z[2],-z[1],z[0],), # 0111--00---0-----0---101
(x[3],-x[2],y[5],y[0],-z[8],z[7],-z[6],-z[2],-z[1],), # --10--1----1---010---00-
(x[5],x[3],-x[2],y[3],-y[2],-y[0],z[5],z[4],z[3],-z[2],), # 1-10----10-0------1110--
(x[3],-x[2],-x[1],y[5],y[3],y[0],-z[10],-z[6],-z[5],), # --100-1-1--1-0---00-----
(x[4],-x[2],-x[1],y[4],-y[3],z[5],-z[4],-z[3],-z[2],z[1],), # -1-00--10---------10001-
(x[3],-x[2],-x[0],y[5],y[3],-y[2],z[5],z[4],z[3],-z[2],), # --10-01-10--------1110--
(-x[5],-x[4],x[0],-y[3],-y[1],-y[0],z[5],-z[4],-z[3],z[1],), # 00---1--0-00------100-1-
(x[5],-x[4],x[3],x[1],x[0],-y[3],-z[5],z[4],z[3],-z[2],), # 101-11--0---------0110--
(x[0],-y[5],-y[4],y[3],y[1],z[11],z[9],-z[6],-z[2],-z[1],), # -----1001-1-1-1--0---00-
(x[5],-x[2],x[1],y[5],-y[4],-y[3],-y[2],-z[7],z[2],z[0],), # 1--01-1000------0----1-1
(-x[4],-x[2],y[5],-y[4],y[0],z[10],-z[6],z[4],z[2],-z[1],), # -0-0--10---1-1---0-1-10-
(x[1],y[4],-y[3],-y[1],z[8],z[7],-z[6],-z[2],z[1],), # ----1--10-0----110---01-
(-x[5],-x[3],x[1],x[0],y[3],-y[2],y[1],-z[5],-z[4],-z[2],), # 0-0-11--101-------00-0--
(-y[5],-y[4],-y[2],-y[1],z[11],z[10],z[5],-z[2],-z[1],-z[0],), # ------00-00-11----1--000
(-x[4],-y[5],-y[4],z[11],z[10],z[8],), # -0----00----11-1--------
(-x[3],x[1],-y[5],y[4],y[1],y[0],z[5],-z[4],-z[3],), # --0-1-01--11------100---
(x[3],x[1],-y[3],y[2],y[1],-z[10],z[8],z[7],z[6],), # --1-1---011--0-111------
(y[5],y[4],-y[3],z[9],z[8],z[5],-z[4],z[3],-z[2],-z[0],), # ------110-----11--1010-0
(x[1],y[1],-z[10],z[8],-z[7],-z[4],-z[3],-z[0],), # ----1-----1--0-10--00--0
(x[4],-x[3],x[2],-y[4],y[3],-y[1],-z[4],-z[1],-z[0],), # -101---01-0--------0--00
(x[5],y[5],y[4],y[1],z[8],-z[5],-z[4],z[2],z[1],-z[0],), # 1-----11--1----1--00-110
(-x[5],x[1],-y[5],-y[2],-y[1],y[0],z[9],z[7],z[6],z[1],), # 0---1-0--001--1-11----1-
(x[5],y[5],y[3],-z[7],z[6],-z[5],z[3],-z[1],-z[0],), # 1-----1-1-------010-1-00
(x[2],y[1],z[11],-z[8],z[7],-z[5],-z[4],z[3],-z[1],-z[0],), # ---1------1-1--01-001-00
(-x[5],x[4],x[1],x[0],-y[4],y[2],y[0],z[6],-z[5],-z[4],), # 01--11-0-1-1-----100----
(x[5],x[0],-z[10],z[7],z[6],z[5],-z[2],-z[1],), # 1----1-------0--111--00-
(x[5],x[3],-x[1],y[5],y[4],y[3],-z[5],-z[2],-z[0],), # 1-1-0-111---------0--0-0
(y[4],-y[3],-y[1],-z[10],-z[5],-z[4],-z[3],-z[2],-z[0],), # -------10-0--0----0000-0
(x[4],-x[1],y[5],y[2],-y[0],-z[8],-z[5],-z[3],-z[2],-z[1],), # -1--0-1--1-0---0--0-000-
(x[4],-x[3],x[0],-y[4],-y[3],y[2],y[0],-z[5],z[3],-z[2],), # -10--1-001-1------0-10--
(-x[4],-x[3],-y[2],y[1],z[10],z[9],-z[7],-z[2],z[1],-z[0],), # -00------01--11-0----010
(x[5],x[4],-x[1],y[5],-y[4],-z[6],-z[4],z[2],-z[1],-z[0],), # 11--0-10---------0-0-100
(x[5],-x[4],-y[3],-y[2],y[1],z[6],z[5],-z[4],-z[2],-z[0],), # 10------001------110-0-0
(x[4],x[1],y[4],y[1],-z[9],-z[8],-z[7],z[4],z[0],), # -1--1--1--1---000--1---1
(-x[5],-x[3],x[2],-y[1],y[0],z[10],-z[8],-z[6],z[4],z[1],), # 0-01------01-1-0-0-1--1-
(x[0],y[4],-y[3],-y[2],-y[1],z[9],z[6],-z[5],z[3],-z[1],), # -----1-1000---1--10-1-0-
(-x[4],-x[2],-y[4],y[3],-y[1],y[0],z[5],z[4],z[3],), # -0-0---01-01------111---
(-x[4],-x[3],x[0],-y[3],y[1],z[4],z[3],z[2],-z[1],), # -00--1--0-1--------1110-
(x[3],-x[1],-y[5],y[4],-y[3],y[0],-z[5],z[4],z[1],), # --1-0-010--1------01--1-
(-x[5],x[4],-x[2],x[0],-y[4],y[3],z[5],z[4],z[2],-z[1],), # 01-0-1-01---------11-10-
(-x[5],x[2],y[5],y[3],y[0],-z[7],-z[6],z[5],-z[4],-z[3],), # 0--1--1-1--1----00100---
(x[3],-x[2],x[1],-y[5],-y[4],-z[7],z[5],-z[4],-z[3],-z[1],), # --101-00--------0-100-0-
(-x[2],x[0],-y[5],y[4],-y[3],y[0],z[9],z[6],-z[3],-z[2],), # ---0-1010--1--1--1--00--
(x[3],-x[2],y[5],y[2],-z[9],-z[8],z[7],z[6],), # --10--1--1----0011------
(-x[5],-y[4],y[2],y[1],z[11],z[10],-z[5],-z[4],-z[1],-z[0],), # 0------0-11-11----00--00
(-x[3],y[2],-y[1],z[9],z[7],z[5],z[4],z[1],-z[0],), # --0------10---1-1-11--10
(-x[3],-x[2],-y[4],-y[3],-y[0],z[10],-z[8],z[6],z[4],z[3],-z[2],z[0],), # --00---00--0-1-0-1-110-1
(x[3],x[2],-x[1],-y[5],y[3],-y[1],z[10],-z[8],z[7],), # --110-0-1-0--1-01-------
(-x[4],x[3],x[1],-y[4],-y[3],y[2],z[4],-z[2],-z[1],), # -01-1--001---------1-00-
(-x[5],x[4],y[5],y[2],-y[1],-y[0],z[9],z[7],z[5],z[3],-z[2],), # 01----1--100--1-1-1-10--
(-x[2],-x[1],-y[5],z[11],z[10],z[8],z[5],z[4],-z[1],-z[0],), # ---00-0-----11-1--11--00
(-x[5],-x[4],x[1],x[0],-y[3],-y[2],y[1],z[5],z[3],-z[2],), # 00--11--001-------1-10--
(x[0],-y[4],y[1],-z[10],-z[9],-z[6],-z[5],-z[1],), # -----1-0--1--00--00---0-
(x[5],x[4],x[2],x[1],y[3],z[8],-z[6],z[1],), # 11-11---1------1-0----1-
(x[5],-x[4],-x[3],x[1],x[0],-y[4],y[0],z[6],-z[3],), # 100-11-0---1-----1--0---
(-x[5],x[4],-y[4],y[3],y[1],z[5],-z[4],z[2],-z[1],z[0],), # 01-----01-1-------10-101
(y[5],-y[4],y[2],y[0],z[10],z[9],z[6],-z[5],-z[3],-z[2],), # ------10-1-1-11--10-00--
(x[4],x[1],x[0],-y[4],y[3],y[1],z[6],-z[4],z[3],), # -1--11-01-1------1-01---
(x[4],-x[3],y[5],-y[4],y[0],-z[5],-z[2],-z[1],), # -10---10---1------0--00-
(x[4],y[5],y[4],y[3],y[1],y[0],-z[6],), # -1----111-11-----0------
(-x[5],x[4],-x[2],y[5],y[3],-y[1],z[8],z[3],z[2],-z[0],), # 01-0--1-1-0----1----11-0
(x[2],x[0],y[5],-y[2],z[10],-z[6],z[4],z[3],z[2],-z[1],), # ---1-11--0---1---0-1110-
(-x[3],-x[2],y[5],y[3],-y[2],-z[9],-z[8],z[7],z[5],), # --00--1-10----001-1-----
(x[4],-y[5],y[3],-y[2],-y[0],-z[6],z[5],z[3],-z[1],z[0],), # -1----0-10-0-----01-1-01
(x[5],-x[2],x[0],-y[4],y[3],-y[2],-z[5],z[4],-z[3],-z[1],), # 1--0-1-010--------010-0-
(x[5],x[3],x[0],y[4],y[3],y[1],-z[5],z[2],), # 1-1--1-11-1-------0--1--
(x[5],-x[4],x[0],y[4],-y[2],y[1],z[5],z[4],-z[3],-z[1],), # 10---1-1-01-------110-0-
(-y[5],y[2],y[1],z[6],z[5],-z[3],z[2],z[1],-z[0],), # ------0--11------11-0110
(x[4],x[1],y[4],y[3],y[0],z[8],z[7],-z[5],-z[3],), # -1--1--11--1---11-0-0---
(x[5],-x[4],-x[3],x[1],-y[4],-y[2],-z[6],z[2],-z[1],), # 100-1--0-0-------0---10-
(x[5],x[4],-x[2],x[0],y[4],-y[3],z[5],-z[4],-z[2],-z[1],), # 11-0-1-10---------10-00-
(-x[3],y[5],y[4],y[3],y[1],y[0],z[5],-z[2],), # --0---111-11------1--0--
(x[5],x[1],y[4],-y[3],-y[2],y[0],-z[6],-z[3],z[2],), # 1---1--100-1-----0--01--
(-x[4],x[2],y[5],y[4],y[3],-y[2],y[0],-z[5],-z[4],-z[2],), # -0-1--1110-1------00-0--
(x[4],-x[3],y[5],y[4],-y[2],y[0],z[5],-z[4],-z[2],-z[1],), # -10---11-0-1------10-00-
(-x[4],x[0],y[5],-y[3],y[2],z[6],z[5],z[3],-z[1],), # -0---11-01-------11-1-0-
(x[5],-x[3],x[2],y[4],y[3],-y[1],-z[6],-z[5],z[1],-z[0],), # 1-01---11-0------00---10
(x[4],x[3],y[5],y[4],y[2],-z[7],-z[5],z[1],z[0],), # -11---11-1------0-0---11
(-x[4],-x[3],x[0],y[3],-y[1],-z[4],-z[3],-z[2],-z[1],), # -00--1--1-0--------0000-
(x[3],-y[4],y[3],-y[2],y[0],-z[4],-z[3],-z[2],-z[1],), # --1----010-1-------0000-
(x[4],-x[2],y[3],-y[2],-y[0],z[4],-z[3],-z[2],), # -1-0----10-0-------100--
(-x[5],-x[4],x[3],y[5],y[4],y[2],-y[1],-z[5],-z[1],-z[0],), # 001---11-10-------0---00
(x[5],x[4],x[0],-y[4],y[3],z[5],-z[2],-z[1],), # 11---1-01---------1--00-
(-x[5],x[4],-x[3],x[0],y[5],-y[4],y[2],y[0],-z[6],-z[3],-z[2],), # 010--110-1-1-----0--00--
(x[4],-x[3],-x[2],-x[1],y[5],y[0],-z[5],-z[1],), # -1000-1----1------0---0-
(x[3],x[1],-y[5],-y[3],-y[2],z[11],z[10],z[5],z[1],-z[0],), # --1-1-0-00--11----1---10
(x[5],x[4],-x[3],x[0],-y[4],y[3],-z[5],z[3],z[2],-z[1],), # 110--1-01---------0-110-
(-x[5],x[4],-x[0],y[4],-y[3],-y[2],-y[1],-z[7],-z[3],z[1],), # 01---0-1000-----0---0-1-
(-x[4],-x[2],x[1],y[5],y[1],y[0],z[6],-z[4],-z[2],), # -0-01-1---11-----1-0-0--
(x[4],-x[3],x[0],-y[4],-y[3],z[11],z[10],-z[5],-z[3],-z[2],-z[1],), # -10--1-00---11----0-000-
(y[2],y[1],-z[11],z[9],z[8],-z[6],-z[5],z[4],z[3],), # ---------11-0-11-0011---
(x[5],x[2],x[0],-y[4],y[3],-y[2],-y[1],-z[5],-z[4],-z[1],), # 1--1-1-0100-------00--0-
(x[3],x[2],y[5],y[2],y[0],-z[10],-z[6],-z[2],), # --11--1--1-1-0---0---0--
(-x[5],-x[3],x[1],-y[2],z[11],z[10],-z[6],z[2],-z[1],), # 0-0-1----0--11---0---10-
(x[4],-y[5],-y[4],y[3],y[2],y[0],-z[5],-z[4],-z[2],-z[1],), # -1----0011-1------00-00-
(x[2],-y[4],-z[11],z[9],-z[7],z[6],-z[2],-z[1],-z[0],), # ---1---0----0-1-01---000
(y[4],y[3],z[7],-z[6],z[5],z[4],z[3],-z[1],-z[0],), # -------11-------10111-00
(-x[5],x[2],x[0],y[3],y[0],z[6],-z[4],z[2],), # 0--1-1--1--1-----1-0-1--
(x[4],x[2],x[0],-y[2],-z[11],-z[7],z[4],z[3],), # -1-1-1---0--0---0--11---
(y[4],-y[1],-z[11],-z[8],z[5],z[4],z[2],z[0],), # -------1--0-0--0--11-1-1
(-y[5],y[4],y[2],-y[1],z[9],-z[6],z[2],-z[1],-z[0],), # ------01-10---1--0---100
(-x[2],-x[1],-y[4],-y[1],-z[11],z[8],-z[6],z[5],-z[3],z[1],), # ---00--0--0-0--1-01-0-1-
(x[1],y[5],-y[2],z[7],z[6],-z[5],z[3],-z[2],-z[0],), # ----1-1--0------110-10-0
(-x[3],-x[1],x[0],-y[5],-z[10],-z[7],-z[6],-z[4],z[2],z[1],), # --0-010------0--00-0-11-
(-x[5],-x[3],-y[3],-y[1],y[0],-z[6],z[3],z[2],z[1],), # 0-0-----0-01-----0--111-
(x[5],y[5],y[3],y[1],-z[5],z[4],-z[3],-z[1],-z[0],), # 1-----1-1-1-------010-00
(x[1],-y[5],y[4],y[1],y[0],z[9],z[8],-z[6],z[3],-z[2],), # ----1-01--11--11-0--10--
(-x[4],-x[3],x[2],-y[5],-y[4],y[2],y[1],z[7],-z[5],z[3],z[0],), # -001--00-11-----1-0-1--1
(-y[4],-y[3],y[1],-z[11],z[10],z[7],z[6],z[5],-z[1],-z[0],), # -------00-1-01--111---00
(x[3],x[2],x[0],-y[5],z[10],-z[9],-z[6],-z[5],-z[3],z[1],), # --11-10------10--00-0-1-
(-y[4],-y[3],-y[1],-z[11],z[8],-z[7],z[2],-z[0],), # -------00-0-0--10----1-0
(-x[4],y[5],y[1],-z[8],-z[6],-z[5],z[4],z[2],z[1],-z[0],), # -0----1---1----0-001-110
(-x[4],x[3],x[0],-y[3],y[0],z[10],z[7],-z[6],-z[5],-z[2],), # -01--1--0--1-1--100--0--
(-x[4],x[3],x[0],y[3],-y[1],-z[4],z[3],z[2],-z[1],), # -01--1--1-0--------0110-
(x[5],x[2],y[4],-y[1],-z[8],z[7],z[6],-z[5],z[4],z[0],), # 1--1---1--0----01101---1
(x[5],-x[4],-x[2],y[3],-z[8],-z[6],z[5],z[4],z[2],-z[1],), # 10-0----1------0-011-10-
(-x[5],x[4],x[3],x[1],-y[3],y[2],z[10],z[9],-z[6],-z[5],-z[2],), # 011-1---01---11--00--0--
(x[5],x[3],x[1],y[5],-y[4],z[8],-z[7],-z[5],), # 1-1-1-10-------10-0-----
(x[5],x[1],y[5],y[3],y[2],y[1],z[8],-z[5],), # 1---1-1-111----1--0-----
(x[3],-x[1],x[0],y[5],-y[3],-z[6],z[3],z[2],z[1],), # --1-011-0--------0--111-
(x[4],x[3],y[5],y[4],-z[8],z[6],z[5],-z[4],-z[2],z[0],), # -11---11-------0-110-0-1
(x[2],y[5],y[1],-z[10],-z[8],-z[7],-z[6],z[0],), # ---1--1---1--0-000-----1
(x[3],-x[2],x[0],y[3],-y[2],-z[5],z[3],z[2],), # --10-1--10--------0-11--
(-x[3],-x[2],-y[3],-y[2],y[1],z[10],z[9],-z[7],-z[6],z[1],), # --00----001--11-00----1-
(x[5],-y[5],-y[3],y[2],-z[5],z[4],z[3],z[2],-z[1],-z[0],), # 1-----0-01--------011100
(x[4],x[1],-y[5],y[0],z[11],z[9],-z[6],z[5],-z[3],-z[1],), # -1--1-0----11-1--01-0-0-
(-x[5],x[1],x[0],-y[4],-y[2],y[1],-z[6],z[5],-z[4],-z[2],), # 0---11-0-01------010-0--
(-x[5],x[1],y[4],-y[2],y[0],z[7],z[6],-z[5],z[4],-z[3],), # 0---1--1-0-1----11010---
(x[1],y[5],-y[2],-z[10],z[9],-z[6],-z[5],z[1],-z[0],), # ----1-1--0---01--00---10
(-x[3],x[2],-x[1],-x[0],z[10],-z[9],z[7],z[5],z[4],-z[3],z[1],), # --0100-------10-1-110-1-
(-x[4],-x[3],y[5],-y[2],z[9],z[7],z[5],-z[4],z[2],-z[0],), # -00---1--0----1-1-10-1-0
(-x[3],x[0],y[4],y[2],y[0],z[11],z[10],-z[9],z[8],z[6],-z[3],), # --0--1-1-1-11101-1--0---
(-x[4],x[3],x[1],x[0],-y[3],y[2],-z[11],z[7],-z[3],), # -01-11--01--0---1---0---
(-x[5],x[2],x[1],-y[5],-y[4],y[3],z[6],-z[3],z[1],-z[0],), # 0--11-001--------1--0-10
(x[3],x[1],-y[4],y[3],-y[2],z[9],-z[8],z[6],-z[5],-z[1],), # --1-1--010----10-10---0-
(x[5],x[3],-x[2],y[4],-y[1],z[7],-z[6],-z[4],-z[1],-z[0],), # 1-10---1--0-----10-0--00
(-x[5],x[2],-y[5],-y[3],y[1],-z[6],z[3],z[2],z[1],-z[0],), # 0--1--0-0-1------0--1110
(x[5],-x[4],-x[3],y[5],y[4],y[1],z[6],-z[5],-z[1],), # 100---11--1------10---0-
(-x[4],-x[2],x[1],-y[5],-y[3],z[11],z[9],z[7],-z[2],-z[0],), # -0-01-0-0---1-1-1----0-0
(-x[3],-x[0],-y[4],-y[3],y[2],y[0],z[4],-z[3],-z[2],), # --0--0-001-1-------100--
(-x[1],y[5],-y[2],-y[1],-y[0],-z[9],-z[8],-z[7],z[6],-z[2],), # ----0-1--000--0001---0--
(-x[1],-x[0],-y[5],-y[4],y[3],y[2],y[1],-z[5],z[0],), # ----0000111-------0----1
(-x[5],-x[4],-y[4],y[1],-y[0],z[6],z[4],z[1],z[0],), # 00-----0--10-----1-1--11
(-x[5],x[2],x[1],-y[4],-y[3],z[11],z[7],-z[2],-z[1],), # 0--11--00---1---1----00-
(x[4],-x[3],-y[5],-y[1],-z[10],z[6],z[3],z[1],-z[0],), # -10---0---0--0---1--1-10
(-x[4],-x[2],x[1],-y[5],y[0],z[8],z[6],z[4],-z[2],), # -0-01-0----1---1-1-1-0--
(x[5],-x[4],-y[3],-y[2],-y[0],z[8],z[6],z[5],z[3],z[1],), # 10------00-0---1-11-1-1-
(x[3],x[2],-y[4],y[2],-z[10],-z[9],-z[7],-z[6],z[1],z[0],), # --11---0-1---00-00----11
(x[5],x[2],y[3],-z[10],-z[8],-z[7],-z[6],z[0],), # 1--1----1----0-000-----1
(-x[4],x[3],-x[1],-y[5],y[1],y[0],-z[6],-z[5],-z[3],-z[2],), # -01-0-0---11-----00-00--
(y[5],-y[3],y[2],y[0],-z[10],z[8],z[7],z[6],-z[2],), # ------1-01-1-0-111---0--
(-x[5],x[3],-x[2],-y[3],y[1],-y[0],z[10],-z[9],z[7],), # 0-10----0-10-10-1-------
(x[5],x[1],-y[1],-y[0],z[5],-z[4],z[3],z[2],z[1],), # 1---1-----00------10111-
(x[4],x[3],-x[2],-x[0],-y[5],y[4],-y[1],-y[0],-z[6],-z[3],-z[2],), # -110-001--00-----0--00--
(-x[5],-x[3],-y[1],z[11],z[9],z[6],z[3],z[2],-z[1],-z[0],), # 0-0-------0-1-1--1--1100
(x[5],-x[3],x[2],-y[5],y[1],-z[7],z[6],z[2],-z[1],-z[0],), # 1-01--0---1-----01---100
(-x[2],x[1],y[5],-y[4],-y[3],-z[7],z[4],-z[3],-z[2],-z[0],), # ---01-100-------0--100-0
(x[3],-x[2],y[5],-y[1],-z[7],z[5],-z[4],-z[2],z[1],-z[0],), # --10--1---0-----0-10-010
(-x[1],-x[0],y[5],-y[4],z[5],z[3],z[2],z[1],z[0],), # ----0010----------1-1111
(-x[5],x[3],x[2],x[0],-y[5],y[4],-y[1],-z[6],-z[3],-z[1],), # 0-11-101--0------0--0-0-
(-x[5],y[5],y[4],-y[3],-y[1],-z[5],-z[4],-z[3],-z[1],-z[0],), # 0-----110-0-------000-00
(-x[3],-x[1],y[5],y[3],-y[2],-y[1],-z[9],-z[8],z[7],), # --0-0-1-100---001-------
(x[5],x[2],y[5],-y[4],-y[1],z[8],-z[5],z[3],z[1],-z[0],), # 1--1--10--0----1--0-1-10
(x[4],-x[2],y[4],y[3],-y[1],z[4],z[3],z[1],-z[0],), # -1-0---11-0--------11-10
(-x[5],x[4],-x[2],-x[1],-y[5],y[3],y[0],-z[6],-z[2],-z[1],), # 01-00-0-1--1-----0---00-
(x[5],-x[4],-x[3],-x[2],x[0],y[4],-y[1],-z[6],z[2],z[1],), # 1000-1-1--0------0---11-
(x[5],x[3],y[4],-y[3],y[0],-z[7],z[6],z[3],-z[1],), # 1-1----10--1----01--1-0-
(x[3],-x[2],-y[5],y[3],y[2],y[1],z[7],-z[6],z[4],z[1],), # --10--0-111-----10-1--1-
(x[2],x[0],y[4],y[3],-y[1],-z[9],-z[7],-z[6],z[2],), # ---1-1-11-0---0-00---1--
(-x[4],x[3],x[2],-x[1],-x[0],y[5],-z[10],z[7],-z[4],), # -011001------0--1--0----
(-x[5],-x[4],x[1],-y[4],y[0],z[11],-z[10],-z[9],-z[6],), # 00--1--0---1100--0------
(x[4],x[2],y[5],y[2],y[0],z[10],z[7],-z[5],z[2],-z[1],), # -1-1--1--1-1-1--1-0--10-
(x[4],-x[3],y[5],-y[4],y[2],y[0],z[5],z[4],z[2],-z[1],), # -10---10-1-1------11-10-
(x[5],x[2],y[3],y[2],z[10],z[7],-z[5],-z[3],z[0],), # 1--1----11---1--1-0-0--1
(y[5],-y[4],-y[3],y[2],z[7],z[6],z[3],-z[2],z[1],-z[0],), # ------1001------11--1010
(x[4],-x[1],-x[0],y[5],y[3],-z[9],z[8],z[5],z[0],), # -1--001-1-----01--1----1
(-x[5],x[1],-y[5],-y[3],y[2],-y[1],-z[7],z[4],-z[2],z[1],), # 0---1-0-010-----0--1-01-
(-x[5],x[3],y[5],-y[3],y[1],z[6],z[4],-z[1],-z[0],), # 0-1---1-0-1------1-1--00
(-x[5],-x[4],x[3],-x[2],-y[4],z[11],-z[8],z[2],-z[0],), # 0010---0----1--0-----1-0
(x[4],-x[2],y[3],y[2],-y[1],z[4],z[3],-z[1],z[0],), # -1-0----110--------11-01
(-x[5],x[4],-x[3],y[5],-y[2],y[1],-z[8],-z[5],-z[1],-z[0],), # 010---1--01----0--0---00
(x[3],-x[2],y[4],-y[2],y[0],z[4],-z[3],-z[2],), # --10---1-0-1-------100--
(x[3],-x[1],y[4],y[3],-y[2],y[0],z[4],z[3],-z[1],), # --1-0--110-1-------11-0-
(x[3],-x[2],y[4],-y[3],-y[2],-z[10],-z[8],-z[4],), # --10---100---0-0---0----
(x[3],y[4],y[2],y[0],-z[10],-z[6],-z[2],z[1],), # --1----1-1-1-0---0---01-
(x[4],x[2],x[0],y[3],-z[10],-z[6],-z[2],z[1],), # -1-1-1--1----0---0---01-
(x[4],-x[2],y[5],-y[4],-y[3],y[1],z[10],z[5],-z[4],-z[1],-z[0],), # -1-0--100-1--1----10--00
(-x[5],x[4],-x[1],-y[4],y[3],y[2],z[6],-z[2],z[1],-z[0],), # 01--0--011-------1---010
(x[5],-x[4],x[0],-y[4],-y[3],y[1],-z[5],z[4],z[2],-z[1],), # 10---1-00-1-------01-10-
(-x[5],-x[4],x[3],y[5],-y[2],-y[1],y[0],-z[6],-z[5],-z[3],-z[2],), # 001---1--001-----00-00--
(-x[3],-x[2],-y[4],-y[3],-y[2],z[11],z[8],z[6],-z[0],), # --00---000--1--1-1-----0
(-x[4],-x[3],x[2],y[5],y[2],y[0],-z[5],z[4],-z[3],), # -001--1--1-1------010---
(x[5],x[4],-x[3],-y[5],y[3],-y[2],y[1],-z[5],-z[2],-z[0],), # 110---0-101-------0--0-0
(-x[4],y[3],-y[2],y[1],-z[4],z[3],z[2],-z[1],z[0],), # -0------101--------01101
(x[5],x[4],-x[2],x[1],y[4],y[2],-z[6],-z[5],-z[1],), # 11-01--1-1-------00---0-
(-x[3],-x[2],x[1],y[4],-y[2],-z[4],-z[3],-z[1],z[0],), # --001--1-0---------00-01
(-x[3],x[2],y[4],-y[2],-y[1],-z[4],z[3],z[2],-z[1],), # --01---1-00--------0110-
(-x[5],-x[4],-x[2],-x[1],-x[0],y[5],z[10],-z[5],z[4],z[2],), # 00-0001------1----01-1--
(-x[4],x[3],y[5],y[2],y[0],z[5],z[4],-z[1],), # -01---1--1-1------11--0-
(-x[4],-y[5],y[3],-y[2],-y[1],z[11],-z[5],-z[3],-z[2],-z[0],), # -0----0-100-1-----0-00-0
(x[4],-x[2],-y[3],y[2],-y[1],-y[0],-z[4],z[3],z[0],), # -1-0----0100-------01--1
(-x[4],-y[5],-y[4],y[2],y[1],z[11],-z[5],z[2],z[1],-z[0],), # -0----00-11-1-----0--110
(x[5],-x[4],-x[2],y[5],-y[4],y[3],y[1],z[5],z[1],-z[0],), # 10-0--101-1-------1---10
(-x[4],-x[2],x[1],y[5],-y[4],y[0],z[9],-z[6],-z[5],-z[2],), # -0-01-10---1--1--00--0--
(x[4],x[2],-x[1],-y[5],y[4],-y[3],y[0],-z[5],z[4],-z[1],), # -1-10-010--1------01--0-
(-x[5],x[4],-x[2],x[0],y[4],-y[3],-z[5],-z[4],-z[2],-z[1],), # 01-0-1-10---------00-00-
(-x[5],-x[4],x[3],x[2],y[5],-y[3],y[1],z[10],-z[5],-z[1],), # 0011--1-0-1--1----0---0-
(x[5],x[4],-x[1],y[4],-y[2],-y[1],-z[9],-z[6],z[0],), # 11--0--1-00---0--0-----1
(-x[4],-x[3],x[0],-y[5],y[4],y[1],z[11],-z[5],z[3],-z[1],), # -00--101--1-1-----0-1-0-
(-x[4],-x[3],y[5],y[4],y[2],y[1],-z[7],z[6],), # -00---11-11-----01------
(-x[4],-x[3],-y[4],y[1],y[0],z[6],z[4],z[3],-z[2],), # -00----0--11-----1-110--
(x[3],-y[4],-y[3],y[2],y[0],-z[4],-z[3],-z[2],-z[1],), # --1----001-1-------0000-
(-x[5],-x[4],x[2],x[0],y[4],y[3],-y[1],-z[5],-z[4],-z[1],), # 00-1-1-11-0-------00--0-
(-x[4],-x[3],x[0],-y[3],-y[1],z[4],-z[3],-z[2],-z[1],), # -00--1--0-0--------1000-
(x[5],x[4],-x[3],x[1],x[0],-y[4],-y[3],y[2],-z[6],-z[5],), # 110-11-001-------00-----
(-x[5],-x[2],x[0],y[4],y[3],y[2],z[5],z[3],-z[1],), # 0--0-1-111--------1-1-0-
(x[5],-x[3],-x[2],-y[5],y[4],y[0],z[10],z[6],-z[2],-z[1],), # 1-00--01---1-1---1---00-
(-x[4],x[3],-x[2],y[2],-y[1],z[11],z[6],-z[3],z[1],-z[0],), # -010-----10-1----1--0-10
(x[5],-x[4],x[2],x[1],-y[4],-y[3],-y[1],-y[0],z[7],z[0],), # 10-11--00-00----1------1
(x[1],-y[5],-y[4],-y[3],y[2],z[8],z[6],z[5],-z[4],-z[3],-z[1],), # ----1-0001-----1-1100-0-
(y[3],-y[0],-z[11],-z[9],-z[8],-z[6],z[2],z[0],), # --------1--00-00-0---1-1
(x[2],-x[1],x[0],y[4],-z[5],z[3],z[2],z[1],), # ---101-1----------0-111-
(-x[4],-y[4],-y[3],-z[11],z[10],z[6],z[5],-z[0],), # -0-----00---01---11----0
(-x[1],x[0],-y[3],-z[11],z[10],z[9],-z[7],-z[6],-z[4],z[3],), # ----01--0---011-00-01---
(-x[1],-y[3],y[2],-z[11],-z[10],z[9],z[5],z[2],-z[1],), # ----0---01--001---1--10-
(-x[4],-x[3],-y[2],-z[11],z[9],z[8],z[5],-z[3],-z[0],), # -00------0--0-11--1-0--0
(x[5],x[3],y[4],-z[8],-z[7],-z[6],z[3],z[2],), # 1-1----1-------000--11--
(x[5],x[1],y[2],-z[10],-z[7],-z[5],-z[4],-z[3],z[1],), # 1---1----1---0--0-000-1-
(x[4],x[1],-y[5],-y[4],z[9],-z[8],-z[7],z[3],z[2],-z[0],), # -1--1-00------100---11-0
(-y[5],y[2],-y[1],z[8],z[7],z[3],-z[2],z[1],-z[0],), # ------0--10----11---1010
(-y[2],-y[1],z[10],-z[9],z[8],-z[5],-z[4],z[2],-z[0],), # ---------00--101--00-1-0
(-x[4],-y[5],y[2],-z[10],z[9],-z[7],z[6],-z[1],-z[0],), # -0----0--1---01-01----00
(x[4],-x[3],x[2],-z[9],z[8],z[6],z[4],z[3],-z[1],-z[0],), # -101----------01-1-11-00
(x[3],-x[1],x[0],-y[5],-y[3],z[6],z[3],z[2],z[1],), # --1-010-0--------1--111-
(x[4],-x[3],x[0],-y[4],-y[3],y[2],-z[9],-z[6],z[5],-z[4],), # -10--1-001----0--010----
(x[4],-y[4],y[1],-z[11],z[8],-z[6],z[2],-z[1],), # -1-----0--1-0--1-0---10-
(-x[2],x[1],-y[4],y[3],-y[2],y[1],z[10],z[9],z[7],-z[5],-z[4],), # ---01--0101--11-1-00----
(x[2],y[5],y[3],-z[10],-z[6],-z[3],z[2],), # ---1--1-1----0---0--01--
(-x[5],-x[4],x[3],x[1],x[0],y[3],y[1],-z[5],z[4],), # 001-11--1-1-------01----
(x[5],y[5],y[2],z[8],-z[7],z[5],z[2],-z[1],-z[0],), # 1-----1--1-----10-1--100
(x[2],-x[1],-y[3],-y[2],-y[1],z[10],-z[8],-z[7],-z[5],z[3],), # ---10---000--1-00-0-1---
(-x[3],x[2],-y[3],y[2],z[10],z[9],z[8],z[6],), # --01----01---111-1------
(-x[5],x[4],x[2],x[1],y[3],z[9],z[6],-z[5],-z[4],), # 01-11---1-----1--100----
(x[4],-y[3],-y[2],-z[11],z[9],-z[5],-z[4],-z[0],), # -1------00--0-1---00---0
(-x[5],-x[4],x[3],x[2],-y[5],y[3],y[1],-z[9],-z[7],-z[4],-z[2],), # 0011--0-1-1---0-0--0-0--
(x[4],x[2],-x[1],y[5],y[4],-y[1],-z[8],z[6],z[5],-z[3],), # -1-10-11--0----0-11-0---
(-x[5],y[5],y[1],z[9],-z[6],-z[5],z[3],-z[1],-z[0],), # 0-----1---1---1--00-1-00
(-x[4],y[3],y[1],z[11],-z[9],-z[8],z[5],z[4],-z[1],-z[0],), # -0------1-1-1-00--11--00
(-x[4],-x[1],-y[2],z[9],-z[8],z[7],-z[4],z[3],-z[2],-z[0],), # -0--0----0----101--010-0
(-x[4],-x[3],-x[1],y[4],y[2],-z[7],z[5],z[3],z[2],-z[0],), # -00-0--1-1------0-1-11-0
(-x[3],x[2],y[5],y[2],y[1],-z[10],z[8],-z[6],), # --01--1--11--0-1-0------
(-x[5],x[4],x[1],-y[4],y[3],y[0],-z[6],-z[4],-z[3],z[2],), # 01--1--01--1-----0-001--
(-y[5],-y[4],-y[2],-y[1],z[9],-z[6],z[2],-z[1],-z[0],), # ------00-00---1--0---100
(x[5],x[4],-y[5],y[2],-y[1],-z[7],-z[5],z[3],-z[2],-z[1],), # 11----0--10-----0-0-100-
(x[5],x[4],x[3],-x[1],y[5],-y[3],-z[6],-z[5],-z[2],), # 111-0-1-0--------00--0--
(x[5],x[3],-x[1],y[5],-y[3],-y[2],y[1],-z[8],-z[6],z[4],), # 1-1-0-1-001----0-0-1----
(x[3],y[4],-y[3],y[2],y[0],z[4],z[3],z[2],-z[1],), # --1----101-1-------1110-
(x[1],-y[5],y[3],z[11],z[10],z[9],z[7],-z[6],-z[5],), # ----1-0-1---111-100-----
(x[4],x[2],y[3],y[0],-z[11],-z[8],z[1],), # -1-1----1--10--0------1-
(-x[5],-x[3],-y[4],-y[1],z[8],z[7],-z[4],z[3],z[1],-z[0],), # 0-0----0--0----11--01-10
(x[4],-x[3],x[2],y[3],-y[1],z[4],-z[3],z[0],), # -101----1-0--------10--1
(-x[2],y[4],-y[3],-y[1],-z[11],z[9],-z[8],z[7],-z[5],z[0],), # ---0---10-0-0-101-0----1
(y[3],-y[1],-z[8],z[7],z[5],z[4],z[3],z[1],-z[0],), # --------1-0----01-111-10
(x[2],y[3],y[2],-z[11],z[9],z[8],-z[7],z[0],), # ---1----11--0-110------1
(y[5],y[3],y[2],y[0],-z[10],-z[6],z[3],), # ------1-11-1-0---0--1---
(-x[3],x[2],-y[4],y[0],z[11],-z[10],-z[8],z[7],z[6],-z[5],), # --01---0---110-0110-----
(x[1],-y[3],-y[1],-y[0],-z[7],z[6],z[5],-z[4],z[2],z[0],), # ----1---0-00----0110-1-1
(x[5],y[5],y[4],y[3],y[2],y[0],-z[6],), # 1-----1111-1-----0------
(x[3],x[2],y[4],y[2],-z[11],-z[7],z[0],), # --11---1-1--0---0------1
(-x[5],x[3],x[2],-y[5],y[1],-z[5],-z[4],z[1],-z[0],), # 0-11--0---1-------00--10
(x[5],x[3],-x[1],-x[0],-y[3],z[7],z[6],z[5],z[4],-z[2],), # 1-1-00--0-------1111-0--
(-x[3],-x[1],y[3],-y[2],-z[3],-z[2],-z[1],), # --0-0---10----------000-
(-x[2],-x[1],y[4],-y[2],-y[1],z[10],-z[9],-z[7],-z[3],), # ---00--1-00--10-0---0---
(-x[5],-x[3],x[2],x[1],-y[4],-y[1],-z[7],z[2],-z[0],), # 0-011--0--0-----0----1-0
(x[4],x[3],x[2],y[2],y[1],z[10],-z[8],-z[7],), # -111-----11--1-00-------
(-x[3],x[2],x[0],-y[5],y[3],z[11],z[9],z[8],z[7],), # --01-10-1---1-111-------
(-x[3],x[1],y[4],-y[3],-z[4],z[3],z[2],-z[1],z[0],), # --0-1--10----------01101
(-x[5],-x[3],x[2],x[0],y[4],y[3],-z[5],-z[4],z[3],-z[1],), # 0-01-1-11---------001-0-
(-x[2],-x[1],y[5],-y[2],-y[1],z[9],z[8],z[7],z[6],z[5],z[1],), # ---00-1--00---11111---1-
(-x[4],-x[2],x[0],y[3],-y[2],-z[4],-z[3],-z[2],), # -0-0-1--10---------000--
(x[4],x[1],x[0],y[4],y[3],y[1],-z[6],z[3],), # -1--11-11-1------0--1---
(x[4],x[2],-x[1],y[4],y[3],z[4],z[3],-z[2],-z[0],), # -1-10--11----------110-0
(-x[4],x[2],x[1],-y[5],y[2],z[9],-z[8],-z[7],-z[6],z[0],), # -0-11-0--1----1000-----1
(-x[5],x[4],-x[3],-x[2],-x[1],x[0],-y[5],y[1],-z[7],-z[4],z[1],), # 0100010---1-----0--0--1-
(-x[5],x[2],-y[5],-y[3],z[7],z[6],-z[3],-z[2],z[1],-z[0],), # 0--1--0-0-------11--0010
(x[5],y[3],y[2],-y[1],y[0],-z[6],z[3],z[2],z[1],), # 1-------1101-----0--111-
(x[1],-y[5],y[3],z[10],-z[9],z[8],-z[5],-z[1],-z[0],), # ----1-0-1----101--0---00
(x[4],x[3],-y[5],-y[3],y[2],y[0],-z[5],-z[4],z[3],-z[1],), # -11---0-01-1------001-0-
(-x[3],-y[5],-y[4],-y[3],-y[2],z[11],z[9],z[4],-z[2],), # --0---0000--1-1----1-0--
(x[4],-x[3],x[2],-y[2],y[1],-z[9],-z[8],-z[7],-z[5],), # -101-----01---000-0-----
(-x[2],y[4],y[3],y[2],z[10],z[9],-z[8],z[7],), # ---0---111---1101-------
(-x[4],x[3],x[0],-y[3],y[1],z[4],-z[3],-z[2],), # -01--1--0-1--------100--
(x[2],-y[5],y[3],y[1],-z[10],-z[6],z[5],z[2],-z[1],), # ---1--0-1-1--0---01--10-
(-x[5],x[4],x[2],y[5],-y[3],y[1],z[10],z[8],-z[6],), # 01-1--1-0-1--1-1-0------
(-x[4],-y[5],-y[4],y[2],y[0],z[5],-z[4],z[3],-z[2],-z[1],), # -0----00-1-1------10100-
(-x[5],x[1],-y[5],-y[4],y[3],y[0],-z[6],z[4],z[3],-z[1],), # 0---1-001--1-----0-11-0-
(x[4],y[4],-y[3],-y[1],-z[4],-z[3],-z[1],-z[0],), # -1-----10-0--------00-00
(-x[2],x[0],y[5],-y[1],-z[10],z[6],-z[4],-z[2],), # ---0-11---0--0---1-0-0--
(x[4],x[3],-x[1],y[4],y[1],-z[10],-z[8],z[4],z[0],), # -11-0--1--1--0-0---1---1
(-x[3],x[2],-y[5],y[4],y[1],z[11],z[10],z[8],), # --01--01--1-11-1--------
(-x[3],-x[1],x[0],-y[5],y[2],z[11],z[10],z[8],-z[6],-z[5],), # --0-010--1--11-1-00-----
(-x[3],-y[4],y[3],-y[2],y[0],z[4],-z[3],-z[2],-z[1],), # --0----010-1-------1000-
(x[4],-x[3],-x[2],-x[1],-y[5],-y[2],z[11],z[9],-z[1],), # -1000-0--0--1-1-------0-
(x[5],-x[1],-y[4],y[1],-z[8],-z[7],-z[6],z[3],-z[2],), # 1---0--0--1----000--10--
(-x[3],-x[1],-y[4],y[3],-y[1],y[0],z[4],z[3],z[2],), # --0-0--01-01-------111--
(-x[3],-y[4],-y[3],y[2],y[0],z[4],z[3],z[2],-z[1],), # --0----001-1-------1110-
(x[3],y[3],y[2],-z[10],-z[8],-z[7],z[4],z[0],), # --1-----11---0-00--1---1
(x[4],-x[3],y[1],z[10],-z[7],z[5],z[3],z[2],z[1],-z[0],), # -10-------1--1--0-1-1110
(-x[5],x[4],-x[2],x[1],y[0],z[10],z[9],z[6],z[2],-z[1],), # 01-01------1-11--1---10-
(-x[4],x[3],y[5],y[3],y[1],y[0],z[6],z[5],-z[3],), # -01---1-1-11-----11-0---
(x[5],x[4],x[3],x[1],x[0],-y[3],z[5],-z[2],), # 111-11--0---------1--0--
(-x[5],-y[5],-y[3],-z[10],-z[6],-z[2],-z[1],-z[0],), # 0-----0-0----0---0---000
(-x[4],-x[1],-y[4],-y[3],z[10],z[7],-z[4],-z[3],z[2],z[1],), # -0--0--00----1--1--0011-
(x[1],-y[5],-y[4],-y[3],y[0],-z[10],-z[5],z[3],-z[1],), # ----1-000--1-0----0-1-0-
(-x[5],-x[3],-x[2],-x[1],x[0],-y[5],-y[2],z[8],z[7],z[6],z[1],), # 0-00010--0-----111----1-
(-x[4],x[3],-x[2],y[5],y[1],-z[10],-z[6],z[4],-z[0],), # -010--1---1--0---0-1---0
(-x[4],x[2],y[4],-y[3],-y[1],z[11],-z[8],-z[7],z[5],z[2],), # -0-1---10-0-1--00-1--1--
(-x[5],x[3],x[1],y[2],y[1],-z[10],z[8],z[7],-z[2],), # 0-1-1----11--0-11----0--
(x[5],x[3],x[2],y[5],z[8],-z[6],-z[5],z[1],-z[0],), # 1-11--1--------1-00---10
(x[4],-x[3],y[4],y[3],-y[1],z[4],-z[3],-z[1],-z[0],), # -10----11-0--------10-00
(-x[5],x[4],-x[2],-x[1],-y[5],y[3],z[6],-z[5],-z[3],-z[2],z[1],), # 01-00-0-1--------10-001-
(-x[5],y[5],-y[4],-y[1],-z[9],-z[7],z[5],-z[1],-z[0],), # 0-----10--0---0-0-1---00
(-x[4],x[3],-y[5],-y[3],y[2],y[0],z[5],-z[4],z[3],-z[1],), # -01---0-01-1------101-0-
(-x[5],x[4],-y[5],-y[4],y[2],y[1],z[5],-z[2],-z[1],-z[0],), # 01----00-11-------1--000
(x[5],-x[4],-x[2],-x[1],y[4],y[2],-y[0],z[8],-z[5],z[4],), # 10-00--1-1-0---1--01----
(x[3],-x[1],y[3],-y[1],-z[11],-z[6],-z[3],), # --1-0---1-0-0----0--0---
(-x[3],x[2],-y[5],-y[4],z[11],-z[7],z[6],-z[5],-z[2],-z[1],), # --01--00----1---010--00-
(x[5],x[4],x[0],y[4],y[3],-z[5],-z[2],-z[1],), # 11---1-11---------0--00-
(x[5],y[5],-y[3],-y[2],z[8],-z[5],z[2],-z[1],-z[0],), # 1-----1-00-----1--0--100
(-x[5],-x[4],-x[3],x[1],x[0],-y[4],y[0],-z[6],-z[3],), # 000-11-0---1-----0--0---
(x[5],-x[1],y[2],y[0],-z[10],-z[7],z[6],-z[3],), # 1---0----1-1-0--01--0---
(-x[4],x[2],x[1],y[4],-z[10],z[9],-z[7],z[0],), # -0-11--1-----01-0------1
(x[5],x[3],x[2],x[1],x[0],y[1],-z[5],), # 1-1111----1-------0-----
(-x[3],y[5],-y[4],-y[3],z[10],z[8],z[6],-z[4],-z[0],), # --0---100----1-1-1-0---0
(-x[5],x[4],-y[5],-y[4],y[2],y[1],-z[6],-z[2],z[1],-z[0],), # 01----00-11------0---010
(x[5],x[4],-x[2],-x[1],-x[0],-y[5],-y[4],z[8],z[6],), # 11-00000-------1-1------
(-x[5],x[4],x[0],y[4],y[3],z[5],-z[2],-z[1],), # 01---1-11---------1--00-
(-x[4],y[5],y[0],-z[10],-z[7],z[3],z[2],-z[1],), # -0----1----1-0--0---110-
(x[5],x[2],-x[1],-x[0],y[4],-y[3],-y[2],z[10],z[8],-z[6],-z[3],), # 1--100-100---1-1-0--0---
(-x[2],-x[1],-y[5],-y[4],y[0],z[10],z[5],z[4],-z[1],), # ---00-00---1-1----11--0-
(-x[5],x[3],-x[2],y[5],-y[4],y[0],-z[7],z[6],-z[4],-z[3],z[1],), # 0-10--10---1----01-00-1-
(-x[4],-y[5],y[4],-y[3],z[11],-z[5],-z[3],z[2],-z[1],-z[0],), # -0----010---1-----0-0100
(-x[4],x[2],y[5],-y[3],y[1],z[8],-z[6],z[5],-z[1],), # -0-1--1-0-1----1-01---0-
(-x[4],-x[1],-y[5],-y[2],-y[1],z[11],-z[8],z[7],z[6],z[5],), # -0--0-0--00-1--0111-----
(x[3],-y[5],-y[4],-y[3],y[1],y[0],z[5],-z[2],), # --1---000-11------1--0--
(-x[5],-x[4],x[0],-y[4],y[3],-y[1],z[5],-z[4],-z[2],-z[1],), # 00---1-01-0-------10-00-
(x[5],x[4],x[3],y[3],-y[0],-z[5],z[1],z[0],), # 111-----1--0------0---11
(x[5],x[4],-x[3],x[2],-x[1],-y[5],-z[5],-z[4],-z[3],-z[0],), # 11010-0-----------000--0
(x[2],-y[4],y[3],y[2],y[1],y[0],-z[6],z[5],), # ---1---01111-----01-----
(-x[5],x[3],-x[1],-x[0],-y[3],-z[8],-z[7],-z[6],z[5],-z[3],z[0],), # 0-1-00--0------0001-0--1
(x[5],-x[2],x[0],-y[5],-y[4],z[10],z[9],z[6],z[5],), # 1--0-100-----11--11-----
(x[4],x[0],y[4],y[3],y[2],y[0],-z[5],), # -1---1-111-1------0-----
(-x[3],-y[5],-y[4],y[0],z[11],z[9],z[6],z[5],-z[1],), # --0---00---11-1--11---0-
(x[3],y[5],y[4],y[3],y[1],y[0],-z[5],), # --1---111-11------0-----
(-x[5],-x[3],x[0],y[3],-y[2],z[5],z[4],-z[2],z[1],), # 0-0--1--10--------11-01-
(x[1],-x[0],y[5],-z[5],z[3],z[2],z[1],z[0],), # ----101-----------0-1111
(x[3],x[2],-x[1],y[5],-y[3],z[9],z[5],z[4],-z[2],z[1],), # --110-1-0-----1---11-01-
(x[5],-x[3],-y[5],y[0],-z[6],z[4],-z[3],z[2],-z[1],), # 1-0---0----1-----0-1010-
(y[5],-y[3],-y[1],z[10],z[9],z[8],z[6],z[5],z[1],-z[0],), # ------1-0-0--111-11---10
(-x[3],-x[1],y[5],y[4],y[1],-z[5],z[4],z[3],z[1],), # --0-0-11--1-------011-1-
(x[5],x[1],x[0],y[4],y[3],-z[6],-z[3],-z[2],), # 1---11-11--------0--00--
(-x[5],x[4],x[3],x[1],y[3],z[9],z[6],-z[3],z[0],), # 011-1---1-----1--1--0--1
(x[5],x[4],x[0],y[4],-y[3],-z[5],z[2],-z[1],), # 11---1-10---------0--10-
(x[5],-x[4],-x[2],-y[5],y[3],-y[2],-z[7],z[5],z[3],-z[2],), # 10-0--0-10------0-1-10--
(-x[3],x[2],-y[5],-y[3],y[0],-z[5],-z[4],-z[2],z[1],), # --01--0-0--1------00-01-
(x[5],-x[3],y[4],-y[2],-y[1],z[10],z[8],z[6],z[2],-z[0],), # 1-0----1-00--1-1-1---1-0
(-x[5],-x[3],x[2],-y[4],-y[1],z[11],-z[8],-z[6],-z[1],-z[0],), # 0-01---0--0-1--0-0----00
(x[5],-x[3],-x[2],y[4],y[3],-y[2],-y[1],z[9],z[6],z[5],z[1],), # 1-00---1100---1--11---1-
(x[4],-x[2],-x[1],-y[5],-y[3],y[1],-z[7],-z[4],-z[3],z[0],), # -1-00-0-0-1-----0--00--1
(-y[4],y[3],y[2],y[1],z[11],z[6],-z[5],-z[2],z[1],), # -------0111-1----10--01-
(-x[4],-x[3],y[4],y[3],-y[2],-z[10],-z[8],z[5],), # -00----110---0-0--1-----
(x[3],-x[2],-x[1],y[4],y[0],-z[4],-z[1],), # --100--1---1-------0--0-
(x[5],-x[3],-x[2],y[5],y[2],-z[9],z[7],-z[6],z[0],), # 1-00--1--1----0-10-----1
(-x[4],x[2],y[5],y[3],-y[2],-y[1],z[10],-z[7],-z[6],), # -0-1--1-100--1--00------
(-x[1],-y[5],y[4],-y[2],z[11],z[10],-z[6],-z[5],z[2],-z[0],), # ----0-01-0--11---00--1-0
(x[4],x[2],y[4],y[2],-z[10],-z[6],-z[2],-z[1],), # -1-1---1-1---0---0---00-
(-x[4],x[2],x[1],-y[5],-y[2],-y[1],z[11],z[8],z[6],z[1],), # -0-11-0--00-1--1-1----1-
(x[3],-x[1],-y[5],-y[3],y[0],z[11],z[9],-z[6],-z[5],z[4],-z[1],), # --1-0-0-0--11-1--001--0-
(-y[5],-y[4],y[3],y[2],y[1],z[11],-z[6],z[2],-z[1],-z[0],), # ------00111-1----0---100
(-x[5],x[4],-x[3],x[2],x[1],y[4],-y[3],-y[2],z[10],-z[7],z[5],), # 01011--100---1--0-1-----
(x[3],-y[5],-y[4],y[2],-y[1],z[11],z[10],z[5],-z[1],-z[0],), # --1---00-10-11----1---00
(x[4],-x[2],-y[4],y[3],-y[1],-z[4],z[3],z[1],-z[0],), # -1-0---01-0--------01-10
(-x[4],-x[1],x[0],y[5],-y[3],-y[2],-z[10],z[6],z[1],), # -0--011-00---0---1----1-
(x[5],x[3],-x[2],-x[1],x[0],y[5],-y[4],-y[3],y[2],-z[6],-z[2],), # 1-10011001-------0---0--
(-x[5],-x[3],-x[2],y[5],y[4],y[1],z[5],-z[1],-z[0],), # 0-00--11--1-------1---00
(x[5],x[1],x[0],-y[3],y[2],y[1],z[5],-z[2],), # 1---11--011-------1--0--
(-x[4],y[5],-y[4],-y[2],y[0],z[5],-z[3],z[2],-z[1],), # -0----10-0-1------1-010-
(x[5],x[4],-y[5],-y[3],-y[2],-y[1],z[5],-z[1],-z[0],), # 11----0-000-------1---00
(-x[4],y[4],y[3],y[2],y[0],z[5],-z[2],z[1],), # -0-----111-1------1--01-
(-x[5],-x[4],x[2],y[2],y[0],z[11],z[10],z[6],-z[5],-z[2],), # 00-1-----1-111---10--0--
(-x[3],-x[1],y[5],-y[4],-y[3],-y[2],y[1],z[9],-z[6],z[1],), # --0-0-10001---1--0----1-
(x[5],-x[4],-x[3],-x[2],x[0],-y[4],z[5],-z[1],), # 1000-1-0----------1---0-
(x[3],y[0],-z[11],z[9],-z[7],-z[6],z[5],-z[4],z[2],), # --1--------10-1-0010-1--
(-x[1],y[3],-z[11],-z[9],z[8],-z[7],z[5],-z[4],), # ----0---1---0-010-10----
(y[2],-z[11],z[10],-z[7],z[6],-z[5],-z[4],-z[0],), # ---------1--01--0100---0
(-x[5],-x[3],-x[1],-y[3],y[2],z[11],z[10],-z[5],z[2],-z[0],), # 0-0-0---01--11----0--1-0
(-x[1],-z[10],z[7],z[6],z[5],z[4],z[1],-z[0],), # ----0--------0--1111--10
(-x[5],-x[4],-x[0],y[4],-y[2],-y[1],-z[10],z[6],z[1],), # 00---0-1-00--0---1----1-
(x[5],-x[4],x[3],-x[2],-y[4],-y[3],-y[1],-y[0],-z[5],-z[4],z[0],), # 1010---00-00------00---1
(x[3],-x[2],-x[1],y[5],y[1],-z[5],-z[2],z[1],), # --100-1---1-------0--01-
(x[5],y[3],-z[9],z[7],-z[6],z[4],-z[2],-z[1],z[0],), # 1-------1-----0-10-1-001
(-x[4],-x[3],-y[1],-z[11],z[10],z[8],-z[4],z[3],z[2],-z[1],), # -00-------0-01-1---0110-
(-x[2],x[1],x[0],y[3],-z[5],z[4],z[3],z[2],), # ---011--1---------0111--
(-y[4],y[3],z[7],z[6],z[4],z[3],z[2],-z[1],-z[0],), # -------01-------11-11100
(y[3],y[0],-z[11],z[10],z[7],z[6],z[5],-z[4],-z[2],), # --------1--101--1110-0--
(-x[3],x[1],-y[5],-y[2],z[9],-z[8],z[6],-z[5],-z[4],-z[0],), # --0-1-0--0----10-100---0
(-x[2],y[4],y[2],y[1],y[0],z[5],-z[4],z[3],), # ---0---1-111------101---
(-x[4],x[1],y[4],y[1],y[0],z[6],-z[4],z[2],), # -0--1--1--11-----1-0-1--
(y[2],-y[0],-z[11],z[10],z[8],-z[6],z[5],-z[3],z[2],), # ---------1-001-1-01-01--
(x[5],x[2],x[1],y[2],-z[10],z[8],z[7],-z[6],), # 1--11----1---0-110------
(x[4],-x[2],x[0],-y[4],-y[3],z[11],z[10],z[5],z[2],-z[1],), # -1-0-1-00---11----1--10-
(-x[3],-y[3],y[1],-z[7],z[6],z[5],z[4],-z[2],z[1],-z[0],), # --0-----0-1-----0111-010
(-x[5],-x[3],-y[2],-y[1],-z[9],z[8],z[7],z[3],-z[2],z[1],), # 0-0------00---011---101-
(x[1],-y[3],y[2],z[9],z[8],z[7],z[5],-z[2],-z[0],), # ----1---01----111-1--0-0
(-z[11],-z[9],-z[8],z[7],z[1],-z[0],), # ------------0-001-----10
(x[5],-y[2],-y[1],-z[9],-z[8],z[7],z[5],-z[4],z[1],), # 1--------00---001-10--1-
(-x[4],-x[3],x[0],-y[2],-z[11],z[8],-z[7],z[3],z[2],), # -00--1---0--0--10---11--
(x[4],-x[2],-y[4],z[8],z[7],z[6],-z[5],-z[1],-z[0],), # -1-0---0-------1110---00
(x[3],x[2],-z[10],-z[9],z[8],-z[7],z[5],-z[3],), # --11---------0010-1-0---
(x[2],x[0],-y[4],y[1],y[0],z[5],-z[4],z[3],), # ---1-1-0--11------101---
(x[2],y[5],y[1],-z[10],-z[7],-z[6],-z[5],z[1],), # ---1--1---1--0--000---1-
(-x[5],-y[5],y[1],z[9],z[6],z[5],z[2],z[1],-z[0],), # 0-----0---1---1--11--110
(-x[1],-z[11],-z[10],z[7],-z[6],z[1],), # ----0-------00--10----1-
(-y[5],-y[3],-z[7],-z[6],-z[5],-z[4],z[2],-z[0],), # ------0-0-------0000-1-0
(x[1],-y[3],z[8],z[7],z[6],-z[5],z[4],z[3],z[2],-z[0],), # ----1---0------1110111-0
(-x[5],x[1],y[3],-y[1],z[7],z[6],-z[4],z[3],z[2],z[1],), # 0---1---1-0-----11-0111-
(-x[5],x[4],x[3],x[1],-y[3],y[0],z[8],-z[7],z[3],z[1],), # 011-1---0--1---10---1-1-
(-x[5],y[3],z[10],z[9],z[5],z[3],-z[2],z[1],-z[0],), # 0-------1----11---1-1010
(-x[5],-x[4],-x[3],x[2],x[1],-y[4],y[2],z[7],-z[4],z[3],), # 00011--0-1------1--01---
(-x[4],x[2],y[3],y[2],-z[11],z[9],z[7],-z[1],), # -0-1----11--0-1-1-----0-
(-x[5],-x[3],-x[1],-y[4],y[3],z[7],z[6],z[4],z[1],), # 0-0-0--01-------11-1--1-
(-x[5],-x[2],x[0],-y[5],y[3],z[8],z[7],z[5],-z[4],z[2],z[1],), # 0--0-10-1------11-10-11-
(x[5],x[3],y[5],y[3],z[8],-z[7],-z[2],-z[1],), # 1-1---1-1------10----00-
(-y[4],-y[3],-y[1],-z[11],z[7],-z[5],-z[3],-z[0],), # -------00-0-0---1-0-0--0
(x[5],x[3],x[2],y[4],y[3],-z[8],), # 1-11---11------0--------
(x[5],x[2],y[5],-y[4],z[8],-z[7],z[6],z[4],-z[2],-z[1],), # 1--1--10-------101-1-00-
(-y[4],-y[3],-y[2],-y[0],-z[11],z[7],z[5],z[3],z[1],), # -------000-00---1-1-1-1-
(x[4],x[3],y[5],y[3],y[2],-z[8],), # -11---1-11-----0--------
(-x[4],x[2],-x[1],-y[3],y[1],z[9],z[7],z[5],-z[3],z[1],), # -0-10---0-1---1-1-1-0-1-
(-x[5],-x[3],x[0],-y[4],-y[3],y[2],y[0],-z[9],z[6],-z[5],), # 0-0--1-001-1--0--10-----
(-x[5],-x[4],x[2],y[3],y[0],-z[10],z[9],-z[8],-z[6],), # 00-1----1--1-010-0------
(x[5],x[1],-y[5],y[4],z[7],z[5],z[4],-z[3],z[2],-z[1],), # 1---1-01--------1-11010-
(x[3],y[3],-z[10],-z[9],z[8],z[7],-z[3],), # --1-----1----0011---0---
(-y[4],y[3],-y[2],z[10],z[9],z[7],-z[6],z[5],-z[4],-z[1],), # -------010---11-1010--0-
(x[4],-y[1],-y[0],-z[10],z[8],-z[5],z[4],-z[3],z[2],), # -1--------00-0-1--0101--
(-x[4],-x[2],y[5],y[3],-y[1],-y[0],-z[8],z[7],z[6],), # -0-0--1-1-00---011------
(-x[4],x[1],-y[5],-y[4],z[10],-z[6],z[4],-z[2],-z[1],), # -0--1-00-----1---0-1-00-
(x[4],-x[2],x[1],y[2],-z[11],-z[8],z[7],), # -1-01----1--0--01-------
(x[3],-y[5],y[3],y[1],z[10],z[5],-z[4],z[1],-z[0],), # --1---0-1-1--1----10--10
(x[5],x[2],-x[0],y[2],-y[1],-z[10],z[7],z[6],z[4],), # 1--1-0---10--0--11-1----
(y[5],y[4],y[2],-z[9],-z[7],-z[6],), # ------11-1----0-00------
(-x[4],x[3],x[1],-y[2],z[10],z[8],z[5],z[4],z[1],-z[0],), # -01-1----0---1-1--11--10
(x[4],-y[4],-y[1],-z[10],-z[9],z[6],z[4],-z[1],), # -1-----0--0--00--1-1--0-
(x[3],x[2],y[3],y[1],-z[10],-z[8],-z[6],z[1],), # --11----1-1--0-0-0----1-
(x[5],-x[4],-x[1],y[2],z[8],z[6],-z[5],-z[4],z[3],-z[0],), # 10--0----1-----1-1001--0
(x[3],-y[1],z[10],z[9],-z[8],z[6],-z[5],z[4],z[2],-z[0],), # --1-------0--110-101-1-0
(x[2],-y[4],-z[11],-z[7],z[6],-z[3],z[2],-z[1],), # ---1---0----0---01--010-
(-y[4],y[2],-y[1],-z[8],-z[7],z[6],z[4],z[1],-z[0],), # -------0-10----001-1--10
(x[0],-y[4],-y[3],y[2],z[9],-z[7],z[6],z[5],z[2],-z[1],), # -----1-001----1-011--10-
(-x[5],x[4],x[0],-y[4],-y[2],y[0],z[8],z[7],-z[6],-z[3],), # 01---1-0-0-1---110--0---
(-x[4],y[4],y[3],-y[2],-z[8],-z[7],z[6],-z[4],z[3],-z[0],), # -0-----110-----001-01--0
(-x[3],x[2],-x[1],-y[4],-y[2],y[1],-z[11],z[10],z[9],z[7],), # --010--0-01-011-1-------
(-x[5],x[4],-x[2],-y[1],z[10],z[7],-z[5],z[3],-z[1],-z[0],), # 01-0------0--1--1-0-1-00
(-x[4],-x[2],-y[5],y[3],y[1],-y[0],-z[8],z[7],z[3],z[1],), # -0-0--0-1-10---01---1-1-
(-x[4],-x[2],x[0],-y[1],z[10],z[9],z[7],z[5],-z[3],-z[2],), # -0-0-1----0--11-1-1-00--
(x[2],x[0],y[4],-z[11],-z[9],-z[7],z[1],), # ---1-1-1----0-0-0-----1-
(-x[0],y[4],y[3],y[2],z[10],-z[8],-z[6],z[5],-z[4],-z[2],), # -----0-111---1-0-010-0--
(-x[4],x[2],x[1],y[3],-z[10],z[9],-z[8],-z[7],), # -0-11---1----0100-------
(x[5],-y[5],y[2],z[7],-z[6],z[5],-z[3],z[2],-z[0],), # 1-----0--1------101-01-0
(-x[2],-x[1],-x[0],y[4],z[9],z[8],-z[7],z[6],z[3],z[2],-z[1],), # ---000-1------1101--110-
(-x[4],x[3],-x[2],y[4],-y[2],y[0],-z[5],z[4],z[1],), # -010---1-0-1------01--1-
(-x[4],x[2],x[1],-y[5],y[3],y[2],y[1],-z[8],-z[7],), # -0-11-0-111----00-------
(x[3],y[2],-z[11],-z[10],-z[7],z[0],), # --1------1--00--0------1
(x[3],y[5],y[3],y[2],z[6],-z[5],z[4],-z[3],-z[0],), # --1---1-11-------1010--0
(x[3],x[2],y[3],-y[2],y[1],z[3],-z[1],), # --11----101---------1-0-
(-x[3],-x[2],y[3],-z[11],z[10],z[8],z[4],-z[0],), # --00----1---01-1---1---0
(x[3],y[5],y[3],y[2],y[1],-z[7],z[2],), # --1---1-111-----0----1--
(-x[3],x[2],-x[1],x[0],-y[3],-z[11],-z[6],-z[5],z[3],), # --0101--0---0----00-1---
(-x[5],x[3],-x[2],-y[5],-y[3],z[5],-z[4],-z[2],-z[0],), # 0-10--0-0---------10-0-0
(-x[4],-x[2],x[1],-y[3],y[2],y[1],-z[11],-z[7],-z[5],), # -0-01---011-0---0-0-----
(-x[5],-x[4],x[3],-y[4],y[1],z[8],z[6],-z[3],z[1],-z[0],), # 001----0--1----1-1--0-10
(-x[3],y[3],-y[2],z[11],-z[8],-z[5],-z[4],-z[2],-z[0],), # --0-----10--1--0--00-0-0
(-x[1],-y[3],-y[2],y[1],-z[11],-z[10],z[7],z[0],), # ----0---001-00--1------1
(x[5],x[4],-x[3],-x[1],y[5],y[2],-y[1],z[7],-z[6],z[5],), # 110-0-1--10-----101-----
(x[3],y[3],-y[2],y[1],-z[11],z[7],z[3],z[0],), # --1-----101-0---1---1--1
(-x[4],x[1],-y[5],y[3],-y[1],-z[7],z[5],-z[3],-z[2],z[1],), # -0--1-0-1-0-----0-1-001-
(-x[5],x[2],-x[1],-y[5],-y[3],z[9],-z[7],-z[6],z[5],-z[0],), # 0--10-0-0-----1-001----0
(x[0],-y[3],z[11],-z[10],-z[9],z[7],-z[3],z[2],-z[1],), # -----1--0---100-1---010-
(-x[3],x[2],-y[5],-y[4],y[3],y[1],y[0],-z[10],z[8],z[7],), # --01--001-11-0-11-------
(x[5],y[2],-y[1],-z[8],-z[7],-z[5],z[4],z[1],-z[0],), # 1--------10----00-01--10
(-x[3],-x[2],y[4],-y[3],-z[10],-z[9],z[8],z[7],), # --00---10----0011-------
(x[3],x[1],-y[5],y[4],y[1],y[0],z[5],z[4],-z[2],), # --1-1-01--11------11-0--
(-x[3],-x[1],-y[4],-y[2],y[1],z[11],z[9],z[8],z[7],), # --0-0--0-01-1-111-------
(-x[3],x[1],-y[5],y[3],-y[2],-z[7],z[6],z[5],-z[1],), # --0-1-0-10------011---0-
(-x[5],x[4],-x[3],-y[5],y[4],-y[3],-y[2],y[0],z[8],z[6],z[2],), # 010---0100-1---1-1---1--
(-x[4],-x[2],-x[1],x[0],-y[5],-y[4],-z[7],-z[6],-z[5],z[4],z[1],), # -0-00100--------0001--1-
(-x[4],-y[3],-y[2],-y[0],z[10],z[9],z[8],z[4],-z[2],), # -0------00-0-111---1-0--
(-x[1],-y[5],y[4],-y[3],z[11],z[9],z[7],-z[6],z[5],z[4],-z[3],z[0],), # ----0-010---1-1-10110--1
(-x[5],x[4],-x[1],-y[4],-y[2],y[0],-z[7],z[4],z[3],z[1],), # 01--0--0-0-1----0--11-1-
(-x[5],x[4],x[3],-y[4],y[2],y[0],z[6],z[3],-z[1],), # 011----0-1-1-----1--1-0-
(-x[3],x[2],-x[1],x[0],-y[5],-y[3],y[2],z[10],-z[6],-z[5],), # --01010-01---1---00-----
(x[2],-x[1],-y[4],-y[3],z[11],-z[9],z[5],-z[4],z[3],-z[0],), # ---10--00---1-0---101--0
(x[4],y[5],y[3],y[2],-z[8],-z[7],), # -1----1-11-----00-------
(y[5],-y[3],-y[1],z[6],-z[5],z[4],-z[2],-z[1],-z[0],), # ------1-0-0------101-000
(-x[4],-x[3],y[4],y[3],-y[2],-z[4],-z[2],-z[1],-z[0],), # -00----110---------0-000
(-x[5],x[3],y[5],-y[2],y[1],z[9],-z[7],z[5],-z[3],-z[1],), # 0-1---1--01---1-0-1-0-0-
(-x[5],-x[3],x[2],x[1],-y[4],y[1],z[7],z[6],z[5],z[0],), # 0-011--0--1-----111----1
(x[5],-x[3],-y[5],y[3],z[9],z[5],-z[4],z[2],-z[0],), # 1-0---0-1-----1---10-1-0
(-x[3],-x[2],x[1],-y[3],-y[2],y[1],-z[5],z[2],z[0],), # --001---001-------0--1-1
(x[5],-x[3],x[2],-y[5],-y[1],-z[7],z[6],z[5],-z[2],z[1],), # 1-01--0---0-----011--01-
(-x[4],x[3],-x[2],y[4],-y[3],-z[4],-z[2],-z[1],-z[0],), # -010---10----------0-000
(-x[4],-x[3],x[2],z[11],-z[9],z[8],z[5],-z[2],-z[1],-z[0],), # -001--------1-01--1--000
(x[3],x[2],y[3],y[2],y[0],z[10],-z[9],-z[7],-z[6],), # --11----11-1-10-00------
(x[4],-x[2],x[1],y[1],-z[7],z[6],z[5],-z[3],z[2],), # -1-01-----1-----011-01--
(y[3],-y[1],-z[10],-z[7],-z[6],-z[4],-z[2],-z[0],), # --------1-0--0--00-0-0-0
(-x[5],-x[4],x[2],-y[5],y[4],-y[2],-y[1],z[6],-z[5],-z[3],z[1],), # 00-1--01-00------10-0-1-
(x[5],x[3],x[1],y[4],-y[3],-y[0],z[7],-z[5],z[3],z[2],), # 1-1-1--10--0----1-0-11--
(-y[5],-y[4],-y[0],z[11],z[10],-z[7],z[5],z[4],z[3],-z[1],), # ------00---011--0-111-0-
(x[4],x[3],x[2],x[1],y[2],-z[7],z[1],), # -1111----1------0-----1-
(x[5],-x[3],y[5],-y[3],y[1],-z[5],z[4],-z[2],-z[0],), # 1-0---1-0-1-------01-0-0
(-x[4],x[1],y[5],-y[4],y[3],z[8],-z[5],z[4],z[2],-z[1],), # -0--1-101------1--01-10-
(-x[3],-x[2],-x[1],-y[4],-y[2],-y[0],-z[11],z[10],z[9],z[7],), # --000--0-0-0011-1-------
(-x[4],-x[3],-x[2],x[1],-y[3],-y[1],z[11],z[10],-z[9],z[6],-z[5],), # -0001---0-0-110--10-----
(x[2],y[3],-y[2],-y[1],-z[6],-z[3],z[2],), # ---1----100------0--01--
(-x[1],x[0],y[4],y[3],-z[5],z[3],z[2],z[1],), # ----01-11---------0-111-
(x[4],x[1],y[4],y[3],-y[2],z[4],-z[3],z[2],-z[0],), # -1--1--110---------101-0
(-x[5],x[4],x[0],-y[5],-y[4],y[0],-z[6],z[3],-z[2],), # 01---100---1-----0--10--
(-x[3],-x[2],y[5],-y[3],-y[2],y[1],z[6],-z[5],-z[4],z[2],z[1],), # --00--1-001------100-11-
(x[5],x[4],x[3],-x[1],-x[0],-y[5],y[3],z[6],-z[5],-z[3],), # 111-000-1--------10-0---
(x[4],-y[5],y[1],z[11],z[10],-z[9],-z[8],-z[5],), # -1----0---1-1100--0-----
(-x[3],-y[2],y[1],z[11],-z[10],z[5],-z[2],z[1],-z[0],), # --0------01-10----1--010
(x[4],x[2],x[1],x[0],y[2],y[0],-z[5],), # -1-111---1-1------0-----
(-x[2],-x[1],-x[0],y[5],-y[3],-y[1],z[9],z[7],z[6],z[4],), # ---0001-0-0---1-11-1----
(-x[4],x[0],-y[5],y[3],-y[2],-z[6],-z[5],-z[3],-z[1],), # -0---10-10-------00-0-0-
(-x[2],x[1],y[5],-y[4],z[7],z[6],z[5],z[3],-z[1],), # ---01-10--------111-1-0-
(-x[4],-x[3],-x[2],-y[3],-y[2],y[1],-z[8],-z[7],z[1],), # -000----001----00-----1-
(x[4],x[3],y[4],-y[3],y[1],z[4],-z[3],-z[1],-z[0],), # -11----10-1--------10-00
(-x[5],-x[3],x[0],-y[4],y[3],-z[5],-z[3],-z[2],-z[1],), # 0-0--1-01---------0-000-
(-x[3],x[2],x[1],y[5],-z[8],-z[5],z[2],-z[1],), # --011-1--------0--0--10-
(x[5],x[3],-x[2],-x[1],y[5],y[3],-y[2],-y[1],z[7],-z[6],), # 1-100-1-100-----10------
(-x[3],-x[1],-y[5],y[2],z[11],z[9],z[7],-z[6],-z[4],z[2],z[0],), # --0-0-0--1--1-1-10-0-1-1
(-x[5],-x[4],-y[2],-y[1],-y[0],-z[10],-z[5],z[2],z[0],), # 00-------000-0----0--1-1
(x[5],-x[3],x[1],-y[4],-y[2],y[1],-z[10],z[7],-z[6],), # 1-0-1--0-01--0--10------
(-x[3],-x[1],y[4],-y[3],-y[2],-z[10],-z[9],z[8],), # --0-0--100---001--------
(x[4],-x[2],x[1],y[5],-y[3],y[2],z[8],-z[6],-z[1],), # -1-01-1-01-----1-0----0-
(x[2],-x[1],y[3],-z[10],-z[6],-z[5],-z[2],-z[0],), # ---10---1----0---00--0-0
(x[4],-x[3],-x[1],y[2],z[11],-z[9],z[5],-z[4],z[1],-z[0],), # -10-0----1--1-0---10--10
(-x[2],-x[1],-y[4],-y[3],y[2],-z[11],-z[8],z[7],), # ---00--001--0--01-------
(-x[4],-y[4],y[1],z[11],-z[6],z[5],z[4],-z[2],z[1],-z[0],), # -0-----0--1-1----011-010
(x[4],-x[2],y[5],-y[4],y[3],z[6],-z[5],-z[4],z[2],z[0],), # -1-0--101--------100-1-1
(-x[4],x[3],y[4],y[3],-y[1],y[0],-z[8],-z[6],-z[4],z[2],), # -01----11-01---0-0-0-1--
(x[3],x[0],y[5],-y[4],-y[2],z[8],-z[7],z[5],-z[3],z[1],), # --1--110-0-----10-1-0-1-
(-x[4],x[1],-y[4],z[11],z[8],z[7],z[6],-z[5],z[1],-z[0],), # -0--1--0----1--1110---10
(-x[5],-x[3],-y[5],y[2],-y[1],z[8],-z[7],-z[5],z[1],-z[0],), # 0-0---0--10----10-0---10
(x[5],x[2],y[5],y[2],-z[6],-z[5],-z[4],-z[2],), # 1--1--1--1-------000-0--
(x[5],-x[4],-y[4],y[2],y[1],-z[8],z[4],-z[2],z[0],), # 10-----0-11----0---1-0-1
(-x[5],-x[3],-y[2],-y[1],z[11],-z[9],z[7],z[6],z[5],-z[2],z[1],), # 0-0------00-1-0-111--01-
(-x[4],x[2],y[5],-y[2],y[0],z[6],z[5],z[4],z[3],), # -0-1--1--0-1-----1111---
(x[4],-x[3],y[4],-y[3],y[1],z[4],z[3],z[1],-z[0],), # -10----10-1--------11-10
(x[4],x[1],y[3],y[0],-z[5],-z[3],z[1],), # -1--1---1--1------0-0-1-
(-x[5],x[3],-x[2],y[5],y[4],-y[3],y[1],-y[0],z[9],z[6],), # 0-10--110-10--1--1------
(x[5],x[3],-y[5],y[3],-y[2],-z[5],z[4],z[2],-z[0],), # 1-1---0-10--------01-1-0
(-x[5],-y[5],y[3],z[11],-z[7],-z[2],-z[1],-z[0],), # 0-----0-1---1---0----000
(-x[4],-y[3],-y[2],y[1],z[11],-z[10],z[6],-z[5],z[1],-z[0],), # -0------001-10---10---10
(-x[2],x[1],x[0],-y[5],y[3],-y[2],y[1],-z[10],z[8],-z[7],), # ---0110-101--0-10-------
(-x[2],x[1],-y[5],y[4],z[11],z[6],z[5],-z[4],-z[1],-z[0],), # ---01-01----1----110--00
(-x[2],x[1],y[4],y[3],z[10],-z[9],z[7],-z[4],z[1],), # ---01--11----10-1--0--1-
(-x[4],-x[3],x[2],-y[5],y[4],-y[3],-y[2],y[1],y[0],z[6],-z[3],), # -001--010011-----1--0---
(-x[4],x[2],y[5],-y[4],y[2],-z[9],z[7],z[3],-z[2],), # -0-1--10-1----0-1---10--
(x[5],-x[4],x[0],y[4],y[2],-z[7],z[5],z[2],-z[1],), # 10---1-1-1------0-1--10-
(x[4],-x[3],-x[2],x[0],-y[4],y[0],z[5],-z[2],), # -100-1-0---1------1--0--
(x[5],x[4],-x[2],-x[0],-y[4],y[3],y[2],z[6],-z[5],), # 11-0-0-011-------10-----
(-x[5],x[1],x[0],-y[4],-y[3],z[6],-z[3],-z[2],), # 0---11-00--------1--00--
(-x[3],x[0],y[5],-y[4],-y[3],y[2],-z[7],z[5],z[4],-z[2],), # --0--11001------0-11-0--
(x[3],x[2],-x[1],y[5],-y[4],y[2],y[1],z[6],-z[3],), # --110-10-11------1--0---
(-x[4],-x[3],y[5],y[2],y[1],-z[10],z[8],z[2],), # -00---1--11--0-1-----1--
(-x[4],x[1],y[4],y[3],-y[2],-z[4],-z[3],z[2],-z[0],), # -0--1--110---------001-0
(x[5],x[2],x[0],y[2],-z[5],-z[3],z[1],), # 1--1-1---1--------0-0-1-
(-x[4],x[0],y[4],-y[3],-y[2],y[0],z[5],-z[2],), # -0---1-100-1------1--0--
(-x[4],-y[3],-y[2],-y[1],-z[11],-z[5],z[1],-z[0],), # -0------000-0-----0---10
(x[4],-x[3],x[2],-x[1],-y[5],-y[4],-y[2],-y[1],y[0],-z[5],-z[4],), # -1010-00-001------00----
(-x[5],x[4],x[3],-y[3],z[11],z[7],z[5],z[3],-z[0],), # 011-----0---1---1-1-1--0
(-x[4],x[3],-y[5],y[4],y[0],-z[5],-z[2],-z[1],), # -01---01---1------0--00-
(x[5],x[4],x[0],-y[4],y[1],z[5],z[4],-z[1],), # 11---1-0--1-------11--0-
(x[5],-x[3],x[1],x[0],y[3],-y[2],y[1],z[5],-z[4],), # 1-0-11--101-------10----
(-x[2],x[1],-y[4],y[2],z[10],z[9],z[6],-z[4],-z[1],), # ---01--0-1---11--1-0--0-
(-x[3],x[1],-y[4],-y[3],z[11],-z[10],z[5],-z[2],-z[0],), # --0-1--00---10----1--0-0
(x[5],-x[3],x[2],x[0],-y[3],-y[1],z[6],-z[4],z[1],), # 1-01-1--0-0------1-0--1-
(x[5],-x[3],x[2],-x[1],-y[5],y[4],-y[2],-y[1],-z[7],z[6],-z[4],), # 1-010-01-00-----01-0----
(-x[5],-x[4],-x[3],x[0],-y[4],y[1],-z[5],z[3],-z[1],), # 000--1-0--1-------0-1-0-
(x[5],-x[3],-y[2],-y[0],z[5],z[2],z[1],z[0],), # 1-0------0-0------1--111
(-x[5],x[3],-x[2],y[5],-y[3],-z[5],-z[4],-z[2],-z[0],), # 0-10--1-0---------00-0-0
(x[4],x[2],-y[5],-y[4],y[1],z[11],-z[6],-z[5],-z[2],), # -1-1--00--1-1----00--0--
(x[4],x[3],x[2],-x[1],-y[2],-z[10],-z[7],z[6],z[0],), # -1110----0---0--01-----1
(-x[4],x[3],-x[1],-x[0],-y[4],-z[6],z[5],z[3],-z[2],z[1],), # -01-00-0---------01-101-
(x[2],y[5],y[2],y[0],-z[5],-z[3],z[1],), # ---1--1--1-1------0-0-1-
(-x[5],x[4],x[3],x[2],x[1],y[5],z[6],-z[1],), # 01111-1----------1----0-
(x[4],x[3],x[2],y[1],-y[0],-z[6],-z[5],z[1],), # -111------10-----00---1-
(x[4],-x[3],-x[2],y[5],y[3],-y[1],-z[9],z[8],), # -100--1-1-0---01--------
(x[5],-x[4],x[0],-y[4],y[3],z[5],z[2],-z[1],), # 10---1-01---------1--10-
(x[5],-x[4],-x[3],x[1],y[5],-y[3],y[2],-z[8],-z[6],), # 100-1-1-01-----0-0------
(-x[5],x[4],y[5],-y[2],y[0],z[10],z[9],z[7],-z[6],), # 01----1--0-1-11-10------
(-x[4],x[2],y[5],-y[3],y[1],-z[10],z[7],-z[1],), # -0-1--1-0-1--0--1-----0-
(-x[5],-x[4],x[1],y[2],z[11],z[9],-z[6],-z[1],-z[0],), # 00--1----1--1-1--0----00
(-x[5],x[0],y[4],-y[2],y[1],z[11],z[8],z[6],z[5],-z[2],), # 0----1-1-01-1--1-11--0--
(x[4],-x[3],-y[4],y[3],-y[2],y[0],z[11],-z[6],-z[5],-z[3],), # -10----010-11----00-0---
(x[5],-x[2],x[0],y[4],y[3],-z[5],-z[4],-z[1],), # 1--0-1-11---------00--0-
(x[3],x[2],-x[1],y[5],y[4],-y[3],z[7],-z[6],-z[0],), # --110-110-------10-----0
(-x[2],-x[0],y[5],-y[3],z[5],z[2],z[1],z[0],), # ---0-01-0---------1--111
(-x[4],x[1],y[5],y[4],y[0],z[5],z[4],-z[1],), # -0--1-11---1------11--0-
(-x[4],x[2],-y[5],-y[4],-y[2],y[0],-z[5],-z[2],-z[1],), # -0-1--00-0-1------0--00-
(-x[5],x[3],x[1],-y[5],-y[3],-y[2],z[7],-z[1],z[0],), # 0-1-1-0-00------1-----01
(x[4],x[3],y[5],y[4],y[0],-z[5],-z[2],-z[1],), # -11---11---1------0--00-
(-x[5],y[3],-y[2],-y[1],z[11],z[9],-z[7],z[6],-z[4],z[1],z[0],), # 0-------100-1-1-01-0--11
(-x[4],-x[3],-y[5],y[3],y[2],y[0],-z[5],-z[2],-z[1],), # -00---0-11-1------0--00-
(-x[5],x[4],-x[3],-x[2],-x[1],y[3],-y[2],-y[1],y[0],z[7],-z[5],), # 01000---1001----1-0-----
(x[5],x[4],x[1],-y[4],-y[3],-y[2],-z[6],-z[1],), # 11--1--000-------0----0-
(-x[4],x[3],-x[1],y[4],y[3],-z[4],z[3],z[1],), # -01-0--11----------01-1-
(-x[5],x[2],-y[4],-y[1],-y[0],z[11],z[8],-z[7],-z[3],-z[2],), # 0--1---0--001--10---00--
(-x[3],x[2],y[5],-y[3],-y[2],-z[10],-z[8],z[1],z[0],), # --01--1-00---0-0------11
(-x[5],x[3],-x[2],y[3],y[1],z[11],z[10],-z[6],-z[2],-z[1],), # 0-10----1-1-11---0---00-
(-x[5],-x[4],-x[3],x[1],x[0],y[4],-z[6],-z[2],), # 000-11-1---------0---0--
(-x[4],-x[3],y[5],-y[4],y[0],z[5],-z[2],-z[1],), # -00---10---1------1--00-
(x[3],y[5],y[4],-y[2],-y[1],-z[9],z[7],-z[6],z[0],), # --1---11-00---0-10-----1
(-x[5],x[4],x[2],x[0],y[5],-y[4],z[6],-z[5],-z[2],), # 01-1-110---------10--0--
(-x[3],y[5],y[4],-y[3],y[2],y[1],y[0],z[6],), # --0---110111-----1------
(-x[4],-x[1],-y[5],-y[4],-y[3],y[0],-z[5],-z[3],-z[1],), # -0--0-000--1------0-0-0-
(-x[5],x[3],x[1],-y[5],-y[3],-y[2],-y[1],-y[0],z[7],z[0],), # 0-1-1-0-0000----1------1
(x[2],y[5],y[3],y[2],y[1],-z[6],-z[5],z[0],), # ---1--1-111------00----1
(x[4],-y[5],-y[4],-y[3],y[1],y[0],-z[6],-z[2],), # -1----000-11-----0---0--
(x[4],-x[3],-y[4],-y[3],y[1],-z[10],-z[8],-z[7],), # -10----00-1--0-00-------
(-x[5],-x[1],y[2],z[11],z[7],z[5],z[2],z[1],-z[0],), # 0---0----1--1---1-1--110
(-x[3],x[2],x[1],y[5],y[1],y[0],z[5],-z[2],), # --011-1---11------1--0--
(x[4],-y[4],y[3],y[2],y[0],z[5],-z[2],z[1],), # -1-----011-1------1--01-
(-x[5],x[4],x[3],-x[2],y[5],-y[4],-y[2],-z[7],z[5],-z[2],), # 0110--10-0------0-1--0--
(-x[4],-x[3],x[2],y[5],y[4],-y[2],-y[0],-z[9],z[6],), # -001--11-0-0--0--1------
(-x[5],-x[4],-x[2],y[5],y[4],y[3],y[1],-y[0],-z[7],), # 00-0--111-10----0-------
(-x[3],-x[2],-x[1],-y[5],-y[4],y[3],y[2],z[10],z[7],z[1],z[0],), # --000-0011---1--1-----11
(-x[5],-x[3],y[5],y[4],-y[2],y[1],y[0],z[7],-z[6],), # 0-0---11-011----10------
(-x[4],-x[1],y[5],y[4],y[0],z[5],-z[4],-z[1],), # -0--0-11---1------10--0-
(x[5],x[3],x[1],-y[5],-y[4],-y[2],-y[1],-z[7],z[6],z[1],), # 1-1-1-00-00-----01----1-
(-x[5],-x[2],-x[1],-y[4],-y[2],-y[1],z[11],-z[8],z[7],z[6],), # 0--00--0-00-1--011------
(-x[4],-x[3],-x[2],-x[1],y[5],y[1],z[6],-z[3],z[1],), # -0000-1---1------1--0-1-
(-y[5],-y[4],-y[3],-y[2],y[0],z[10],z[5],z[2],-z[1],), # ------0000-1-1----1--10-
(-x[4],-x[2],-y[5],-y[4],-y[3],y[2],z[11],-z[8],-z[4],z[1],), # -0-0--0001--1--0---0--1-
(x[5],-x[3],-x[2],-x[1],-y[4],z[9],-z[5],z[1],-z[0],), # 1-000--0------1---0---10
(-x[5],x[4],-x[3],-x[2],y[5],-y[3],z[7],z[2],-z[1],z[0],), # 0100--1-0-------1----101
(x[2],-y[3],y[1],z[9],z[6],z[5],z[4],-z[3],z[2],-z[1],), # ---1----0-1---1--111010-
(-y[3],-z[11],-z[9],-z[7],-z[1],-z[0],), # --------0---0-0-0-----00
(x[5],-x[4],-x[3],x[1],x[0],y[3],-z[5],-z[2],), # 100-11--1---------0--0--
(x[4],x[3],x[2],-x[1],-y[5],-y[4],z[11],-z[6],-z[2],-z[0],), # -1110-00----1----0---0-0
(-x[5],x[4],x[2],-x[1],y[4],-y[2],-y[1],z[10],z[6],-z[3],z[0],), # 01-10--1-00--1---1--0--1
(-x[4],x[0],-y[5],y[4],z[11],z[9],-z[6],z[2],-z[1],), # -0---101----1-1--0---10-
(-x[4],x[3],x[2],x[0],-y[4],-z[5],-z[2],z[1],), # -011-1-0----------0--01-
(x[3],x[2],-x[1],-y[1],z[10],-z[8],z[7],z[6],z[5],-z[4],z[3],), # --110-----0--1-011101---
(x[3],y[5],-y[4],-y[3],y[1],y[0],-z[5],-z[2],), # --1---100-11------0--0--
(x[5],-x[3],-x[2],-x[1],x[0],-y[5],-y[3],z[10],-z[7],-z[5],), # 1-00010-0----1--0-0-----
(x[3],y[3],-z[11],-z[7],-z[5],z[4],), # --1-----1---0---0-01----
(x[5],x[1],-y[3],-y[2],-y[1],z[5],-z[2],z[1],), # 1---1---000-------1--01-
(-x[5],-x[3],y[5],-y[3],-y[2],-y[1],y[0],z[10],-z[7],-z[5],), # 0-0---1-0001-1--0-0-----
(x[5],-x[4],-x[3],x[1],x[0],-y[3],z[5],-z[2],), # 100-11--0---------1--0--
(x[5],-x[4],x[3],x[1],-y[4],-y[3],y[2],-y[1],-z[6],z[1],), # 101-1--0010------0----1-
(-x[4],-y[4],y[2],z[10],z[8],-z[6],z[4],z[3],-z[0],), # -0-----0-1---1-1-0-11--0
(-x[3],y[5],-y[4],-y[3],y[1],y[0],z[5],-z[2],), # --0---100-11------1--0--
(-x[4],-x[2],-z[11],z[8],z[7],-z[6],z[4],z[3],z[2],z[0],), # -0-0--------0--110-111-1
(-x[4],x[3],-x[2],x[1],y[5],y[4],-y[3],-y[2],-y[0],-z[6],), # -0101-1100-0-----0------
(y[1],z[11],-z[10],-z[9],z[5],z[4],-z[3],z[1],-z[0],), # ----------1-100---110-10
(-z[11],-z[8],z[7],-z[3],z[2],z[1],-z[0],), # ------------0--01---0110
(x[3],x[2],-y[3],y[1],-y[0],-z[9],z[8],-z[6],z[5],-z[3],), # --11----0-10--01-01-0---
(-x[3],y[4],-y[2],-z[11],-z[7],z[4],z[3],-z[2],z[1],), # --0----1-0--0---0--1101-
(-x[5],-x[4],x[3],-x[2],y[4],-y[3],y[2],y[0],z[11],-z[6],), # 0010---101-11----0------
(x[4],-x[2],-y[4],-y[1],z[9],z[8],z[5],-z[4],z[3],-z[0],), # -1-0---0--0---11--101--0
(x[3],-x[2],y[2],z[10],-z[9],z[8],-z[5],-z[4],z[3],-z[1],z[0],), # --10-----1---101--001-01
(x[4],x[2],-x[1],y[3],-y[2],z[10],z[9],z[7],-z[6],z[5],-z[4],), # -1-10---10---11-1010----
(-x[4],x[1],y[4],y[3],-y[1],z[9],-z[7],-z[6],-z[4],), # -0--1--11-0---1-00-0----
(y[3],y[2],y[1],z[10],-z[9],z[8],z[5],z[1],-z[0],), # --------111--101--1---10
(y[5],-y[4],-y[3],-y[2],-y[1],z[10],-z[5],z[1],-z[0],), # ------10000--1----0---10
(x[4],-x[2],-x[1],y[4],-y[2],-y[1],z[9],z[8],z[5],z[4],z[2],), # -1-00--1-00---11--11-1--
(x[5],x[4],x[2],y[5],y[3],z[7],-z[6],-z[5],), # 11-1--1-1-------100-----
(-x[2],x[0],-y[4],y[2],y[1],y[0],-z[5],-z[4],), # ---0-1-0-111------00----
(-x[3],x[2],x[1],y[3],y[2],-z[9],z[8],z[7],), # --011---11----011-------
(-x[4],x[3],-x[1],y[5],-z[9],-z[7],-z[6],z[5],z[3],), # -01-0-1-------0-001-1---
(-y[5],y[2],y[1],z[9],z[7],-z[6],-z[3],-z[2],-z[1],), # ------0--11---1-10--000-
(y[5],y[4],y[3],y[2],y[1],-z[6],), # ------11111------0------
(-x[5],x[3],-y[2],z[9],-z[8],z[7],z[6],-z[5],-z[0],), # 0-1------0----10110----0
(-x[4],-x[2],x[1],-y[5],y[0],-z[9],z[8],z[6],-z[5],-z[4],), # -0-01-0----1--01-100----
(-x[4],x[3],-y[5],y[3],z[10],z[9],z[8],-z[7],), # -01---0-1----1110-------
(x[3],x[1],y[2],-y[0],-z[9],-z[7],-z[6],-z[5],-z[4],z[3],), # --1-1----1-0--0-00001---
(x[5],x[3],y[5],y[4],y[3],y[1],-z[7],), # 1-1---111-1-----0-------
(-x[2],-y[5],-y[4],-z[8],z[6],-z[5],-z[4],-z[2],-z[0],), # ---0--00-------0-100-0-0
(x[3],x[1],-y[3],y[1],y[0],z[5],-z[4],z[3],), # --1-1---0-11------101---
(x[5],x[4],x[3],y[5],y[4],y[3],-z[6],), # 111---111--------0------
(x[2],-y[4],-y[3],y[2],-z[10],-z[9],z[8],-z[6],), # ---1---001---001-0------
(x[3],-y[5],y[4],-y[1],y[0],z[10],z[9],-z[6],z[4],-z[3],z[2],), # --1---01--01-11--0-101--
(x[3],-x[2],y[4],-y[3],z[10],z[6],z[5],z[4],-z[3],-z[0],), # --10---10----1---1110--0
(-y[4],z[11],z[9],-z[8],z[6],z[5],z[4],z[2],-z[1],-z[0],), # -------0----1-10-111-100
(x[4],x[2],y[4],y[2],z[9],z[8],z[6],-z[5],-z[4],), # -1-1---1-1----11-100----
(-x[3],x[2],-y[2],y[1],y[0],z[5],z[3],z[2],), # --01-----011------1-11--
(-x[5],-x[3],-y[5],-z[9],z[8],z[6],-z[5],-z[2],z[1],-z[0],), # 0-0---0-------01-10--010
(x[0],-y[5],y[2],-y[1],z[10],-z[8],-z[6],z[4],-z[3],-z[2],), # -----10--10--1-0-0-100--
(-x[5],x[3],-y[2],z[10],z[8],z[7],-z[6],-z[3],-z[1],-z[0],), # 0-1------0---1-110--0-00
(-y[5],z[10],z[8],z[7],-z[6],z[5],z[3],z[1],-z[0],), # ------0------1-1101-1-10
(-x[3],-y[5],y[1],z[6],-z[5],z[4],-z[2],-z[1],-z[0],), # --0---0---1------101-000
(x[3],y[4],-z[11],-z[8],-z[7],z[2],z[1],), # --1----1----0--00----11-
(x[4],y[4],y[3],y[2],-z[9],-z[8],), # -1-----111----00--------
(x[1],y[1],-z[11],-z[10],-z[7],z[0],), # ----1-----1-00--0------1
(x[5],x[3],x[2],y[5],y[2],-z[6],-z[5],z[2],-z[1],), # 1-11--1--1-------00--10-
(x[4],x[2],x[1],-y[2],y[0],z[5],-z[4],z[2],), # -1-11----0-1------10-1--
(-x[3],x[2],-x[0],-y[4],-z[9],-z[8],-z[6],z[3],z[0],), # --01-0-0------00-0--1--1
(x[5],x[1],y[4],-y[2],-z[8],-z[7],-z[6],z[4],-z[2],z[1],), # 1---1--1-0-----000-1-01-
(-y[5],-y[4],y[3],y[2],z[6],z[5],z[4],z[2],-z[0],), # ------0011-------111-1-0
(-x[1],-y[3],-y[2],z[9],z[7],-z[6],-z[5],-z[2],-z[0],), # ----0---00----1-100--0-0
(-y[4],z[11],-z[9],z[8],z[6],z[5],z[3],-z[2],z[1],-z[0],), # -------0----1-01-11-1010
(-x[4],x[2],z[10],z[9],z[5],z[4],z[2],z[1],-z[0],), # -0-1---------11---11-110
(-x[1],x[0],-y[4],y[3],z[5],z[3],z[2],z[1],), # ----01-01---------1-111-
(-x[5],x[2],-y[4],y[3],y[1],z[6],z[5],-z[4],-z[0],), # 0--1---01-1------110---0
(-x[2],-y[2],-z[9],-z[8],-z[6],-z[4],-z[3],z[1],), # ---0-----0----00-0-00-1-
(-x[3],-y[4],y[2],y[1],z[7],z[5],-z[4],z[1],-z[0],), # --0----0-11-----1-10--10
(-x[4],x[2],-x[1],-y[3],-y[2],-z[11],z[10],-z[8],-z[7],z[5],), # -0-10---00--01-00-1-----
(x[5],x[3],x[2],y[5],y[4],-y[1],z[7],-z[6],z[5],), # 1-11--11--0-----101-----
(-x[4],y[2],-y[1],y[0],z[5],z[3],z[2],z[1],), # -0-------101------1-111-
(-x[5],-x[4],x[2],-y[4],y[3],y[1],-z[8],z[6],-z[0],), # 00-1---01-1----0-1-----0
(-x[4],x[2],x[1],y[3],y[2],-y[1],z[6],z[5],-z[3],), # -0-11---110------11-0---
(x[1],-y[3],-z[11],z[10],-z[7],-z[6],z[2],-z[1],), # ----1---0---01--00---10-
(-x[3],-x[2],x[1],-y[3],-z[11],z[10],z[7],-z[3],z[2],), # --001---0---01--1---01--
(x[4],x[1],-y[4],y[3],-y[2],-z[4],-z[3],z[2],-z[0],), # -1--1--010---------001-0
(-x[5],-y[5],-y[2],-z[8],-z[7],z[5],z[2],-z[1],-z[0],), # 0-----0--0-----00-1--100
(-x[4],x[3],-y[5],-y[4],y[3],y[1],z[6],-z[4],-z[3],z[1],), # -01---001-1------1-00-1-
(x[4],x[3],x[1],-y[5],y[4],-y[1],-z[7],-z[6],-z[4],-z[3],), # -11-1-01--0-----00-00---
(-x[3],-y[5],y[3],-z[8],z[7],z[6],-z[4],-z[2],-z[1],), # --0---0-1------011-0-00-
(-x[4],y[4],-y[3],-y[2],y[1],-y[0],z[6],-z[5],-z[3],-z[2],z[1],), # -0-----10010-----10-001-
(x[0],y[4],y[0],-z[10],-z[6],z[5],-z[3],-z[2],), # -----1-1---1-0---01-00--
(x[4],x[2],-x[1],-y[4],y[3],-y[2],-z[4],z[3],-z[0],), # -1-10--010---------01--0
(x[3],y[4],-y[3],y[2],z[8],-z[6],z[4],z[3],z[1],), # --1----101-----1-0-11-1-
(x[3],-x[2],y[5],-y[3],y[1],z[10],z[8],z[5],-z[4],-z[3],-z[2],), # --10--1-0-1--1-1--1000--
(-x[2],-x[1],-y[5],-y[4],y[3],z[6],-z[4],z[3],z[2],z[1],), # ---00-001--------1-0111-
(x[3],-x[2],x[0],-y[5],y[4],-y[2],z[9],z[7],-z[6],z[3],), # --10-101-0----1-10--1---
(x[3],x[0],-y[4],y[1],y[0],z[5],-z[3],), # --1--1-0--11------1-0---
(-x[5],x[0],-y[4],-z[5],z[4],z[3],-z[2],-z[1],), # 0----1-0----------01100-
(x[3],-x[2],x[1],y[3],y[2],z[3],-z[1],), # --101---11----------1-0-
(-x[3],-y[5],-y[3],-y[0],-z[7],z[6],z[5],z[3],-z[2],z[0],), # --0---0-0--0----011-10-1
(x[4],x[1],x[0],-y[3],y[0],z[5],-z[3],), # -1--11--0--1------1-0---
(x[2],-y[5],-y[4],y[3],-y[0],z[9],-z[8],-z[6],z[5],z[0],), # ---1--001--0--10-01----1
(-x[5],-x[3],-x[2],-x[1],y[2],-y[1],-z[10],-z[8],z[7],), # 0-000----10--0-01-------
(-x[3],x[2],-y[3],y[2],-z[10],-z[9],-z[8],-z[7],), # --01----01---0000-------
(x[3],x[1],-x[0],-y[5],y[4],z[10],-z[8],-z[5],-z[2],), # --1-1001-----1-0--0--0--
(x[3],-y[5],y[1],y[0],z[5],-z[4],z[3],-z[2],), # --1---0---11------1010--
(x[4],x[3],y[5],y[4],-y[1],z[8],-z[7],z[6],), # -11---11--0----101------
(-y[5],y[4],y[3],y[2],y[1],z[6],z[5],z[1],-z[0],), # ------01111------11---10
(x[4],x[1],-x[0],y[4],-y[3],z[9],-z[8],-z[6],z[5],-z[4],), # -1--10-10-----10-010----
(-x[4],x[1],y[3],y[0],z[5],-z[3],z[1],), # -0--1---1--1------1-0-1-
(x[5],-x[3],x[2],y[5],y[4],-z[7],-z[6],-z[2],), # 1-01--11--------00---0--
(x[3],-x[2],y[2],z[9],-z[8],-z[7],-z[6],z[5],-z[1],), # --10-----1----10001---0-
(x[3],x[1],y[3],-y[2],z[3],z[2],z[1],-z[0],), # --1-1---10----------1110
(x[4],-x[3],-y[5],z[8],-z[6],-z[5],z[2],z[1],-z[0],), # -10---0--------1-00--110
(-x[1],-y[5],y[4],-y[3],z[10],z[8],-z[5],-z[3],-z[2],-z[0],), # ----0-010----1-1--0-00-0
(-x[5],x[3],y[1],-y[0],z[5],z[2],z[1],z[0],), # 0-1-------10------1--111
(x[4],-x[3],-y[4],-y[3],y[1],-z[4],z[3],z[1],-z[0],), # -10----00-1--------01-10
(-x[4],x[1],-y[4],y[3],-y[2],z[4],-z[3],z[2],-z[0],), # -0--1--010---------101-0
(x[4],-x[3],-y[1],-y[0],z[4],-z[3],z[1],z[0],), # -10-------00-------10-11
(x[4],x[3],-x[1],-y[3],-y[2],y[1],-z[10],z[7],-z[4],), # -11-0---001--0--1--0----
(-x[4],-x[3],x[1],y[4],-y[3],-z[4],z[3],z[1],-z[0],), # -00-1--10----------01-10
(x[4],x[3],x[0],y[3],-z[9],-z[8],-z[7],z[4],), # -11--1--1-----000--1----
(x[3],x[2],-y[3],y[1],-z[3],-z[2],-z[1],), # --11----0-1---------000-
(-x[4],x[3],-x[2],-x[1],x[0],-y[4],y[2],z[9],z[5],-z[4],-z[2],), # -01001-0-1----1---10-0--
(x[4],x[1],-y[4],-y[3],z[4],-z[3],-z[0],), # -1--1--00----------10--0
(-x[3],x[1],y[0],z[11],-z[10],-z[9],z[8],-z[6],-z[1],), # --0-1------11001-0----0-
(-x[3],-x[1],-y[4],-y[2],y[1],-z[5],z[2],z[1],), # --0-0--0-01-------0--11-
(-x[3],x[1],y[3],y[2],-z[3],-z[2],-z[1],), # --0-1---11----------000-
(-x[4],-x[3],-y[4],y[2],-y[1],z[4],-z[3],z[2],-z[0],), # -00----0-10--------101-0
(-x[4],-x[3],-x[2],x[1],-x[0],-y[4],y[3],-z[11],z[5],z[4],), # -00010-01---0-----11----
(x[4],x[3],y[5],y[2],y[1],-z[10],), # -11---1--11--0----------
(x[1],-x[0],-y[5],z[5],z[3],z[2],z[1],z[0],), # ----100-----------1-1111
(-x[4],x[3],-x[1],-y[4],-y[3],z[4],-z[3],-z[1],-z[0],), # -01-0--00----------10-00
(x[5],-x[4],x[3],y[5],-y[2],z[8],z[6],-z[3],z[2],z[1],), # 101---1--0-----1-1--011-
(x[3],y[4],y[2],-y[0],-z[9],-z[8],-z[6],-z[2],-z[1],), # --1----1-1-0--00-0---00-
(-x[2],x[1],-y[4],-y[1],y[0],z[11],-z[10],z[8],-z[7],-z[5],), # ---01--0--0110-10-0-----
(x[4],-x[3],x[1],-x[0],-y[5],y[3],-y[2],z[6],z[5],-z[2],z[1],), # -10-100-10-------11--01-
(-x[4],-x[2],x[1],y[2],z[11],-z[10],z[7],z[5],z[3],-z[1],), # -0-01----1--10--1-1-1-0-
(-x[2],x[1],y[2],y[1],-z[11],z[8],-z[7],z[0],), # ---01----11-0--10------1
(x[4],-x[2],x[1],-y[5],y[4],z[10],-z[8],z[7],), # -1-01-01-----1-01-------
(-x[5],x[3],-y[3],y[1],z[11],-z[10],z[6],z[5],z[4],-z[1],), # 0-1-----0-1-10---111--0-
(-x[3],x[2],-y[3],y[1],z[3],-z[2],-z[1],), # --01----0-1---------100-
(-x[5],-x[1],-x[0],-y[3],-y[1],z[10],z[9],-z[6],z[4],-z[2],), # 0---00--0-0--11--0-1-0--
(-x[3],x[2],y[5],-y[3],y[2],y[1],z[6],-z[5],z[1],), # --01--1-011------10---1-
(-x[3],-x[1],-y[4],-y[2],y[0],z[10],z[7],-z[6],-z[5],-z[4],), # --0-0--0-0-1-1--1000----
(x[5],y[5],-y[3],-z[8],-z[7],z[6],-z[3],-z[2],), # 1-----1-0------001--00--
(x[3],x[2],-x[1],y[3],z[3],z[2],z[1],-z[0],), # --110---1-----------1110
(-x[4],-x[3],-x[2],x[0],y[4],y[0],z[5],-z[2],), # -000-1-1---1------1--0--
(-x[4],-x[2],x[0],-y[3],-y[1],-z[5],z[2],z[1],), # -0-0-1--0-0-------0--11-
(-x[5],x[0],-y[5],y[3],y[1],-z[7],z[6],-z[3],-z[1],), # 0----10-1-1-----01--0-0-
(-x[3],-x[2],-y[3],-y[1],z[3],-z[2],-z[1],-z[0],), # --00----0-0---------1000
(-x[3],-x[1],-y[5],-y[4],y[3],-z[6],-z[4],z[2],-z[0],), # --0-0-001--------0-0-1-0
(x[5],-x[3],-x[2],-y[5],-y[4],-y[2],z[9],z[7],), # 1-00--00-0----1-1-------
(x[2],-x[1],x[0],-y[5],y[3],y[2],y[1],z[6],-z[5],), # ---1010-111------10-----
(x[5],x[4],x[3],-z[8],-z[7],-z[6],), # 111------------000------
(-x[4],y[5],y[4],y[3],-y[1],z[7],z[6],z[5],), # -0----111-0-----111-----
(x[5],-x[2],y[2],-y[1],-z[10],z[7],z[6],z[5],z[1],), # 1--0-----10--0--111---1-
(-x[3],-x[2],x[1],-y[5],y[3],-z[9],z[8],-z[7],-z[6],z[1],), # --001-0-1-----0100----1-
(-x[4],x[3],x[2],-y[1],y[0],z[5],z[2],z[1],), # -011------01------1--11-
(-x[2],y[5],-y[4],-y[1],z[8],z[7],z[6],-z[5],z[4],z[1],), # ---0--10--0----11101--1-
(-x[4],-x[2],-x[1],-y[1],-z[10],-z[8],-z[7],z[5],-z[3],-z[1],), # -0-00-----0--0-00-1-0-0-
(-x[4],-x[3],-y[4],y[3],-y[2],z[4],-z[2],-z[1],-z[0],), # -00----010---------1-000
(y[4],-y[3],y[2],-y[1],-z[10],z[6],-z[5],z[4],), # -------1010--0---101----
(-x[4],x[3],x[2],x[0],y[4],y[0],z[5],-z[2],), # -011-1-1---1------1--0--
(-x[5],x[3],x[2],x[1],y[2],-y[1],y[0],z[6],-z[5],), # 0-111----101-----10-----
(-x[5],x[2],-x[1],-y[2],y[0],z[7],-z[6],z[5],z[3],), # 0--10----0-1----101-1---
(-x[5],y[5],-y[4],z[6],z[5],-z[4],z[2],-z[1],-z[0],), # 0-----10---------110-100
(-x[5],-x[3],-x[0],-y[3],-y[2],z[10],z[9],-z[8],z[2],), # 0-0--0--00---110-----1--
(x[5],x[4],x[2],y[4],y[3],-y[1],-z[7],-z[4],), # 11-1---11-0-----0--0----
(-x[5],y[2],-y[0],z[5],-z[3],z[2],z[1],z[0],), # 0--------1-0------1-0111
(x[2],-y[4],-y[3],-y[2],-z[11],z[8],z[2],z[1],), # ---1---000--0--1-----11-
(x[2],-x[1],y[3],-y[2],z[10],z[9],-z[8],-z[7],-z[6],), # ---10---10---11000------
(-x[5],x[4],-x[2],x[1],-y[4],-y[1],-z[6],-z[5],z[4],z[1],), # 01-01--0--0------001--1-
(-x[3],-x[1],-y[3],-y[2],z[11],z[9],z[8],z[7],-z[2],), # --0-0---00--1-111----0--
(x[4],-x[2],-y[2],-z[10],-z[9],-z[8],-z[5],-z[1],z[0],), # -1-0-----0---000--0---01
(x[4],-x[3],x[2],x[1],-y[5],y[0],-z[5],-z[4],-z[2],), # -1011-0----1------00-0--
(-x[3],-y[3],-y[2],y[1],z[3],z[2],z[1],-z[0],), # --0-----001---------1110
(-x[4],x[2],-y[1],-y[0],-z[4],-z[3],z[2],z[0],), # -0-1------00-------001-1
(-x[4],-x[3],x[2],-y[3],-y[2],y[1],z[11],z[10],-z[9],z[7],-z[4],), # -001----001-110-1--0----
(x[4],x[1],y[4],y[3],-z[4],z[3],-z[0],), # -1--1--11----------01--0
(x[5],-x[3],-x[2],-x[1],y[2],-z[10],z[7],-z[6],), # 1-000----1---0--10------
(x[2],-y[5],y[2],y[0],z[5],-z[3],z[1],), # ---1--0--1-1------1-0-1-
(-x[5],-x[3],-y[5],y[3],-y[2],z[7],z[5],-z[2],-z[0],), # 0-0---0-10------1-1--0-0
(-x[3],y[4],-y[3],-y[2],y[0],z[4],-z[1],), # --0----100-1-------1--0-
(-x[5],x[1],y[4],-y[3],-y[2],-y[1],z[6],-z[3],z[2],z[1],), # 0---1--1000------1--011-
(-x[2],-y[5],-y[4],-y[3],-y[2],z[8],-z[1],-z[0],), # ---0--0000-----1------00
(-x[4],x[2],x[1],-y[4],y[2],y[1],-z[7],-z[6],-z[4],), # -0-11--0-11-----00-0----
(x[4],-x[3],x[2],x[1],-y[3],y[2],z[11],-z[8],z[7],z[6],), # -1011---01--1--011------
(-x[4],x[3],-y[4],y[3],-y[1],z[4],z[3],z[1],-z[0],), # -01----01-0--------11-10
(-x[5],x[4],x[2],-x[0],-y[5],y[3],-y[2],-z[8],-z[5],-z[2],z[0],), # 01-1-00-10-----0--0--0-1
(x[4],-x[3],-y[3],z[11],z[7],z[5],z[4],-z[1],-z[0],), # -10-----0---1---1-11--00
(-x[5],x[3],y[2],-z[8],-z[7],-z[6],-z[4],z[2],-z[1],), # 0-1------1-----000-0-10-
(x[3],x[2],-y[3],-y[1],-z[3],z[2],z[1],), # --11----0-0---------011-
(-x[2],x[1],-y[5],y[4],z[11],z[8],z[6],z[5],z[4],-z[1],), # ---01-01----1--1-111--0-
(-x[5],-x[4],x[0],y[4],-y[2],z[7],z[5],z[2],-z[1],), # 00---1-1-0------1-1--10-
(-x[3],-x[2],x[1],-y[4],-y[3],y[1],-z[6],-z[5],z[2],z[0],), # --001--00-1------00--1-1
(-x[4],x[3],-x[1],y[4],-y[3],-y[1],-z[7],z[6],z[4],), # -01-0--10-0-----01-1----
(-x[4],-y[3],-y[2],-y[1],z[10],z[9],z[5],-z[1],-z[0],), # -0------000--11---1---00
(x[5],x[2],x[1],y[3],-z[10],z[8],-z[2],), # 1--11---1----0-1-----0--
(x[5],x[2],-y[4],y[3],-y[2],z[10],-z[8],z[7],z[6],), # 1--1---010---1-011------
(-x[5],-x[2],y[5],-y[3],-z[7],z[6],z[5],z[4],-z[0],), # 0--0--1-0-------0111---0
(x[4],x[3],x[0],-y[4],-y[2],y[0],-z[5],z[4],z[3],), # -11--1-0-0-1------011---
(-x[5],-x[3],-y[2],-y[0],-z[5],z[2],z[1],z[0],), # 0-0------0-0------0--111
(-x[4],-x[3],-x[2],-y[5],y[1],z[6],-z[5],-z[1],-z[0],), # -000--0---1------10---00
(x[5],x[2],-x[1],-y[5],y[1],z[8],-z[7],-z[6],-z[2],), # 1--10-0---1----100---0--
(x[4],-x[1],y[4],-y[3],-z[4],z[3],-z[0],), # -1--0--10----------01--0
(-x[3],-x[1],-y[3],y[2],-y[1],z[3],z[2],), # --0-0---010---------11--
(-x[5],x[3],x[1],y[3],y[2],-y[1],-z[5],-z[4],z[1],), # 0-1-1---110-------00--1-
(x[2],-x[1],-y[5],-y[4],-y[3],z[11],z[9],-z[8],z[7],), # ---10-000---1-101-------
(x[5],-x[4],-x[3],-x[2],y[5],y[4],-y[1],-z[6],-z[5],), # 1000--11--0------00-----
(-x[5],x[1],x[0],y[3],y[2],y[1],z[5],-z[2],), # 0---11--111-------1--0--
(-x[2],-x[0],-y[5],-y[3],-z[5],z[2],z[1],z[0],), # ---0-00-0---------0--111
(-x[5],x[4],x[2],x[1],-y[4],y[2],-y[1],-z[7],z[6],z[0],), # 01-11--0-10-----01-----1
(-x[4],-x[3],x[2],y[2],-z[11],z[8],-z[2],), # -001-----1--0--1-----0--
(-x[4],-y[4],y[3],y[2],y[0],-z[5],-z[2],z[1],), # -0-----011-1------0--01-
(x[2],x[1],-y[5],y[3],y[2],-y[1],z[11],z[10],-z[7],-z[5],), # ---11-0-110-11--0-0-----
(x[4],-x[2],-x[1],y[5],-y[4],-y[0],z[10],z[8],z[5],-z[3],-z[2],), # -1-00-10---0-1-1--1-00--
(x[4],y[4],-z[10],z[9],z[6],z[1],-z[0],), # -1-----1-----01--1----10
(-x[1],-y[5],y[4],y[2],z[11],z[10],z[8],z[6],z[2],-z[1],), # ----0-01-1--11-1-1---10-
(-x[4],-x[3],-y[4],-y[3],y[2],y[1],z[4],z[1],-z[0],), # -00----0011--------1--10
(x[4],x[0],-y[4],-y[3],-y[2],y[0],z[5],-z[2],), # -1---1-000-1------1--0--
(-x[5],-x[3],x[0],y[3],y[2],z[11],-z[9],-z[7],z[5],-z[2],), # 0-0--1--11--1-0-0-1--0--
(-x[3],-x[2],y[4],-y[2],y[0],z[4],z[2],-z[1],), # --00---1-0-1-------1-10-
(-x[3],-x[1],-x[0],-y[5],-y[4],-y[2],z[5],-z[4],-z[3],z[0],), # --0-0000-0--------100--1
(x[5],-x[3],x[2],x[0],y[4],-y[2],-z[7],-z[6],-z[5],z[1],), # 1-01-1-1-0------000---1-
(-x[5],-x[4],-x[3],x[1],-y[4],-y[1],z[11],-z[7],z[6],-z[3],z[2],), # 000-1--0--0-1---01--01--
(y[4],y[3],y[2],y[1],-z[10],-z[5],-z[0],), # -------1111--0----0----0
(-x[5],-x[4],-x[2],x[1],-y[5],y[3],-y[2],-z[5],-z[4],-z[1],), # 00-01-0-10--------00--0-
(x[4],-x[3],x[2],y[4],-y[1],z[4],-z[3],z[2],), # -101---1--0--------101--
(x[5],-x[4],y[5],-y[4],-z[6],-z[2],-z[1],-z[0],), # 10----10---------0---000
(-x[4],-x[3],y[3],-y[2],-y[0],z[11],-z[10],-z[7],z[3],z[1],), # -00-----10-010--0---1-1-
(-x[3],-y[5],y[4],y[3],y[1],y[0],-z[5],-z[2],), # --0---011-11------0--0--
(-x[5],-x[4],-x[3],x[2],x[1],-y[4],-y[3],z[7],z[4],-z[3],), # 00011--00-------1--10---
(-x[4],-x[1],-y[5],y[1],z[6],z[5],-z[2],z[1],), # -0--0-0---1------11--01-
(-x[5],x[1],-y[4],-y[1],z[6],z[5],-z[2],z[1],), # 0---1--0--0------11--01-
(x[3],x[2],-x[1],y[4],y[2],-z[10],z[6],z[2],z[0],), # --110--1-1---0---1---1-1
(-x[4],x[3],x[2],y[5],y[2],z[10],z[8],-z[6],-z[3],), # -011--1--1---1-1-0--0---
(-x[5],x[1],x[0],-y[3],y[2],y[1],-z[5],-z[2],), # 0---11--011-------0--0--
(-x[5],-x[2],-y[5],-y[4],-y[3],-y[2],y[0],-z[8],z[2],z[1],), # 0--0--0000-1---0-----11-
(x[5],x[2],x[1],-y[4],-y[3],-y[2],z[7],-z[6],), # 1--11--000------10------
(-x[4],-x[3],y[5],y[4],-y[1],-y[0],z[8],z[7],z[6],), # -00---11--00---111------
(-x[5],-x[4],-x[1],-y[4],-y[2],-y[0],z[11],-z[9],-z[6],), # 00--0--0-0-01-0--0------
(x[4],x[3],-y[5],y[4],-y[3],-z[7],z[6],-z[5],-z[0],), # -11---010-------010----0
(-x[4],-x[3],x[2],-x[1],-y[5],y[2],z[10],-z[7],-z[4],z[1],z[0],), # -0010-0--1---1--0--0--11
(-x[4],-x[3],x[2],y[5],-y[3],-y[1],-z[10],z[7],-z[6],), # -001--1-0-0--0--10------
(x[4],-x[3],-x[1],y[5],-y[3],z[6],-z[5],-z[4],-z[3],z[0],), # -10-0-1-0--------1000--1
(x[4],-x[1],y[4],y[3],-z[4],-z[3],-z[0],), # -1--0--11----------00--0
(x[5],x[2],x[1],y[5],-y[4],-y[3],z[7],z[6],-z[5],), # 1--11-100-------110-----
(x[4],-x[3],-x[2],-x[1],y[5],-y[4],y[2],-y[0],z[6],-z[5],), # -1000-10-1-0-----10-----
(-x[4],x[3],y[4],y[3],z[4],-z[1],-z[0],), # -01----11----------1--00
(x[4],x[3],y[5],-y[2],y[0],-z[5],-z[4],-z[1],), # -11---1--0-1------00--0-
(-x[2],y[5],-y[4],-y[2],z[10],z[6],-z[5],-z[4],-z[2],-z[1],), # ---0--10-0---1---100-00-
(x[5],-x[1],-y[4],-y[3],-y[2],-y[1],-z[10],z[7],z[6],), # 1---0--0000--0--11------
(-x[4],x[0],-y[4],-y[3],-y[2],y[0],-z[5],-z[2],), # -0---1-000-1------0--0--
(-x[5],x[3],-x[2],y[5],-y[2],-y[1],-z[8],-z[7],-z[2],), # 0-10--1--00----00----0--
(x[4],-x[3],-y[5],-y[4],y[0],z[5],-z[2],-z[1],), # -10---00---1------1--00-
(-x[5],x[4],-x[3],-x[2],y[4],y[3],-y[1],z[9],-z[5],z[4],), # 0100---11-0---1---01----
(x[3],-x[2],-x[1],-y[5],y[1],z[5],-z[2],z[1],), # --100-0---1-------1--01-
(x[4],x[3],-y[5],y[4],-y[2],y[1],z[6],-z[4],-z[3],z[0],), # -11---01-01------1-00--1
(x[4],-x[3],-x[2],-x[1],y[5],-y[2],y[1],z[9],-z[6],-z[4],z[0],), # -1000-1--01---1--0-0---1
(x[4],-x[2],x[1],-x[0],y[5],-y[4],-y[2],-z[6],z[5],z[1],), # -1-01010-0-------01---1-
(-x[4],-x[1],-y[5],-y[3],-y[2],z[11],z[10],z[8],), # -0--0-0-00--11-1--------
(x[5],y[3],y[2],y[1],-z[5],-z[2],z[1],z[0],), # 1-------111-------0--011
(-x[4],x[1],-y[5],y[2],y[1],z[11],z[9],-z[7],-z[6],z[0],), # -0--1-0--11-1-1-00-----1
(-x[4],x[2],y[5],y[3],-y[2],y[1],z[6],-z[5],-z[3],z[0],), # -0-1--1-101------10-0--1
(-x[3],-x[1],y[5],-y[4],-y[3],-y[2],-y[1],z[10],z[8],), # --0-0-10000--1-1--------
(x[4],x[3],x[2],y[5],y[4],y[1],-z[6],z[0],), # -111--11--1------0-----1
(x[0],-y[5],-y[4],-y[3],-y[2],y[0],-z[7],-z[2],), # -----10000-1----0----0--
(-x[2],-x[1],y[5],-y[4],-y[3],-y[2],-y[1],z[9],z[7],z[2],), # ---00-10000---1-1----1--
(-x[5],x[4],y[5],-y[4],-y[3],y[1],-z[7],z[2],-z[0],), # 01----100-1-----0----1-0
(x[5],-x[3],-x[1],-x[0],y[5],y[3],-y[2],-y[1],z[7],z[6],), # 1-0-001-100-----11------
(x[4],x[3],x[2],x[0],-y[4],z[5],-z[2],z[1],), # -111-1-0----------1--01-
(x[5],-x[4],x[3],-x[2],x[1],-y[4],y[3],-y[2],-z[6],-z[5],z[1],), # 10101--010-------00---1-
(x[5],-x[4],-y[4],y[3],-y[1],-y[0],-z[6],z[3],-z[2],z[1],), # 10-----01-00-----0--101-
(-x[1],-y[5],-y[4],-y[3],z[11],z[9],z[5],z[2],-z[0],), # ----0-000---1-1---1--1-0
(x[5],-x[4],-x[2],x[0],-y[5],y[2],-y[1],z[7],z[6],-z[5],), # 10-0-10--10-----110-----
(-x[3],x[1],-y[5],-y[4],y[2],z[11],z[7],-z[5],-z[1],), # --0-1-00-1--1---1-0---0-
(-x[5],-x[4],y[3],-y[1],-y[0],z[11],z[10],z[8],z[7],), # 00------1-0011-11-------
(x[3],-x[2],-z[10],z[9],z[8],-z[7],z[5],-z[3],-z[0],), # --10---------0110-1-0--0
(x[4],-x[1],y[5],-y[4],y[0],-z[5],z[4],-z[1],), # -1--0-10---1------01--0-
(x[5],x[2],x[0],-y[4],-y[3],z[5],-z[4],-z[1],), # 1--1-1-00---------10--0-
(x[4],-x[3],-x[2],x[0],y[4],y[0],-z[5],-z[2],), # -100-1-1---1------0--0--
(x[0],y[4],-y[3],-y[2],z[11],z[9],z[7],-z[5],-z[1],), # -----1-100--1-1-1-0---0-
(x[3],-x[0],-y[5],-y[4],z[11],z[10],-z[6],z[4],z[2],z[0],), # --1--000----11---0-1-1-1
(x[0],-y[5],-y[4],-y[3],z[11],z[10],z[9],z[6],-z[5],), # -----1000---111--10-----
(-x[4],-x[0],-y[4],-y[3],-y[2],z[10],-z[6],z[2],-z[1],), # -0---0-000---1---0---10-
(x[3],-x[2],-y[4],y[2],-z[10],-z[7],z[6],z[4],z[3],), # --10---0-1---0--01-11---
(-x[4],-x[2],-x[1],-y[5],-y[3],-y[2],y[1],z[10],-z[8],z[6],z[0],), # -0-00-0-001--1-0-1-----1
(-x[3],-x[2],-x[1],-y[5],y[1],-z[5],-z[2],z[1],), # --000-0---1-------0--01-
(-x[4],-x[3],y[5],y[2],y[0],z[5],-z[4],-z[1],), # -00---1--1-1------10--0-
(-x[4],x[1],-y[5],y[2],z[11],z[10],z[6],z[2],-z[1],), # -0--1-0--1--11---1---10-
(-x[4],x[1],y[5],-y[4],y[0],z[5],-z[4],-z[1],), # -0--1-10---1------10--0-
(x[3],-y[4],y[3],y[2],y[0],z[4],-z[1],), # --1----011-1-------1--0-
(z[10],z[8],-z[7],-z[6],z[5],z[4],z[3],-z[2],-z[0],), # -------------1-1001110-0
(-x[4],-x[3],-x[2],-x[1],y[5],-y[2],-y[0],z[10],z[7],z[5],), # -0000-1--0-0-1--1-1-----
(-x[5],-x[4],x[3],x[2],y[2],-y[1],-y[0],z[11],z[10],-z[6],z[3],), # 0011-----10011---0--1---
(x[5],-x[4],x[0],-y[4],-y[1],z[5],z[4],-z[1],), # 10---1-0--0-------11--0-
(-x[5],x[1],-y[3],-y[2],-y[1],-z[5],-z[2],z[1],), # 0---1---000-------0--01-
(x[5],-x[3],x[2],-x[1],-x[0],y[3],-y[2],-y[1],z[10],-z[7],z[5],), # 1-0100--100--1--0-1-----
(x[5],-x[4],x[0],y[4],-y[3],-z[5],-z[2],-z[1],), # 10---1-10---------0--00-
(x[5],-x[3],x[2],-x[1],-x[0],-y[4],-y[3],z[10],z[9],-z[7],), # 1-0100-00----11-0-------
(-x[5],x[4],-x[3],-x[1],-x[0],y[5],-y[1],z[10],z[8],-z[5],), # 010-001---0--1-1--0-----
(x[4],x[3],-y[5],y[4],y[0],z[5],-z[2],-z[1],), # -11---01---1------1--00-
(x[4],-y[2],y[1],z[9],-z[8],z[5],-z[4],-z[3],-z[1],), # -1-------01---10--100-0-
(x[5],-x[4],-x[3],-x[2],-x[1],y[5],-z[5],-z[0],), # 10000-1-----------0----0
(-x[4],-x[2],-x[1],-y[5],-y[3],-y[1],z[11],z[10],z[7],), # -0-00-0-0-0-11--1-------
(-x[4],x[1],-y[3],-z[11],z[8],z[7],z[5],-z[4],-z[3],), # -0--1---0---0--11-100---
(-x[4],x[2],-x[1],y[5],-y[3],-y[1],-y[0],-z[10],-z[7],), # -0-10-1-0-00-0--0-------
(x[4],x[3],x[1],y[4],y[1],-z[6],-z[5],z[0],), # -11-1--1--1------00----1
(-x[5],x[4],-x[1],y[5],-y[3],-y[2],-y[1],-z[7],-z[6],z[3],z[0],), # 01--0-1-000-----00--1--1
(-x[4],-x[2],x[1],y[5],-y[3],y[2],y[1],z[7],-z[5],z[0],), # -0-01-1-011-----1-0----1
(x[3],-x[2],-x[1],y[3],-z[11],z[9],-z[7],), # --100---1---0-1-0-------
(-x[5],-x[4],x[3],-y[4],-y[3],y[1],z[11],-z[9],z[2],z[0],), # 001----00-1-1-0------1-1
(-x[2],-y[2],-z[11],z[9],z[8],z[7],z[5],-z[3],), # ---0-----0--0-111-1-0---
(x[5],x[1],-y[4],-y[3],-y[2],-z[10],z[7],z[1],z[0],), # 1---1--000---0--1-----11
(-x[5],-x[4],x[3],x[2],-y[3],-y[1],z[11],-z[7],z[6],-z[0],), # 0011----0-0-1---01-----0
(-x[5],x[0],-y[4],z[11],z[10],z[6],z[2],-z[1],), # 0----1-0----11---1---10-
(x[4],-x[3],y[3],-y[2],z[9],z[8],z[6],z[5],-z[2],), # -10-----10----11-11--0--
(x[5],-x[1],x[0],y[5],-y[4],-y[3],-y[2],-y[1],-z[6],), # 1---0110000------0------
(-x[5],x[1],-y[0],z[10],z[9],-z[8],z[7],-z[6],-z[4],-z[3],), # 0---1------0-11010-00---
(x[1],y[2],-y[1],-z[11],-z[7],z[6],-z[5],z[4],), # ----1----10-0---0101----
(x[3],x[2],y[4],-z[11],-z[8],z[3],), # --11---1----0--0----1---
(-x[4],-x[3],-x[2],x[0],-y[4],y[0],-z[5],-z[2],), # -000-1-0---1------0--0--
(-x[5],-x[3],-x[0],z[10],z[9],z[6],-z[5],z[3],z[2],-z[1],), # 0-0--0-------11--10-110-
(x[4],-x[3],-x[2],-y[4],y[1],-z[8],-z[7],-z[6],-z[5],), # -100---0--1----0000-----
(-x[4],x[2],-y[4],y[2],-z[11],-z[8],-z[7],-z[5],z[2],), # -0-1---0-1--0--00-0--1--
(-x[5],-x[4],x[3],-x[2],-y[4],y[2],-y[1],y[0],z[11],z[8],), # 0010---0-1011--1--------
(-x[3],-y[5],-y[4],y[0],-z[10],z[7],-z[6],-z[5],z[4],z[2],), # --0---00---1-0--1001-1--
(x[2],-y[3],-y[2],z[9],z[7],z[5],z[4],z[3],-z[1],), # ---1----00----1-1-111-0-
(-x[5],x[3],-y[5],-y[4],y[3],-z[10],z[9],), # 0-1---001----01---------
(-x[5],x[3],-x[2],-y[5],y[3],-y[2],-z[8],z[7],z[5],-z[1],), # 0-10--0-10-----01-1---0-
(-x[5],x[1],z[10],z[9],-z[8],-z[5],z[3],-z[2],-z[0],), # 0---1--------110--0-10-0
(x[5],-y[5],-y[4],-y[3],-y[2],y[0],-z[6],-z[1],), # 1-----0000-1-----0----0-
(-x[4],-x[3],x[2],-x[1],-y[5],y[4],-y[3],y[2],z[11],-z[7],z[0],), # -0010-0101--1---0------1
(-x[5],x[1],z[10],-z[7],z[5],-z[4],-z[3],z[2],-z[0],), # 0---1--------1--0-1001-0
(-x[5],-x[4],x[3],-x[2],-y[4],y[3],-y[2],y[1],z[11],-z[7],z[0],), # 0010---0101-1---0------1
(x[2],x[1],x[0],y[2],y[1],y[0],-z[5],), # ---111---111------0-----
(x[2],y[4],y[3],y[1],z[10],z[9],-z[8],-z[7],z[2],), # ---1---11-1--1100----1--
(x[3],y[3],y[2],-z[11],-z[9],-z[8],), # --1-----11--0-00--------
(-x[4],-x[1],-y[5],y[2],-z[7],z[6],-z[5],-z[3],z[2],), # -0--0-0--1------010-01--
(x[3],z[10],z[9],-z[6],-z[5],-z[4],z[2],z[1],-z[0],), # --1----------11--000-110
(x[4],x[2],y[3],y[2],-z[11],-z[8],), # -1-1----11--0--0--------
(-x[4],x[1],-y[4],y[1],-z[9],z[8],-z[6],-z[5],z[0],), # -0--1--0--1---01-00----1
(-x[5],x[3],-y[4],-y[3],-y[1],-z[8],z[7],z[5],-z[3],-z[2],), # 0-1----00-0----01-1-00--
(-x[5],-x[4],-y[2],-y[1],-z[10],z[7],z[6],-z[5],z[2],-z[1],), # 00-------00--0--110--10-
(-x[3],x[1],y[1],-z[11],-z[9],-z[7],-z[6],z[0],), # --0-1-----1-0-0-00-----1
(-x[4],x[2],-y[4],y[2],-z[7],z[6],z[4],z[3],z[2],-z[1],z[0],), # -0-1---0-1------01-11101
(-x[2],x[1],y[4],y[2],-z[10],z[7],-z[6],z[4],-z[3],), # ---01--1-1---0--10-10---
(x[4],-x[3],-x[2],-x[1],-y[5],y[4],-y[2],-z[8],-z[6],z[3],), # -1000-01-0-----0-0--1---
(x[3],x[2],-x[1],-x[0],-y[5],y[3],y[2],z[7],z[5],), # --11000-11------1-1-----
(-x[4],-x[3],x[1],y[3],-y[2],-z[9],z[8],-z[7],-z[5],), # -00-1---10----010-0-----
(-x[1],-y[4],-y[3],y[2],-y[0],z[9],z[8],-z[6],z[5],-z[2],), # ----0--001-0--11-01--0--
(x[3],-x[1],-y[5],y[4],z[8],z[5],-z[4],-z[2],-z[0],), # --1-0-01-------1--10-0-0
(-x[4],-x[3],-x[1],y[4],z[8],-z[5],z[4],-z[0],), # -00-0--1-------1--01---0
(-x[3],x[2],y[3],-y[2],-z[11],-z[9],z[8],), # --01----10--0-01--------
(-x[3],x[0],y[4],y[1],y[0],z[5],-z[3],), # --0--1-1--11------1-0---
(x[2],x[0],-y[3],y[0],z[4],-z[3],z[2],), # ---1-1--0--1-------101--
(-x[3],x[0],y[2],y[0],z[4],-z[3],z[2],), # --0--1---1-1-------101--
(-x[3],-y[3],-z[11],z[7],-z[5],z[3],-z[2],-z[1],z[0],), # --0-----0---0---1-0-1001
(-x[5],x[4],-x[3],-y[3],y[2],-z[9],z[8],z[5],-z[2],z[0],), # 010-----01----01--1--0-1
(-x[4],x[3],x[2],x[1],-y[3],y[2],y[1],z[7],), # -0111---011-----1-------
(-x[3],-x[2],x[1],-y[4],y[2],y[1],-z[10],z[8],-z[7],), # --001--0-11--0-10-------
(x[4],x[1],-y[4],y[3],z[4],z[3],-z[0],), # -1--1--01----------11--0
(-x[5],x[4],x[1],-x[0],-y[5],-z[8],z[7],-z[6],-z[2],z[1],), # 01--100--------010---01-
(x[4],y[4],y[3],-z[9],-z[8],-z[7],), # -1-----11-----000-------
(-x[5],-x[4],x[3],-y[4],y[3],-y[1],z[8],-z[7],z[6],z[5],z[2],), # 001----01-0----1011--1--
(-x[1],-y[1],z[11],z[10],-z[9],-z[8],-z[7],z[5],-z[4],z[2],), # ----0-----0-11000-10-1--
(-x[5],y[4],-y[1],z[10],z[6],-z[5],-z[4],z[3],-z[2],-z[1],z[0],), # 0------1--0--1---1001001
(x[5],-x[1],y[5],-y[1],-z[7],z[6],z[5],z[3],z[2],), # 1---0-1---0-----011-11--
(x[4],x[3],y[4],-z[9],-z[8],-z[7],), # -11----1------000-------
(x[4],x[2],x[1],y[3],y[1],-z[6],-z[5],z[2],), # -1-11---1-1------00--1--
(x[3],-x[2],-y[5],y[4],-y[0],z[9],z[7],-z[6],z[2],-z[1],), # --10--01---0--1-10---10-
(x[4],-x[1],-y[2],-z[10],-z[9],-z[7],z[3],z[2],), # -1--0----0---00-0---11--
(-x[4],x[1],x[0],-y[4],y[1],y[0],-z[6],-z[4],), # -0--11-0--11-----0-0----
(-y[5],-y[4],y[2],-y[0],z[10],-z[7],z[6],z[4],z[3],z[1],), # ------00-1-0-1--01-11-1-
(x[4],-x[1],-y[4],-y[3],z[4],z[3],-z[0],), # -1--0--00----------11--0
(x[5],-x[2],x[1],-y[3],z[9],-z[8],-z[7],-z[6],z[5],), # 1--01---0-----10001-----
(-x[4],x[2],x[1],-y[2],y[0],-z[5],-z[4],z[2],), # -0-11----0-1------00-1--
(x[3],x[2],x[1],y[2],-z[6],-z[4],z[1],z[0],), # --111----1-------0-0--11
(-x[5],-x[4],-x[3],x[2],x[1],-z[8],-z[5],-z[2],), # 00011----------0--0--0--
(-x[4],x[2],x[1],-y[5],y[4],-z[6],z[5],-z[4],-z[2],), # -0-11-01---------010-0--
(x[4],-x[1],y[5],-y[4],y[3],z[9],z[7],z[5],-z[4],-z[1],), # -1--0-101-----1-1-10--0-
(-x[5],x[4],-x[1],y[3],-y[2],-y[1],-z[7],z[6],-z[3],z[2],), # 01--0---100-----01--01--
(-x[5],x[4],-x[2],y[5],-y[2],-z[7],z[6],z[4],-z[3],z[2],), # 01-0--1--0------01-101--
(x[4],x[1],-x[0],y[5],-z[8],-z[5],z[4],z[3],z[0],), # -1--101--------0--011--1
(-x[5],-x[2],-x[1],-y[5],y[4],-y[3],-z[9],z[7],-z[6],-z[5],z[1],), # 0--00-010-----0-100---1-
(-x[4],-x[3],x[2],y[4],y[1],-y[0],-z[7],z[6],z[2],z[1],), # -001---1--10----01---11-
(-x[3],x[1],x[0],y[4],-y[3],y[2],z[6],-z[5],z[4],), # --0-11-101-------101----
(-y[5],-y[4],-y[3],y[2],y[1],-z[7],-z[4],-z[3],-z[0],), # ------00011-----0--00--0
(-x[5],-x[4],x[3],x[2],-y[4],-y[3],y[2],y[1],-z[8],-z[7],), # 0011---0011----00-------
(x[4],-y[5],-y[4],-y[3],y[2],-y[0],z[6],-z[4],z[3],-z[2],), # -1----0001-0-----1-010--
(-x[4],-y[1],-z[10],z[8],z[5],-z[4],z[2],-z[0],), # -0--------0--0-1--10-1-0
(x[3],x[2],x[1],-y[4],y[1],z[8],-z[6],z[0],), # --111--0--1----1-0-----1
(-x[4],-y[4],z[11],-z[10],z[9],z[6],-z[5],z[3],-z[0],), # -0-----0----101--10-1--0
(x[4],x[3],x[2],y[3],-z[11],), # -111----1---0-----------
(-x[5],-x[2],x[1],-y[5],y[4],y[3],z[7],z[4],-z[3],z[1],), # 0--01-011-------1--10-1-
(-x[5],-x[3],x[2],-y[4],-y[3],y[1],-z[9],z[8],-z[7],z[1],), # 0-01---00-1---010-----1-
(-x[5],x[3],-y[5],-y[3],y[1],-y[0],-z[10],z[6],-z[2],z[1],), # 0-1---0-0-10-0---1---01-
(x[3],-y[5],-y[3],y[2],y[1],z[10],z[9],-z[8],-z[5],), # --1---0-011--110--0-----
(x[3],-x[2],-x[1],y[2],-z[6],-z[3],z[2],), # --100----1-------0--01--
(x[5],-x[4],x[2],-y[5],-y[1],-z[6],z[5],-z[4],z[3],-z[2],), # 10-1--0---0------01010--
(x[5],x[3],x[2],y[4],-z[8],-z[7],), # 1-11---1-------00-------
(-x[4],-x[3],-y[2],z[10],-z[8],z[6],z[4],z[1],-z[0],), # -00------0---1-0-1-1--10
(-x[2],x[1],x[0],-y[3],y[2],y[1],z[5],z[2],), # ---011--011-------1--1--
(-x[5],-x[3],-x[2],x[1],x[0],y[3],z[5],-z[4],z[3],), # 0-0011--1---------101---
(-x[5],x[4],x[3],-y[5],y[4],z[10],), # 011---01-----1----------
(-x[5],x[4],-y[4],-y[2],-y[1],y[0],-z[7],-z[6],-z[4],z[2],), # 01-----0-001----00-0-1--
(-x[2],-y[2],-z[11],z[10],-z[6],z[5],-z[2],-z[1],), # ---0-----0--01---01--00-
(x[4],x[3],-x[2],x[1],-y[4],z[6],-z[5],z[3],z[1],z[0],), # -1101--0---------10-1-11
(-x[5],x[3],x[2],-y[5],-y[1],z[8],-z[6],z[5],-z[2],z[1],), # 0-11--0---0----1-01--01-
(-x[4],-x[1],-y[5],y[4],y[3],-y[2],y[1],z[10],-z[6],-z[3],z[2],), # -0--0-01101--1---0--01--
(-x[4],x[1],-y[4],y[1],z[7],z[6],z[5],-z[3],z[0],), # -0--1--0--1-----111-0--1
(x[5],x[2],y[5],-y[3],y[2],-z[8],z[7],-z[6],), # 1--1--1-01-----010------
(-x[4],x[3],-x[2],-x[1],y[4],-y[1],y[0],-z[5],-z[4],-z[3],), # -0100--1--01------000---
(-x[3],y[5],y[3],-y[0],z[10],z[7],z[6],z[5],z[3],-z[1],), # --0---1-1--0-1--111-1-0-
(-x[5],x[4],x[2],-y[3],y[1],z[10],z[5],-z[3],-z[0],), # 01-1----0-1--1----1-0--0
(-x[5],x[3],-y[5],-y[3],-y[2],-y[1],z[8],z[6],z[2],-z[1],), # 0-1---0-000----1-1---10-
(x[4],-x[1],-y[4],y[3],z[4],-z[3],-z[0],), # -1--0--01----------10--0
(x[3],-x[2],-y[2],y[1],-z[10],-z[7],-z[6],-z[4],z[1],), # --10-----01--0--00-0--1-
(-x[3],-y[5],y[4],-y[3],z[10],z[6],z[5],-z[3],-z[0],), # --0---010----1---11-0--0
(-x[1],-y[4],-y[3],y[2],z[10],z[8],z[7],z[6],z[5],-z[2],), # ----0--001---1-1111--0--
(-x[5],-x[3],-y[5],y[4],y[3],z[8],-z[5],z[2],-z[0],), # 0-0---011------1--0--1-0
(-x[5],-x[4],x[2],x[1],y[3],z[9],-z[6],-z[3],), # 00-11---1-----1--0--0---
(x[5],-x[2],-x[1],-y[3],-y[2],-z[9],z[8],z[7],z[6],), # 1--00---00----0111------
(-x[5],x[3],x[2],-x[1],-y[5],y[4],-y[3],y[2],-z[9],z[6],), # 0-110-0101----0--1------
(-x[4],x[3],y[4],-z[10],z[9],-z[8],), # -01----1-----010--------
(x[5],x[4],x[1],-y[4],y[3],-z[8],z[7],-z[6],), # 11--1--01------010------
(-x[4],x[3],y[4],-y[3],z[4],z[1],-z[0],), # -01----10----------1--10
(x[5],x[3],-x[2],-y[2],y[1],z[9],-z[8],-z[6],-z[4],z[0],), # 1-10-----01---10-0-0---1
(x[3],x[2],-y[4],y[2],-z[11],z[9],z[8],z[0],), # --11---0-1--0-11-------1
(-x[5],-x[4],-x[1],-y[5],y[4],y[3],y[0],-z[7],z[4],-z[3],), # 00--0-011--1----0--10---
(x[5],-x[3],x[1],-y[3],y[2],z[10],z[9],-z[7],z[6],-z[5],), # 1-0-1---01---11-010-----
(x[3],y[3],y[2],y[1],-z[10],-z[8],-z[7],), # --1-----111--0-00-------
(-x[5],-x[4],-x[2],-x[1],y[4],y[1],-z[9],z[7],z[1],), # 00-00--1--1---0-1-----1-
(-x[3],-x[2],-y[5],-y[4],z[11],z[9],z[8],), # --00--00----1-11--------
(-x[5],x[2],x[1],-y[5],y[2],y[1],-z[8],-z[6],z[0],), # 0--11-0--11----0-0-----1
(x[4],-x[2],y[4],-y[3],-y[2],z[11],z[9],z[6],z[4],z[3],), # -1-0---100--1-1--1-11---
(-x[5],x[4],x[2],-y[4],y[3],y[1],z[10],-z[7],-z[6],z[1],), # 01-1---01-1--1--00----1-
(-x[2],-x[1],-y[5],y[4],-y[3],y[2],-y[1],z[9],-z[7],z[3],), # ---00-01010---1-0---1---
(-x[5],x[1],x[0],y[4],-y[3],-z[6],-z[3],-z[2],), # 0---11-10--------0--00--
(-x[2],-x[1],-y[4],-y[3],-y[2],-y[1],z[10],z[8],z[7],), # ---00--0000--1-11-------
(-x[5],-x[4],x[0],-y[3],-z[10],-z[5],-z[2],-z[1],), # 00---1--0----0----0--00-
(x[4],y[4],z[10],-z[9],-z[5],z[1],-z[0],), # -1-----1-----10---0---10
(-x[5],y[5],y[4],-y[0],z[9],z[8],z[7],z[5],), # 0-----11---0--111-1-----
(-x[5],-y[5],-y[4],-y[3],-z[5],-z[3],z[2],-z[1],-z[0],), # 0-----000---------0-0100
(x[4],-x[3],x[1],-y[3],-y[2],y[1],z[9],z[6],-z[5],z[0],), # -10-1---001---1--10----1
(x[5],-x[2],-x[0],-y[3],-y[1],z[9],-z[6],-z[5],-z[4],-z[1],), # 1--0-0--0-0---1--000--0-
(x[4],x[3],x[1],-x[0],-y[4],y[3],-y[2],z[9],-z[7],), # -11-10-010----1-0-------
(x[4],x[3],y[4],y[3],-z[4],-z[1],-z[0],), # -11----11----------0--00
(-x[4],-x[3],y[4],-y[3],z[4],-z[1],-z[0],), # -00----10----------1--00
(-x[3],-x[2],-y[5],y[1],y[0],z[10],-z[6],z[4],-z[2],), # --00--0---11-1---0-1-0--
(-x[5],x[4],-x[2],x[1],y[3],-y[2],z[9],-z[8],-z[7],z[0],), # 01-01---10----100------1
(x[5],x[2],-x[1],y[3],-y[1],-z[10],z[8],-z[7],), # 1--10---1-0--0-10-------
(-x[3],-x[2],-x[1],y[4],y[2],-y[1],z[9],-z[8],-z[7],z[6],), # --000--1-10---1001------
(-x[5],x[2],-y[5],-y[3],-y[2],-y[0],-z[10],z[8],z[2],), # 0--1--0-00-0-0-1-----1--
(-x[5],-x[4],-x[1],-y[4],-y[3],-y[1],-z[9],-z[7],-z[4],), # 00--0--00-0---0-0--0----
(-x[5],x[1],-y[3],-y[1],-y[0],-z[5],-z[4],z[3],z[0],), # 0---1---0-00------001--1
(x[5],-x[4],-x[3],-x[2],y[2],z[10],z[9],-z[7],z[6],), # 1000-----1---11-01------
(x[4],-x[3],y[4],-y[3],y[2],-y[1],-z[4],-z[3],-z[2],), # -10----1010--------000--
(-x[1],-x[0],y[4],-y[3],y[1],z[4],z[2],z[0],), # ----00-10-1--------1-1-1
(-x[5],-x[4],x[0],-y[5],y[4],y[3],-z[6],-z[4],-z[2],z[1],), # 00---1011--------0-0-01-
(x[4],x[1],-y[5],-y[4],y[0],z[5],-z[4],-z[1],), # -1--1-00---1------10--0-
(-x[2],x[1],-y[4],-y[3],-y[2],-z[11],-z[8],z[0],), # ---01--000--0--0-------1
(-x[4],x[1],-y[5],y[4],y[0],-z[5],z[4],-z[1],), # -0--1-01---1------01--0-
(x[4],-x[3],x[2],-x[1],-y[4],-y[3],-y[1],-y[0],-z[4],-z[3],), # -1010--00-00-------00---
(y[5],y[3],y[2],y[1],z[7],-z[6],-z[3],), # ------1-111-----10--0---
(-x[4],x[2],-y[4],y[2],z[9],-z[7],z[6],-z[2],), # -0-1---0-1----1-01---0--
(x[4],-x[3],y[5],y[2],y[1],-z[9],z[7],z[1],), # -10---1--11---0-1-----1-
(x[2],y[5],-y[3],y[2],-z[9],z[8],-z[7],-z[6],z[0],), # ---1--1-01----0100-----1
(-x[4],-x[1],-x[0],-y[5],-y[2],-y[1],z[10],z[8],z[6],z[3],), # -0--000--00--1-1-1--1---
(-x[4],-x[2],-y[5],-y[3],z[11],z[10],z[7],z[4],-z[2],), # -0-0--0-0---11--1--1-0--
(-x[4],-x[3],-x[1],-x[0],y[4],-y[3],y[2],-y[1],-z[4],-z[3],), # -00-00-1010--------00---
(-x[5],x[4],-x[0],-y[4],-y[1],z[11],-z[6],z[4],-z[3],z[2],), # 01---0-0--0-1----0-101--
(-x[4],-y[4],-y[3],-y[2],z[10],z[9],z[6],), # -0-----000---11--1------
(x[4],x[3],-x[2],-y[3],y[2],-z[10],-z[8],z[7],), # -110----01---0-01-------
(x[5],x[2],-x[1],y[3],-y[2],y[1],-z[10],z[8],), # 1--10---101--0-1--------
(x[4],-x[3],-y[5],y[4],y[0],z[5],z[2],-z[1],), # -10---01---1------1--10-
(-x[5],x[4],x[2],-x[0],-y[5],-y[3],z[8],-z[3],-z[2],z[0],), # 01-1-00-0------1----00-1
(-x[3],x[2],y[5],-y[2],-y[1],-z[10],z[8],z[7],), # --01--1--00--0-11-------
(-x[5],x[4],x[0],y[4],-y[3],z[5],z[2],-z[1],), # 01---1-10---------1--10-
(-x[5],-x[3],x[1],-y[5],y[3],y[2],-y[1],z[8],-z[5],z[4],z[0],), # 0-0-1-0-110----1--01---1
(x[4],x[3],x[2],x[1],-z[10],-z[5],-z[0],), # -1111--------0----0----0
(x[5],-x[3],x[1],y[4],-y[1],-z[6],-z[5],z[3],-z[2],z[0],), # 1-0-1--1--0------00-10-1
(-x[5],x[4],-y[4],y[3],y[2],z[11],z[9],), # 01-----011--1-1---------
(-x[5],-x[2],-y[4],y[2],-y[1],z[11],z[7],z[6],z[5],-z[3],-z[1],), # 0--0---0-10-1---111-0-0-
(x[4],-x[3],-x[2],y[3],-y[2],-y[1],z[9],z[8],-z[7],), # -100----100---110-------
(-x[4],-x[2],-x[1],y[3],-y[1],-z[11],z[9],-z[7],z[0],), # -0-00---1-0-0-1-0------1
(-x[5],-x[3],-x[2],y[4],-y[3],-z[6],-z[4],-z[0],), # 0-00---10--------0-0---0
(-x[3],-x[1],y[4],y[3],-y[1],z[11],-z[7],-z[6],z[5],z[4],), # --0-0--11-0-1---0011----
(-x[5],-x[4],x[2],-x[1],-y[3],z[10],z[8],-z[5],z[4],z[2],z[0],), # 00-10---0----1-1--01-1-1
(-y[5],y[3],-y[1],-y[0],z[11],z[6],z[4],-z[3],z[2],-z[1],), # ------0-1-001----1-1010-
(x[4],x[3],x[2],x[0],y[4],y[0],-z[5],), # -111-1-1---1------0-----
(x[5],-x[4],x[3],-x[2],x[1],y[2],-z[8],z[6],-z[3],z[0],), # 10101----1-----0-1--0--1
(-x[4],x[2],-y[4],-y[3],y[2],z[11],z[10],z[7],-z[1],), # -0-1---001--11--1-----0-
(x[5],x[3],x[1],y[4],y[2],-z[6],-z[5],z[1],), # 1-1-1--1-1-------00---1-
(x[5],x[2],-x[0],y[4],-y[3],-y[2],-y[1],z[6],-z[5],-z[4],), # 1--1-0-1000------100----
(-x[4],-x[3],x[1],-y[4],-y[2],-y[1],z[11],z[9],-z[7],z[6],), # -00-1--0-00-1-1-01------
(-x[4],-x[3],y[5],y[4],y[2],-y[1],z[9],-z[7],z[5],), # -00---11-10---1-0-1-----
(-x[4],x[3],-x[1],-y[5],y[4],-y[3],-z[6],z[2],-z[0],), # -01-0-010--------0---1-0
(-y[5],-y[4],-y[1],-z[10],-z[6],-z[5],-z[2],-z[0],), # ------00--0--0---00--0-0
(x[4],-x[3],-x[2],-z[10],z[6],z[5],-z[2],-z[1],z[0],), # -100---------0---11--001
(-x[4],x[2],x[1],y[3],-y[2],y[1],z[6],-z[5],z[0],), # -0-11---101------10----1
(x[4],-x[3],-x[2],y[4],y[3],-y[2],-y[0],z[9],z[6],z[4],), # -100---110-0--1--1-1----
(-x[5],x[4],x[2],-x[1],y[2],-y[1],-y[0],-z[9],z[7],-z[6],), # 01-10----100--0-10------
(-x[5],-x[2],x[1],-y[5],y[3],y[2],-y[1],-z[10],-z[7],z[6],), # 0--01-0-110--0--01------
(x[4],-x[1],x[0],-y[5],-y[4],-y[3],y[1],z[10],-z[7],z[6],), # -1--01000-1--1--01------
(-x[3],-x[2],x[1],-y[2],y[1],-z[10],-z[8],z[7],z[0],), # --001----01--0-01------1
(x[5],-x[4],-x[3],-x[2],y[5],-y[2],y[1],-z[7],-z[6],), # 1000--1--01-----00------
(-x[1],-x[0],-y[4],-y[3],y[1],-z[4],z[2],z[0],), # ----00-00-1--------0-1-1
(-x[5],-x[4],x[3],x[1],y[3],-y[2],-y[1],-z[7],z[3],z[0],), # 001-1---100-----0---1--1
(x[4],x[2],-x[0],-y[5],y[4],y[3],z[10],z[8],z[5],), # -1-1-0011----1-1--1-----
(-x[1],-x[0],-y[5],y[4],y[3],-z[6],z[5],z[3],z[2],z[1],), # ----00011--------01-111-
(-x[3],-y[5],y[4],y[3],y[2],y[1],z[8],z[0],), # --0---01111----1-------1
(-x[3],-x[2],-x[1],-y[4],y[0],-z[4],-z[1],), # --000--0---1-------0--0-
(-x[4],x[3],-x[2],-y[5],-y[4],y[3],z[11],-z[8],z[7],), # -010--001---1--01-------
(x[5],x[4],-x[3],-x[2],-x[1],y[3],y[2],z[7],-z[6],), # 11000---11------10------
(x[4],x[3],-x[1],x[0],y[5],-y[3],-z[6],-z[5],z[2],), # -11-011-0--------00--1--
(-x[4],x[2],x[0],-y[5],-y[4],y[2],z[11],-z[9],z[8],), # -0-1-100-1--1-01--------
(-x[5],-x[4],x[0],y[4],-y[3],z[5],-z[2],-z[1],), # 00---1-10---------1--00-
(-x[5],x[4],x[2],-x[1],y[5],-y[4],-y[0],z[8],-z[7],-z[5],), # 01-10-10---0---10-0-----
(x[5],-x[3],x[2],-x[1],y[5],-y[4],-y[2],-z[7],z[6],), # 1-010-10-0------01------
(-x[4],-x[3],-x[2],y[5],-y[4],-y[3],z[9],z[7],), # -000--100-----1-1-------
(x[4],-x[3],-x[2],x[1],-y[5],y[4],-y[3],-y[2],z[10],-z[7],), # -1001-0100---1--0-------
(-x[4],-x[3],-y[5],y[4],y[0],-z[5],z[2],-z[1],), # -00---01---1------0--10-
(-x[5],x[4],x[0],-y[4],-y[3],-z[5],z[2],-z[1],), # 01---1-00---------0--10-
(x[5],x[3],-x[2],-x[1],-x[0],-y[5],y[3],z[6],-z[4],-z[1],), # 1-10000-1--------1-0--0-
(x[5],-x[2],x[1],y[5],-y[4],-y[3],-y[2],-z[7],-z[5],), # 1--01-1000------0-0-----
(x[4],x[2],-y[5],y[4],z[10],-z[9],z[0],), # -1-1--01-----10--------1
(x[4],x[0],-y[3],-y[2],-y[1],z[4],-z[1],), # -1---1--000--------1--0-
(-x[3],-x[2],-x[1],-y[4],-y[1],z[10],z[9],z[8],-z[1],), # --000--0--0--111------0-
(-x[4],-x[3],-x[2],-x[1],-y[5],z[11],z[10],z[6],), # -0000-0-----11---1------
(-x[4],-x[3],x[2],x[1],-y[3],-y[2],y[1],-z[6],-z[5],z[0],), # -0011---001------00----1
(-x[5],x[4],-x[2],-x[0],y[5],-y[3],y[2],z[8],z[7],-z[1],), # 01-0-01-01-----11-----0-
(-x[4],-y[4],z[11],z[10],-z[9],-z[7],-z[5],z[1],-z[0],), # -0-----0----110-0-0---10
(-x[5],-x[4],-x[3],-y[5],y[3],-y[1],-z[5],z[2],-z[0],), # 000---0-1-0-------0--1-0
(x[3],-x[2],-x[1],y[3],-y[2],-y[1],z[10],-z[8],z[6],-z[5],), # --100---100--1-0-10-----
(-x[4],-x[3],-x[2],x[1],-y[4],-y[1],-z[11],z[7],z[0],), # -0001--0--0-0---1------1
(-x[5],x[4],x[3],-y[4],-y[3],-y[2],-y[0],-z[5],-z[2],z[0],), # 011----000-0------0--0-1
(x[5],-x[1],-x[0],-y[5],-y[4],y[3],y[2],y[1],-z[5],-z[4],), # 1---0000111-------00----
(-x[4],x[3],-y[5],-y[4],y[0],-z[5],z[2],-z[1],), # -01---00---1------0--10-
(z[11],-z[10],z[9],z[8],z[7],-z[6],-z[5],-z[4],z[3],z[2],), # ------------1011100011--
(x[3],x[2],x[1],y[5],-z[5],-z[2],z[1],z[0],), # --111-1-----------0--011
(-x[4],-x[3],-x[2],-y[3],-y[2],-y[0],z[8],z[6],z[3],), # -000----00-0---1-1--1---
(-x[5],x[3],x[2],-x[0],y[5],-y[4],y[3],-y[2],-z[7],z[4],), # 0-11-01010------0--1----
(x[5],x[4],-x[3],-x[2],-x[1],-y[3],y[2],-z[7],-z[6],), # 11000---01------00------
(x[5],x[4],-x[2],x[1],-y[4],y[3],y[2],z[6],z[1],), # 11-01--011-------1----1-
(-x[4],-x[2],-y[5],z[11],-z[6],z[4],z[3],z[1],-z[0],), # -0-0--0-----1----0-11-10
(x[4],x[0],y[4],-y[3],-y[2],y[0],-z[5],-z[2],), # -1---1-100-1------0--0--
(-x[4],-x[3],x[2],y[5],y[4],-y[2],-y[1],z[8],-z[6],), # -001--11-00----1-0------
(x[5],x[1],y[3],-y[2],-y[1],-z[5],-z[2],z[1],), # 1---1---100-------0--01-
(-x[5],x[3],-x[2],y[5],-y[4],y[3],y[2],-y[1],z[7],-z[6],), # 0-10--10110-----10------
(x[5],-x[4],-y[5],y[4],-z[6],z[2],z[1],-z[0],), # 10----01---------0---110
(-x[4],-x[2],x[1],y[5],y[3],-y[2],-y[1],z[7],z[5],), # -0-01-1-100-----1-1-----
(-x[3],x[2],-x[1],-y[5],-y[4],y[3],z[11],-z[7],z[6],z[1],), # --010-001---1---01----1-
(z[8],-z[7],-z[6],-z[5],z[4],-z[3],-z[2],-z[0],), # ---------------1000100-0
(-x[3],-x[1],-x[0],-y[5],-y[2],-y[1],z[11],z[9],z[7],-z[6],), # --0-000--00-1-1-10------
(x[4],x[3],x[2],x[1],-y[2],-z[10],z[7],z[0],), # -1111----0---0--1------1
(x[5],-x[2],-x[1],-y[4],-y[3],-y[2],-z[10],z[8],), # 1--00--000---0-1--------
(-x[5],-x[4],x[3],y[4],y[3],-y[2],-y[0],z[6],-z[5],-z[2],), # 001----110-0-----10--0--
(-x[4],-x[3],-y[4],-y[3],y[2],z[10],-z[8],-z[7],), # -00----001---1-00-------
(x[3],x[2],x[1],y[4],y[0],-z[4],), # --111--1---1-------0----
(-x[5],-x[4],x[3],-y[5],y[4],-y[3],-y[2],-z[9],z[0],), # 001---0100----0--------1
(x[0],-y[5],-y[4],-y[3],-y[2],z[11],z[10],-z[9],z[6],), # -----10000--110--1------
(x[4],x[3],x[2],x[0],y[3],-z[4],), # -111-1--1----------0----
(-x[2],x[1],-y[5],y[4],-z[8],z[7],z[5],-z[4],z[3],-z[2],), # ---01-01-------01-1010--
(-x[4],x[3],-x[2],y[5],-y[3],y[2],-y[1],z[10],-z[7],z[6],), # -010--1-010--1--01------
(-x[3],-x[2],-x[1],y[5],y[1],z[5],-z[2],z[1],), # --000-1---1-------1--01-
(x[5],x[4],x[1],-x[0],-y[5],-y[4],-y[3],-z[7],z[6],), # 11--10000-------01------
(-x[5],x[3],-x[2],y[5],-y[4],y[2],z[7],-z[4],-z[1],z[0],), # 0-10--10-1------1--0--01
(x[3],y[4],y[3],y[2],y[0],-z[4],), # --1----111-1-------0----
(-x[4],-x[3],-x[2],x[1],-y[5],-y[2],-y[1],z[11],-z[7],z[6],), # -0001-0--00-1---01------
(-x[3],-x[1],-y[5],-y[4],-y[3],y[2],z[10],-z[7],-z[6],z[0],), # --0-0-0001---1--00-----1
(x[5],-x[4],-y[4],-y[3],y[1],z[9],z[6],-z[2],z[1],z[0],), # 10-----00-1---1--1---011
(-x[2],y[4],y[1],y[0],z[4],-z[2],), # ---0---1--11-------1-0--
(-x[4],x[2],-y[5],y[3],-z[10],z[9],-z[6],z[5],z[3],z[2],), # -0-1--0-1----01--01-11--
(x[3],x[2],-y[4],y[3],-y[2],y[0],-z[4],z[2],), # --11---010-1-------0-1--
(x[5],x[2],-x[1],-x[0],-y[4],-y[2],-y[1],z[10],z[6],z[5],), # 1--100-0-00--1---11-----
(x[4],-x[2],y[5],-y[3],y[2],y[1],-z[7],-z[6],z[0],), # -1-0--1-011-----00-----1
(-x[2],y[5],-y[4],y[3],y[2],y[1],z[6],-z[5],z[0],), # ---0--10111------10----1
(x[4],x[3],x[2],x[0],-y[3],z[4],-z[1],), # -111-1--0----------1--0-
(-x[5],-x[4],-y[2],-y[1],y[0],z[11],z[10],-z[8],-z[7],), # 00-------00111-00-------
(x[4],x[3],-x[1],-x[0],y[5],-y[4],-y[3],-y[2],y[1],z[6],), # -11-0010001------1------
(-x[5],-x[4],-x[3],x[2],-y[3],y[2],z[11],z[10],-z[7],-z[1],), # 0001----01--11--0-----0-
(-x[5],-x[4],-x[2],-x[1],-y[4],-y[3],y[1],z[11],-z[7],z[6],), # 00-00--00-1-1---01------
(-x[5],-x[4],-x[2],-x[1],-x[0],-y[1],z[11],-z[8],-z[5],-z[2],), # 00-000----0-1--0--0--0--
(-x[4],-x[2],-x[0],-y[5],-y[3],-y[2],z[11],z[10],z[7],), # -0-0-00-00--11--1-------
(-x[5],-x[4],x[3],x[2],-y[3],-y[2],z[11],z[10],-z[8],), # 0011----00--11-0--------
(-x[2],y[4],-y[3],y[1],-y[0],-z[9],-z[7],z[6],z[5],-z[4],), # ---0---10-10--0-0110----
(x[3],x[2],y[1],-z[11],z[9],-z[8],-z[3],), # --11------1-0-10----0---
(-x[4],x[1],-y[4],y[1],-z[9],-z[6],-z[5],z[4],-z[2],), # -0--1--0--1---0--001-0--
(-x[4],-x[3],-x[2],-x[1],-y[1],-y[0],z[11],z[10],z[6],z[5],), # -0000-----0011---11-----
(-x[4],-y[3],y[2],y[1],-z[4],-z[1],z[0],), # -0------011--------0--01
(-x[5],x[4],-x[3],x[2],-x[1],-x[0],-z[7],z[5],z[0],), # 010100----------0-1----1
(x[2],x[1],y[4],-y[3],-y[2],-z[9],-z[8],-z[7],-z[4],), # ---11--100----000--0----
(x[5],-x[4],-x[3],-x[2],-y[3],y[2],y[1],-z[8],z[1],z[0],), # 1000----011----0------11
(x[2],y[2],-z[11],z[10],z[8],z[7],-z[6],z[2],), # ---1-----1--01-110---1--
(-x[3],-y[3],-z[11],z[7],z[6],-z[3],z[2],-z[1],), # --0-----0---0---11--010-
(-x[5],-x[4],x[3],-x[2],-y[4],-y[3],y[2],-y[0],z[11],z[8],), # 0010---001-01--1--------
(-x[5],-x[4],-x[3],x[2],-y[4],y[3],-y[1],-y[0],z[11],-z[7],), # 0001---01-001---0-------
(x[4],-x[3],x[2],x[0],-y[5],-y[4],y[3],-y[2],z[11],-z[6],), # -101-10010--1----0------
(-x[4],x[3],-x[1],-x[0],-y[5],y[4],-y[3],-y[1],z[11],z[5],z[2],), # -01-00010-0-1-----1--1--
(x[0],y[3],z[10],-z[9],z[6],-z[5],z[3],-z[2],z[1],), # -----1--1----10--10-101-
(-x[1],x[0],-y[5],z[8],-z[7],z[6],-z[4],z[3],-z[2],), # ----010--------101-010--
(x[3],-x[2],y[4],-y[3],z[10],z[9],z[8],z[7],z[6],z[5],), # --10---10----111111-----
(x[3],-x[1],-y[5],y[2],-z[7],z[6],-z[5],-z[4],-z[3],z[1],), # --1-0-0--1------01000-1-
(-x[4],-x[1],-x[0],-y[5],-y[4],-y[3],y[2],-y[1],z[11],-z[7],), # -0--0000010-1---0-------
(-x[5],x[4],y[3],y[1],-z[9],z[7],-z[5],z[4],-z[3],), # 01------1-1---0-1-010---
(-x[4],y[5],-z[9],-z[7],z[6],z[5],-z[3],-z[2],z[1],), # -0----1-------0-011-001-
(-x[2],-x[0],-y[4],z[10],z[9],z[8],z[7],z[5],z[4],), # ---0-0-0-----1111-11----
(-x[4],-x[2],-y[5],y[4],y[2],z[8],z[7],-z[5],z[3],-z[1],), # -0-0--01-1-----11-0-1-0-
(x[3],x[0],y[4],y[1],-z[5],-z[3],z[1],), # --1--1-1--1-------0-0-1-
(-x[5],x[3],x[2],y[4],-y[3],y[1],-z[9],z[8],-z[7],z[1],), # 0-11---10-1---010-----1-
(-x[2],y[3],-y[2],z[11],-z[8],-z[7],z[6],z[5],z[4],-z[3],), # ---0----10--1--001110---
(x[3],x[1],x[0],-y[2],z[4],-z[3],z[2],), # --1-11---0---------101--
(-x[5],x[2],-x[1],y[2],-y[1],-y[0],-z[10],z[9],z[7],z[6],), # 0--10----100-01-11------
(-x[3],x[2],x[1],y[4],-z[7],-z[5],-z[4],-z[0],), # --011--1--------0-00---0
(x[2],-y[5],y[3],y[2],z[10],-z[9],-z[7],-z[6],-z[1],), # ---1--0-11---10-00----0-
(x[3],y[3],-z[10],z[8],z[7],z[5],-z[2],-z[1],), # --1-----1----0-11-1--00-
(-x[5],x[4],-x[2],x[1],-y[5],y[2],-z[9],-z[7],-z[3],z[1],), # 01-01-0--1----0-0---0-1-
(x[4],y[4],-y[1],-z[8],z[5],z[4],z[3],-z[2],z[1],), # -1-----1--0----0--11101-
(-x[4],-y[2],-z[9],z[6],-z[5],-z[4],z[3],-z[2],z[1],), # -0-------0----0--100101-
(-z[11],-z[10],-z[6],-z[0],), # ------------00---0-----0
(x[3],-y[5],y[4],y[0],z[10],-z[8],-z[6],-z[3],-z[2],), # --1---01---1-1-0-0--00--
(-x[2],-y[2],z[11],z[8],z[7],z[5],z[3],z[2],-z[1],), # ---0-----0--1--11-1-110-
(x[3],x[2],x[1],-y[5],y[3],z[10],-z[9],-z[7],-z[6],), # --111-0-1----10-00------
(-x[4],-x[3],-x[2],-x[1],-y[5],-y[2],z[11],-z[7],z[1],z[0],), # -0000-0--0--1---0-----11
(-x[2],-y[5],-y[2],y[1],z[10],z[8],z[7],z[6],z[4],z[1],), # ---0--0--01--1-111-1--1-
(x[1],-y[5],y[4],y[2],z[10],-z[9],z[8],-z[6],z[1],), # ----1-01-1---101-0----1-
(-x[2],x[0],-y[2],y[1],y[0],z[4],z[3],), # ---0-1---011-------11---
(-x[3],x[1],-y[2],y[0],-z[4],-z[3],z[2],), # --0-1----0-1-------001--
(x[4],x[2],-y[3],-y[2],y[1],-z[4],z[3],z[2],), # -1-1----001--------011--
(-x[5],x[4],-x[2],-y[5],y[4],z[7],-z[6],z[4],z[2],z[1],), # 01-0--01--------10-1-11-
(-x[2],x[0],-y[3],y[1],-z[4],-z[3],z[2],), # ---0-1--0-1--------001--
(x[5],x[3],y[5],y[3],z[8],-z[7],-z[6],), # 1-1---1-1------100------
(-x[5],x[4],-x[3],y[3],-y[2],y[1],-y[0],z[6],z[4],-z[3],), # 010-----1010-----1-10---
(x[1],-y[5],y[4],y[3],y[2],z[10],z[9],-z[6],z[1],), # ----1-0111---11--0----1-
(-x[4],x[3],x[2],-y[3],y[2],y[1],z[7],-z[4],z[1],), # -011----011-----1--0--1-
(-x[0],y[4],-z[4],z[3],z[2],z[1],z[0],), # -----0-1-----------01111
(-x[4],y[4],-y[3],y[1],-z[4],-z[3],z[2],-z[1],), # -0-----10-1--------0010-
(-x[5],x[3],-x[1],-y[4],y[2],-y[1],z[7],z[6],-z[5],z[3],), # 0-1-0--0-10-----110-1---
(-x[4],x[3],-y[4],y[3],z[8],z[7],z[6],-z[3],-z[2],z[0],), # -01----01------111--00-1
(-x[4],-x[2],-y[5],y[4],y[2],y[1],z[7],z[6],-z[3],z[1],), # -0-0--01-11-----11--0-1-
(-x[5],-x[0],-y[5],-y[4],-y[2],-z[10],z[7],z[6],z[4],z[1],), # 0----000-0---0--11-1--1-
(-x[4],-x[3],-x[1],-y[4],-y[3],-y[1],z[9],z[5],z[4],), # -00-0--00-0---1---11----
(x[3],x[1],x[0],y[2],y[0],-z[4],), # --1-11---1-1-------0----
(-x[3],y[4],y[0],z[4],z[3],-z[2],-z[1],), # --0----1---1-------1100-
(-x[2],y[3],y[1],y[0],z[4],-z[3],z[2],), # ---0----1-11-------101--
(-x[5],x[3],-x[2],-y[5],y[3],z[7],-z[5],-z[4],z[2],z[1],), # 0-10--0-1-------1-00-11-
(-x[3],-x[1],-y[5],y[4],y[1],z[6],z[4],z[3],z[2],z[0],), # --0-0-01--1------1-111-1
(x[3],-x[2],-y[2],y[1],-z[11],-z[8],-z[7],z[0],), # --10-----01-0--00------1
(x[3],y[5],y[2],y[1],-z[9],z[8],-z[7],z[1],), # --1---1--11---010-----1-
(-x[4],-x[2],-y[4],-y[3],-z[11],z[10],z[8],), # -0-0---00---01-1--------
(-x[4],-y[5],y[4],y[2],-y[1],-y[0],z[6],-z[5],z[4],-z[1],), # -0----01-100-----101--0-
(-x[3],x[1],-y[5],-y[4],-y[3],y[2],-z[9],-z[8],), # --0-1-0001----00--------
(x[1],-y[4],y[1],y[0],z[4],-z[3],z[2],), # ----1--0--11-------101--
(-x[5],x[4],-y[5],y[4],z[9],z[7],-z[5],-z[0],), # 01----01------1-1-0----0
(-x[5],x[4],-x[3],x[2],y[2],-z[9],z[7],-z[4],z[1],z[0],), # 0101-----1----0-1--0--11
(-x[5],-x[3],-x[2],y[4],-y[0],z[8],z[7],z[6],z[2],), # 0-00---1---0---111---1--
(-x[5],-x[3],x[2],-y[5],-y[3],y[2],z[8],z[7],z[6],), # 0-01--0-01-----111------
(-x[0],-y[4],z[4],z[3],z[2],z[1],z[0],), # -----0-0-----------11111
(x[3],x[2],y[3],-y[1],-z[3],-z[1],-z[0],), # --11----1-0---------0-00
(-x[3],x[2],-y[1],y[0],z[4],z[2],z[1],), # --01------01-------1-11-
(-x[1],x[0],-y[3],y[2],z[4],z[2],z[1],), # ----01--01---------1-11-
(x[3],-y[4],y[0],z[4],z[3],-z[2],-z[1],), # --1----0---1-------1100-
(-x[3],-x[2],y[4],-y[1],-y[0],z[10],z[7],z[6],z[5],-z[1],), # --00---1--00-1--111---0-
(x[1],y[4],y[2],y[1],y[0],-z[4],), # ----1--1-111-------0----
(x[3],-y[4],y[0],z[4],-z[3],z[2],-z[1],), # --1----0---1-------1010-
(x[4],y[1],-y[0],-z[4],z[2],z[1],z[0],), # -1--------10-------0-111
(-x[4],-x[1],-y[5],-y[3],y[1],-z[9],z[7],-z[6],-z[3],z[0],), # -0--0-0-0-1---0-10--0--1
(x[4],-x[1],y[3],-y[2],z[11],-z[8],-z[7],-z[6],-z[5],-z[1],), # -1--0---10--1--0000---0-
(-x[1],-y[1],z[11],-z[10],z[9],-z[6],-z[4],z[3],-z[1],), # ----0-----0-101--0-01-0-
(x[3],x[2],-y[5],y[4],-y[3],y[2],-z[9],z[7],z[2],z[0],), # --11--0101----0-1----1-1
(-x[4],x[2],-x[1],y[3],-y[2],-y[1],-z[11],-z[8],), # -0-10---100-0--0--------
(x[2],-y[4],-y[3],-z[11],z[8],-z[7],-z[2],z[0],), # ---1---00---0--10----0-1
(x[5],x[4],x[2],x[1],y[3],z[8],-z[6],z[2],), # 11-11---1------1-0---1--
(-x[5],-x[3],x[2],y[3],-y[0],z[10],z[9],-z[8],-z[6],), # 0-01----1--0-110-0------
(-x[4],x[3],x[2],x[1],-y[3],y[0],z[7],-z[5],z[2],), # -0111---0--1----1-0--1--
(x[4],-x[3],-y[5],y[4],-y[3],-y[2],y[1],-z[6],-z[4],z[1],), # -10---01001------0-0--1-
(-x[3],x[1],-y[5],-y[4],y[3],y[2],y[1],z[7],z[6],), # --0-1-00111-----11------
(-x[5],-x[3],-y[2],z[11],z[9],z[8],-z[7],z[6],-z[1],), # 0-0------0--1-1101----0-
(x[5],-x[3],x[2],y[5],-y[3],-z[8],-z[7],z[2],), # 1-01--1-0------00----1--
(-x[4],-x[2],-y[5],-z[8],-z[6],-z[5],z[1],-z[0],), # -0-0--0--------0-00---10
(-x[3],-x[1],y[3],-y[1],y[0],z[4],z[1],), # --0-0---1-01-------1--1-
(-x[5],x[4],-x[3],x[2],-x[1],-x[0],-z[8],-z[6],-z[1],), # 010100---------0-0----0-
(-x[5],-x[2],-x[1],-y[5],-y[2],-z[10],z[8],z[7],z[5],), # 0--00-0--0---0-11-1-----
(-x[5],x[4],-x[3],-x[2],-y[5],y[4],-y[3],-y[2],-z[9],z[8],), # 0100--0100----01--------
(x[4],-x[3],-x[2],-y[4],y[2],y[1],z[9],z[6],z[5],z[0],), # -100---0-11---1--11----1
(-x[4],-y[3],z[11],z[10],z[9],z[8],z[7],), # -0------0---11111-------
(x[5],x[3],x[2],-y[4],y[3],z[7],z[5],-z[3],), # 1-11---01-------1-1-0---
(x[5],x[2],x[1],-y[5],-y[4],-z[9],z[8],-z[7],), # 1--11-00------010-------
(-x[4],y[1],-y[0],z[4],z[2],z[1],z[0],), # -0--------10-------1-111
(x[2],y[4],y[1],y[0],-z[4],-z[2],), # ---1---1--11-------0-0--
(-x[3],-x[2],-x[0],-y[4],-y[2],z[10],z[9],z[8],), # --00-0-0-0---111--------
(x[4],x[1],x[0],y[2],-z[4],-z[2],), # -1--11---1---------0-0--
(-x[4],x[3],-y[3],-y[1],-y[0],z[4],z[3],z[2],z[0],), # -01-----0-00-------111-1
(x[5],-x[4],x[3],x[2],y[4],-y[2],z[9],z[6],-z[5],), # 1011---1-0----1--10-----
(-x[5],x[3],x[2],y[4],y[3],-y[2],z[8],z[7],), # 0-11---110-----11-------
(x[4],x[0],-y[3],y[2],y[1],z[4],-z[1],), # -1---1--011--------1--0-
(x[4],-x[3],-x[2],x[1],-x[0],-y[5],y[4],-y[3],-z[7],z[3],), # -10010010-------0---1---
(x[4],-x[3],-x[2],x[0],-y[4],-y[2],y[1],z[8],z[6],), # -100-1-0-01----1-1------
(-x[3],-x[2],-x[1],y[2],y[1],z[6],-z[3],z[1],), # --000----11------1--0-1-
(-x[4],x[3],-x[2],x[1],-y[4],-y[3],-z[8],z[6],z[4],z[0],), # -0101--00------0-1-1---1
(x[3],-x[1],y[3],-y[1],z[11],z[10],-z[8],-z[6],z[3],z[2],), # --1-0---1-0-11-0-0--11--
(-x[4],-x[3],-x[2],y[2],-z[11],z[8],-z[7],z[0],), # -000-----1--0--10------1
(-x[4],-x[2],-x[1],-y[3],y[2],z[11],z[9],z[8],z[7],), # -0-00---01--1-111-------
(-x[5],x[4],-x[3],-x[0],-y[5],-y[2],-y[1],z[9],-z[7],-z[4],), # 010--00--00---1-0--0----
(-x[4],x[0],y[3],y[2],y[1],z[4],-z[1],), # -0---1--111--------1--0-
(-x[3],y[4],y[3],y[2],y[0],z[4],-z[1],), # --0----111-1-------1--0-
(-x[4],-x[3],-y[4],-y[3],z[11],z[9],z[8],), # -00----00---1-11--------
(-x[3],-x[2],-x[1],-y[5],-y[2],y[1],-z[8],z[6],-z[4],z[0],), # --000-0--01----0-1-0---1
(x[3],-x[2],-x[0],y[5],-y[4],z[7],z[5],z[4],-z[1],), # --10-010--------1-11--0-
(x[5],x[3],x[2],x[1],-y[5],z[9],-z[7],), # 1-111-0-------1-0-------
(-x[5],-x[4],-x[3],x[2],y[4],y[3],-y[1],-y[0],z[7],-z[3],), # 0001---11-00----1---0---
(-x[4],-x[2],-x[1],-y[4],z[10],-z[8],-z[3],-z[0],), # -0-00--0-----1-0----0--0
(-x[5],-x[4],x[3],x[2],-x[0],-y[5],y[4],z[6],-z[2],-z[1],), # 0011-001---------1---00-
(-x[4],x[3],y[5],-y[3],y[2],z[10],-z[8],z[7],), # -01---1-01---1-01-------
(x[4],-x[3],y[4],-y[3],z[11],z[9],z[7],z[6],), # -10----10---1-1-11------
(x[3],y[3],-y[1],-z[7],-z[5],-z[4],z[3],z[2],z[0],), # --1-----1-0-----0-0011-1
(-x[5],-x[4],x[3],x[2],-y[4],-y[3],-y[0],z[8],z[7],z[2],), # 0011---00--0---11----1--
(x[4],-x[3],x[1],y[4],y[3],-y[2],z[7],-z[6],-z[5],), # -10-1--110------100-----
(x[4],-x[3],x[1],-y[5],-y[4],y[3],-z[9],z[7],z[6],), # -10-1-001-----0-11------
(-x[3],-x[1],x[0],-y[3],-y[1],-z[4],z[1],), # --0-01--0-0--------0--1-
(-x[5],x[3],-x[2],-y[5],-y[3],-z[10],-z[8],-z[7],-z[1],), # 0-10--0-0----0-00-----0-
(x[4],-x[2],-y[5],-y[4],y[2],-y[1],z[7],z[5],z[3],), # -1-0--00-10-----1-1-1---
(x[4],-x[3],y[4],y[1],-z[4],-z[3],-z[0],), # -10----1--1--------00--0
(x[4],x[2],-x[1],-y[5],-y[3],-y[2],-y[1],-z[8],z[7],), # -1-10-0-000----01-------
(-y[5],-y[4],-y[3],-y[2],z[10],-z[9],-z[6],-z[0],), # ------0000---10--0-----0
(x[2],-y[4],y[1],y[0],z[4],-z[2],), # ---1---0--11-------1-0--
(-x[1],y[3],y[1],z[3],-z[2],z[1],), # ----0---1-1---------101-
(x[5],x[4],x[2],-y[4],y[3],-z[8],z[7],), # 11-1---01------01-------
(-x[3],-x[2],-y[4],-y[3],z[11],z[10],z[8],z[7],), # --00---00---11-11-------
(-x[4],-x[3],-x[2],-y[2],y[1],-z[11],-z[8],z[0],), # -000-----01-0--0-------1
(x[5],x[2],-x[1],-y[5],z[10],z[9],z[7],z[6],), # 1--10-0------11-11------
(-x[5],x[3],-y[4],-y[3],y[2],z[9],-z[8],-z[7],z[1],z[0],), # 0-1----001----100-----11
(-x[5],-x[3],x[2],y[4],-y[2],z[11],-z[7],-z[5],z[4],-z[1],), # 0-01---1-0--1---0-01--0-
(-x[5],-x[4],-y[5],y[4],y[2],-z[7],-z[6],z[2],-z[1],z[0],), # 00----01-1------00---101
(x[5],x[3],x[2],x[0],-y[5],z[9],-z[7],), # 1-11-10-------1-0-------
(-x[4],x[1],x[0],y[2],z[4],-z[2],), # -0--11---1---------1-0--
(-x[3],-x[0],-y[5],y[2],-y[1],z[11],-z[9],z[8],-z[6],z[5],), # --0--00--10-1-01-01-----
(-x[3],x[2],-x[1],-y[4],y[3],-y[2],y[1],-z[8],z[6],z[0],), # --010--0101----0-1-----1
(x[3],-x[2],-y[3],y[1],-z[9],z[8],-z[7],-z[6],z[0],), # --10----0-1---0100-----1
(-x[4],-x[3],-x[2],-x[1],-y[5],-y[2],-z[6],z[2],z[1],), # -0000-0--0-------0---11-
(x[4],-x[3],-x[2],x[0],y[3],-z[4],-z[1],), # -100-1--1----------0--0-
(x[4],x[0],y[3],-y[2],-y[1],-z[4],-z[1],), # -1---1--100--------0--0-
(-x[5],-y[5],z[11],z[7],z[2],-z[1],-z[0],), # 0-----0-----1---1----100
(-x[3],x[2],x[1],-y[3],y[2],y[1],z[6],z[0],), # --011---011------1-----1
(x[3],x[1],-y[4],-y[3],y[2],y[1],-z[6],z[5],z[0],), # --1-1--0011------01----1
(-x[5],x[4],y[5],-y[2],y[1],z[10],z[9],z[7],), # 01----1--01--11-1-------
(-x[5],x[4],-y[4],y[3],z[11],z[9],-z[6],), # 01-----01---1-1--0------
(x[2],-y[5],y[4],-y[3],-y[1],z[11],z[7],-z[5],z[3],-z[2],), # ---1--010-0-1---1-0-10--
(-x[5],-x[3],x[1],-y[4],y[3],-y[2],-y[1],z[10],z[7],z[6],), # 0-0-1--0100--1--11------
(-x[5],-x[4],-x[3],x[2],-y[3],y[1],z[10],z[7],-z[6],z[1],), # 0001----0-1--1--10----1-
(-x[5],-x[3],x[2],x[1],-y[3],-y[1],-z[6],-z[5],-z[4],z[0],), # 0-011---0-0------000---1
(-x[5],-x[4],-y[3],z[11],z[10],z[9],z[7],), # 00------0---111-1-------
(-x[5],x[4],-x[3],-x[2],y[4],-y[3],-y[2],y[1],z[10],-z[7],), # 0100---1001--1--0-------
(-x[5],x[3],x[2],x[1],-y[3],y[1],-z[7],-z[6],z[0],), # 0-111---0-1-----00-----1
(x[3],y[4],-y[3],-y[2],y[0],-z[4],-z[1],), # --1----100-1-------0--0-
(-x[5],x[4],-x[3],x[2],-x[1],-y[1],z[8],z[6],-z[1],), # 01010-----0----1-1----0-
(-x[4],y[5],-y[3],-y[2],-z[10],z[9],z[8],), # -0----1-00---011--------
(-x[3],x[2],x[1],-y[4],y[0],-z[4],-z[1],), # --011--0---1-------0--0-
(-x[5],x[4],-x[2],x[1],-y[4],y[3],-y[2],z[8],-z[3],z[0],), # 01-01--010-----1----0--1
(x[5],-x[4],x[2],-x[1],-y[5],y[3],-y[2],-z[9],z[7],), # 10-10-0-10----0-1-------
(-x[5],-x[2],-x[1],-y[5],-y[2],z[8],z[7],-z[5],-z[2],), # 0--00-0--0-----11-0--0--
(-x[3],-y[4],y[3],y[2],y[0],-z[4],-z[1],), # --0----011-1-------0--0-
(x[4],-x[3],y[4],-y[1],-z[4],z[3],-z[0],), # -10----1--0--------01--0
(x[4],-x[3],-x[2],x[0],-y[3],z[4],-z[1],), # -100-1--0----------1--0-
(-y[4],-y[3],-y[2],-y[1],-z[11],z[6],-z[1],z[0],), # -------0000-0----1----01
(-x[4],x[3],x[2],x[0],-y[3],-z[4],-z[1],), # -011-1--0----------0--0-
(-x[4],x[3],-y[5],y[4],-y[3],z[11],z[8],-z[2],-z[1],), # -01---010---1--1-----00-
(-x[5],x[4],-y[4],y[3],z[11],z[9],-z[8],), # 01-----01---1-10--------
(-x[5],x[3],y[3],-y[2],y[1],z[11],z[10],z[7],-z[6],), # 0-1-----101-11--10------
(-x[4],-x[3],-x[2],x[0],y[3],z[4],-z[1],), # -000-1--1----------1--0-
(-x[4],x[0],y[3],-y[2],-y[1],z[4],-z[1],), # -0---1--100--------1--0-
(x[4],-x[2],x[1],-y[5],y[3],-y[2],-y[1],-z[9],z[7],), # -1-01-0-100---0-1-------
(-x[5],x[4],x[3],y[2],-y[1],z[11],z[10],z[7],z[6],), # 011------10-11--11------
(-x[4],-x[2],-x[0],-y[5],-y[3],z[8],z[6],-z[2],z[0],), # -0-0-00-0------1-1---0-1
(x[2],y[4],y[3],y[2],y[1],-z[7],z[1],), # ---1---1111-----0-----1-
(-x[4],-y[5],-y[4],z[11],z[10],z[6],-z[3],-z[2],), # -0----00----11---1--00--
(x[4],-x[1],-x[0],-y[5],y[4],y[1],-z[6],z[5],-z[2],), # -1--0001--1------01--0--
(-x[5],x[4],x[3],y[5],-y[3],y[2],z[8],-z[6],), # 011---1-01-----1-0------
(x[5],-x[3],-x[2],-y[4],y[3],-y[2],z[10],-z[8],-z[7],), # 1-00---010---1-00-------
(x[3],-y[4],-y[3],-y[2],y[0],z[4],-z[1],), # --1----000-1-------1--0-
(-x[5],-x[4],x[3],-x[2],-x[0],-y[5],y[4],-y[2],y[1],z[8],), # 0010-001-01----1--------
(x[4],x[3],-y[4],y[3],z[4],-z[1],-z[0],), # -11----01----------1--00
(-x[4],-x[3],-x[2],-y[5],z[11],z[10],z[7],), # -000--0-----11--1-------
(-x[5],-x[4],x[3],x[2],x[1],-y[2],-y[1],-z[6],-z[5],z[0],), # 00111----00------00----1
(-x[5],-y[1],y[0],z[11],z[10],z[9],z[8],z[6],), # 0---------011111-1------
(-x[5],-x[4],-x[3],y[5],y[3],-z[9],z[7],), # 000---1-1-----0-1-------
(-x[3],x[2],y[3],-y[2],-z[9],z[8],-z[6],z[1],z[0],), # --01----10----01-0----11
(-x[4],-x[3],-x[2],x[0],-y[3],-z[4],-z[1],), # -000-1--0----------0--0-
(-x[4],x[0],-y[3],-y[2],-y[1],-z[4],-z[1],), # -0---1--000--------0--0-
(-x[3],-y[4],-y[3],-y[2],y[0],-z[4],-z[1],), # --0----000-1-------0--0-
(-x[4],-x[3],-x[2],-x[1],z[11],-z[10],z[5],-z[0],), # -0000-------10----1----0
(-x[5],-x[4],y[4],y[3],y[0],z[11],z[6],z[5],-z[2],), # 00-----11--11----11--0--
(-x[5],-x[4],-x[3],-x[2],y[1],z[11],z[7],-z[6],), # 0000------1-1---10------
(-y[4],-y[3],-y[2],-y[1],z[11],-z[10],z[5],-z[0],), # -------0000-10----1----0
(x[4],x[3],y[4],-y[3],-z[4],z[1],-z[0],), # -11----10----------0--10
(-x[4],-x[2],x[1],-y[5],-y[3],y[2],z[11],-z[9],-z[7],z[1],), # -0-01-0-01--1-0-0-----1-
(-x[5],x[4],-x[3],-x[2],-y[5],-y[4],y[3],-z[9],z[0],), # 0100--001-----0--------1
(-x[4],y[3],z[8],-z[7],-z[6],z[4],-z[3],-z[2],-z[1],), # -0------1------100-1000-
(-x[4],-x[2],-y[5],-y[3],z[11],z[10],z[8],), # -0-0--0-0---11-1--------
(-x[5],x[4],x[2],-y[3],y[2],z[11],z[10],z[8],), # 01-1----01--11-1--------
(-x[5],-x[4],x[3],-x[2],-y[5],y[4],-y[3],-z[9],z[0],), # 0010--010-----0--------1
(-x[5],x[4],-x[3],-x[2],-y[4],-y[2],-y[0],z[11],-z[9],z[7],), # 0100---0-0-01-0-1-------
(-x[5],-x[4],x[3],-y[3],-y[2],y[1],z[11],z[10],-z[8],), # 001-----001-11-0--------
(-x[5],-x[3],-x[1],-y[5],-y[3],-y[1],-z[7],-z[6],-z[1],), # 0-0-0-0-0-0-----00----0-
(-x[4],x[3],-x[2],-x[1],-y[5],-y[4],y[3],z[11],-z[8],), # -0100-001---1--0--------
(z[11],-z[10],z[7],-z[6],z[5],z[4],z[3],z[2],-z[1],), # ------------10--1011110-
(-x[5],-x[4],-y[4],-y[3],y[2],z[10],-z[6],-z[1],z[0],), # 00-----001---1---0----01
(x[4],x[3],-x[1],-x[0],-y[5],-y[4],-y[3],z[11],z[7],), # -11-00000---1---1-------
(x[3],-x[2],-x[1],y[3],-y[2],-y[1],-z[10],z[7],), # --100---100--0--1-------
(-x[5],-x[2],y[4],-y[3],-y[2],-y[1],-y[0],z[11],z[9],), # 0--0---100001-1---------
(x[3],x[2],-x[1],-y[5],-y[4],-y[3],z[11],z[10],z[5],), # --110-000---11----1-----
(-x[5],-x[4],-x[3],x[2],x[1],-y[3],-y[1],z[10],-z[7],z[0],), # 00011---0-0--1--0------1
(-x[1],-x[0],-y[5],-y[4],-y[3],z[11],z[10],z[7],z[6],), # ----00000---11--11------
(-x[5],-x[1],y[4],-y[3],-y[2],-y[1],-y[0],z[11],z[5],-z[4],), # 0---0--100001-----10----
(-x[2],y[3],-y[1],z[10],-z[9],-z[8],-z[7],z[6],-z[2],), # ---0----1-0--10001---0--
(x[1],y[4],y[3],y[2],y[1],-z[6],z[0],), # ----1--1111------0-----1
(x[3],-x[2],y[3],-z[11],z[9],-z[8],z[7],), # --10----1---0-101-------
(-x[2],x[1],-y[5],y[3],y[2],-z[10],z[8],z[7],-z[6],), # ---01-0-11---0-110------
(-x[4],y[4],-y[3],y[2],z[8],z[6],z[5],z[4],-z[2],), # -0-----101-----1-111-0--
(-x[5],-x[4],-y[2],-y[1],-z[9],z[7],-z[6],-z[4],-z[3],), # 00-------00---0-10-00---
(x[5],-x[1],x[0],-y[5],-y[4],-y[3],-y[2],-z[7],), # 1---010000------0-------
(-x[5],x[2],-y[5],y[2],-z[8],z[7],z[5],z[3],-z[1],), # 0--1--0--1-----01-1-1-0-
(-x[3],-y[5],y[2],z[9],-z[7],z[6],z[5],-z[2],-z[1],), # --0---0--1----1-011--00-
(-z[11],-z[8],-z[2],-z[1],-z[0],), # ------------0--0-----000
(-x[5],-y[5],-z[10],z[9],z[6],z[5],-z[4],-z[1],z[0],), # 0-----0------01--110--01
(-x[3],-y[3],y[2],-z[11],-z[9],-z[8],), # --0-----01--0-00--------
(-x[3],-x[0],-y[5],y[3],y[2],-z[10],z[8],z[7],z[2],), # --0--00-11---0-11----1--
(-x[5],-x[3],y[4],-y[2],z[7],z[4],z[3],z[2],z[1],), # 0-0----1-0------1--1111-
(x[3],x[2],-y[4],-y[3],-z[11],z[9],-z[8],), # --11---00---0-10--------
(-x[5],x[3],-x[2],-y[3],y[1],-y[0],-z[9],-z[8],z[7],), # 0-10----0-10--001-------
(-x[4],-y[4],y[3],y[2],z[10],-z[8],z[7],z[6],-z[2],), # -0-----011---1-011---0--
(-x[5],-x[3],x[2],-y[5],y[3],-y[2],-z[10],-z[8],z[7],), # 0-01--0-10---0-01-------
(-x[4],-x[3],-y[3],-y[2],z[9],z[7],z[6],z[5],-z[1],), # -00-----00----1-111---0-
(-x[4],x[2],-y[4],y[3],y[2],y[1],z[8],z[7],), # -0-1---0111----11-------
(-x[4],x[1],y[4],y[3],z[4],z[3],-z[0],), # -0--1--11----------11--0
(x[2],x[0],y[3],y[1],y[0],-z[4],), # ---1-1--1-11-------0----
(-x[5],x[3],x[1],-y[4],y[3],-z[6],z[4],-z[3],z[1],), # 0-1-1--01--------0-10-1-
(-x[3],-x[2],-y[3],-y[2],z[10],z[9],-z[8],z[7],z[6],), # --00----00---11011------
(x[2],-x[1],-y[5],-y[3],-y[2],y[1],-z[8],z[6],z[3],), # ---10-0-001----0-1--1---
(-x[5],-x[4],-x[3],-x[1],y[2],z[8],-z[7],-z[6],-z[4],), # 000-0----1-----100-0----
(x[4],-x[3],-y[4],y[1],z[4],-z[3],-z[0],), # -10----0--1--------10--0
(-x[4],-x[3],y[4],y[1],z[4],-z[3],-z[0],), # -00----1--1--------10--0
(-x[3],-x[2],-y[3],y[2],-z[11],z[9],z[8],), # --00----01--0-11--------
(x[4],-x[2],y[4],y[2],-z[9],z[8],-z[7],-z[1],), # -1-0---1-1----010-----0-
(-x[5],x[2],x[1],-y[5],-y[2],-y[1],-z[8],z[6],-z[3],), # 0--11-0--00----0-1--0---
(-x[5],x[3],x[2],y[3],-y[2],y[1],z[10],-z[8],z[7],), # 0-11----101--1-01-------
(x[3],-x[2],-x[1],y[4],-y[3],-y[2],z[9],z[8],-z[7],), # --100--100----110-------
(-x[4],x[3],y[4],-y[1],z[4],-z[3],-z[0],), # -01----1--0--------10--0
(x[3],-x[1],-y[5],-y[4],-y[1],-y[0],-z[9],-z[8],-z[5],), # --1-0-00--00--00--0-----
(-x[5],x[4],x[1],y[4],-y[1],-y[0],-z[6],z[5],-z[2],), # 01--1--1--00-----01--0--
(-x[1],-y[5],-y[4],y[2],-y[0],z[7],-z[6],-z[5],-z[3],), # ----0-00-1-0----100-0---
(-x[3],-x[0],-y[5],-y[3],z[6],-z[5],z[4],-z[3],z[1],), # --0--00-0--------1010-1-
(x[4],x[2],-y[5],y[3],z[10],-z[9],-z[7],), # -1-1--0-1----10-0-------
(-x[3],-y[4],-y[3],-y[2],-z[11],z[9],z[8],), # --0----000--0-11--------
(-x[4],x[1],-y[4],y[3],-z[4],z[3],-z[0],), # -0--1--01----------01--0
(x[4],-x[3],-y[4],-y[1],z[4],z[3],-z[0],), # -10----0--0--------11--0
(-x[5],-x[0],-y[4],-y[3],-z[7],z[6],-z[5],z[2],-z[1],), # 0----0-00-------010--10-
(x[2],x[0],-y[2],z[3],-z[2],z[1],), # ---1-1---0----------101-
(-x[4],-x[3],x[2],-y[5],-y[2],z[10],-z[8],z[7],z[5],), # -001--0--0---1-01-1-----
(-x[2],y[2],y[0],z[3],-z[2],z[1],), # ---0-----1-1--------101-
(-x[4],-x[1],y[4],-y[3],z[4],z[3],-z[0],), # -0--0--10----------11--0
(x[5],-x[4],y[4],y[3],y[2],z[9],-z[7],), # 10-----111----1-0-------
(x[5],x[3],y[5],-z[9],-z[8],), # 1-1---1-------00--------
(x[4],y[5],y[4],y[2],z[8],-z[7],-z[6],), # -1----11-1-----100------
(x[3],x[0],-y[3],y[0],z[4],-z[2],), # --1--1--0--1-------1-0--
(x[4],x[3],x[2],x[1],-y[1],-y[0],-z[6],z[5],), # -1111-----00-----01-----
(x[4],x[3],x[2],y[5],-y[4],z[9],-z[7],), # -111--10------1-0-------
(-x[3],x[0],y[1],z[3],-z[2],z[1],), # --0--1----1---------101-
(-x[5],y[5],y[3],y[2],y[1],z[9],-z[7],), # 0-----1-111---1-0-------
(-x[5],-x[3],x[2],-y[5],y[3],-z[10],z[8],-z[7],z[0],), # 0-01--0-1----0-10------1
(x[3],x[2],x[1],y[3],z[11],z[9],-z[8],-z[7],z[1],), # --111---1---1-100-----1-
(x[4],y[4],y[2],-z[11],), # -1-----1-1--0-----------
(-x[4],x[1],-y[4],-y[3],-z[4],-z[3],-z[0],), # -0--1--00----------00--0
(x[4],x[3],y[4],y[3],-z[9],), # -11----11-----0---------
(-x[4],-x[1],-y[4],y[3],-z[4],-z[3],-z[0],), # -0--0--01----------00--0
(-x[4],x[3],-y[4],y[3],-z[4],-z[1],-z[0],), # -01----01----------0--00
(-x[5],-x[2],-y[5],-y[2],z[11],-z[6],z[4],z[3],), # 0--0--0--0--1----0-11---
(-x[5],x[4],x[3],-x[2],-y[5],y[3],-y[2],z[8],-z[7],), # 0110--0-10-----10-------
(x[3],x[1],-y[1],z[3],-z[2],z[1],), # --1-1-----0---------101-
(-x[4],x[3],-x[2],x[1],-y[5],-y[4],-y[2],-z[8],-z[7],), # -0101-00-0-----00-------
(x[4],x[3],y[3],z[10],-z[8],-z[7],-z[4],), # -11-----1----1-00--0----
(-x[5],-x[4],x[3],x[2],-y[4],-y[2],-y[1],-z[8],z[7],), # 0011---0-00----01-------
(-x[3],x[2],-y[0],z[3],z[1],z[0],), # --01-------0--------1-11
(-x[5],y[3],-y[2],-y[1],-y[0],z[10],z[8],z[7],-z[2],), # 0-------1000-1-11----0--
(-x[4],-x[1],-y[4],-y[3],-z[4],z[3],-z[0],), # -0--0--00----------01--0
(x[5],x[4],-x[3],y[4],y[3],z[8],-z[7],), # 110----11------10-------
(x[4],x[3],-y[4],-y[3],z[4],z[1],-z[0],), # -11----00----------1--10
(x[5],x[4],-x[2],-y[4],z[8],z[7],z[6],), # 11-0---0-------111------
(-x[4],-x[3],-x[2],-x[1],-y[1],-z[10],z[6],-z[5],z[0],), # -0000-----0--0---10----1
(-x[2],x[1],-y[5],-y[4],-y[3],-y[2],-z[8],-z[7],), # ---01-0000-----00-------
(-x[5],y[4],y[3],y[2],z[10],-z[8],), # 0------111---1-0--------
(-x[4],y[5],y[4],-y[2],z[8],z[7],z[6],), # -0----11-0-----111------
(-x[5],-x[4],-x[3],-x[2],x[1],-y[5],-y[2],-z[8],-z[7],), # 00001-0--0-----00-------
(-x[5],-y[5],-y[4],-y[2],-y[1],-y[0],z[6],-z[5],z[3],), # 0-----00-000-----10-1---
(x[1],-y[1],y[0],-z[2],z[1],), # ----1-----01---------01-
(x[4],x[3],y[5],y[4],-y[3],z[8],-z[7],), # -11---110------10-------
(-x[5],-x[3],y[4],-y[3],-z[10],z[9],), # 0-0----10----01---------
(-x[5],x[4],-y[4],y[3],y[1],z[11],z[9],), # 01-----01-1-1-1---------
(-x[4],-x[3],-y[4],-y[3],-z[4],-z[1],-z[0],), # -00----00----------0--00
(-x[4],x[3],x[2],y[5],-y[4],-y[3],-z[9],-z[7],), # -011--100-----0-0-------
(-x[5],x[4],-y[4],y[2],z[11],z[9],-z[8],), # 01-----0-1--1-10--------
(-x[5],x[4],x[3],x[2],y[5],-y[2],z[7],-z[6],), # 0111--1--0------10------
(-x[4],-x[3],-y[4],y[3],-z[4],z[1],-z[0],), # -00----01----------0--10
(-x[4],-x[2],-x[1],-y[4],-y[3],y[2],z[10],-z[7],z[6],), # -0-00--001---1--01------
(-x[4],x[3],-y[4],-y[3],-z[4],z[1],-z[0],), # -01----00----------0--10
(-x[5],-x[4],-x[3],-x[2],-y[5],z[11],z[7],), # 0000--0-----1---1-------
(-x[4],x[3],x[2],x[1],-y[2],y[1],z[6],z[0],), # -0111----01------1-----1
(-x[5],-x[4],-x[3],y[5],-y[2],y[1],-z[8],-z[7],), # 000---1--01----00-------
(-x[2],x[1],-y[4],y[3],y[2],y[1],z[6],z[0],), # ---01--0111------1-----1
(-x[5],x[3],-y[4],y[3],z[11],z[9],-z[8],), # 0-1----01---1-10--------
(-x[5],x[4],-x[2],-x[1],-y[5],-y[4],-y[3],y[2],-z[8],), # 01-00-0001-----0--------
(-x[4],x[3],-x[2],y[5],-y[4],-y[2],-z[8],z[7],), # -010--10-0-----01-------
(x[4],x[2],y[4],y[2],-z[7],-z[6],z[2],z[0],), # -1-1---1-1------00---1-1
(-x[3],x[2],y[5],-y[4],-y[3],-y[2],-z[8],-z[7],), # --01--1000-----00-------
(x[3],x[1],-y[3],-y[2],y[1],-z[3],z[2],), # --1-1---001---------01--
(-x[3],-x[2],-y[1],-y[0],-z[3],z[1],z[0],), # --00------00--------0-11
(x[2],-x[1],-y[5],y[4],y[3],y[2],z[11],z[7],z[6],), # ---10-0111--1---11------
(-x[5],x[4],x[3],-y[3],y[1],z[11],z[10],z[8],), # 011-----0-1-11-1--------
(-x[5],-x[1],-y[4],-y[3],-y[2],-y[1],-y[0],-z[7],-z[6],), # 0---0--00000----00------
(x[3],-x[2],-x[1],-y[5],y[4],y[3],z[11],z[8],z[6],), # --100-011---1--1-1------
(x[1],-y[5],-y[4],-y[3],z[11],z[10],z[7],-z[6],), # ----1-000---11--10------
(-x[4],x[2],-y[5],y[4],-y[3],-y[2],z[11],-z[8],-z[7],), # -0-1--0100--1--00-------
(-x[4],-x[3],x[2],-y[5],y[4],-y[3],z[11],-z[8],z[7],), # -001--010---1--01-------
(-x[5],-x[4],-x[3],-x[2],-y[2],z[11],z[8],z[7],), # 0000-----0--1--11-------
(-x[3],-y[3],y[2],y[1],-z[3],-z[0],), # --0-----011---------0--0
(-x[4],-x[3],-x[2],-x[1],-y[5],y[2],y[1],z[7],z[0],), # -0000-0--11-----1------1
(-x[3],x[2],x[1],-y[3],-z[3],-z[0],), # --011---0-----------0--0
(-x[5],-x[4],-x[3],-x[2],y[5],-y[1],-z[7],-z[6],), # 0000--1---0-----00------
(-x[4],-x[3],-x[2],-y[5],-y[3],y[2],z[11],-z[8],-z[7],), # -000--0-01--1--00-------
(-x[4],-x[3],-x[2],-y[5],-y[2],z[11],-z[7],-z[6],-z[1],), # -000--0--0--1---00----0-
(-x[4],x[3],-y[4],y[3],z[11],-z[9],z[8],z[0],), # -01----01---1-01-------1
(-x[5],-x[4],-x[3],-x[2],-x[1],-y[5],z[6],-z[1],z[0],), # 00000-0----------1----01
(-x[4],-x[3],-x[2],-x[1],-y[2],-y[1],z[11],z[7],z[6],), # -0000----00-1---11------
(-x[2],-y[5],y[4],y[3],y[2],y[1],z[7],z[0],), # ---0--01111-----1------1
(-x[4],-x[3],-x[2],-x[1],-y[4],-y[1],z[10],-z[6],z[0],), # -0000--0--0--1---0-----1
(-x[5],x[4],x[3],x[2],x[1],-y[1],z[6],z[0],), # 01111-----0------1-----1
(-x[5],-x[4],-x[3],-x[2],-x[1],y[5],-y[0],-z[6],), # 00000-1----0-----0------
(-x[5],-x[2],x[1],-y[4],-y[3],-y[2],-y[1],z[11],-z[7],), # 0--01--0000-1---0-------
(x[3],y[3],y[2],-z[11],z[9],z[8],), # --1-----11--0-11--------
(-x[4],x[3],-y[5],y[4],z[11],z[9],z[1],z[0],), # -01---01----1-1-------11
(x[3],x[2],y[3],y[2],-z[10],-z[8],), # --11----11---0-0--------
(-x[3],x[2],-y[5],y[2],z[8],-z[7],z[5],-z[1],), # --01--0--1-----10-1---0-
(x[3],-x[2],y[3],-y[2],-z[9],z[8],-z[1],), # --10----10----01------0-
(x[4],y[4],y[3],-z[11],), # -1-----11---0-----------
(x[3],x[0],y[3],y[0],-z[4],-z[2],), # --1--1--1--1-------0-0--
(x[4],-x[2],-y[4],y[3],y[2],z[10],-z[8],-z[7],), # -1-0---011---1-00-------
(x[5],x[4],y[5],y[4],-z[8],), # 11----11-------0--------
(x[3],y[3],-z[3],-z[2],z[1],-z[0],), # --1-----1-----------0010
(-x[3],y[3],y[2],y[1],z[3],-z[0],), # --0-----111---------1--0
(-x[5],-x[3],-y[3],y[2],z[10],-z[8],z[7],-z[2],), # 0-0-----01---1-01----0--
(x[4],y[5],y[3],z[9],-z[8],-z[7],), # -1----1-1-----100-------
(x[4],x[1],x[0],-y[2],z[4],-z[2],), # -1--11---0---------1-0--
(-x[4],x[3],x[1],-y[5],-y[3],y[2],z[9],-z[8],), # -01-1-0-01----10--------
(x[3],-y[3],y[2],y[1],z[3],-z[0],), # --1-----011---------1--0
(-x[3],x[2],x[1],y[3],z[3],-z[0],), # --011---1-----------1--0
(x[4],x[2],y[4],-z[11],), # -1-1---1----0-----------
(-x[2],x[0],-y[2],y[0],-z[3],-z[2],), # ---0-1---0-1--------00--
(x[3],x[0],y[1],-z[3],-z[2],z[1],), # --1--1----1---------001-
(-x[1],x[0],-y[2],y[1],z[3],z[1],), # ----01---01---------1-1-
(x[3],x[2],x[1],-y[3],z[3],-z[0],), # --111---0-----------1--0
(-x[4],-x[3],-y[5],-y[4],z[10],z[9],), # -00---00-----11---------
(-x[5],x[4],-x[3],-y[5],-y[4],y[3],-z[9],-z[1],), # 010---001-----0-------0-
(-x[5],-x[4],x[3],-y[5],y[4],-y[3],-z[9],-z[1],), # 001---010-----0-------0-
(x[3],-y[0],-z[3],z[2],z[1],z[0],), # --1--------0--------0111
(-x[2],x[0],-y[1],z[3],z[2],z[1],), # ---0-1----0---------111-
(-x[2],-y[4],y[1],y[0],-z[4],-z[2],), # ---0---0--11-------0-0--
(x[5],-x[4],-x[3],-y[4],y[3],-z[9],-z[8],), # 100----01-----00--------
(x[3],y[4],y[3],z[10],-z[8],-z[7],z[0],), # --1----11----1-00------1
(x[3],-x[2],-x[1],y[3],-z[3],-z[0],), # --100---1-----------0--0
(-x[4],x[1],x[0],-y[2],-z[4],-z[2],), # -0--11---0---------0-0--
(x[3],x[0],y[2],-z[3],-z[1],), # --1--1---1----------0-0-
(-x[1],-y[3],y[1],-z[3],-z[2],z[1],), # ----0---0-1---------001-
(-x[4],-y[4],y[3],y[2],z[11],-z[9],z[8],-z[7],), # -0-----011--1-010-------
(-x[4],-x[3],-y[3],-y[2],z[10],z[9],z[8],), # -00-----00---111--------
(x[2],-y[5],-y[3],z[11],z[9],-z[8],z[7],-z[2],), # ---1--0-0---1-101----0--
(x[2],y[3],y[0],-z[3],-z[1],), # ---1----1--1--------0-0-
(-x[3],y[3],-y[2],-y[1],z[3],-z[0],), # --0-----100---------1--0
(-x[3],-x[2],-x[1],y[3],z[3],-z[0],), # --000---1-----------1--0
(x[5],x[3],x[2],x[1],-y[3],z[7],-z[6],), # 1-111---0-------10------
(x[3],x[0],-y[2],z[3],-z[1],), # --1--1---0----------1-0-
(-x[3],x[0],y[2],z[3],-z[1],), # --0--1---1----------1-0-
(x[3],-y[3],-y[2],-y[1],z[3],-z[0],), # --1-----000---------1--0
(-x[5],-x[4],y[5],-y[3],y[2],-z[9],-z[8],), # 00----1-01----00--------
(-x[4],x[3],x[2],y[3],-y[0],z[4],z[0],), # -011----1--0-------1---1
(x[3],-x[2],-x[1],-y[3],z[3],-z[0],), # --100---0-----------1--0
(-x[2],y[3],y[0],z[3],-z[1],), # ---0----1--1--------1-0-
(x[1],-x[0],-y[3],z[3],z[1],z[0],), # ----10--0-----------1-11
(-x[4],x[3],y[3],y[2],z[11],z[9],-z[7],-z[6],), # -01-----11--1-1-00------
(x[2],-y[3],y[0],z[3],-z[1],), # ---1----0--1--------1-0-
(x[4],-x[3],-x[2],-y[5],z[11],z[9],z[7],), # -100--0-----1-1-1-------
(x[1],-y[2],y[0],z[2],-z[1],), # ----1----0-1---------10-
(-x[3],x[0],-y[2],-z[3],-z[1],), # --0--1---0----------0-0-
(-x[3],-y[3],-y[2],-y[1],-z[3],-z[0],), # --0-----000---------0--0
(x[2],x[0],-y[1],z[2],-z[1],), # ---1-1----0----------10-
(x[4],x[3],x[2],y[2],z[10],-z[7],-z[6],), # -111-----1---1--00------
(-x[3],-x[2],-x[1],-y[3],-z[3],-z[0],), # --000---0-----------0--0
(-x[1],y[2],y[0],z[2],-z[1],), # ----0----1-1---------10-
(x[3],y[3],y[2],y[1],-z[3],), # --1-----111---------0---
(-x[2],-y[3],y[0],-z[3],-z[1],), # ---0----0--1--------0-0-
(x[3],-x[2],-y[5],z[11],z[10],z[8],z[7],), # --10--0-----11-11-------
(-x[4],x[3],x[2],-y[4],y[3],y[2],z[8],z[0],), # -011---011-----1-------1
(-x[5],x[4],x[3],y[3],-y[2],z[11],z[8],z[7],), # 011-----10--1--11-------
(x[4],x[0],y[3],y[2],y[1],-z[4],), # -1---1--111--------0----
(-x[3],-x[2],-y[3],-y[2],z[11],z[9],z[8],z[7],), # --00----00--1-111-------
(-x[4],-x[1],-y[5],-y[4],-y[3],-y[2],z[10],z[7],), # -0--0-0000---1--1-------
(x[3],y[3],-z[9],z[8],z[7],z[6],-z[1],), # --1-----1-----0111----0-
(-x[5],-x[3],-y[4],-y[2],z[11],z[10],z[8],), # 0-0----0-0--11-1--------
(-x[5],-x[4],y[4],y[3],-y[2],-y[1],z[11],z[8],), # 00-----1100-1--1--------
(x[4],x[3],-x[2],-x[1],-y[5],-y[4],z[11],z[8],), # -1100-00----1--1--------
(-x[5],-y[4],-y[3],-y[2],z[11],z[10],z[7],), # 0------000--11--1-------
(-x[5],-x[3],-x[2],-y[4],-y[3],z[11],z[10],), # 0-00---00---11----------
(x[5],x[3],y[4],z[9],-z[8],-z[7],), # 1-1----1------100-------
(-x[4],-x[3],-y[4],z[10],z[9],z[7],), # -00----0-----11-1-------
(-x[3],x[2],-y[5],-y[4],-y[3],-z[9],-z[8],), # --01--000-----00--------
(x[2],x[0],y[2],y[0],-z[3],), # ---1-1---1-1--------0---
(x[5],y[4],-z[10],-z[9],), # 1------1-----00---------
(-x[5],-x[4],-x[3],y[3],y[2],z[9],-z[8],), # 000-----11----10--------
(x[4],y[5],-z[10],-z[9],), # -1----1------00---------
(-x[3],-x[1],y[3],y[2],-z[3],z[2],z[1],), # --0-0---11----------011-
(x[1],y[3],y[1],y[0],-z[3],), # ----1---1-11--------0---
(x[5],-x[4],y[4],y[3],z[9],-z[8],), # 10-----11-----10--------
(x[4],x[3],y[5],-y[4],z[9],-z[8],), # -11---10------10--------
(x[5],y[5],y[4],-z[9],), # 1-----11------0---------
(x[5],-x[3],-y[4],z[9],z[8],z[7],), # 1-0----0------111-------
(x[5],x[3],x[2],-y[5],z[9],-z[8],), # 1-11--0-------10--------
(-x[0],-y[2],z[2],z[1],z[0],), # -----0---0-----------111
(-x[5],x[4],-y[4],-y[3],z[11],-z[9],z[8],), # 01-----00---1-01--------
(x[2],-y[0],-z[2],z[1],z[0],), # ---1-------0---------011
(-x[0],y[2],-z[2],z[1],z[0],), # -----0---1-----------011
(-x[2],-x[1],-y[1],-y[0],-z[2],z[0],), # ---00-----00---------0-1
(-x[1],-x[0],-y[2],-y[1],-z[2],z[0],), # ----00---00----------0-1
(-x[5],-x[4],-x[3],-y[5],z[11],z[8],), # 000---0-----1--1--------
(-x[4],x[3],-y[5],y[4],y[3],z[11],z[9],), # -01---011---1-1---------
(-x[4],-x[3],-y[5],z[11],z[10],z[8],), # -00---0-----11-1--------
(y[4],-z[11],-z[10],), # -------1----00----------
(-x[5],-x[4],-y[4],y[3],-z[10],-z[9],), # 00-----01----00---------
(-x[4],x[3],-y[5],-y[4],-z[10],-z[9],), # -01---00-----00---------
(x[5],x[4],y[5],-z[9],), # 11----1-------0---------
(x[2],y[2],-z[2],-z[0],), # ---1-----1-----------0-0
(x[2],-y[2],z[2],-z[0],), # ---1-----0-----------1-0
(-x[2],y[2],z[2],-z[0],), # ---0-----1-----------1-0
(-x[2],-y[2],-z[2],-z[0],), # ---0-----0-----------0-0
(-x[1],-y[1],-z[1],-z[0],), # ----0-----0-----------00
(-x[2],y[1],-y[0],z[2],z[0],), # ---0------10---------1-1
(y[1],y[0],-z[1],), # ----------11----------0-
(x[1],-y[0],-z[1],z[0],), # ----1------0----------01
(x[4],-x[3],-y[5],z[11],z[9],z[8],), # -10---0-----1-11--------
(-x[5],-y[5],-y[4],z[11],z[9],), # 0-----00----1-1---------
(-x[5],y[4],-y[3],z[11],z[9],z[8],), # 0------10---1-11--------
(x[4],y[4],z[10],-z[9],-z[8],), # -1-----1-----100--------
(x[4],-z[11],-z[10],), # -1----------00----------
(-x[5],y[4],y[3],z[10],-z[9],), # 0------11----10---------
(x[4],x[3],-y[5],z[10],-z[9],), # -11---0------10---------
(-x[4],-y[4],z[10],z[9],z[8],), # -0-----0-----111--------
(x[2],x[0],y[1],-z[2],), # ---1-1----1----------0--
(x[1],y[2],y[0],-z[2],), # ----1----1-1---------0--
(x[5],x[4],-z[10],), # 11-----------0----------
(y[5],y[4],-z[10],), # ------11-----0----------
(-x[1],-y[1],z[2],z[1],z[0],), # ----0-----0----------111
(x[5],y[5],-z[10],), # 1-----1------0----------
(-x[1],y[1],-y[0],z[1],), # ----0-----10----------1-
(x[1],-x[0],-y[1],z[1],), # ----10----0-----------1-
(-x[5],-y[5],z[11],z[10],), # 0-----0-----11----------
(y[5],-z[11],), # ------1-----0-----------
(x[5],-z[11],), # 1-----------0-----------
(-x[0],-y[0],z[0],), # -----0-----0-----------1
(x[0],y[0],-z[1],), # -----1-----1----------0-
(x[1],y[1],-z[1],), # ----1-----1-----------0-
(x[0],-z[0],), # -----1-----------------0
(y[0],-z[0],), # -----------1-----------0
]
def adder_8bit(cin, x, y, z, cout):
return [(cin,x[7],y[6],y[5],y[4],y[3],y[2],y[1],-cout,-z[0],), # 00--------000000-1-------1
(x[7],x[0],y[6],y[5],y[4],y[3],y[2],y[1],y[0],-cout,), # -0------0-00000001--------
(-cin,-y[6],-y[5],-y[4],-y[3],-y[2],-y[1],cout,z[7],z[0],), # 1---------111111-00------0
(-x[0],-y[6],-y[5],-y[4],-y[3],-y[2],-y[1],-y[0],cout,z[7],), # --------1-111111100-------
(-cin,-x[7],-y[7],-y[6],-y[5],-y[4],-y[3],-y[2],-y[1],z[7],z[0],), # 11-------1111111--0------0
(cin,x[7],y[7],y[6],y[5],y[4],y[3],y[2],y[1],-z[7],-z[0],), # 00-------0000000--1------1
(-x[7],-x[0],-y[7],-y[6],-y[5],-y[4],-y[3],-y[2],-y[1],-y[0],z[7],), # -1------111111111-0-------
(x[7],x[0],y[7],y[6],y[5],y[4],y[3],y[2],y[1],y[0],-z[7],), # -0------000000000-1-------
(x[7],x[1],y[6],y[5],y[4],y[3],y[2],-cout,-z[1],), # -0-----0--00000--1------1-
(-x[1],-y[6],-y[5],-y[4],-y[3],-y[2],cout,z[7],z[1],), # -------1--11111--00-----0-
(-x[7],-x[1],-y[7],-y[6],-y[5],-y[4],-y[3],-y[2],z[7],z[1],), # -1-----1-111111---0-----0-
(x[7],x[1],y[7],y[6],y[5],y[4],y[3],y[2],-z[7],-z[1],), # -0-----0-000000---1-----1-
(-cin,-y[7],-y[6],-y[5],-y[4],-y[3],-y[2],-y[1],cout,z[0],), # 1--------1111111-0-------0
(-x[0],-y[7],-y[6],-y[5],-y[4],-y[3],-y[2],-y[1],-y[0],cout,), # --------1111111110--------
(cin,y[7],y[6],y[5],y[4],y[3],y[2],y[1],-cout,-z[0],), # 0--------0000000-1-------1
(x[0],y[7],y[6],y[5],y[4],y[3],y[2],y[1],y[0],-cout,), # --------0000000001--------
(cin,-x[7],-y[7],y[6],y[5],y[4],y[3],y[2],y[1],-z[7],-z[0],), # 01-------1000000--1------1
(-x[7],x[0],-y[7],y[6],y[5],y[4],y[3],y[2],y[1],y[0],-z[7],), # -1------010000000-1-------
(-cin,-x[7],y[7],-y[6],-y[5],-y[4],-y[3],-y[2],-y[1],-z[7],z[0],), # 11-------0111111--1------0
(-x[7],-x[0],y[7],-y[6],-y[5],-y[4],-y[3],-y[2],-y[1],-y[0],-z[7],), # -1------101111111-1-------
(x[7],x[2],y[6],y[5],y[4],y[3],-cout,-z[2],), # -0----0---0000---1-----1--
(-x[2],-y[6],-y[5],-y[4],-y[3],cout,z[7],z[2],), # ------1---1111---00----0--
(-x[7],-x[2],-y[7],-y[6],-y[5],-y[4],-y[3],z[7],z[2],), # -1----1--11111----0----0--
(x[7],x[2],y[7],y[6],y[5],y[4],y[3],-z[7],-z[2],), # -0----0--00000----1----1--
(-cin,x[6],y[6],-y[5],-y[4],-y[3],-y[2],-y[1],z[6],z[0],), # 1-0-------011111---0-----0
(-cin,-x[6],-y[6],-y[5],-y[4],-y[3],-y[2],-y[1],z[6],z[0],), # 1-1-------111111---0-----0
(-cin,-x[6],y[6],-y[5],-y[4],-y[3],-y[2],-y[1],-z[6],z[0],), # 1-1-------011111---1-----0
(cin,x[6],-y[6],y[5],y[4],y[3],y[2],y[1],z[6],-z[0],), # 0-0-------100000---0-----1
(cin,x[6],y[6],y[5],y[4],y[3],y[2],y[1],-z[6],-z[0],), # 0-0-------000000---1-----1
(cin,-x[6],-y[6],y[5],y[4],y[3],y[2],y[1],-z[6],-z[0],), # 0-1-------100000---1-----1
(-x[1],-y[7],-y[6],-y[5],-y[4],-y[3],-y[2],cout,z[1],), # -------1-111111--0------0-
(x[6],x[0],-y[6],y[5],y[4],y[3],y[2],y[1],y[0],z[6],), # --0-----0-1000000--0------
(x[6],-x[0],y[6],-y[5],-y[4],-y[3],-y[2],-y[1],-y[0],z[6],), # --0-----1-0111111--0------
(-x[6],-x[0],-y[6],-y[5],-y[4],-y[3],-y[2],-y[1],-y[0],z[6],), # --1-----1-1111111--0------
(x[6],x[0],y[6],y[5],y[4],y[3],y[2],y[1],y[0],-z[6],), # --0-----0-0000000--1------
(-x[6],x[0],-y[6],y[5],y[4],y[3],y[2],y[1],y[0],-z[6],), # --1-----0-1000000--1------
(-x[6],-x[0],y[6],-y[5],-y[4],-y[3],-y[2],-y[1],-y[0],-z[6],), # --1-----1-0111111--1------
(x[1],y[7],y[6],y[5],y[4],y[3],y[2],-cout,-z[1],), # -------0-000000--1------1-
(-x[7],x[1],-y[7],y[6],y[5],y[4],y[3],y[2],-z[7],-z[1],), # -1-----0-100000---1-----1-
(-x[7],-x[1],y[7],-y[6],-y[5],-y[4],-y[3],-y[2],-z[7],z[1],), # -1-----1-011111---1-----0-
(x[7],x[3],y[6],y[5],y[4],-cout,-z[3],), # -0---0----000----1----1---
(-x[3],-y[6],-y[5],-y[4],cout,z[7],z[3],), # -----1----111----00---0---
(-x[7],-x[3],-y[7],-y[6],-y[5],-y[4],z[7],z[3],), # -1---1---1111-----0---0---
(x[7],x[3],y[7],y[6],y[5],y[4],-z[7],-z[3],), # -0---0---0000-----1---1---
(-x[2],-y[7],-y[6],-y[5],-y[4],-y[3],cout,z[2],), # ------1--11111---0-----0--
(x[2],y[7],y[6],y[5],y[4],y[3],-cout,-z[2],), # ------0--00000---1-----1--
(-x[7],x[2],-y[7],y[6],y[5],y[4],y[3],-z[7],-z[2],), # -1----0--10000----1----1--
(-cin,x[5],y[5],-y[4],-y[3],-y[2],-y[1],z[5],z[0],), # 1--0-------01111----0----0
(-cin,-x[5],-y[5],-y[4],-y[3],-y[2],-y[1],z[5],z[0],), # 1--1-------11111----0----0
(-cin,-x[5],y[5],-y[4],-y[3],-y[2],-y[1],-z[5],z[0],), # 1--1-------01111----1----0
(cin,x[5],-y[5],y[4],y[3],y[2],y[1],z[5],-z[0],), # 0--0-------10000----0----1
(cin,x[5],y[5],y[4],y[3],y[2],y[1],-z[5],-z[0],), # 0--0-------00000----1----1
(cin,-x[5],-y[5],y[4],y[3],y[2],y[1],-z[5],-z[0],), # 0--1-------10000----1----1
(-x[7],-x[2],y[7],-y[6],-y[5],-y[4],-y[3],-z[7],z[2],), # -1----1--01111----1----0--
(x[5],x[0],-y[5],y[4],y[3],y[2],y[1],y[0],z[5],), # ---0----0--100000---0-----
(x[5],-x[0],y[5],-y[4],-y[3],-y[2],-y[1],-y[0],z[5],), # ---0----1--011111---0-----
(-x[5],-x[0],-y[5],-y[4],-y[3],-y[2],-y[1],-y[0],z[5],), # ---1----1--111111---0-----
(x[5],x[0],y[5],y[4],y[3],y[2],y[1],y[0],-z[5],), # ---0----0--000000---1-----
(-x[5],x[0],-y[5],y[4],y[3],y[2],y[1],y[0],-z[5],), # ---1----0--100000---1-----
(-x[5],-x[0],y[5],-y[4],-y[3],-y[2],-y[1],-y[0],-z[5],), # ---1----1--011111---1-----
(x[6],-x[1],y[6],-y[5],-y[4],-y[3],-y[2],z[6],z[1],), # --0----1--01111----0----0-
(-x[6],-x[1],-y[6],-y[5],-y[4],-y[3],-y[2],z[6],z[1],), # --1----1--11111----0----0-
(-x[6],-x[1],y[6],-y[5],-y[4],-y[3],-y[2],-z[6],z[1],), # --1----1--01111----1----0-
(x[6],x[1],-y[6],y[5],y[4],y[3],y[2],z[6],-z[1],), # --0----0--10000----0----1-
(x[6],x[1],y[6],y[5],y[4],y[3],y[2],-z[6],-z[1],), # --0----0--00000----1----1-
(-x[6],x[1],-y[6],y[5],y[4],y[3],y[2],-z[6],-z[1],), # --1----0--10000----1----1-
(x[7],x[4],y[6],y[5],-cout,-z[4],), # -0--0-----00-----1---1----
(-x[4],-y[6],-y[5],cout,z[7],z[4],), # ----1-----11-----00--0----
(-x[7],-x[4],-y[7],-y[6],-y[5],z[7],z[4],), # -1--1----111------0--0----
(x[7],x[4],y[7],y[6],y[5],-z[7],-z[4],), # -0--0----000------1--1----
(-x[3],-y[7],-y[6],-y[5],-y[4],cout,z[3],), # -----1---1111----0----0---
(x[3],y[7],y[6],y[5],y[4],-cout,-z[3],), # -----0---0000----1----1---
(-x[7],x[3],-y[7],y[6],y[5],y[4],-z[7],-z[3],), # -1---0---1000-----1---1---
(-x[7],-x[3],y[7],-y[6],-y[5],-y[4],-z[7],z[3],), # -1---1---0111-----1---0---
(-cin,x[4],y[4],-y[3],-y[2],-y[1],z[4],z[0],), # 1---0-------0111-----0---0
(-cin,-x[4],-y[4],-y[3],-y[2],-y[1],z[4],z[0],), # 1---1-------1111-----0---0
(-cin,-x[4],y[4],-y[3],-y[2],-y[1],-z[4],z[0],), # 1---1-------0111-----1---0
(cin,x[4],-y[4],y[3],y[2],y[1],z[4],-z[0],), # 0---0-------1000-----0---1
(cin,x[4],y[4],y[3],y[2],y[1],-z[4],-z[0],), # 0---0-------0000-----1---1
(cin,-x[4],-y[4],y[3],y[2],y[1],-z[4],-z[0],), # 0---1-------1000-----1---1
(x[4],x[0],-y[4],y[3],y[2],y[1],y[0],z[4],), # ----0---0---10000----0----
(x[4],-x[0],y[4],-y[3],-y[2],-y[1],-y[0],z[4],), # ----0---1---01111----0----
(-x[4],-x[0],-y[4],-y[3],-y[2],-y[1],-y[0],z[4],), # ----1---1---11111----0----
(x[4],x[0],y[4],y[3],y[2],y[1],y[0],-z[4],), # ----0---0---00000----1----
(-x[4],x[0],-y[4],y[3],y[2],y[1],y[0],-z[4],), # ----1---0---10000----1----
(-x[4],-x[0],y[4],-y[3],-y[2],-y[1],-y[0],-z[4],), # ----1---1---01111----1----
(x[6],-x[2],y[6],-y[5],-y[4],-y[3],z[6],z[2],), # --0---1---0111-----0---0--
(-x[6],-x[2],-y[6],-y[5],-y[4],-y[3],z[6],z[2],), # --1---1---1111-----0---0--
(-x[6],-x[2],y[6],-y[5],-y[4],-y[3],-z[6],z[2],), # --1---1---0111-----1---0--
(x[6],x[2],-y[6],y[5],y[4],y[3],z[6],-z[2],), # --0---0---1000-----0---1--
(x[6],x[2],y[6],y[5],y[4],y[3],-z[6],-z[2],), # --0---0---0000-----1---1--
(-x[6],x[2],-y[6],y[5],y[4],y[3],-z[6],-z[2],), # --1---0---1000-----1---1--
(x[5],-x[1],y[5],-y[4],-y[3],-y[2],z[5],z[1],), # ---0---1---0111-----0---0-
(-x[5],-x[1],-y[5],-y[4],-y[3],-y[2],z[5],z[1],), # ---1---1---1111-----0---0-
(-x[5],-x[1],y[5],-y[4],-y[3],-y[2],-z[5],z[1],), # ---1---1---0111-----1---0-
(x[5],x[1],-y[5],y[4],y[3],y[2],z[5],-z[1],), # ---0---0---1000-----0---1-
(x[5],x[1],y[5],y[4],y[3],y[2],-z[5],-z[1],), # ---0---0---0000-----1---1-
(-x[5],x[1],-y[5],y[4],y[3],y[2],-z[5],-z[1],), # ---1---0---1000-----1---1-
(x[7],x[5],y[6],-cout,-z[5],), # -0-0------0------1--1-----
(-x[5],-y[6],cout,z[7],z[5],), # ---1------1------00-0-----
(-x[7],-x[5],-y[7],-y[6],z[7],z[5],), # -1-1-----11-------0-0-----
(x[7],x[5],y[7],y[6],-z[7],-z[5],), # -0-0-----00-------1-1-----
(-x[4],-y[7],-y[6],-y[5],cout,z[4],), # ----1----111-----0---0----
(x[4],y[7],y[6],y[5],-cout,-z[4],), # ----0----000-----1---1----
(-x[7],x[4],-y[7],y[6],y[5],-z[7],-z[4],), # -1--0----100------1--1----
(-x[7],-x[4],y[7],-y[6],-y[5],-z[7],z[4],), # -1--1----011------1--0----
(-cin,x[3],y[3],-y[2],-y[1],z[3],z[0],), # 1----0-------011------0--0
(-cin,-x[3],-y[3],-y[2],-y[1],z[3],z[0],), # 1----1-------111------0--0
(-cin,-x[3],y[3],-y[2],-y[1],-z[3],z[0],), # 1----1-------011------1--0
(cin,x[3],-y[3],y[2],y[1],z[3],-z[0],), # 0----0-------100------0--1
(cin,x[3],y[3],y[2],y[1],-z[3],-z[0],), # 0----0-------000------1--1
(cin,-x[3],-y[3],y[2],y[1],-z[3],-z[0],), # 0----1-------100------1--1
(x[3],x[0],-y[3],y[2],y[1],y[0],z[3],), # -----0--0----1000-----0---
(x[3],-x[0],y[3],-y[2],-y[1],-y[0],z[3],), # -----0--1----0111-----0---
(-x[3],-x[0],-y[3],-y[2],-y[1],-y[0],z[3],), # -----1--1----1111-----0---
(x[3],x[0],y[3],y[2],y[1],y[0],-z[3],), # -----0--0----0000-----1---
(-x[3],x[0],-y[3],y[2],y[1],y[0],-z[3],), # -----1--0----1000-----1---
(-x[3],-x[0],y[3],-y[2],-y[1],-y[0],-z[3],), # -----1--1----0111-----1---
(x[6],-x[3],y[6],-y[5],-y[4],z[6],z[3],), # --0--1----011------0--0---
(-x[6],-x[3],-y[6],-y[5],-y[4],z[6],z[3],), # --1--1----111------0--0---
(-x[6],-x[3],y[6],-y[5],-y[4],-z[6],z[3],), # --1--1----011------1--0---
(x[6],x[3],-y[6],y[5],y[4],z[6],-z[3],), # --0--0----100------0--1---
(x[6],x[3],y[6],y[5],y[4],-z[6],-z[3],), # --0--0----000------1--1---
(-x[6],x[3],-y[6],y[5],y[4],-z[6],-z[3],), # --1--0----100------1--1---
(x[4],-x[1],y[4],-y[3],-y[2],z[4],z[1],), # ----0--1----011------0--0-
(-x[4],-x[1],-y[4],-y[3],-y[2],z[4],z[1],), # ----1--1----111------0--0-
(-x[4],-x[1],y[4],-y[3],-y[2],-z[4],z[1],), # ----1--1----011------1--0-
(x[4],x[1],-y[4],y[3],y[2],z[4],-z[1],), # ----0--0----100------0--1-
(x[4],x[1],y[4],y[3],y[2],-z[4],-z[1],), # ----0--0----000------1--1-
(-x[4],x[1],-y[4],y[3],y[2],-z[4],-z[1],), # ----1--0----100------1--1-
(x[5],-x[2],y[5],-y[4],-y[3],z[5],z[2],), # ---0--1----011------0--0--
(-x[5],-x[2],-y[5],-y[4],-y[3],z[5],z[2],), # ---1--1----111------0--0--
(-x[5],-x[2],y[5],-y[4],-y[3],-z[5],z[2],), # ---1--1----011------1--0--
(x[5],x[2],-y[5],y[4],y[3],z[5],-z[2],), # ---0--0----100------0--1--
(x[5],x[2],y[5],y[4],y[3],-z[5],-z[2],), # ---0--0----000------1--1--
(-x[5],x[2],-y[5],y[4],y[3],-z[5],-z[2],), # ---1--0----100------1--1--
(x[7],x[6],-cout,-z[6],), # -00--------------1-1------
(-x[6],cout,z[7],z[6],), # --1--------------000------
(-x[7],-x[6],-y[7],z[7],z[6],), # -11------1--------00------
(x[7],x[6],y[7],-z[7],-z[6],), # -00------0--------11------
(-x[5],-y[7],-y[6],cout,z[5],), # ---1-----11------0--0-----
(x[5],y[7],y[6],-cout,-z[5],), # ---0-----00------1--1-----
(-x[7],x[5],-y[7],y[6],-z[7],-z[5],), # -1-0-----10-------1-1-----
(-cin,x[2],y[2],-y[1],z[2],z[0],), # 1-----0-------01-------0-0
(-cin,-x[2],-y[2],-y[1],z[2],z[0],), # 1-----1-------11-------0-0
(-cin,-x[2],y[2],-y[1],-z[2],z[0],), # 1-----1-------01-------1-0
(cin,x[2],-y[2],y[1],z[2],-z[0],), # 0-----0-------10-------0-1
(cin,x[2],y[2],y[1],-z[2],-z[0],), # 0-----0-------00-------1-1
(cin,-x[2],-y[2],y[1],-z[2],-z[0],), # 0-----1-------10-------1-1
(x[2],x[0],-y[2],y[1],y[0],z[2],), # ------0-0-----100------0--
(x[2],-x[0],y[2],-y[1],-y[0],z[2],), # ------0-1-----011------0--
(-x[2],-x[0],-y[2],-y[1],-y[0],z[2],), # ------1-1-----111------0--
(x[2],x[0],y[2],y[1],y[0],-z[2],), # ------0-0-----000------1--
(-x[2],x[0],-y[2],y[1],y[0],-z[2],), # ------1-0-----100------1--
(-x[2],-x[0],y[2],-y[1],-y[0],-z[2],), # ------1-1-----011------1--
(-x[7],-x[5],y[7],-y[6],-z[7],z[5],), # -1-1-----01-------1-0-----
(x[6],-x[4],y[6],-y[5],z[6],z[4],), # --0-1-----01-------0-0----
(-x[6],-x[4],-y[6],-y[5],z[6],z[4],), # --1-1-----11-------0-0----
(-x[6],-x[4],y[6],-y[5],-z[6],z[4],), # --1-1-----01-------1-0----
(x[6],x[4],-y[6],y[5],z[6],-z[4],), # --0-0-----10-------0-1----
(x[6],x[4],y[6],y[5],-z[6],-z[4],), # --0-0-----00-------1-1----
(-x[6],x[4],-y[6],y[5],-z[6],-z[4],), # --1-0-----10-------1-1----
(x[3],-x[1],y[3],-y[2],z[3],z[1],), # -----0-1-----01-------0-0-
(-x[3],-x[1],-y[3],-y[2],z[3],z[1],), # -----1-1-----11-------0-0-
(-x[3],-x[1],y[3],-y[2],-z[3],z[1],), # -----1-1-----01-------1-0-
(x[3],x[1],-y[3],y[2],z[3],-z[1],), # -----0-0-----10-------0-1-
(x[3],x[1],y[3],y[2],-z[3],-z[1],), # -----0-0-----00-------1-1-
(-x[3],x[1],-y[3],y[2],-z[3],-z[1],), # -----1-0-----10-------1-1-
(x[5],-x[3],y[5],-y[4],z[5],z[3],), # ---0-1-----01-------0-0---
(-x[5],-x[3],-y[5],-y[4],z[5],z[3],), # ---1-1-----11-------0-0---
(-x[5],-x[3],y[5],-y[4],-z[5],z[3],), # ---1-1-----01-------1-0---
(x[5],x[3],-y[5],y[4],z[5],-z[3],), # ---0-0-----10-------0-1---
(x[5],x[3],y[5],y[4],-z[5],-z[3],), # ---0-0-----00-------1-1---
(-x[5],x[3],-y[5],y[4],-z[5],-z[3],), # ---1-0-----10-------1-1---
(x[4],-x[2],y[4],-y[3],z[4],z[2],), # ----0-1-----01-------0-0--
(-x[4],-x[2],-y[4],-y[3],z[4],z[2],), # ----1-1-----11-------0-0--
(-x[4],-x[2],y[4],-y[3],-z[4],z[2],), # ----1-1-----01-------1-0--
(x[4],x[2],-y[4],y[3],z[4],-z[2],), # ----0-0-----10-------0-1--
(x[4],x[2],y[4],y[3],-z[4],-z[2],), # ----0-0-----00-------1-1--
(-x[4],x[2],-y[4],y[3],-z[4],-z[2],), # ----1-0-----10-------1-1--
(-cin,x[1],y[1],z[1],z[0],), # 1------0-------0--------00
(-cin,-x[1],-y[1],z[1],z[0],), # 1------1-------1--------00
(-cin,-x[1],y[1],-z[1],z[0],), # 1------1-------0--------10
(cin,x[1],-y[1],z[1],-z[0],), # 0------0-------1--------01
(cin,x[1],y[1],-z[1],-z[0],), # 0------0-------0--------11
(cin,-x[1],-y[1],-z[1],-z[0],), # 0------1-------1--------11
(x[1],x[0],-y[1],y[0],z[1],), # -------00------10-------0-
(x[1],-x[0],y[1],-y[0],z[1],), # -------01------01-------0-
(-x[1],-x[0],-y[1],-y[0],z[1],), # -------11------11-------0-
(x[1],x[0],y[1],y[0],-z[1],), # -------00------00-------1-
(-x[1],x[0],-y[1],y[0],-z[1],), # -------10------10-------1-
(-x[1],-x[0],y[1],-y[0],-z[1],), # -------11------01-------1-
(-x[6],-y[7],cout,z[6],), # --1------1-------0-0------
(x[6],y[7],-cout,-z[6],), # --0------0-------1-1------
(x[6],-x[5],y[6],z[6],z[5],), # --01------0--------00-----
(-x[6],-x[5],-y[6],z[6],z[5],), # --11------1--------00-----
(-x[6],-x[5],y[6],-z[6],z[5],), # --11------0--------10-----
(x[6],x[5],-y[6],z[6],-z[5],), # --00------1--------01-----
(x[6],x[5],y[6],-z[6],-z[5],), # --00------0--------11-----
(-x[6],x[5],-y[6],-z[6],-z[5],), # --10------1--------11-----
(-x[7],x[6],-y[7],-z[7],-z[6],), # -10------1--------11------
(-x[7],-x[6],y[7],-z[7],z[6],), # -11------0--------10------
(x[2],-x[1],y[2],z[2],z[1],), # ------01------0--------00-
(-x[2],-x[1],-y[2],z[2],z[1],), # ------11------1--------00-
(-x[2],-x[1],y[2],-z[2],z[1],), # ------11------0--------10-
(x[2],x[1],-y[2],z[2],-z[1],), # ------00------1--------01-
(x[2],x[1],y[2],-z[2],-z[1],), # ------00------0--------11-
(-x[2],x[1],-y[2],-z[2],-z[1],), # ------10------1--------11-
(x[5],-x[4],y[5],z[5],z[4],), # ---01------0--------00----
(-x[5],-x[4],-y[5],z[5],z[4],), # ---11------1--------00----
(-x[5],-x[4],y[5],-z[5],z[4],), # ---11------0--------10----
(x[5],x[4],-y[5],z[5],-z[4],), # ---00------1--------01----
(x[5],x[4],y[5],-z[5],-z[4],), # ---00------0--------11----
(-x[5],x[4],-y[5],-z[5],-z[4],), # ---10------1--------11----
(x[3],-x[2],y[3],z[3],z[2],), # -----01------0--------00--
(-x[3],-x[2],-y[3],z[3],z[2],), # -----11------1--------00--
(-x[3],-x[2],y[3],-z[3],z[2],), # -----11------0--------10--
(x[3],x[2],-y[3],z[3],-z[2],), # -----00------1--------01--
(x[3],x[2],y[3],-z[3],-z[2],), # -----00------0--------11--
(-x[3],x[2],-y[3],-z[3],-z[2],), # -----10------1--------11--
(x[4],-x[3],y[4],z[4],z[3],), # ----01------0--------00---
(-x[4],-x[3],-y[4],z[4],z[3],), # ----11------1--------00---
(-x[4],-x[3],y[4],-z[4],z[3],), # ----11------0--------10---
(x[4],x[3],-y[4],z[4],-z[3],), # ----00------1--------01---
(x[4],x[3],y[4],-z[4],-z[3],), # ----00------0--------11---
(-x[4],x[3],-y[4],-z[4],-z[3],), # ----10------1--------11---
(cin,-x[0],y[0],z[0],), # 0-------1-------0--------0
(cin,x[0],-y[0],z[0],), # 0-------0-------1--------0
(-cin,-x[0],y[0],-z[0],), # 1-------1-------0--------1
(-cin,x[0],-y[0],-z[0],), # 1-------0-------1--------1
(x[7],y[7],-cout,), # -0-------0-------1--------
(-x[7],cout,z[7],), # -1---------------00-------
(x[7],-cout,-z[7],), # -0---------------11-------
(-y[7],cout,z[7],), # ---------1-------00-------
(-cin,-x[0],-y[0],z[0],), # 1-------1-------1--------0
(cin,x[0],y[0],-z[0],), # 0-------0-------0--------1
]
adders = {8: adder_8bit, 4: adder_4bit, 3:adder_3bit, 2:adder_2bit, 1: adder_1bit}
#from mult_7x7 import *
#multipliers = {7: mult_7x7, 6: mult_6x6, 5: mult_5x5, 4: mult_4x4, 3: mult_3x3, 2: mult_2x2}
multipliers = {6: mult_6x6, 5: mult_5x5, 4: mult_4x4, 3: mult_3x3, 2: mult_2x2}
```
#### File: joebebel/toughsat/factoring.py
```python
import math, collections, random, sys, functools, itertools, time
from circuit_ops import *
#TODO: integrate and/or ops into clauses (unneeded?)
#todo: find and chain adders?
def num_var(cnf):
return len(set(abs(literal) for clause in cnf for literal in clause))
def cnf_to_dimacs(cnf, n_a, n_b, target, a,b, includefactors, variables = False):
#print(cnf)
dimacs = "p cnf %d %d \n" % (num_var(cnf), len(cnf))
dimacs += "c Factors encoded in variables 1-%d and %d-%d\n" % (n_a, n_a+1,n_a+n_b)
dimacs += "c Target number: %d\n" % (target)
if includefactors:
dimacs += "c Factors: %d x %d\n" % (a,b)
dimacs += " 0\n".join( (" ".join(map(str, clause)) for clause in cnf) ) + " 0\n"
return dimacs
def circuit_to_cnf(circuit, equals, inverses, n_a, n_b, optimize=True, variables=None):
cnf = []
if not variables:
# defaultdict that increments default variable number every time we use a new variable
variables = collections.defaultdict((lambda k: lambda: next(k))(itertools.count(1)))
#add inputs to veriable list so they're the first
for i in range(n_a):
variables["x_" + str(i)]
for i in range(n_b):
variables["y_" + str(i)]
#simplify equal variables
for x,y in equals:
variables[y] = variables[x]
for x,y in inverses:
variables[y] = -variables[x]
# start with our zero and one constants
cnf, variables['zero'] = [(variables["one"],)], -variables['one']
# #implement circuit operations
for line in circuit:
cnf.extend(line['op'](v=variables, **line))
#eliminate any variables that are known to be constants
def constant_equivs(clause, one_equivs):
for i in one_equivs:
if i in clause: return tuple()
return tuple(L for L in clause if -L not in one_equivs)
input_constants = []
for cleanups in range(10):
one_equivs = tuple(clause[0] for clause in cnf if len(clause) == 1)
input_constants.extend( (i for i in one_equivs if abs(i) <= n_a+n_b) )
if len(one_equivs) == 0: break
cnf = set(constant_equivs(clause, one_equivs) for clause in cnf)
cnf.update(set((i,) for i in input_constants))
return set(clause for clause in cnf if len(clause) > 0), variables
def convert_to_3cnf(cnf):
good_clauses = [c for c in cnf if len(c) <= 3]
bad_clauses = [c for c in cnf if len(c) > 3]
tmp_var = num_var(cnf) + 1
def reduce_clause(clause, tmp_var):
cur_var = tmp_var
if len(clause) <= 3:
return [clause], tmp_var
tmp_clause = list(clause[2:])
tmp_clause.append(cur_var)
tmp_clause2, tmp_var = reduce_clause(tmp_clause, tmp_var+1)
tmp_clause2.append( [clause[0], clause[1], -cur_var])
return tmp_clause2, tmp_var
for c in bad_clauses:
tmp_clause3, tmp_var = reduce_clause(c, tmp_var)
good_clauses.extend(tmp_clause3)
return good_clauses
bits = lambda t: int(math.ceil(math.log(t+1)/math.log(2)))
def generate_instance_known_factors(a,b, includefactors=True):
a, b = max(a,b), min(a,b) # a is the longer
n_a, n_b = bits(a), bits(b)
return generate_instance(a*b, n_a, n_b, a, b, includefactors)
def generate_instance(target, n_a, n_b, a=0, b=0, includefactors=False):
n = bits(target)
n_a, n_b = max(n_a, n_b),min(n_a, n_b)
x = tuple('x_' + str(i) for i in range(n_a)) # x_0 ... x_(n_a-1)
y = tuple('y_' + str(i) for i in range(n_b)) # y_0 ... y_(n_b-1)
circuit = [ {'op':atleastoneof, 'x':x[1:]}, {'op':atleastoneof, 'x':y[1:]} ]
equals, inverses = [],[]
dummy = ('d_' + str(i) for i in itertools.count())
def invert_string(s):
return list(not_v for (v, not_v) in zip(s, (next(dummy) for b in s)) if not inverses.append((v, not_v)))
def addbits(_x,_y, cin='zero', sub=False): #assume x >= y
if len(_x) < len(_y):
if sub: print("ERROR NEGATIVE NUM")
_y,_x=_x,_y
cout = _x[0] if len(_x) > len(_y) else _y[0]
_x, _y, xplusy = list(_x), list(_y)+['zero']*(len(_x)-len(_y)), []
addsub = subtractor if sub else adder
for adder_size in adders:
while len(_x) >= adder_size and len(_y) >= adder_size:
xplusy.extend( tuple(next(dummy) for i in range(adder_size)) )
cout = next(dummy)
circuit.append( {'op':addsub, 'cin':str(cin), 'x':_x[:adder_size], 'y':_y[:adder_size], 'z':xplusy[-adder_size:], 'cout':str(cout)})
cin,_x,_y = cout,_x[adder_size:],_y[adder_size:]
equals.append(('one', cout)) if sub else xplusy.append(cout)
return tuple(xplusy)
def karatsuba(_x,_y): #input two vectors of bits
if len(_x) == 0 or len(_y) == 0: return ('zero',)
(_x,_y) = (_x, _y) if len(_x) >= len(_y) else (_y,_x)
midpoint = -(-len(_x)//2)
smaller_size, larger_size = sorted((len(_x),len(_y)))
if smaller_size == 1:
circuit.append( {'op':and_gates, 'x': _x*len(_y), 'y':_y*len(_x), 'z':map(next,(dummy,)*larger_size)})
return circuit[-1]['z']
if larger_size <= max(multipliers):
z= tuple(next(dummy) for i in range(2*larger_size))
pad_x, pad_y = _x+('zero',)*(larger_size-len(_x)),_y+('zero',)*(larger_size-len(_y))
circuit.append({'op': multiplier, 'x': pad_x, 'y': pad_y, 'z': z})
return z
x0, x1, y0, y1 = _x[0:midpoint], _x[midpoint:], _y[0:midpoint], _y[midpoint:]
z0, z2, x1plusx0, y1plusy0 = karatsuba(x0, y0), karatsuba(x1, y1), addbits(x0, x1), addbits(y0, y1)
x1plusx0timesy1plusy0 = karatsuba(x1plusx0, y1plusy0)
z1plusz0 = addbits(x1plusx0timesy1plusy0, z2, cin='one', sub=True)
z1 = addbits(z1plusz0, z0, cin='one', sub=True)
return z0[0:midpoint] + addbits(z0[midpoint:2*midpoint] + z2, z1)
z = karatsuba(x,y)
target_bits = tuple('one' if i=='1' else 'zero' for i in ('{0:0' + str(n) + 'b}').format(target)[::-1])
equals.extend(zip(target_bits + ('zero',)*(len(z)-len(target_bits)),z))
#print("constructed circuit")
#return {'circuit':circuit, 'equals': equals, 'inverses':inverses, 'n_a':n_a, 'n_b':n_b}
return cnf_to_dimacs(circuit_to_cnf(circuit, equals, inverses, n_a, n_b)[0] , n_a, n_b, target, a, b, includefactors)
def t(a,b,nm):
c = generate_instance_known_factors(a,b)
cnf, var = circuit_to_cnf(**c)
open(str(nm)+'.dimacs', 'w').write(cnf_to_dimacs(cnf, c['n_a'], c['n_b'], var))
def undovariables(dimacs, solution):
import json
variables = json.loads(dimacs.split('c $$$')[1])
n = variables['__numberofbitsinfactors']
x = ""
y = ""
solns = solution.split('\n')[1].split(' ')
for i in range(n):
if int(solns[variables['x' + str(i)]-1]) > 0:
x = '1' + x
else:
x = '0' + x
if int(solns[variables['y' + str(i)]-1]) > 0:
y = '1' + y
else:
y = '0' + y
print("x = " + str(int(x,2)))
print("y = " + str(int(y,2)))
primes = { 16 : [37423, 59167, 48907, 54499, 34231, 48523, 44959, 62383, 44537,
62801, 56941, 59539, 47149, 62743, 49037, 55691, 52103, 56951, 40253,
55837, 60103, 49121, 57667, 63367, 36269, 48533, 33461, 41999, 44131,
61879],
17: [121367, 89977, 104009, 113963, 70237, 112603, 103723, 122167, 86297,
83137, 120737, 124147, 123581, 105817, 76103, 121883, 106531, 112859,
93761, 102829, 88259, 87539, 95549, 99829, 67369, 66179, 86423,
96181, 112397, 72823],
18: [240073, 216157, 164071, 163063, 201683, 206501, 259723, 175621,
184007, 219727, 131759, 229499, 151279, 247993, 247463, 163351,
158761, 176213, 217499, 231019, 193301, 241667, 213539, 189479,
247393, 160049, 187843, 161461, 146539, 192133],
19: [332951, 515153, 501133, 514741, 423427, 316861, 380117, 279689,
292079, 370663, 392087, 426161, 417097, 446921, 471949, 429467,
508451, 361687, 484027, 405343, 281069, 514277, 467021, 396293,
304807, 389999, 282563, 474647, 341879, 355087],
20:[581411, 666901, 949129, 875983, 1022129, 688951, 533573, 865211,
770167, 1010549, 569671, 914723, 847193, 760373, 1013399, 531143,
605323, 655331, 881099, 1046081, 936361, 681049, 636749, 681949,
619027, 992513, 991057, 652903, 559549, 620603],
21: [1848641, 1953811, 1815733, 1388011, 1417183, 1978199, 1434023,
1128629, 1097483, 1338367, 1865893, 2025187, 1057367, 1237433,
1113199, 1313041, 1393927, 1967419, 1567901, 2067211, 1588661,
1951793, 1219919, 2074031, 1759159, 1147417, 1873093, 1813817,
1843997, 1249243],
22:[2986397, 2721197, 2697697, 2744933, 3209681, 2934143, 2407943,
2279419, 2968223, 2300021, 3964589, 3252409, 3280187, 2781377,
3210017, 2540339, 2201543, 3690329, 2601337, 3880421, 3450121,
2308589, 2643133, 3133171, 2240159, 3355699, 3360197, 3823559,
3859019, 3182479],
23:[8381123, 6760003, 7264009, 6142261, 5730073, 8004047, 5478677,
7573519, 8105221, 8143271, 7703741, 4908107, 7400293, 6830869,
5806961, 6273053, 5092861, 6541831, 6027247, 4675249, 5294587,
6214223, 5329229, 7698703, 7952909, 6986219, 4922681, 6088763,
6325031, 6486791],
24: [8475119, 9735949, 11919983, 16759969, 16085261, 9600319, 11406401,
12738307, 13025561, 9151573, 11588561, 14732299, 13674113, 13628039,
13420229, 12528793, 11695297, 11119021, 14590091, 11417477, 12987497,
10273787, 11059271, 13254821, 9909791, 9255991, 9920021, 11932153,
13335349, 8389001],
25: [20148367, 17223923, 21937841, 18842869, 29602789, 28371269, 30312157,
26098027, 18715727, 28008797, 18396347, 29792327, 30940411, 31788971,
31376879, 22125023, 23925179, 27990247, 16925917, 23687777, 21231407,
30647147, 29172401, 25249867, 26738077, 27389641, 28014013, 16847893,
18558797, 24051067],
26: [63565213, 62604193, 48382603, 62933953, 51809077, 64852063, 64662337,
53881363, 60617593, 55437163, 50132947, 61865047, 50933711, 41659927,
52975397, 44929217, 51105023, 50735827, 66312893, 64471201, 44249687,
43595371, 56933857, 45752717, 59466611, 38168671, 56192399, 53748001,
40364689, 38103509],
27:[112480981, 91908007, 123176831, 128189381, 131734177, 117071819,
91636327, 103446689, 81981343, 70843057, 127639483, 90571097,
127346647, 112658291, 106392287, 96907309, 132096551, 80467771,
72280939, 107715271, 112768129, 120226783, 104635961, 117347227,
124050211, 71984191, 86668597, 68874283, 83833637, 98594039],
28:[266527097, 239217977, 258529763, 182592757, 242662093, 134715079,
176160601, 247051139, 242139659, 210624103, 248873791, 215287687,
200808269, 153112451, 248589973, 190121287, 176670071, 192618193,
172962949, 166009871, 159323939, 236079931, 173200771, 242682943,
244860589, 252829553, 217950203, 162146449, 138098041, 245202677],
29:[445611937, 404744867, 489132331, 388883309, 535756099, 305146739,
504601921, 353449661, 381145451, 457740313, 427705963, 445403477,
282394271, 324445699, 388591589, 491535053, 351507389, 375748073,
312441517, 406498321, 514507619, 342047813, 368706773, 454001747,
360623573, 415095097, 269444171, 339985231, 461853949, 457639859],
30:[570381719, 1029149119, 762263443, 761364511, 900644531, 665902603,
742600757, 977965609, 1054312921, 896469293, 1001675371, 1068045967,
669501533, 1022632757, 1055926381, 894399491, 785917129, 934443163,
980081639, 1066293187, 981066553, 824430049, 713499187, 829943011,
826787627, 903790577, 953283491, 720905047, 988189607, 614524403],
31:[1099864511, 1856571671, 1579366871, 1734843631, 2048762893,
1185234023, 1908915317, 1248552857, 1473372959, 1725167707,
1596040063, 2016084209, 1173572207, 1608645361, 1519634617,
1939847839, 1593501521, 1136824237, 1883033357, 1200205211,
1857889687, 1364162771, 1206941023, 1899910139, 1641146513,
2006223629, 1970456287, 1934505401, 1608090079, 1076775407],
32:(2316644917, 4173991301, 3503565953, 2658438689, 2244625459,
3241345823, 2811374053, 2199635257, 2553909179, 3007351843,
3236271187, 3936839003, 2476529479, 3862827361, 2575414991,
4202873849, 3679876063, 3135672637, 3619587007, 2414296271,
2826875627, 3974822087, 4120038761, 2648270887, 2621519437,
3247434259, 2288597141, 3686287247, 2906348671, 2634343799),
64:(10086124837380661049, 18311984027837140229, 13147305481532659531, \
12460583606501790241, 12303475786185894377, 12801478627450700269, \
15862226639395282849, 9548662038335876783, 15214273286930516683, \
12862743339916456229, 13844811189923386181, 15333876750005584241, \
10814462913795860149, 10026898481225127647, 12214723832217529979, \
10410870213229651049, 11296652295987291151, 10456684402009108687, \
13367411165667845773, 16047111683829323887, 16297044460459749743, \
12416930095903594589, 14866113315256690489, 15255620538830977933, \
17523311071498959079, 10109194564259170903, 9482918037137737001, \
14701277006332016851, 11141258962047518699, 15544657161291927089),
256:(66472471648529495886964553550517070180699507238687807583096518162159299199373,
59021768262109476587361698420173898869557952423161767465608254828850881775213),
128:(306109526669749265476345451342494701457,
235730238689668179669179458194650948543)
}
def soln_to_factors(s):
s = s.replace('\nv', '').split(' ')
s.reverse()
s = (1 if int(i) > 0 else 0 if int(i) < 0 else -1 for i in (j for j in s if j != ''))
return int("".join(str(i) for i in s),2)
``` |
{
"source": "joebentley/simba",
"score": 3
} |
#### File: simba/simba/config.py
```python
import enum
from contextlib import contextmanager
class Param(enum.Enum):
"""Enum representing a parameter. Param.ON is truthy, everything else is falsey."""
ON = 0 # force on
OFF = 1 # force off
AUTO = 2 # set using init_params
def __bool__(self):
return self == Param.ON
params = {
# run slow but important checks to verify results
'checks': Param.ON,
# use wolframscript for more intensive symbolic manipulations
'wolframscript': Param.OFF
}
def is_wolframscript_installed():
"""Check whether wolframscript is installed and in PATH."""
from shutil import which
return which("wolframscript") is not None
def init_params():
"""Check what to set params to if they are set to "auto"."""
if params['wolframscript'] == Param.AUTO and is_wolframscript_installed():
params['wolframscript'] = Param.ON
if params['wolframscript'] == Param.ON and params['checks'] == Param.AUTO:
params['checks'] = Param.ON
@contextmanager
def temp_set_param(param, to):
"""
Use via ``with`` to temporarily set param to given value, changing it back afterwards.
E.g.
.. code-block:: python
with temp_set_param('wolframscript', Param.ON):
# do stuff using wolframscript
# wolframscript now disabled
"""
previous = params[param]
params[param] = to
yield
params[param] = previous
@contextmanager
def temp_set_params(params_to_merge):
"""
Same as `temp_set_param` but params_to_merge is a dictionary of params to `Param` values to update
"""
from copy import deepcopy
previous = deepcopy(params)
params.update(params_to_merge)
yield
params.update(previous)
``` |
{
"source": "Joe-Bentley/team_totem",
"score": 2
} |
#### File: team_totem/artifacts/models.py
```python
import datetime
from django.db import models
from django.utils import timezone
class Location(models.Model):
image = models.ImageField(upload_to = 'artifacts/uploads', default = 'artifacts/uploads/qmark.png')
text = models.CharField(max_length=200)
def __str__(self):
return self.text
class Artifact(models.Model):
location = models.ForeignKey(Location, on_delete=models.CASCADE, default = 1)
text = models.CharField(max_length=200)
info = models.TextField(blank = True)
discovered_by = models.CharField(max_length=200, default="unknown")
pub_date = models.DateField('Date Published', default=datetime.date.today)
image = models.ImageField(upload_to = 'artifacts/uploads', default = 'artifacts/uploads/qmark.png')
def __str__(self):
return f'{self.text} : {self.info[:25]}...'
```
#### File: team_totem/artifacts/views.py
```python
from django.shortcuts import render
from django.http import HttpResponse
from .models import Artifact, Location
def artifacts(request):
artifacts = Artifact.objects.all()
return render(request, "artifacts/artifacts.html", {"artifacts": artifacts})
def artifact_info(request, artifact_id):
return render(request, "artifacts/singleartifact.html", {"artifact": Artifact.objects.get(pk=artifact_id), "host_prefix": request.get_host()})
def locations(request):
locations = Location.objects.all()
return render(request, "artifacts/locations.html", {"locations": locations, "host_prefix": request.get_host()})
def location_info(request, location_id):
shared_location = Location.objects.get(pk=location_id)
all_artifacts = Artifact.objects.filter(location = shared_location)
return render (
request,
"artifacts/singlelocation.html",
{"artifacts": all_artifacts, "location": shared_location, "host_prefix": request.get_host()}
)
def discovered_year(request, year):
artifacts = Artifact.objects.filter(pub_date__year=year)
return render(
request,
"artifacts/discovered.html",
{"artifacts": artifacts, "date": year}
)
def about(request):
return render (request, "artifacts/about.html")
def discovered_year_month(request, year, month):
return HttpResponse("Year/Month Discovered")
def discovered_year_month_day(request, year, month, day):
return HttpResponse("Year/Month/Day Discovered")
``` |
{
"source": "joebentley/world-builder",
"score": 2
} |
#### File: world-builder/worldbuilder/player.py
```python
class Player:
def __init__(self):
self.current_room = 0
self.inventory = []
``` |
{
"source": "joebhakim/mimic_understander",
"score": 2
} |
#### File: src/features/build_features.py
```python
import click
import logging
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
import pandas as pd
from features_utils.data_cleaning import (
clean_static_df, clean_dynamic_df, clean_treat_df, clean_outcome_df,
get_CXYT_for_modeling
)
from features_utils.data_preprocessing import (
preprocess_CYXT, impute_dynamic_data, save_data_matrix
)
@click.command()
@click.argument('input_filepath', type=click.Path(exists=True))
@click.argument('output_filepath', type=click.Path())
def main(input_filepath, output_filepath):
print('cleaning dfs')
dynamic_df = pd.read_csv(input_filepath + 'dynamic_vars.csv')
# to skip annoying index line
static_df = pd.read_csv(
input_filepath + 'static_vars.csv').drop('Unnamed: 0', axis=1)
treat_df = pd.read_csv(input_filepath + 'treatment_vars.csv')
static_df_clean = clean_static_df(static_df)
dynamic_df_clean = clean_dynamic_df(dynamic_df, static_df)
treat_df_clean = clean_treat_df(treat_df, static_df)
outcome_df_clean = clean_outcome_df(static_df)
static_df_clean.to_csv(output_filepath + '/static_vars.csv')
dynamic_df_clean.to_csv(output_filepath + '/dynamic_vars.csv')
treat_df_clean.to_csv(output_filepath + '/treat_vars.csv')
outcome_df_clean.to_csv(output_filepath + '/outcome_vars.csv')
print('getting CYXT tensor for downstream modeling...')
CXYT_df = get_CXYT_for_modeling(static_df_clean,
dynamic_df_clean,
treat_df_clean,
outcome_df_clean,
output_filepath)
CXYT_df = preprocess_CYXT(CXYT_df)
save_data_matrix(CXYT_df, output_filepath)
if __name__ == '__main__':
log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(level=logging.INFO, format=log_fmt)
# not used in this stub but often useful for finding various files
project_dir = Path(__file__).resolve().parents[2]
# find .env automagically by walking up directories until it's found, then
# load up the .env entries as environment variables
load_dotenv(find_dotenv())
main()
``` |
{
"source": "Joe-Biden/Kerberos",
"score": 2
} |
#### File: scalable/scripts/script_gui.py
```python
try:
import gconf
except:
print "You do not have the gconf module installed, however it is optional."
try:
import gtk
import gtk.glade
import sys, os
import subprocess
import ConfigParser
import shutil
import gettext
import locale
except:
print "Some dependencies are missing!"
print "The following ones are required:"
print "gtk, gtk.glade, sys, os, subprocess,"
print "shutil, gettext, ConfigParser"
sys.exit(1)
#for arg in sys.argv:
# print arg
class ACYLGUI:
def __init__(self):
APP = 'acyl'
DIR = 'locale'
locale.setlocale(locale.LC_ALL, '')
for module in (gettext, gtk.glade):
module.bindtextdomain(APP, DIR)
module.textdomain(APP)
_ = gettext.gettext
self.widgetTree = gtk.glade.XML("gui.glade", None, APP)
self.loadState("./current_state/gui_config.ini")
self.widgetTree.get_widget("combobox1").set_active(0)
self.CurrentSettings = str()
self.colorset = str()
self.gradset = str()
self.filtset = str()
self.codeset = str()
if self.NbrColors == 1:
self.widgetTree.get_widget("button6").set_sensitive(False)
if self.NbrColors == 100:
self.widgetTree.get_widget("button5").set_sensitive(False)
self.FilterChange(self)
if self.widgetTree.get_widget("combobox2").get_active() >= 1:
self.widgetTree.get_widget("frame11").hide()
self.widgetTree.get_widget("frame12").hide()
self.widgetTree.get_widget("frame35").hide()
self.widgetTree.get_widget("frame8").show()
self.widgetTree.get_widget("frame9").show()
self.widgetTree.get_widget("frame10").show()
else:
self.widgetTree.get_widget("frame8").hide()
self.widgetTree.get_widget("frame9").hide()
self.widgetTree.get_widget("frame10").hide()
self.widgetTree.get_widget("frame11").show()
self.widgetTree.get_widget("frame12").show()
self.widgetTree.get_widget("frame35").show()
dic = { \
"on_close" : self.quit, \
"on_notebook1_switch_page" : self.pageChange, \
"on_combobox2_changed" : self.GradientChange, \
"on_combobox3_changed" : self.FilterChange, \
"on_folder_changed" : self.FolderChange, \
"on_nav_changed" : self.navigationChange, \
"on_logo_changed" : self.LogoChange, \
"on_preset_change" : self.changePreset, \
"on_custom_change" : self.CustomChange, \
"on_import_from_graphic" : self.importGraphic, \
"on_refresh" : self.RefreshPreview, \
"on_apply_clicked" : self.ApplySettings, \
"on_apply_icon_switch" : self.switchIcons, \
"on_root_copy" : self.copyToRoot, \
"on_make_exec" : self.makeExec, \
"on_app_copy" : self.appCopy, \
"on_about" : self.showAbout, \
"on_import_settings" : self.importSettings, \
"on_export_settings" : self.exportSettings, \
"on_restore_settings" : self.restoreSettings, \
"on_button5_clicked" : self.AddColor, \
"on_button6_clicked" : self.RemoveColor \
}
self.widgetTree.signal_autoconnect(dic)
def pageChange(self, widget, page, pagenum):
if pagenum == 0:
self.widgetTree.get_widget("button1").set_sensitive(True)
self.widgetTree.get_widget("button3").set_sensitive(True)
self.widgetTree.get_widget("combobox1").set_sensitive(True)
if pagenum == 1:
self.widgetTree.get_widget("button1").set_sensitive(True)
self.widgetTree.get_widget("button3").set_sensitive(True)
self.widgetTree.get_widget("combobox1").set_sensitive(True)
if pagenum == 2:
self.widgetTree.get_widget("button1").set_sensitive(False)
self.widgetTree.get_widget("button3").set_sensitive(True)
self.widgetTree.get_widget("combobox1").set_sensitive(False)
if pagenum == 3:
self.widgetTree.get_widget("button1").set_sensitive(False)
self.widgetTree.get_widget("button3").set_sensitive(False)
self.widgetTree.get_widget("combobox1").set_sensitive(False)
def AddColor(self, widget):
self.NbrColors = self.NbrColors + 1
self.widgetTree.get_widget("colorbox" + str(self.NbrColors)).show()
self.widgetTree.get_widget("button6").set_sensitive(True)
if self.widgetTree.get_widget("checkbuttonOffset").get_active():
if self.NbrColors > 1:
step = (1.0 / (self.NbrColors-1))
for i in range(0, self.NbrColors):
self.widgetTree.get_widget("offsetbutton" + str(i+1)).set_value(step * i)
else:
self.widgetTree.get_widget("offsetbutton1").set_value(0);
if self.NbrColors == 100:
self.widgetTree.get_widget("button5").set_sensitive(False)
self.RefreshPreview(self)
def RemoveColor(self, widget):
self.widgetTree.get_widget("colorbox" + str(self.NbrColors)).hide()
self.NbrColors = self.NbrColors - 1
self.widgetTree.get_widget("button5").set_sensitive(True)
if self.widgetTree.get_widget("checkbuttonOffset").get_active():
if self.NbrColors > 1:
step = (1.0 / (self.NbrColors-1))
for i in range(0, self.NbrColors):
self.widgetTree.get_widget("offsetbutton" + str(i+1)).set_value(step * i)
else:
self.widgetTree.get_widget("offsetbutton1").set_value(0);
if self.NbrColors == 1:
self.widgetTree.get_widget("button6").set_sensitive(False)
self.RefreshPreview(self)
def ApplySettings(self, widget):
self.RefreshPreview(self)
page = self.widgetTree.get_widget("notebook1").get_current_page()
if page <= 1:
target = self.widgetTree.get_widget("combobox1").get_active()
if target == 0:
process = subprocess.Popen("source ./script_functions && apply_all " + self.CurrentSettings, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
self.setTheme(self)
self.RefreshPreview(self)
elif target == 1:
self.showApplyCutom(self)
elif page == 2:
self.switchIcons(self)
def setTheme(self, widget):
try:
client = gconf.client_get_default ()
client.unset ("/desktop/gnome/interface/icon_theme")
client.set_string ("/desktop/gnome/interface/icon_theme","")
client.set_string ("/desktop/gnome/interface/icon_theme", "ACYL_Icon_Theme_0.9.4")
except:
print "The python gconf module is requierd to automatically set the icon-theme to this system."
try:
process = subprocess.Popen("killall gnome-panel", shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
except:
print "Gnome-panel restart failed."
def GradientChange(self, widget):
if self.widgetTree.get_widget("combobox2").get_active() >= 1:
self.widgetTree.get_widget("frame11").hide()
self.widgetTree.get_widget("frame12").hide()
self.widgetTree.get_widget("frame8").show()
self.widgetTree.get_widget("frame9").show()
self.widgetTree.get_widget("frame10").show()
self.widgetTree.get_widget("frame35").hide()
else:
self.widgetTree.get_widget("frame35").show()
self.widgetTree.get_widget("frame8").hide()
self.widgetTree.get_widget("frame9").hide()
self.widgetTree.get_widget("frame10").hide()
self.widgetTree.get_widget("frame11").show()
self.widgetTree.get_widget("frame12").show()
def FilterChange(self, widget):
if self.widgetTree.get_widget("combobox3").get_active() == 3:
self.widgetTree.get_widget("filterbutton1").show()
self.widgetTree.get_widget("filterbutton2").hide()
self.widgetTree.get_widget("filterbutton3").hide()
elif self.widgetTree.get_widget("combobox3").get_active() == 7:
self.widgetTree.get_widget("filterbutton1").show()
self.widgetTree.get_widget("filterbutton2").hide()
self.widgetTree.get_widget("filterbutton3").hide()
elif self.widgetTree.get_widget("combobox3").get_active() == 10:
self.widgetTree.get_widget("filterbutton1").show()
self.widgetTree.get_widget("filterbutton2").hide()
self.widgetTree.get_widget("filterbutton3").hide()
else:
self.widgetTree.get_widget("filterbutton1").hide()
self.widgetTree.get_widget("filterbutton2").hide()
self.widgetTree.get_widget("filterbutton3").hide()
def RefreshPreview(self, widget):
page = self.widgetTree.get_widget("notebook1").get_current_page()
if page == 0:
self.makeSettingsGraphic(self)
elif page == 1:
self.makeSettingsCode(self)
if page <= 1:
process = subprocess.Popen("source ./script_functions && apply_preview " + self.CurrentSettings, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
self.saveState("./current_state/gui_config.ini")
self.widgetTree.get_widget("image1").set_from_file("./preview_icons/apps.svg")
self.widgetTree.get_widget("image2").set_from_file("./preview_icons/actions.svg")
self.widgetTree.get_widget("image3").set_from_file("./preview_icons/emblems.svg")
def importGraphic(self, widget):
self.makeSettingsGraphic(self)
self.widgetTree.get_widget("textview1").get_buffer().set_text(self.colorset + self.gradset + self.filtset)
def makeSettingsCode(self, widget):
start = self.widgetTree.get_widget("textview1").get_buffer().get_start_iter()
end = self.widgetTree.get_widget("textview1").get_buffer().get_end_iter()
self.codeset = self.widgetTree.get_widget("textview1").get_buffer().get_text(start, end, True)
self.CurrentSettings ='''\''''+ str(self.codeset) + '''\''''
def makeSettingsGraphic(self, widget):
colorset = '''<linearGradient
id=\"linearGradient4321\">'''
for i in range(1, self.NbrColors + 1):
color = "#" + self.getColor("colorbutton" + str(i))
alpha = self.widgetTree.get_widget("colorbutton" + str(i)).get_alpha()/65535.0
offset = self.widgetTree.get_widget("offsetbutton" + str(i)).get_value()
#print "Color: " + color + " Alpha: " + str(alpha) + " Offset: " + str(offset)
colorset = colorset + '''\n <stop
style=\"stop-color:''' + color + ''';stop-opacity:''' + str(alpha) + ''';\"
offset=\"''' + str(offset) + '''\"
id=\"stop''' + str(i) + '''\" />'''
self.colorset = colorset + '''\n </linearGradient>'''
if self.widgetTree.get_widget("combobox2").get_active() == 1:
r = self.widgetTree.get_widget("spinbutton-radius").get_value()
cx = self.widgetTree.get_widget("spinbutton-center-x").get_value()
cy = self.widgetTree.get_widget("spinbutton-center-y").get_value()
fx = self.widgetTree.get_widget("spinbutton-focus-x").get_value()
fy = self.widgetTree.get_widget("spinbutton-focus-y").get_value()
self.gradset = '''<radialGradient
inkscape:collect=\"always\"
xlink:href=\"#linearGradient4321\"
id=\"acyl_gradient\"
cx=\"''' + str(cx) + '''%\"
cy=\"''' + str(cy) + '''%\"
fx=\\"''' + str(fx) + '''%\"
fy="''' + str(fy) + '''%\"
r=\"''' + str(r) + '''%\"
/>'''
else:
sx = self.widgetTree.get_widget("spinbutton-start-x").get_value()
sy = self.widgetTree.get_widget("spinbutton-start-y").get_value()
ex = self.widgetTree.get_widget("spinbutton-end-x").get_value()
ey = self.widgetTree.get_widget("spinbutton-end-y").get_value()
self.gradset = '''<linearGradient
inkscape:collect=\"always\"
xlink:href=\"#linearGradient4321\"
id=\"acyl_gradient\"
x1=\"''' + str(sx) + '''%\"
y1=\"''' + str(sy) + '''%\"
x2=\"''' + str(ex) + '''%\"
y2=\"''' + str(ey) + '''%\" />'''
if self.widgetTree.get_widget("combobox3").get_active()==0:filtset = 'disabled'
if self.widgetTree.get_widget("combobox3").get_active()==1:filtset = 'wood'
if self.widgetTree.get_widget("combobox3").get_active()==2:filtset = 'glass'
if self.widgetTree.get_widget("combobox3").get_active()==3:
alpha = self.widgetTree.get_widget("filterbutton1").get_alpha()/65535.0
color = self.getColor("filterbutton1")
filtset = 'paper \#' + str(color) + ' ' + str(alpha)
if self.widgetTree.get_widget("combobox3").get_active()==4:filtset = 'cutout'
if self.widgetTree.get_widget("combobox3").get_active()==5:filtset = 'brushed_metal'
if self.widgetTree.get_widget("combobox3").get_active()==6:filtset = 'flame'
if self.widgetTree.get_widget("combobox3").get_active()==7:
alpha = self.widgetTree.get_widget("filterbutton1").get_alpha()/65535.0
color = self.getColor("filterbutton1")
filtset = 'quadratic \#' + str(color) + ' ' + str(alpha)
if self.widgetTree.get_widget("combobox3").get_active()==8:filtset = 'bevel'
if self.widgetTree.get_widget("combobox3").get_active()==9:filtset = 'outline'
if self.widgetTree.get_widget("combobox3").get_active()==10:
alpha = self.widgetTree.get_widget("filterbutton1").get_alpha()/65535.0
color = self.getColor("filterbutton1")
filtset = 'orb \#' + str(color) + ' ' + str(alpha)
if self.widgetTree.get_widget("combobox3").get_active()==11:filtset = 'grungy'
if self.widgetTree.get_widget("combobox3").get_active()==12:filtset = 'splatter'
temp1 = subprocess.Popen('''source ./script_functions && get_filter var ''' + str(filtset) +''' && eval "echo -e '$var'"''', shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
temp2 = str(temp1.communicate()[0])
self.filtset = temp2[:-1]
self.CurrentSettings ='''\''''+ str(self.colorset) + '''\' \'''' + str(self.gradset) + '''\' \'''' + str(self.filtset) + '''\''''
def getColor(self, button):
color = self.widgetTree.get_widget(button).get_color()
red = color.red*255/65535
green = color.green*255/65535
blue = color.blue*255/65535
red = ("%X" % red).zfill(2)
green = ("%X" % green).zfill(2)
blue = ("%X" % blue).zfill(2)
color = red + green + blue
return str(color)
def getAlpha(self, button):
alpha = self.widgetTree.get_widget(button).get_alpha()/65535.0
return str(alpha)
def loadState(self, setfile):
cp = ConfigParser.ConfigParser()
cp.read(setfile)
self.NbrColors = int(cp.get("state-graphicview", "nbrcol"))
if self.NbrColors <= 100:
self.widgetTree.get_widget("button6").set_sensitive(True)
if self.NbrColors >= 1:
self.widgetTree.get_widget("button5").set_sensitive(True)
if self.NbrColors == 100:
self.widgetTree.get_widget("button5").set_sensitive(False)
if self.NbrColors == 1:
self.widgetTree.get_widget("button6").set_sensitive(False)
colorlist = cp.get("state-graphicview", "colors").split("', '")
alphalist = cp.get("state-graphicview", "alphas").split("', '")
offsetlist = cp.get("state-graphicview", "offsets").split(", ")
if self.NbrColors != 1:
colorlist[0] = str(colorlist[0])[-6:]
colorlist[-1] = str(colorlist[-1])[:-2]
alphalist[0] = str(alphalist[0])[2:]
alphalist[-1] = str(alphalist[-1])[:-2]
offsetlist[0] = str(offsetlist[0])[1:]
offsetlist[-1] = str(offsetlist[-1])[:-1]
else:
colorlist[0] = str(colorlist[0])[2:-2]
alphalist[0] = str(alphalist[0])[2:-2]
offsetlist[0] = str(offsetlist[0])[1:-1]
for i in range(1, self.NbrColors + 1):
color = colorlist[i - 1]
alpha = int(float(alphalist[i - 1])*65535)
offset = float(offsetlist[i - 1])
self.widgetTree.get_widget("colorbutton" + str(i)).set_color(gtk.gdk.Color('#' + color))
self.widgetTree.get_widget("colorbutton" + str(i)).set_alpha(alpha)
self.widgetTree.get_widget("offsetbutton" + str(i)).set_value(offset)
self.widgetTree.get_widget("colorbox" + str(i)).show()
for i in range(self.NbrColors + 1, 101):
self.widgetTree.get_widget("colorbutton" + str(i)).set_color(gtk.gdk.Color('#000000'))
self.widgetTree.get_widget("colorbutton" + str(i)).set_alpha(int(65535))
self.widgetTree.get_widget("offsetbutton" + str(i)).set_value(int(1.0))
self.widgetTree.get_widget("colorbox" + str(i)).hide()
self.widgetTree.get_widget("spinbutton-radius").set_value(float(cp.get("state-graphicview", "radius")))
self.widgetTree.get_widget("spinbutton-center-x").set_value(float(cp.get("state-graphicview", "center-x")))
self.widgetTree.get_widget("spinbutton-center-y").set_value(float(cp.get("state-graphicview", "center-y")))
self.widgetTree.get_widget("spinbutton-focus-x").set_value(float(cp.get("state-graphicview", "focus-x")))
self.widgetTree.get_widget("spinbutton-focus-y").set_value(float(cp.get("state-graphicview", "focus-y")))
self.widgetTree.get_widget("spinbutton-start-x").set_value(float(cp.get("state-graphicview", "start-x")))
self.widgetTree.get_widget("spinbutton-start-y").set_value(float(cp.get("state-graphicview", "start-y")))
self.widgetTree.get_widget("spinbutton-end-x").set_value(float(cp.get("state-graphicview", "end-x")))
self.widgetTree.get_widget("spinbutton-end-y").set_value(float(cp.get("state-graphicview", "end-y")))
self.widgetTree.get_widget("combobox2").set_active(int(cp.get("state-graphicview", "gradtype")))
self.widgetTree.get_widget("combobox3").set_active(int(cp.get("state-graphicview", "filter")))
color = cp.get("state-graphicview", "filtercolor1")
alpha = int(float(cp.get("state-graphicview", "filteralpha1"))*65535)
self.widgetTree.get_widget("filterbutton1").set_color(gtk.gdk.Color('#' + color))
self.widgetTree.get_widget("filterbutton1").set_alpha(alpha)
color = cp.get("state-graphicview", "filtercolor2")
alpha = int(float(cp.get("state-graphicview", "filteralpha2"))*65535)
self.widgetTree.get_widget("filterbutton2").set_color(gtk.gdk.Color('#' + color))
self.widgetTree.get_widget("filterbutton2").set_alpha(alpha)
color = cp.get("state-graphicview", "filtercolor3")
alpha = int(float(cp.get("state-graphicview", "filteralpha3"))*65535)
self.widgetTree.get_widget("filterbutton3").set_color(gtk.gdk.Color('#' + color))
self.widgetTree.get_widget("filterbutton3").set_alpha(alpha)
self.widgetTree.get_widget("textview1").get_buffer().set_text(cp.get("state-codeview", "settings"))
self.widgetTree.get_widget("combobox6").set_active(int(cp.get("state-switchicons", "logo")))
self.widgetTree.get_widget("combobox5").set_active(int(cp.get("state-switchicons", "navigation")))
self.widgetTree.get_widget("combobox4").set_active(int(cp.get("state-switchicons", "folder")))
def saveState(self, setfile):
cp = ConfigParser.ConfigParser()
cp.read(setfile)
colorlist = []
alphalist = []
offsetlist = []
for i in range(1, self.NbrColors + 1):
colorlist.append(self.getColor("colorbutton" + str(i)))
alphalist.append(self.getAlpha("colorbutton" + str(i)))
offsetlist.append(self.widgetTree.get_widget("offsetbutton" + str(i)).get_value())
cp.set("state-graphicview", "colors", colorlist)
cp.set("state-graphicview", "alphas", alphalist)
cp.set("state-graphicview", "offsets", offsetlist)
cp.set("state-graphicview", "nbrcol", self.NbrColors)
cp.set("state-graphicview", "filtercolor1", self.getColor("filterbutton1"))
cp.set("state-graphicview", "filtercolor2", self.getColor("filterbutton2"))
cp.set("state-graphicview", "filtercolor3", self.getColor("filterbutton3"))
cp.set("state-graphicview", "filteralpha1", self.getAlpha("filterbutton1"))
cp.set("state-graphicview", "filteralpha2", self.getAlpha("filterbutton2"))
cp.set("state-graphicview", "filteralpha3", self.getAlpha("filterbutton3"))
cp.set("state-graphicview", "radius", self.widgetTree.get_widget("spinbutton-radius").get_value())
cp.set("state-graphicview", "center-x", self.widgetTree.get_widget("spinbutton-center-x").get_value())
cp.set("state-graphicview", "center-y", self.widgetTree.get_widget("spinbutton-center-y").get_value())
cp.set("state-graphicview", "focus-x", self.widgetTree.get_widget("spinbutton-focus-x").get_value())
cp.set("state-graphicview", "focus-y", self.widgetTree.get_widget("spinbutton-focus-y").get_value())
cp.set("state-graphicview", "start-x", self.widgetTree.get_widget("spinbutton-start-x").get_value())
cp.set("state-graphicview", "start-y", self.widgetTree.get_widget("spinbutton-start-y").get_value())
cp.set("state-graphicview", "end-x", self.widgetTree.get_widget("spinbutton-end-x").get_value())
cp.set("state-graphicview", "end-y", self.widgetTree.get_widget("spinbutton-end-y").get_value())
cp.set("state-graphicview", "gradtype", self.widgetTree.get_widget("combobox2").get_active())
cp.set("state-graphicview", "filter", self.widgetTree.get_widget("combobox3").get_active())
start = self.widgetTree.get_widget("textview1").get_buffer().get_start_iter()
end = self.widgetTree.get_widget("textview1").get_buffer().get_end_iter()
cp.set("state-codeview", "settings", self.widgetTree.get_widget("textview1").get_buffer().get_text(start, end, True))
cp.set("state-switchicons", "folder", self.widgetTree.get_widget("combobox4").get_active())
cp.set("state-switchicons", "navigation", self.widgetTree.get_widget("combobox5").get_active())
cp.set("state-switchicons", "logo", self.widgetTree.get_widget("combobox6").get_active())
cp.write(open(setfile, "w"))
def FolderChange(self, widget):
temp = self.widgetTree.get_widget("combobox4").get_active()
self.folder = "acyl_" + str(int(temp) + 1)
self.widgetTree.get_widget("image4").set_from_file("../alternative_icons/folders/"+ self.folder +"/places/folder.svg")
def LogoChange(self, widget):
temp = self.widgetTree.get_widget("combobox6").get_active()
if temp == 0:
self.logo = "arch"
self.widgetTree.get_widget("filechooserbutton1").hide()
elif temp == 1:
self.logo = "debian"
self.widgetTree.get_widget("filechooserbutton1").hide()
elif temp == 2:
self.logo = "fedora"
self.widgetTree.get_widget("filechooserbutton1").hide()
elif temp == 3:
self.logo = "gnome"
self.widgetTree.get_widget("filechooserbutton1").hide()
elif temp == 4:
self.logo = "ubuntu"
self.widgetTree.get_widget("filechooserbutton1").hide()
elif temp == 5:
self.logo = "zenwalk"
self.widgetTree.get_widget("filechooserbutton1").hide()
elif temp == 6:
self.logo = "gentoo"
self.widgetTree.get_widget("filechooserbutton1").hide()
elif temp == 7:
self.logo = "bodhi"
self.widgetTree.get_widget("filechooserbutton1").show()
elif temp == 8:
self.logo = "custom"
self.widgetTree.get_widget("filechooserbutton1").show()
self.widgetTree.get_widget("image5").set_from_file("../alternative_icons/logos/" + self.logo)
def CustomChange(self, widget):
custom = str(self.widgetTree.get_widget("filechooserbutton1").get_filename())
process = subprocess.Popen("source ./script_functions && set_custom_logo " + custom, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
self.widgetTree.get_widget("image5").set_from_file("../alternative_icons/logos/custom")
def navigationChange(self, widget):
tempn = self.widgetTree.get_widget("combobox5").get_active()
if tempn == 0:
self.nav = "default"
elif tempn == 1:
self.nav = "moblin"
elif tempn == 2:
self.nav = "minimal"
self.widgetTree.get_widget("image6").set_from_file("../alternative_icons/navigation/"+ self.nav +"/back.svg")
def switchIcons(self, widget):
tempf = self.widgetTree.get_widget("combobox4").get_active()
self.folder = "acyl_" + str(int(tempf) + 1)
temp = self.widgetTree.get_widget("combobox6").get_active()
if temp == 0:
self.logo = "arch"
elif temp == 1:
self.logo = "debian"
elif temp == 2:
self.logo = "fedora"
elif temp == 3:
self.logo = "gnome"
elif temp == 4:
self.logo = "ubuntu"
elif temp == 5:
self.logo = "zenwalk"
elif temp == 6:
self.logo = "gentoo"
elif temp == 7:
self.logo = "custom"
tempn = self.widgetTree.get_widget("combobox5").get_active()
if tempn == 0:
self.nav = "default"
elif tempn == 1:
self.nav = "moblin"
elif tempn == 2:
self.nav = "minimal"
process = subprocess.Popen("source ./script_functions && logo_change " + self.logo, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process = subprocess.Popen("source ./script_functions && folder_change " + self.folder, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process = subprocess.Popen("source ./script_functions && navigation_change " + self.nav, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
self.saveState("./current_state/gui_config.ini")
self.setTheme(self)
def copyToRoot(self, widget):
pwd = self.widgetTree.get_widget("entry1").get_text()
if len(pwd) > 0:
process = subprocess.Popen("source ./script_functions && root_copy " + pwd, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
else:
self.askPwd(self)
def makeExec(self, widget):
pwd = self.widgetTree.get_widget("entry1").get_text()
if len(pwd) > 0:
process = subprocess.Popen("source ./script_functions && make_exec " + pwd, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
else:
self.askPwd(self)
def changePreset(self, widget):
temp = self.widgetTree.get_widget("combobox9").get_active()
if temp == 0:
self.widgetTree.get_widget("spinbutton-start-x").set_value(50)
self.widgetTree.get_widget("spinbutton-start-y").set_value(0)
self.widgetTree.get_widget("spinbutton-end-x").set_value(50)
self.widgetTree.get_widget("spinbutton-end-y").set_value(100)
elif temp == 1:
self.widgetTree.get_widget("spinbutton-start-x").set_value(0)
self.widgetTree.get_widget("spinbutton-start-y").set_value(50)
self.widgetTree.get_widget("spinbutton-end-x").set_value(100)
self.widgetTree.get_widget("spinbutton-end-y").set_value(50)
else:
self.widgetTree.get_widget("spinbutton-start-x").set_value(0)
self.widgetTree.get_widget("spinbutton-start-y").set_value(0)
self.widgetTree.get_widget("spinbutton-end-x").set_value(100)
self.widgetTree.get_widget("spinbutton-end-y").set_value(100)
def appCopy(self, widget):
pwd = self.widgetTree.get_widget("entry1").get_text()
if len(pwd) > 0:
active = self.widgetTree.get_widget("combobox8").get_active()
if active != -1:
if active == 0:
app = "pidgin"
elif active == 1:
app = "sonata"
elif active == 2:
app = "emesene"
elif active == 3:
app = "wicd"
process = subprocess.Popen("source ./script_functions && " + app + "_copy " + pwd, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
else:
self.askPwd(self)
def importSettings(self, widget):
dialog = gtk.FileChooserDialog("Open file", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialog.set_default_response(gtk.RESPONSE_OK)
dialog.set_default_response(gtk.RESPONSE_OK)
filter = gtk.FileFilter()
filter.set_name("All files")
filter.add_pattern("*")
dialog.add_filter(filter)
response = dialog.run()
if response == gtk.RESPONSE_OK:
self.loadState(dialog.get_filename())
self.RefreshPreview(self)
dialog.destroy()
def exportSettings(self, widget):
dialog = gtk.FileChooserDialog("Save file", None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
dialog.set_default_response(gtk.RESPONSE_OK)
dialog.set_default_response(gtk.RESPONSE_OK)
dialog.set_do_overwrite_confirmation(True)
filter = gtk.FileFilter()
filter.set_name("All files")
filter.add_pattern("*")
dialog.add_filter(filter)
response = dialog.run()
if response == gtk.RESPONSE_OK:
src = "./current_state/gui_config.ini"
dest = dialog.get_filename()
shutil.copyfile(src, dest)
self.RefreshPreview(self)
dialog.destroy()
def restoreSettings(self, widget):
self.loadState("./gui_config_default.ini")
self.RefreshPreview(self)
def quit(self, widget):
self.saveState("./current_state/gui_config.ini")
gtk.main_quit()
####### Dialog1 #######
def showDialog(self, widget):
self.dialog = gtk.glade.XML("gui.glade", "window2")
dialog_dic = { \
"on_close" : self.closeDialog \
}
self.dialog.signal_autoconnect(dialog_dic)
self.mdialog = self.dialog.get_widget("window2")
self.widgetTree.get_widget("button15").set_sensitive(False)
self.widgetTree.get_widget("button16").set_sensitive(False)
self.widgetTree.get_widget("button17").set_sensitive(False)
self.widgetTree.get_widget("combobox8").set_sensitive(False)
self.mdialog.show()
def closeDialog(self, widget=None, data=None):
self.mdialog.destroy()
####### askPwd #######
def askPwd(self, widget):
self.dialog = gtk.glade.XML("gui.glade", "window2")
dialog_dic = { \
"on_ok" : self.dialogOk \
}
self.dialog.signal_autoconnect(dialog_dic)
self.pwdDialog = self.dialog.get_widget("window2")
self.pwdDialog.show()
def dialogOk(self, widget=None, data=None):
self.pwdDialog.destroy()
####### AboutDialog1 #######
def showAbout(self, widget):
self.dialog = gtk.glade.XML("gui.glade", "aboutdialog1")
dialog_dic = { \
"on_close_dialog" : self.closeDialog \
}
self.dialog.signal_autoconnect(dialog_dic)
self.mdialog = self.dialog.get_widget("aboutdialog1")
self.mdialog.show()
def closeDialog(self, widget=None, data=None):
self.mdialog.destroy()
####### ApplyCutom #######
def showApplyCutom(self, widget):
self.dialog = gtk.glade.XML("gui.glade", "ApplyCustom")
dialog_dic = { \
"on_apply_custom" : self.applyCustom, \
"on_close_dialog" : self.closeDialog \
}
self.dialog.signal_autoconnect(dialog_dic)
self.mdialog = self.dialog.get_widget("ApplyCustom")
self.mdialog.show()
def closeDialog(self, widget=None, data=None):
self.mdialog.destroy()
def applyCustom(self, widget=None, data=None):
self.RefreshPreview(self)
if self.dialog.get_widget("checkbutton1").get_active():
process = subprocess.Popen("source ./script_functions && apply_actions " + self.CurrentSettings, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
if self.dialog.get_widget("checkbutton2").get_active():
process = subprocess.Popen("source ./script_functions && apply_emblems " + self.CurrentSettings, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
if self.dialog.get_widget("checkbutton3").get_active():
process = subprocess.Popen("source ./script_functions && apply_places " + self.CurrentSettings, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
if self.dialog.get_widget("checkbutton4").get_active():
process = subprocess.Popen("source ./script_functions && apply_mimetype " + self.CurrentSettings, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
if self.dialog.get_widget("checkbutton5").get_active():
process = subprocess.Popen("source ./script_functions && apply_status " + self.CurrentSettings, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
if self.dialog.get_widget("checkbutton6").get_active():
process = subprocess.Popen("source ./script_functions && apply_apps " + self.CurrentSettings, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
if self.dialog.get_widget("checkbutton7").get_active():
process = subprocess.Popen("source ./script_functions && apply_except " + self.CurrentSettings, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.wait()
self.setTheme(self)
self.mdialog.destroy()
def main(self):
gtk.main()
if __name__ == "__main__":
acyl = ACYLGUI()
acyl.main()
``` |
{
"source": "joebieb/halite",
"score": 2
} |
#### File: joebieb/halite/MyBot.py
```python
import hlt
import logging
from collections import OrderedDict
# GAME START
game = hlt.Game("Spoof_v7")
logging.info('Starting my %s bot!', game._name)
TURN = 0
def navigate(ship, entity, multiplier = 1):
navigate_command = ship.navigate(
ship.closest_point_to(entity),
game_map,
speed=int(hlt.constants.MAX_SPEED * multiplier),
ignore_ships=True)
if navigate_command:
command_queue.append(navigate_command)
def kamikazee(ship, entity):
navigate_command = ship.navigate(
entity,
game_map,
speed=int(hlt.constants.MAX_SPEED),
ignore_ships=False)
if navigate_command:
command_queue.append(navigate_command)
while True:
# TURN START
TURN += 1
group_attack_limit = 3
attack_ship_modifier = .4
game_map = game.update_map()
command_queue = []
me = game_map.get_me()
enemies = [enemy for enemy in game_map.all_players() if enemy.id != me.id]
my_ships = me.all_ships()
my_docked_ships = [ship for ship in my_ships if ship.docking_status != ship.DockingStatus.UNDOCKED]
#planet_docking_status = []
enemy_ships = [ship for ship in game_map._all_ships() if ship not in my_ships]
docked_enemy_ships = [ship for ship in enemy_ships if ship.docking_status != ship.DockingStatus.UNDOCKED]
unowned_planets = [planet for planet in game_map.all_planets() if not planet.is_owned()]
my_planets = [planet for planet in game_map.all_planets() if planet.is_owned() and planet.owner.id == me.id]
enemy_planets = [planet for planet in game_map.all_planets() if planet.is_owned() and planet.owner.id != me.id]
targeted_planets = []
targeted_ships = []
# find center of enemy mass
planet_x = [planet.x for planet in enemy_planets]
ship_x = [ship.x for ship in enemy_ships]
planet_y = [planet.y for planet in enemy_planets]
ship_y = [ship.y for ship in enemy_ships]
x = planet_x + ship_x
y = planet_y + ship_y
enemy_centroid = hlt.entity.Position(0,0)
if len(x):
enemy_centroid = hlt.entity.Position(sum(x) / len(x), sum(y) / len(y))
entities_by_distance_to_enemy_centroid = OrderedDict(sorted(game_map.nearby_entities_by_distance(enemy_centroid).items(), key=lambda t: t[0]))
my_ships_by_distance_to_enemy_centroid = [entities_by_distance_to_enemy_centroid[distance][0]
for distance in entities_by_distance_to_enemy_centroid
if entities_by_distance_to_enemy_centroid[distance][0] in my_ships
and entities_by_distance_to_enemy_centroid[distance][0] not in my_docked_ships]
# adjust limits based on ship counts
my_ship_count = len(my_ships)
enemy_ship_count = len(enemy_ships)
if my_ship_count > 0 and enemy_ship_count > 0:
ratio = (my_ship_count / enemy_ship_count)
if ratio > 1:
group_attack_limit *= ratio
# logging.info('group attack limit: %s', group_attack_limit)
#logging.info(enemy_centroid)
# find undocked ships that are closest to action and make them fighters first set the rest as miners
attack_ships = my_ships_by_distance_to_enemy_centroid[0 : int(len(my_ships_by_distance_to_enemy_centroid) * attack_ship_modifier)]
# logging.info('Number of attack ships: %s', len(attack_ships))
# For every ship that I control
for ship in my_ships:
# If the ship is docked
if ship.docking_status != ship.DockingStatus.UNDOCKED:
# Skip this ship
continue
entities_by_distance = OrderedDict(sorted(game_map.nearby_entities_by_distance(ship).items(), key=lambda t: t[0]))
target_planets = [entities_by_distance[distance][0] for distance in entities_by_distance if entities_by_distance[distance][0] in game_map.all_planets() and entities_by_distance[distance][0] not in targeted_planets]
target_unowned_planets = [entities_by_distance[distance][0] for distance in entities_by_distance if entities_by_distance[distance][0] in unowned_planets and entities_by_distance[distance][0] not in targeted_planets]
target_enemy_planets = [entities_by_distance[distance][0] for distance in entities_by_distance if entities_by_distance[distance][0] in enemy_planets]
target_ships = [entities_by_distance[distance][0] for distance in entities_by_distance if entities_by_distance[distance][0] in enemy_ships]
target_docked_ships = [entities_by_distance[distance][0] for distance in entities_by_distance if entities_by_distance[distance][0] in docked_enemy_ships]
# if ship in attack_ships attack
if ship in attack_ships:
for enemy_ship in target_ships:
# if unowned planet is closer, then dock, otherwise attack
# if target_unowned_planets[0]:
# if ship.calculate_distance_between(target_unowned_planets[0]) < ship.calculate_distance_between(enemy_ship):
# if ship.can_dock(target_unowned_planets[0]):
# command_queue.append(ship.dock(target_unowned_planets[0]))
# else:
# navigate(ship, enemy_ship, 1)
# else:
# if enemy is targeted by n ships then get next closest ship
if enemy_ship in targeted_ships:
if targeted_ships.count(enemy_ship) >= group_attack_limit:
# logging.info('group attack limit met, trying next ship')
continue
targeted_ships.append(enemy_ship)
navigate(ship, enemy_ship, 1)
break
else:
for planet in target_planets:
# If we can dock, let's (try to) dock. If two ships try to dock at once, neither will be able to.
if ship.can_dock(planet) and planet in unowned_planets:
command_queue.append(ship.dock(planet))
elif ship.can_dock(planet) and planet in my_planets and not planet.is_full():
command_queue.append(ship.dock(planet))
# if planet is owned then attack
elif planet.is_owned() and planet in enemy_planets:
for enemy_ship in planet.all_docked_ships():
if enemy_ship:
navigate(ship, enemy_ship)
break
else:
targeted_planets.append(planet)
navigate(ship, planet)
break
# Send our set of commands to the Halite engine for this turn
game.send_command_queue(command_queue)
# TURN END
# GAME END
``` |
{
"source": "JoeBlack220/django_blog",
"score": 3
} |
#### File: django_blog/blog/utils.py
```python
from bs4 import BeautifulSoup
def parse_li(html, level):
soup = BeautifulSoup(html, features="html.parser")
li = soup.findChildren(recursive=False)[0]
li['class'] = "nav-item nav-level-" + str(level)
for child in li.findChildren(recursive=False):
if child.name == "a":
child['class'] = "nav-link"
child.replace_with(parse_a(child.__str__()))
elif child.name == "ul":
child.replace_with(parse_ol(child.__str__(), level+1))
return soup
def parse_a(html):
soup = BeautifulSoup(html, features="html.parser")
a = soup.findChildren(recursive=False)[0]
if not len(a.findChildren(recursive=False)):
new_tag = soup.new_tag('span')
new_tag['class'] = "nav-text"
if(a.string):
new_tag.string = a.string
a.string = ""
a.append(new_tag)
else:
child = a.findChildren(recursive=False)[0]
a.replace_with(parse_a(child.__str__()))
return a
def parse_ol(html, level):
soup = BeautifulSoup(html, features="html.parser")
ol = soup.findChildren(recursive=False)[0]
ol.name = 'ol'
if level == 1:
ol['class'] = "nav"
else:
ol['class'] = 'nav-child'
for li in ol.findChildren(recursive=False):
li.replace_with(parse_li(li.__str__(), level))
return soup
def convert_toc(toc):
return parse_ol(toc, 1).prettify()
# print(convert_toc('''<ul>
# <li><a href="#fdas">fdas</a>
# <ul>
# <li><a href="#fjdaskjfldka">fjdaskjfldka</a></li>
# </ul>
# </li>
# <li><a href="#fdas">fdas</a>
# </li>
# </ul>'''))
``` |
{
"source": "JoeBlackSci/grokking_algorithms",
"score": 4
} |
#### File: grokking_algorithms/grokking_algorithms/dynamic.py
```python
def fill_contianer(container_limit, items, show_grid=False):
"""Fill container with optimal value."""
grid = _make_grid(items, container_limit)
best = _get_best_combo(grid)
if show_grid:
print(grid)
return best
def _make_grid(items, columns):
# Initalise
items = dict(sorted(items.items(), key=lambda item: item[1]))
rows = [[[-float('inf'), None] for i in range(columns+1)]]
for item in items:
# Change item from key to value
row = [item]
item = items[item]
for i in range(columns):
# If item fits
if item[1] <= i+1:
# Prepare item for append to row
row_insert = [item[0], row[0]]
# If item does not take up all space in column
if item[1] < i+1 and len(rows) > 1:
# Get remaining space
idx_lookup = i+1 - item[1]
# Get optimal items to fill that space
add_val = rows[-1][idx_lookup][0]
add_item = rows[-1][idx_lookup][1]
# Add optimal space fillers
row_insert[0] += add_val
row_insert[1] += ', ' + add_item
# If this is still less optimal than previous solution
if row_insert[0] < rows[-1][i+1][0]:
# Set insert to previous solution
row_insert = rows[-1][i+1]
else:
# Set item to previous row best solution
row_insert = rows[-1][i+1]
# Append column to row
row.append(row_insert)
# Append row to grid
rows.append(row)
del rows[0]
return rows
def _get_best_combo(grid):
grid = [row[1:] for row in grid]
max_value = -float('inf')
best_combo = None
for row in grid:
for col in row:
if col[0] > max_value:
max_value = col[0]
best_combo = col[1]
return best_combo, max_value
```
#### File: grokking_algorithms/grokking_algorithms/quicksort.py
```python
def euclid_algorithm(area):
"""Return the largest square to subdivide area by."""
height = area[0]
width = area[1]
maxdim = max(height, width)
mindim = min(height, width)
remainder = maxdim % mindim
if remainder == 0:
return mindim
else:
return euclid_algorithm((mindim, remainder))
def recursive_sum(arr):
"""Return the sum of a 2D array."""
if len(arr) == 0:
return 0
else:
return arr[0] + recursive_sum(arr[1:])
def quicksort(arr, pivi=0):
"""Return a sorted 2D numerical array smallest -> largest."""
if len(arr) < 2:
return arr
else:
piv = arr[pivi]
lower = [v for v in arr[1:] if v <= piv]
higher = [v for v in arr[1:] if v > piv]
return quicksort(lower) + [piv] + quicksort(higher)
``` |
{
"source": "joeblackwaslike/flask-sqlalchemy",
"score": 3
} |
#### File: flask-sqlalchemy/tests/test_meta_data.py
```python
import sqlalchemy as sa
from quart_sqlalchemy import SQLAlchemy
def test_default_metadata(app):
db = SQLAlchemy(app, metadata=None)
class One(db.Model):
id = db.Column(db.Integer, primary_key=True)
myindex = db.Column(db.Integer, index=True)
class Two(db.Model):
id = db.Column(db.Integer, primary_key=True)
one_id = db.Column(db.Integer, db.ForeignKey(One.id))
myunique = db.Column(db.Integer, unique=True)
assert One.metadata.__class__ is sa.MetaData
assert Two.metadata.__class__ is sa.MetaData
assert One.__table__.schema is None
assert Two.__table__.schema is None
def test_custom_metadata(app):
class CustomMetaData(sa.MetaData):
pass
custom_metadata = CustomMetaData(schema="test_schema")
db = SQLAlchemy(app, metadata=custom_metadata)
class One(db.Model):
id = db.Column(db.Integer, primary_key=True)
myindex = db.Column(db.Integer, index=True)
class Two(db.Model):
id = db.Column(db.Integer, primary_key=True)
one_id = db.Column(db.Integer, db.ForeignKey(One.id))
myunique = db.Column(db.Integer, unique=True)
assert One.metadata is custom_metadata
assert Two.metadata is custom_metadata
assert One.metadata.__class__ is not sa.MetaData
assert One.metadata.__class__ is CustomMetaData
assert Two.metadata.__class__ is not sa.MetaData
assert Two.metadata.__class__ is CustomMetaData
assert One.__table__.schema == "test_schema"
assert Two.__table__.schema == "test_schema"
```
#### File: flask-sqlalchemy/tests/test_query_property.py
```python
import pytest
from werkzeug.exceptions import NotFound
from quart_sqlalchemy import SQLAlchemy
async def test_no_app_bound(app):
db = SQLAlchemy()
db.init_app(app)
class Foo(db.Model):
id = db.Column(db.Integer, primary_key=True)
# If no app is bound to the SQLAlchemy instance, a
# request context is required to access Model.query.
pytest.raises(RuntimeError, getattr, Foo, "query")
async with app.test_request_context("/"):
db.create_all()
foo = Foo()
db.session.add(foo)
db.session.commit()
assert len(Foo.query.all()) == 1
def test_app_bound(db, Todo):
# If an app was passed to the SQLAlchemy constructor,
# the query property is always available.
todo = Todo("Test", "test")
db.session.add(todo)
db.session.commit()
assert len(Todo.query.all()) == 1
def test_get_or_404(Todo):
with pytest.raises(NotFound):
Todo.query.get_or_404(1)
expected = "Expected message"
with pytest.raises(NotFound) as e_info:
Todo.query.get_or_404(1, description=expected)
assert e_info.value.description == expected
def test_first_or_404(Todo):
with pytest.raises(NotFound):
Todo.query.first_or_404()
expected = "Expected message"
with pytest.raises(NotFound) as e_info:
Todo.query.first_or_404(description=expected)
assert e_info.value.description == expected
``` |
{
"source": "joeblackwaslike/gpgkeyring",
"score": 2
} |
#### File: gpgkeyring/gpgkeyring/decorators.py
```python
from functools import wraps
from . import events
__all__ = ["expires_cache", "passthru"]
def expires_cache(func):
"""Automatically expire cache.
:param typing.Callable func: the function to expire cache for.
:returns: the wrapped function.
:rtype: instance of :class:`typing.Callable`.
:emits: :term:`event` of :class:`gpgkeyring.events.KeyCacheExpiry`.
"""
@wraps(func)
def _wrapper(self, *args, **kwargs):
load_func = getattr(self, "_load", None)
load_func.cache_clear()
result = func(self, *args, **kwargs)
load_func.cache_clear()
return result
return _wrapper
def passthru(func):
"""Return value of function by same name in proxied object.
Proxied object is located as an attribute named `_wrapped` in proxy object.
"""
@wraps(func)
def _wrapper(self, *args, **kwargs):
name = func.__name__
return getattr(self._wrapped, func.__name__)(*args, **kwargs)
return _wrapper
```
#### File: gpgkeyring/gpgkeyring/events.py
```python
from typing import Union, Tuple
import gnupg
from . import interfaces as iface
__all__ = [
"BeforeInitializeGPG",
"AfterInitializeGPG",
"MessageEncrypted",
"MessageDecrypted",
"MessageSigned",
"MessageVerified",
"KeysLoaded",
"KeysExported",
"KeysImported",
"KeysTrusted",
"KeysDeleted",
"KeysSentToServer",
"KeysReceivedFromServer",
"BeforeGenerateKey",
"AfterGenerateKey",
]
class BeforeInitializeGPG:
"""Emitted before GPG instance is initialized.
All event arguments are parameters relavent to the construction of the
GPG instance and its subsequent ZCA component registration.
"""
options: dict = None
name: str = ""
def __init__(self, options, name):
self.options = options
self.name = name
class AfterInitializeGPG:
"""Emitted after GPG instance is initialized.
Any modifications of `gpg` will be reflected in the instance emitting
this event.
"""
gpg: iface.IGPG = None
name: str = ""
def __init__(self, gpg, name):
self.gpg = gpg
self.name = name
class MessageEncrypted:
"""Emitted after a message is encrypted."""
gpg: iface.IGPG = None
result: gnupg.Crypt = None
def __init__(self, gpg, result):
self.gpg = gpg
self.result = result
class MessageDecrypted:
"""Emitted after a message is decrypted."""
gpg: iface.IGPG = None
result: gnupg.Crypt = None
key: iface.IKey = None
def __init__(self, gpg, result, key=None):
self.gpg = gpg
self.result = result
self.key = key
class MessageSigned:
"""Emitted after a message is signed."""
gpg: iface.IGPG = None
result: gnupg.Sign = None
def __init__(self, gpg, result):
self.gpg = gpg
self.result = result
class MessageVerified:
"""Emitted after a message is verified."""
gpg: iface.IGPG = None
result: gnupg.Verify = None
key: iface.IKey = None
def __init__(self, gpg, result, key=None):
self.gpg = gpg
self.result = result
self.key = key
# @attr.s
class KeysLoaded:
"""Emitted after keys are loaded in Keyring."""
gpg: iface.IGPG = None
type: str = ""
keys: gnupg.ListKeys = None
def __init__(self, gpg, type, keys):
self.gpg = gpg
self.type = type
self.keys = keys
class KeysExported:
"""Emitted after key(s) exported."""
gpg: iface.IGPG = None
result: gnupg.ExportResult = None
keys: Union[iface.IKey, Tuple[iface.IKey]] = None
def __init__(self, gpg, result, keys):
self.gpg = gpg
self.result = result
self.keys = keys
class KeysImported:
"""Emitted after key(s) imported."""
gpg: iface.IGPG = None
result: gnupg.ImportResult = None
keys: Union[iface.IKey, Tuple[iface.IKey]] = None
def __init__(self, gpg, result, keys):
self.gpg = gpg
self.result = result
self.keys = keys
class KeysTrusted:
"""Emitted after key(s) trusted."""
gpg: iface.IGPG = None
result: gnupg.DeleteResult = None
keys: Union[iface.IKey, Tuple[iface.IKey]] = None
def __init__(self, gpg, result, keys):
self.gpg = gpg
self.result = result
self.keys = keys
class KeysDeleted:
"""Emitted after key(s) deleted."""
gpg: iface.IGPG = None
result: gnupg.DeleteResult = None
keys: Union[iface.IKey, Tuple[iface.IKey]] = None
def __init__(self, gpg, result, keys):
self.gpg = gpg
self.result = result
self.keys = keys
class KeysSentToServer:
"""Emitted after key(s) sent to keyserver."""
gpg: iface.IGPG = None
result: gnupg.SendResult = None
keys: Union[iface.IKey, Tuple[iface.IKey]] = None
def __init__(self, gpg, result, keys):
self.gpg = gpg
self.result = result
self.keys = keys
class KeysReceivedFromServer:
"""Emitted after key(s) received from keyserver."""
gpg: iface.IGPG = None
result: gnupg.ImportResult = None
keys: Union[iface.IKey, Tuple[iface.IKey]] = None
def __init__(self, gpg, result, keys):
self.gpg = gpg
self.result = result
self.keys = keys
class BeforeGenerateKey:
"""Emitted before a new key is generated.
Modify `options` on event to modify the options passed to the key
generation function.
"""
gpg: iface.IGPG = None
options: dict = None
def __init__(self, gpg, options):
self.gpg = gpg
self.options = options
class AfterGenerateKey:
"""Emitted after a new key is generated.
It might be useful to do something with the `key` object generated here
such as update a setting or signing a payload..
"""
gpg: iface.IGPG = None
cmd: str = ""
result: gnupg.GenKey = None
key: iface.IKey = None
def __init__(self, gpg, cmd, result, key):
self.gpg = gpg
self.cmd = cmd
self.result = result
self.key = key
```
#### File: gpgkeyring/gpgkeyring/metaconfigure.py
```python
from zope.component import provideUtility
from zope.component.zcml import ComponentConfigurationError
from gpgkeyring.interfaces import IGPG
def _register_gpg_service(
factory, name, gnupghome, verbose, useagent, keyring, gpgbinary, encoding
):
options = dict(
gnupghome=gnupghome,
verbose=verbose,
use_agent=useagent,
keyring=keyring,
gpgbinary=gpgbinary,
encoding=encoding,
)
gpg = factory(options, name)
provideUtility(gpg, IGPG, name=name)
def gpgKeyringHandler(
_context,
factory,
name="",
gnupghome="~/.gnupg",
verbose=False,
useagent=True,
keyring=None,
keyserver="pool.sks-keyservers.net",
gpgbinary="gpg2",
encoding="utf-8",
):
factories = factory
if len(factories) == 1:
factory = factories[0]
elif len(factories) < 1:
raise ComponentConfigurationError("No factory specified")
elif len(factories) > 1 and len(for_) != 1:
raise ComponentConfigurationError(
"Can't use multiple factories and multiple for"
)
else:
factory = zope.component.zcml._rolledUpFactory(factories)
_context.action(
discriminator=("gpgService", factory, name),
callable=_register_gpg_service,
args=(
factory,
name,
gnupghome,
verbose,
useagent,
keyring,
keyserver,
gpgbinary,
encoding,
),
)
_context.action(
discriminator=None,
callable=zope.component.provideInterface,
args=("", provides),
)
```
#### File: gpgkeyring/gpgkeyring/trust.py
```python
import enum
__all__ = ["UNDEFINED", "NEVER", "MARGINAL", "FULLY", "ULTIMATE"]
class Levels(enum.Enum):
"""The levels of trust for a GPG key."""
UNDEFINED = "TRUST_UNDEFINED"
NEVER = "TRUST_NEVER"
MARGINAL = "TRUST_MARGINAL"
FULLY = "TRUST_FULLY"
ULTIMATE = "TRUST_ULTIMATE"
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
return NotImplemented
def __repr__(self):
return "<{}: {}>".format(type(self).__name__, self.name)
def __str__(self):
return str(self.value)
def __hash__(self):
return hash(self.value)
def __eq__(self, other):
if isinstance(other, str):
return bool(other in self.value)
return enum.Enum.__eq__(self, other)
UNDEFINED = Levels.UNDEFINED
NEVER = Levels.NEVER
MARGINAL = Levels.MARGINAL
FULLY = Levels.FULLY
ULTIMATE = Levels.ULTIMATE
_TRUST_MAP = dict(n=NEVER, m=MARGINAL, f=FULLY, u=ULTIMATE, q=UNDEFINED)
def coerce_trust(value):
""""Return trust CONSTANT value to replace a gpg raw trust value.
:param Union[Levels, str] value: the object to check.
:returns: a trust Level enum member.
:rtype: member of enum :class:`.Levels`.
Usage::
>>> coerce_trust('n')
<Levels: NEVER>
"""
if isinstance(value, Levels):
return
return _TRUST_MAP[value]
```
#### File: tests/helpers/util.py
```python
from os.path import join, dirname
import copy
import pickle
import zope.component
def is_nested(*items):
return isinstance(items[0], (tuple, list))
def safe_len(item, default=1):
if is_container(item):
return len(item)
return default
def is_container(item):
return isinstance(item, (tuple, list))
def merge_into(d1, **kwargs):
d1 = copy.deepcopy(d1)
d1.update(**kwargs)
return d1
def testdata_path(path, base=__file__):
return join(dirname(base), "data", path)
def load_testdata(path, mode="rt", base=__file__, unpickle=False):
path = testdata_path(path, base=base)
with open(path, mode) as fd:
data = fd.read()
if unpickle:
data = pickle.loads(data)
return data
def setdefaults(defaults, **kwargs):
defaults = defaults.copy()
defaults.update(**kwargs)
return defaults
def subscribe_event(event):
_events = []
@zope.component.adapter(event)
def _handle_event(_event):
_events.append(_event)
registry = zope.component.getGlobalSiteManager()
registry.registerHandler(_handle_event)
def return_event():
assert len(_events) == 1
return _events.pop()
return return_event
```
#### File: tests/unit/test_decorators.py
```python
import types
import pytest
from gpgkeyring.decorators import expires_cache, passthru
@pytest.fixture()
def spy(mocker):
mock = mocker.MagicMock(
instance=True,
test_expires=mocker.MagicMock(side_effect=lambda self, arg: arg),
test_wrapped=mocker.MagicMock(
__name__="test_wrapped", side_effect=lambda self, arg: arg
),
_wrapped=mocker.MagicMock(
instance=True,
test_wrapped=mocker.MagicMock(
__name__="test_wrapped", side_effect=lambda arg: arg
),
),
)
mock._expires_mock = mock.test_expires
mock._wrapped_mock = mock.test_wrapped
mock.test_expires = types.MethodType(
expires_cache(mock.test_expires), mock
)
mock.test_wrapped = types.MethodType(passthru(mock.test_wrapped), mock)
return mock
class TestDecorators:
def test_expires_cache_decorator(self, spy, mocker):
result = spy.test_expires("arg")
spy._load.cache_clear.assert_has_calls([mocker.call(), mocker.call()])
spy._expires_mock.assert_called_once_with(spy, "arg")
assert result == "arg"
def test_passthru_decorator(self, spy, mocker):
result = spy.test_wrapped("arg")
spy._wrapped.test_wrapped.assert_called_once_with("arg")
spy._wrapped_mock.assert_not_called()
assert result == "arg"
```
#### File: tests/unit/test_trust.py
```python
import pytest
import gpgkeyring
from ..helpers import testdata
TRUST_VALUE_MAP = gpgkeyring.trust._TRUST_MAP.items()
class TestEnum:
@pytest.fixture(params=testdata.TRUST_LEVELS)
def level(self, request):
yield request.param
def test_trust_level_value(self, level):
assert getattr(gpgkeyring.trust.Levels, level.name) == level
def test_trust_level_repr(self, level):
assert (
repr(level) == "<{}: {}>".format(type(level).__name__, level.name)
)
def test_trust_level_str(self, level):
assert str(level) == level.value
def test_trust_level_eq_str(self, level):
assert level == str(level)
class TestCoerce:
@pytest.mark.parametrize("raw, expected", TRUST_VALUE_MAP)
def test_coerce_trust(self, raw, expected):
assert gpgkeyring.trust.coerce_trust(raw) == expected
``` |
{
"source": "joeblackwaslike/graphene",
"score": 2
} |
#### File: graphene/types/inputfield.py
```python
from .mountedtype import MountedType
from .structures import NonNull
from .utils import get_type
class InputField(MountedType):
def __init__(
self,
type_,
name=None,
default_value=None,
deprecation_reason=None,
description=None,
required=False,
_creation_counter=None,
**extra_args
):
super(InputField, self).__init__(_creation_counter=_creation_counter)
self.name = name
if required:
type_ = NonNull(type_)
self._type = type_
self.deprecation_reason = deprecation_reason
self.default_value = default_value
self.description = description
@property
def type(self):
return get_type(self._type)
```
#### File: graphene/types/union.py
```python
from .base import BaseOptions, BaseType
from .unmountedtype import UnmountedType
# For static type checking with Mypy
MYPY = False
if MYPY:
from .objecttype import ObjectType # NOQA
from typing import Iterable, Type # NOQA
class UnionOptions(BaseOptions):
types = () # type: Iterable[Type[ObjectType]]
class Union(UnmountedType, BaseType):
"""
Union Type Definition
When a field can return one of a heterogeneous set of types, a Union type
is used to describe what types are possible as well as providing a function
to determine which type is actually used when the field is resolved.
"""
@classmethod
def __init_subclass_with_meta__(cls, types=None, **options):
assert (
isinstance(types, (list, tuple)) and len(types) > 0
), "Must provide types for Union {name}.".format(name=cls.__name__)
_meta = UnionOptions(cls)
_meta.types = types
super(Union, cls).__init_subclass_with_meta__(_meta=_meta, **options)
@classmethod
def get_type(cls):
"""
This function is called when the unmounted type (Union instance)
is mounted (as a Field, InputField or Argument)
"""
return cls
@classmethod
def _resolve_type(cls, instance, info):
from .objecttype import ObjectType # NOQA
if isinstance(instance, ObjectType):
return type(instance)
``` |
{
"source": "joeblackwaslike/hashidtools",
"score": 2
} |
#### File: hashidtools/hashidtools/__init__.py
```python
__version__ = '1.0.2'
__title__ = "hashidtools"
from zope.configuration import xmlconfig
from . import interfaces, exceptions, types, fields
from .types import HashIDGenerator, HashID, HashIDManager
xmlconfig.file('configure.zcml', __import__('sys').modules[__name__])
``` |
{
"source": "joeblackwaslike/kubed",
"score": 2
} |
#### File: objects/api/resources.py
```python
from datetime import timedelta
from . import util
from .bases import APIObjectBase
from .groups import (
CoreAPIGroup,
ExtensionsAPIGroup,
AppsAPIGroup,
BatchAPIGroup,
APIextensionsAPIGroup
)
from .properties import (
Namespaced,
Phased,
Configuration,
Encoded,
Replicating,
Selecting,
Storage,
Bindable
)
from ... import rest
class Pod(Namespaced, Phased, APIObjectBase, CoreAPIGroup):
def exec(self, command=None, container=None, shell=None, interactive=False,
tty=False, **kwargs):
container = container or self.spec.containers[0].name
# [fixme] even though stdout by default is True, this is required to
# make exec work properly.
# INFO: this kwarg itself isn't required, but one of stdout,
# stderr, or stdin set to True is. Investigate later
# edit: this if fixed here:
# https://github.com/kubernetes-client/python-base/pull/35/files
# but not in the latest version of the python client yet
if all([not kwargs.get('stdout'),
not kwargs.get('stderr'),
not kwargs.get('stdin')]):
kwargs['stdout'] = True
if interactive:
kwargs['stdin'] = True
kwargs['_preload_content'] = False
if tty:
kwargs['tty'] = True
request = rest.StreamRequest(
self._manager.clone(),
'exec',
name=self.name,
namespace=self.namespace,
command=util.shlex(command, shell),
container=container,
**kwargs
)
return request.execute()
def logs(self, container=None, follow=False, since=None, tail=None,
previous=False, **kwargs):
"""Returns logs from the attached pod.
args:
since: timedelta, defaults to None.
example:
from datetime import timedelta
logs = pod.logs(since=timedelta(minutes=5))
[todo] implement streaming logs with follow=True
"""
container = container or self.spec.containers[0].name
if follow:
kwargs['_preload_content'] = False
if since:
if isinstance(since, timedelta):
since = round(since.total_seconds())
kwargs['since_seconds'] = since
if tail:
kwargs['tail_lines'] = tail
request = rest.Request(
self._manager.clone(),
'logs',
name=self.name,
namespace=self.namespace,
container=container,
previous=previous,
follow=follow,
**kwargs
)
return request.execute()
class Node(APIObjectBase, CoreAPIGroup):
@property
def ready(self):
for condition in self.status.conditions:
if condition.type == 'Ready' and condition.status == 'True':
return True
return False
@property
def address(self):
for addr in self.status.addresses:
if addr.type == 'InternalIP':
return addr.address
@property
def hostname(self):
for addr in self.status.addresses:
if addr.type == 'Hostname':
return addr.address
def wait(self):
while not self.ready:
time.sleep(6)
self.reload()
self.reload()
class ConfigMap(Namespaced, Configuration, APIObjectBase, CoreAPIGroup):
pass
class Secret(Namespaced, Configuration, Encoded, APIObjectBase, CoreAPIGroup):
_transforms = APIObjectBase._transforms + ('B64TranslateMap',)
class Endpoints(Namespaced, APIObjectBase, CoreAPIGroup):
@property
def _addresses(self):
return [address for address in self.subsets[0].addresses]
@property
def nodes(self):
return [address.node_name for address in self._addresses]
@property
def ips(self):
return [address.ip for address in self._addresses]
@property
def _targets(self):
references = [address.target_ref for address in self._addresses]
return [(ref.kind, ref.name, ref.namespace) for ref in references]
@property
def pods(self):
objects = []
for kind, name, namespace in self._targets:
manager = self._manager.client.manager_for(kind)
objects.append(manager.get(name=name, namespace=namespace).first())
return objects
class Service(Namespaced, Selecting, APIObjectBase, CoreAPIGroup):
@property
def type(self):
return self.spec.type
class ReplicaSet(Namespaced, Replicating, Selecting, APIObjectBase,
ExtensionsAPIGroup):
pass
class Deployment(Namespaced, Replicating, Selecting, APIObjectBase,
ExtensionsAPIGroup):
pass
class StatefulSet(Namespaced, Replicating, Selecting, APIObjectBase,
AppsAPIGroup):
pass
class DaemonSet(Namespaced, Replicating, Selecting, APIObjectBase,
ExtensionsAPIGroup):
@property
def ready(self):
return all([
self.status.observed_generation >= self.metadata.generation,
self.status.desired_number_scheduled == self.status.number_ready]
)
class Ingress(Namespaced, APIObjectBase, ExtensionsAPIGroup):
pass
class Namespace(APIObjectBase, CoreAPIGroup):
pass
class Job(Namespaced, Selecting, APIObjectBase, BatchAPIGroup):
@property
def complete(self):
for condition in self.status.conditions:
if condition.type == 'Complete' and condition.status == 'True':
return True
return False
@property
def succeeded(self):
return self.status.succeeded >= len(self.spec.template.spec.containers)
class CronJob(Namespaced, Selecting, APIObjectBase, BatchAPIGroup):
pass
class PersistentVolume(Storage, Bindable, APIObjectBase, CoreAPIGroup):
@property
def claim(self):
ref = self.spec.claim_ref
manager = self._manager.client.manager_for(ref.kind)
return manager.get(
name=ref.name, namespace=ref.namespace).first()
class PersistentVolumeClaim(Namespaced, Storage, Bindable, APIObjectBase,
CoreAPIGroup):
@property
def volume(self):
manager = self._manager.client.manager_for('PersistentVolume')
return manager.get(name=self.spec.volume_name).first()
class ServiceAccount(Namespaced, APIObjectBase, CoreAPIGroup):
pass
class CustomResourceDefinition(APIObjectBase, APIextensionsAPIGroup):
pass
```
#### File: rest/response/base.py
```python
import urllib3
from . import transforms
from ..constants import TRANSFORMS_DEFAULT
from ...exceptions import NoPodsFoundError
class ResponseBase:
def __init__(self, request, body):
self.request = request
self._resource = request.resource
self._manager = request.manager
@property
def namespace(self):
return self.request.params.namespace
def __repr__(self):
class_name = type(self).__name__
resource_name = self._resource.__name__
return f'{class_name}(resource: {resource_name})'
class ResponseText(ResponseBase):
def __init__(self, request, body):
ResponseBase.__init__(self, request, body)
self.body = body
@property
def streaming(self):
return isinstance(self.body, urllib3.response.HTTPResponse)
@property
def text(self):
if self.streaming:
return self.body.read().strip()
return self.body.strip()
def __iter__(self):
if self.streaming:
return iter(self.body.stream())
return iter(self.text.splitlines())
def __len__(self):
return len(self.text.splitlines())
class ResponseJSON(ResponseBase):
"""Parses and contains all information in response to an API request.
"""
def __init__(self, request, body):
ResponseBase.__init__(self, request, body)
if body:
self.raw = body
if isinstance(body, dict):
if 'items' in body:
body = body['items']
elif hasattr(body, 'items'):
body = body.items or []
else:
body = [body]
if not len(body):
raise NoPodsFoundError('No pods found matching criteria!')
self.body = body
for name in self._resource._transforms:
transform = transforms.TransformBase.get_transform(name)
transform(self).apply()
def first(self, count=1):
if count == 1:
return self.body[0]
return self.body[0:count]
def all(self):
return self.body
```
#### File: rest/response/stream.py
```python
import time
import kubernetes
from . import base
from ...meta.decorators import lazy_property
_RESPONSE_TIMEOUT_DEFAULT = 3
class StreamResponseBase(base.ResponseBase):
"""Parses and contains all information in response to a streamed request.
"""
def __init__(self, request, response, **kwargs):
base.ResponseBase.__init__(self, request, response)
self._params = kwargs
class StreamResponseText(base.ResponseText):
def __init__(self, request, response, **kwargs):
base.ResponseText.__init__(self, request, response)
self._params = kwargs
class StreamResponseJSON(base.ResponseJSON):
def __init__(self, request, response, **kwargs):
base.ResponseJSON.__init__(self, request, response)
self._params = kwargs
class StreamResponseExec(StreamResponseText):
def __init__(self, request, response, **kwargs):
StreamResponseText.__init__(self, request, response, **kwargs)
@lazy_property
def text(self):
return self.body.strip()
@property
def interactive(self):
return False
@lazy_property
def tty(self):
return bool(self._params.get('tty'))
class StreamResponseInteractiveExec(StreamResponseExec):
def __init__(self, request, streamer, **kwargs):
StreamResponseExec.__init__(self, request, None, **kwargs)
self._streamer = streamer
@property
def interactive(self):
return True
def close(self):
self._streamer.close()
def execute(self, command, timeout=_RESPONSE_TIMEOUT_DEFAULT):
if not self._streamer.is_open():
# [todo] make custom error type for this
raise RuntimeError('Stream: %s is not open', self._streamer)
self._streamer.write_stdin(command + '\n')
while not self._streamer.peek_stdout() or self._streamer.peek_stderr():
time.sleep(1)
return (
self._streamer.read_stdout(timeout=timeout),
self._streamer.read_stderr(timeout=timeout)
)
```
#### File: kubed/kubed/strutil.py
```python
import re
import base64
def snake_case(string):
"""Convert string into snake case.
Join punctuation with underscore
Args:
string: String to convert.
Returns:
string: Snake cased string.
"""
string = re.sub(r"[\-\.\s]", '_', str(string))
if not string:
return string
return string[0].lower() + re.sub(
r"[A-Z]",
lambda matched: '_' + matched.group(0).lower(),
string[1:]
)
def camel_case(string):
""" Convert string into camel case.
Args:
string: String to convert.
Returns:
string: Camel case string.
"""
string = re.sub(r"^[\-_\.]", '', str(string))
if not string:
return string
return string[0].lower() + re.sub(
r"[\-_\.\s]([a-z])",
lambda matched: matched.group(1).upper(),
string[1:]
)
def b64encode(data):
if isinstance(data, str):
data = data.encode()
return base64.b64encode(data).decode()
def b64decode(data):
if isinstance(data, str):
data = data.encode()
return base64.b64decode(data).decode()
```
#### File: tools/leader/election.py
```python
import time
import socket
import threading
from .constants import DEFAULT_SYNC_INTERVAL
from .record import LeaderElectionRecord
from .resource_lock import EndpointsLock
from ...exceptions import ResourceVersionConflictError
from ...client import APIClient
class LeaderElection(threading.Thread):
"""Elect the leader for a specified kubernetes endpoint object
Example:
from kubed.tools.leader import LeaderElection
election = LeaderElection(client, name='couchdb', namespace='default')
with election:
election.start()
# insert event loop here
"""
def __init__(self, client=None, name='none', namespace=None, identity=None):
threading.Thread.__init__(self)
self._client = client or APIClient()
self.name = name
self.namespace = namespace or self._client.namespace
self.identity = identity or socket.gethostname()
self.lock = EndpointsLock(
self._client, self.identity, self.name, self.namespace)
self.running = False
def __enter__(self):
return self
def __exit__(self, *args):
self.running = False
@property
def leader(self):
return self.lock.get()
def _try_acquire_lease(self):
"""Try to acquire leader lease.
Returns:
True if successful, False otherwise.
"""
record = self.lock.get()
if record.identity is self.identity:
return True
if record.expired:
try:
record = self.lock.create()
return True
except ResourceVersionConflictError:
return False
return False
def _try_renew_lease(self):
"""Try to renew existing lease.
Returns:
True if successful, False otherwise.
"""
record = self.lock.get()
if record.identity != self.identity:
return False
if record.should_renew:
self.lock.create() # lock.create() can also renew lease
return True
def _acquire(self):
"""Continually try to acquire a lease while running and lease not
already acquired.
"""
while self.running and not self._try_acquire_lease():
print('trying to acquire lease')
print('leader: ', self.leader)
time.sleep(DEFAULT_SYNC_INTERVAL)
return True
def _renew(self):
"""Continually renew acquired lease while running until not running or
renew is not successful.
"""
while self.running and self._try_renew_lease():
print('renewing lease')
print('leader: ', self.leader)
time.sleep(DEFAULT_SYNC_INTERVAL)
def run(self):
self.running = True
while self.running:
self._acquire()
self._renew()
def stop(self):
self.running = False
def __repr__(self):
class_name = type(self).__name__
alive = self.is_alive()
return f'{class_name}(running: {self.running}, alive: {alive})'
``` |
{
"source": "joeblackwaslike/pricing",
"score": 4
} |
#### File: pricing/pricing/babel_numbers.py
```python
import decimal
import babel.numbers
from babel.core import Locale
from babel.numbers import NumberPattern as _NumberPattern
from babel.numbers import LC_NUMERIC, number_re, UnknownCurrencyFormatError
__all__ = ['format_currency']
def format_currency(number, currency, format=None,
locale=LC_NUMERIC, currency_digits=True,
format_type='standard', decimal_quantization=True):
"""Return formatted currency value.
>>> format_currency(1099.98, 'USD', locale='en_US')
u'$1,099.98'
>>> format_currency(1099.98, 'USD', locale='es_CO')
u'US$\\xa01.099,98'
>>> format_currency(1099.98, 'EUR', locale='de_DE')
u'1.099,98\\xa0\\u20ac'
The format can also be specified explicitly. The currency is
placed with the '¤' sign. As the sign gets repeated the format
expands (¤ being the symbol, ¤¤ is the currency abbreviation and
¤¤¤ is the full name of the currency):
>>> format_currency(1099.98, 'EUR', u'\xa4\xa4 #,##0.00', locale='en_US')
u'EUR 1,099.98'
>>> format_currency(1099.98, 'EUR', u'#,##0.00 \xa4\xa4\xa4',
... locale='en_US')
u'1,099.98 euros'
Currencies usually have a specific number of decimal digits. This function
favours that information over the given format:
>>> format_currency(1099.98, 'JPY', locale='en_US')
u'\\xa51,100'
>>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES')
u'1.100'
However, the number of decimal digits can be overriden from the currency
information, by setting the last parameter to ``False``:
>>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
u'\\xa51,099.98'
>>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES',
... currency_digits=False)
u'1.099,98'
If a format is not specified the type of currency format to use
from the locale can be specified:
>>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
u'\\u20ac1,099.98'
When the given currency format type is not available, an exception is
raised:
>>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
Traceback (most recent call last):
...
UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
By default the locale is allowed to truncate and round a high-precision
number by forcing its format pattern onto the decimal part. You can bypass
this behavior with the `decimal_quantization` parameter:
>>> format_currency(1099.9876, 'USD', locale='en_US')
u'$1,099.99'
>>> format_currency(1099.9876, 'USD', locale='en_US',
... decimal_quantization=False)
u'$1,099.9876'
:param number: the number to format
:param currency: the currency code
:param format: the format string to use
:param locale: the `Locale` object or locale identifier
:param currency_digits: use the currency's natural number of decimal digits
:param format_type: the currency format type to use
:param decimal_quantization: Truncate and round high-precision numbers to
the format pattern. Defaults to `True`.
"""
locale = Locale.parse(locale)
if format:
pattern = parse_pattern(format)
else:
try:
p = locale.currency_formats[format_type]
pattern = NumberPattern(
p.pattern, p.prefix, p.suffix, p.grouping, p.int_prec,
p.frac_prec, p.exp_prec, p.exp_plus)
except KeyError:
raise UnknownCurrencyFormatError(
"%r is not a known currency format type" % format_type)
return pattern.apply(
number, locale, currency=currency, currency_digits=currency_digits,
decimal_quantization=decimal_quantization)
def parse_pattern(pattern):
"""Parse number format patterns"""
if isinstance(pattern, NumberPattern):
return pattern
def _match_number(pattern):
rv = number_re.search(pattern)
if rv is None:
raise ValueError('Invalid number pattern %r' % pattern)
return rv.groups()
pos_pattern = pattern
# Do we have a negative subpattern?
if ';' in pattern:
pos_pattern, neg_pattern = pattern.split(';', 1)
pos_prefix, number, pos_suffix = _match_number(pos_pattern)
neg_prefix, _, neg_suffix = _match_number(neg_pattern)
else:
pos_prefix, number, pos_suffix = _match_number(pos_pattern)
neg_prefix = '-' + pos_prefix
neg_suffix = pos_suffix
if 'E' in number:
number, exp = number.split('E', 1)
else:
exp = None
if '@' in number:
if '.' in number and '0' in number:
raise ValueError('Significant digit patterns can not contain '
'"@" or "0"')
if '.' in number:
integer, fraction = number.rsplit('.', 1)
else:
integer = number
fraction = ''
def parse_precision(p):
"""Calculate the min and max allowed digits"""
min = max = 0
for c in p:
if c in '@0':
min += 1
max += 1
elif c == '#':
max += 1
elif c == ',':
continue
else:
break
return min, max
int_prec = parse_precision(integer)
frac_prec = parse_precision(fraction)
if exp:
exp_plus = exp.startswith('+')
exp = exp.lstrip('+')
exp_prec = parse_precision(exp)
else:
exp_plus = None
exp_prec = None
grouping = babel.numbers.parse_grouping(integer)
return NumberPattern(pattern, (pos_prefix, neg_prefix),
(pos_suffix, neg_suffix), grouping,
int_prec, frac_prec,
exp_prec, exp_plus)
class NumberPattern(_NumberPattern):
"""Overriding babel.numbers.NumberPattern.apply to newer version."""
def apply(
self, value, locale, currency=None, currency_digits=True,
decimal_quantization=True):
"""Renders into a string a number following the defined pattern.
Forced decimal quantization is active by default so we'll produce a
number string that is strictly following CLDR pattern definitions.
"""
if not isinstance(value, decimal.Decimal):
value = decimal.Decimal(str(value))
value = value.scaleb(self.scale)
# Separate the absolute value from its sign.
is_negative = int(value.is_signed())
value = abs(value).normalize()
# Prepare scientific notation metadata.
if self.exp_prec:
value, exp, exp_sign = self.scientific_notation_elements(
value, locale)
# Adjust the precision of the fractionnal part and force it to the
# currency's if neccessary.
frac_prec = self.frac_prec
if currency and currency_digits:
frac_prec = (babel.numbers.get_currency_precision(currency), ) * 2
# Bump decimal precision to the natural precision of the number if it
# exceeds the one we're about to use. This adaptative precision is only
# triggered if the decimal quantization is disabled or if a scientific
# notation pattern has a missing mandatory fractional part (as in the
# default '#E0' pattern). This special case has been extensively
# discussed at
# https://github.com/python-babel/babel/pull/494#issuecomment-307649969
if not decimal_quantization or (self.exp_prec and frac_prec == (0, 0)):
frac_prec = (frac_prec[0], max([frac_prec[1],
get_decimal_precision(value)]))
# Render scientific notation.
if self.exp_prec:
number = ''.join([
self._quantize_value(value, locale, frac_prec),
babel.numbers.get_exponential_symbol(locale),
exp_sign,
self._format_int(
str(exp), self.exp_prec[0], self.exp_prec[1], locale)])
# Is it a siginificant digits pattern?
elif '@' in self.pattern:
text = self._format_significant(value,
self.int_prec[0],
self.int_prec[1])
a, sep, b = text.partition(".")
number = self._format_int(a, 0, 1000, locale)
if sep:
number += babel.numbers.get_decimal_symbol(locale) + b
# A normal number pattern.
else:
number = self._quantize_value(value, locale, frac_prec)
retval = ''.join([
self.prefix[is_negative],
number,
self.suffix[is_negative]])
if u'¤' in retval:
retval = retval.replace(u'¤¤¤',
babel.numbers.get_currency_name(
currency, value, locale))
retval = retval.replace(u'¤¤', currency.upper())
retval = retval.replace(u'¤', babel.numbers.get_currency_symbol(
currency, locale))
return retval
def _quantize_value(self, value, locale, frac_prec):
quantum = get_decimal_quantum(frac_prec[1])
rounded = value.quantize(quantum)
a, sep, b = str(rounded).partition(".")
number = (self._format_int(a, self.int_prec[0],
self.int_prec[1], locale) +
self._format_frac(b or '0', locale, frac_prec))
return number
def scientific_notation_elements(self, value, locale):
""" Returns normalized scientific notation components of a value."""
# Normalize value to only have one lead digit.
exp = value.adjusted()
value = value * get_decimal_quantum(exp)
assert value.adjusted() == 0
# Shift exponent and value by the minimum number of leading digits
# imposed by the rendering pattern. And always make that number
# greater or equal to 1.
lead_shift = max([1, min(self.int_prec)]) - 1
exp = exp - lead_shift
value = value * get_decimal_quantum(-lead_shift)
# Get exponent sign symbol.
exp_sign = ''
if exp < 0:
exp_sign = babel.numbers.get_minus_sign_symbol(locale)
elif self.exp_plus:
exp_sign = babel.numbers.get_plus_sign_symbol(locale)
# Normalize exponent value now that we have the sign.
exp = abs(exp)
return value, exp, exp_sign
def get_decimal_quantum(precision):
"""Return minimal quantum of a number, as defined by precision."""
assert isinstance(precision, (int, decimal.Decimal))
return decimal.Decimal(10) ** (-precision)
def get_decimal_precision(number):
"""Return maximum precision of a decimal instance's fractional part.
Precision is extracted from the fractional part only.
"""
# Copied from: https://github.com/mahmoud/boltons/pull/59
assert isinstance(number, decimal.Decimal)
decimal_tuple = number.normalize().as_tuple()
if decimal_tuple.exponent >= 0:
return 0
return abs(decimal_tuple.exponent)
```
#### File: pricing/pricing/exchange.py
```python
from decimal import Decimal
from datetime import timedelta
import importlib
from typing import ClassVar
from zope.interface import implementer
import attr
from attr.validators import instance_of
import requests
import zulu
from .interfaces import IExchangeBackend, IExchange
from .exceptions import ExchangeBackendNotInstalled
__all__ = ['BackendBase', 'SimpleBackend', 'CoinBaseBackend', 'Exchange']
def ensure_fresh_rates(func):
"""Decorator for Backend that ensures rates are fresh within last 5 mins"""
def wrapper(self, *args, **kwargs):
if self.last_updated + timedelta(minutes=5) < zulu.now():
self.refresh()
return func(self, *args, **kwargs)
return wrapper
class BackendBase:
"""Base class API for exchange backends"""
def quotation(self, origin, target):
"""Return quotation between two currencies (origin, target)"""
a = self.rate(origin)
b = self.rate(target)
if a and b:
return Decimal(b) / Decimal(a)
return None
@implementer(IExchangeBackend)
@attr.s
class SimpleBackend(BackendBase):
"""Simple Backend implementation.
:param base str: An ISO4217 currency code.
:return: A `SimpleBackend` object.
:rtype: :inst:`SimpleBackend`
Usage::
>>> SimpleBackend(base='USD')
SimpleBackend(base='USD')
"""
base: str = attr.ib(default='USD', validator=instance_of(str))
_rates: dict = attr.ib(init=False, repr=False, factory=dict,
validator=instance_of(dict))
def setrate(self, currency, rate):
"""Sets the rate for currency to provided rate."""
if not self.base:
raise Warning("set the base first: backend.base = currency")
self._rates[currency] = rate
def rate(self, currency):
"""Returns the rate of exchange from base -> currency."""
if currency == self.base:
rate = 1
else:
rate = self._rates.get(currency, None)
if rate:
return Decimal(rate)
def quotation(self, origin, target):
"""Returns the rate of exchange from origin -> target currency."""
return super(SimpleBackend, self).quotation(origin, target)
@implementer(IExchangeBackend)
@attr.s
class CoinBaseBackend(BackendBase):
"""Backend implementation that uses the Coinbase API for rates.
:param base str: An ISO4217 currency code.
:return: An `CoinBaseBackend` object.
:rtype: :inst:`CoinBaseBackend`
Usage::
>>> CoinBaseBackend(base='USD')
CoinBaseBackend(base='USD', last_updated=<Zulu [...]>)
"""
base: str = attr.ib(default='USD', validator=instance_of(str))
_rates: dict = attr.ib(repr=False, init=False, factory=dict)
_headers: ClassVar[dict] = {
'Accept': 'application/json', 'Content-Type': 'application/json'}
_base_url: ClassVar[str] = 'https://api.coinbase.com/v2'
last_updated: zulu.Zulu = attr.ib(init=False)
@last_updated.default
def last_updated_default(self):
now = zulu.now()
return now - timedelta(minutes=5)
def _rates_refresh(self, values=None):
if values:
base_url = values['_base_url']
base = values['base']
headers = values['_headers']
else:
base_url = self._base_url
base = self.base
headers = self._headers
url = base_url + '/exchange-rates?currency={}'.format(base)
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()['data']['rates']
def refresh(self):
"""Refresh rates and update last_updated timestamp."""
self._rates = self._rates_refresh()
self.last_updated = zulu.now()
@ensure_fresh_rates
def rate(self, currency):
"""Returns the rate of exchange from base -> currency."""
if currency == self.base:
rate = 1
else:
rate = self._rates.get(currency, None)
if rate:
return Decimal(rate)
@ensure_fresh_rates
def quotation(self, origin, target):
"""Returns the rate of exchange from origin -> target currency."""
return super(CoinBaseBackend, self).quotation(origin, target)
@implementer(IExchange)
@attr.s
class Exchange:
"""Currency rate exchange class.
:param _backend IExchangeBackend:
An instance of an ExchangeBackend providing IExchangeBackend interface.
:return: An `Exchange` object.
:rtype: :inst:`Exchange`
Usage::
>>> backend = CoinBaseBackend(base='USD')
... exchange = Exchange(backend=backend)
... exchange
Exchange(_backend=CoinBaseBackend(
... base='USD', last_updated=<Zulu [...]>))
>>> exchange.rate('EUR')
Decimal('...')
... exchange.quotation('EUR', 'GBP')
Decimal('...')
"""
_backend: IExchangeBackend = attr.ib(default=None)
def __nonzero__(self):
return self.__bool__()
def __bool__(self):
return bool(self._backend)
def install(self, backend='pricing.exchange.SimpleBackend'):
"""Install an exchange rates backend using a python path string"""
if isinstance(backend, str):
path, name = backend.rsplit('.', 1)
module = importlib.import_module(path)
backend = getattr(module, name)()
elif isinstance(backend, type):
backend = backend()
if not isinstance(backend, BackendBase):
raise TypeError("backend '{}' is not a subclass of "
"pricing.exchange.BackendBase".format(backend))
self._backend = backend
def uninstall(self):
"""Uninstall any exchange rates backend"""
self._backend = None
@property
def backend_name(self):
"""Return the class name of the currently installed backend or None."""
if not self._backend:
return None
return self._backend.__class__.__name__
@property
def base(self):
"""Return the base currency."""
if not self._backend:
raise ExchangeBackendNotInstalled()
return self._backend.base
def rate(self, currency):
"""Returns the rate of exchange from base -> currency."""
if not self._backend:
raise ExchangeBackendNotInstalled()
return self._backend.rate(currency)
def quotation(self, origin, target):
"""Returns the rate of exchange from origin -> target currency."""
if not self._backend:
raise ExchangeBackendNotInstalled()
return self._backend.quotation(origin, target)
def __getattr__(self, key):
return getattr(self._backend, key)
def __setattr__(self, key, value):
if key == '_backend':
self.__dict__[key] = value
elif self._backend is None:
raise ExchangeBackendNotInstalled()
else:
setattr(self._backend, key, value)
```
#### File: pricing/pricing/formats.py
```python
import re
import attr
from attr.validators import instance_of, optional
from zope.interface import implementer
from .interfaces import ICurrencyFormat
__all__ = ['CurrencyFormat']
@implementer(ICurrencyFormat)
@attr.s(frozen=True)
class CurrencyFormat:
"""Represents a custom currency's formatting parameters.
:param name str: Currency name, ex: bitcoin.
:param code str: An ISO4217 currency code, ex: USD
:param symbol str: A currency symbol, ex: $
:param format str: A CLDR compatible currency format pattern.
:param currency_digits bool: Zero pad to currency precision if True
:param decimal_quantization bool: Decimal Quantization.
:return: a CurrencyFormat object.
:rtype: :inst:`CurrencyFormat`
Usage::
>>> BTC = CurrencyFormat(
'bitcoin', 'BTC', symbol='₿', format="¤#,##0.########",
currency_digits=False, decimal_quantization=True)
... BTC
CurrencyFormat(name='bitcoin', code='BTC', symbol='\u20bf',
... format='¤#,##0.########', currency_digits=False,
... decimal_quantization=True)
"""
name: str = attr.ib(
validator=instance_of(str))
code: str = attr.ib(
validator=instance_of(str))
symbol: str = attr.ib(
validator=instance_of(str))
format: str = attr.ib(
default=None,
validator=optional(instance_of(str)))
currency_digits: bool = attr.ib(
default=True,
validator=instance_of(bool))
decimal_quantization: bool = attr.ib(
default=True,
validator=instance_of(bool))
@code.validator
def validate_currency(self, attribute, value):
if not bool(re.compile(r'^[A-Z]{3}$').match(value)):
raise ValueError('Invalid currency code: {}'.format(value))
```
#### File: pricing/pricing/interfaces.py
```python
from zope.interface import Interface, Attribute
__all__ = [
'ICurrencyFormat',
'IExchangeBackend',
'IPrice',
'IPriceRange',
'IExchange'
]
class ICurrencyFormat(Interface):
"""Formal specification for formatting a currency type."""
name = Attribute('Name of the currency being formatted')
code = Attribute('ISO code for currency being formatted')
symbol = Attribute('Symbol for currency being formatted')
currency_digits = Attribute('')
decimal_quantization = Attribute('Quantize decimal')
class IExchangeBackend(Interface):
"""Backend provider for the Exchange, exchange-rates system."""
base = Attribute('Base currency for exchange rates')
def rate(currency):
"""Return the rate of exchange from the base currency to currency."""
def quotation(origin, target):
"""Return a quotation from origin to target currency."""
class IPrice(Interface):
"""Represents a known quantity of a specific currency."""
amount = Attribute('Currency amount for instance')
currency = Attribute('Currency type for instance')
def format(locale='en_US', pattern=None, format_type='standard', **kwargs):
"""Return a locale-aware, currency-formatted string."""
def to(currency):
"""Return equivalent price object in another currency"""
class IPriceRange(Interface):
"""Represents a range between start and stop price."""
start = Attribute('Low end of price range')
stop = Attribute('High end of price range')
currency = Attribute('Currency unit of range')
def __contains__(self, item):
"""Return whether item (Price obj) is contained within range."""
def evolve(start=None, stop=None):
"""Return new range with start or stop replaced with given values."""
class IExchange(Interface):
"""Converts between currencies and manages the exchange backend"""
base = Attribute('Base currency for conversion.')
backend_name = Attribute(
'Return class name of the currently installed backend')
def rate(currency):
"""Return quotation between the base and another currency"""
def quotation(origin, target):
"""Return quotation between two currencies (origin, target)"""
class IBIP21PaymentURI(Interface):
"""A BIP21 Payment URI class."""
currency = Attribute('Currency type, ex: bitcoin, litecoin, etc')
address = Attribute('The address to send payment')
amount = Attribute('The amount requested')
def to_uri():
"""Return a formatted BIP21 Payment URI."""
def parse_uri(uri):
"""Parses a BIP21 Payment URI into this class"""
class IEIP681PaymentURI(Interface):
"""An EIP681 Payment URI class."""
currency = Attribute('Currency type, ex: bitcoin, litecoin, etc')
address = Attribute('The address to send payment')
value = Attribute('The value requested')
def to_uri():
"""Return a formatted EIP681 Payment URI."""
def parse_uri(uri):
"""Parses a EIP681 Payment URI into this class"""
```
#### File: pricing/tests/test_price.py
```python
import unittest
from pricing import Price
from . import mixins
class TestPriceInstantiation(mixins.InstantiationMixin, unittest.TestCase):
def setUp(self):
self.PriceClass = Price
class TestPriceClass(mixins.ClassMixin, unittest.TestCase):
def setUp(self):
self.price = Price('2.99', 'XXX')
class TestPriceRepresentations(mixins.RepresentationsMixin, unittest.TestCase):
def setUp(self):
self.price = Price('1234.567', 'XXX')
class TestPriceFormatting(mixins.FormattingMixin, unittest.TestCase):
def setUp(self):
self.price = Price('-1234.567', 'USD')
class TestPriceParser(mixins.ParserMixin, unittest.TestCase):
def setUp(self):
self.PriceClass = Price
class TestPriceNumericOperations(mixins.NumericOperationsMixin, unittest.TestCase):
def setUp(self):
self.PriceClass = Price
class TestPriceUnaryOperationsReturnNew(mixins.UnaryOperationsReturnNewMixin, unittest.TestCase):
def setUp(self):
self.price = Price('2.99', 'XXX')
class TestPriceLeftmostTypePrevails(mixins.LeftmostTypePrevailsMixin, unittest.TestCase):
def setUp(self):
self.PriceClass = Price
self.price = self.PriceClass('2.99', 'XXX')
self.PriceSubclass = type('PriceSubclass', (self.PriceClass,), {})
self.other_price = self.PriceSubclass('2.99', 'XXX')
```
#### File: pricing/tests/test_uris.py
```python
import unittest
from pricing.interfaces import IBIP21PaymentURI, IEIP681PaymentURI
from pricing.uris import BIP21PaymentURI, EIP681PaymentURI
class TestCurrencyFormat(unittest.TestCase):
def test_interfaces(self):
uri = BIP21PaymentURI(
'bitcoin', address='19kxPokCjD6tUU3sHaLZgEQBkRsCTBt3jj',
amount='2.425222')
self.assertTrue(IBIP21PaymentURI.providedBy(uri))
uri = EIP681PaymentURI(
'ethereum', address='077a7506b69e37e4f6852577190f04a35df9a36c',
value='2.425222')
self.assertTrue(IEIP681PaymentURI.providedBy(uri))
def test_bip21_payment_uri(self):
uri = BIP21PaymentURI(
'bitcoin', address='19kxPokCjD6tUU3sHaLZgEQBkRsCTBt3jj',
amount='2.425222')
self.assertEqual(
str(uri),
'bitcoin:19kxPokCjD6tUU3sHaLZgEQBkRsCTBt3jj?amount=2.425222')
def test_eip681_payment_uri(self):
uri = EIP681PaymentURI(
'ethereum', address='077a7506b69e37e4f6852577190f04a35df9a36c',
value='2.425222')
uri2 = EIP681PaymentURI(
'ethereum', address='0x077a7506b69e37e4f6852577190f04a35df9a36c',
value='2.425222')
self.assertEqual(
str(uri),
'ethereum:0x077a7506b69e37e4f6852577190f04a35df9a36c?value=2.425222'
)
self.assertEqual(str(uri), str(uri2))
``` |
{
"source": "joeblackwaslike/pyramid_bootstrap",
"score": 2
} |
#### File: joeblackwaslike/pyramid_bootstrap/tasks.py
```python
from invoke import task
@task
def test(ctx):
ctx.run('pytest --cov tests')
@task
def install(ctx):
ctx.run('pip3 install -e ".[testing]"')
@task
def check(ctx):
ctx.run('pyroma .')
ctx.run('pylint pyramid_bootstrap')
ctx.run('pycodestyle')
@task
def clean(ctx):
ctx.run('rm -rf build dist')
@task(pre=[clean])
def build(ctx):
ctx.run('python3 setup.py sdist bdist_wheel')
@task
def upload(ctx, environment='production'):
if environment == 'production':
server = 'pypi'
elif environment == 'test':
server = 'test'
ctx.run(
'twine upload -r {} --sign --identity E23F8CA8 dist/*'.format(server))
```
#### File: pyramid_bootstrap/tests/test_pyramid_bootstrap.py
```python
import unittest
from pyramid.config import Configurator
from pyramid.testing import cleanUp
from pyramid import testing
import pyramid_bootstrap
class PyramidBootstrapTest(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def test_placeholder(self):
self.assertTrue(True)
def tearDown(self):
testing.tearDown()
if __name__ == '__main__':
unittest.main()
``` |
{
"source": "joeblackwaslike/pytest-asyncio",
"score": 2
} |
#### File: tests/loop_fixture_scope/test_loop_fixture_scope.py
```python
import asyncio
import pytest
@pytest.mark.asyncio
async def test_for_custom_loop():
"""This test should be executed using the custom loop."""
await asyncio.sleep(0.01)
assert type(asyncio.get_event_loop()).__name__ == "CustomSelectorLoop"
@pytest.mark.asyncio
async def test_dependent_fixture(dependent_fixture):
await asyncio.sleep(0.1)
``` |
{
"source": "joeblackwaslike/resume-builder",
"score": 2
} |
#### File: resume-builder/builder/documents.py
```python
from os.path import relpath, join
import yaml
from pylatex import Document, Command, NoEscape
from .commands import (
Section,
Award,
Skill,
Experience,
Item,
Activity,
Education,
OSProject,
MakeCVHeader,
)
from .environments import Paragraph, Awards, Skills, Entries, Projects, Items
class ResumeDocument(Document):
def __init__(self, *args, **kwargs):
kwargs.setdefault("default_filepath", relpath(join(".", "export")))
kwargs.setdefault("document_options", ["11pt", "letterpaper"])
kwargs.setdefault("documentclass", "awesomecv")
kwargs.setdefault("accent_color", "awesome-emerald")
kwargs.setdefault("fontenc", None)
kwargs.setdefault("inputenc", None)
kwargs.setdefault("font_size", None)
kwargs.setdefault("lmodern", None)
kwargs.setdefault("textcomp", None)
kwargs.setdefault("page_numbers", None)
accent_color = kwargs.pop("accent_color")
super().__init__(*args, **kwargs)
self.preamble.append(
Command("colorlet", ["awesome", NoEscape(accent_color)])
)
self.data.clear()
def add_basics(self, basics):
location = basics["location"]
for command in [
Command("name", basics["name"].split()),
Command("position", basics["label"]),
Command("address", f"{location['city']}, {location['region']}"),
Command("mobile", basics["phone"]),
Command("email", basics["email"]),
Command("homepage", basics["website"]),
]:
self.preamble.append(command)
for profile in basics["profiles"]:
self.preamble.append(
Command(profile["network"].lower(), profile["username"])
)
def add_header(self):
self.append(MakeCVHeader(options=["L"]))
def add_section(self, title):
self.append(Section(title))
def load_metadata(self, resume):
self._meta = resume["meta"]
self._basic = resume["basics"]
@property
def file_name(self):
m = self._meta
elements = [
e.replace(" ", "_")
for e in [
self._basic["name"],
m["name"],
m["role"],
m["focus"],
m["company"],
m["version"],
]
if e
]
return "_".join(elements)
def export(self, path):
with open(path, "w") as fd:
fd.write(self.dumps())
@classmethod
def from_jsonresume(cls, path, **kwargs):
with open(path) as fd:
resume = yaml.load(fd)
doc = cls(**kwargs)
doc.load_metadata(resume)
doc.add_basics(resume["basics"])
doc.add_header()
# doc.add_section("Summary")
# with doc.create(Paragraph()) as block:
# block.append(resume["basics"]["summary"])
doc.add_section("Skills")
with doc.create(Skills()) as skills:
for item in resume["skills"]:
skills.append(Skill.from_jsonresume(item))
doc.add_section("Work Experience")
with doc.create(Entries()) as entries:
for item in resume["work"]:
entry = Experience.from_jsonresume(item)
with entry.create(Items()) as items:
summary = item.get("summary")
if summary:
items.append(Item(summary))
for bullet in item.get("highlights", []):
items.append(Item(bullet))
entries.append(entry)
doc.add_section("Extracurricular Activities")
with doc.create(Entries()) as entries:
for item in resume["volunteer"]:
entry = Activity.from_jsonresume(item)
with entry.create(Items()) as items:
summary = item.get("summary")
if summary:
items.append(Item(summary))
entries.append(entry)
doc.add_section("Awards")
with doc.create(Awards()) as awards:
for item in resume["awards"]:
awards.append(Award.from_jsonresume(item))
# doc.add_section("Education")
# with doc.create(Entries()) as entries:
# for item in resume["education"]:
# entry = Education.from_jsonresume(item)
# entries.append(entry)
doc.add_section("Open Source Projects")
with doc.create(Projects()) as entries:
for item in resume["projects"]:
entry = OSProject.from_jsonresume(item)
entries.append(entry)
return doc
``` |
{
"source": "joeblake/AgileMe",
"score": 2
} |
#### File: AgileMe/boards/models.py
```python
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime, timezone, date
# Create your models here.
DEFAULT_BOARD_USER_ID = 1
class Board(models.Model):
name = models.CharField(max_length = 32)
user = models.ForeignKey(User, on_delete = models.CASCADE,default = DEFAULT_BOARD_USER_ID)
use_due_date = models.BooleanField(default = False)
def __str__(self):
return self.name
class Task(models.Model):
board = models.ForeignKey(Board, on_delete=models.CASCADE)
name = models.CharField(max_length = 64)
points = models.IntegerField(default = 0)
due_date = models.DateField(blank = True, null = True)
in_scrum = models.BooleanField(default = False)
def __str__(self):
return self.name + "- linked to board: " + self.board.name
def do_work(self, work_done):
self.points = self.points - work_done
if(self.points <= 0):
self.delete()
else:
self.save()
def is_done(self):
return (self.points <= 0)
@property
def ppd(self):
if self.due_date == None:
return None
else:
days_left = (date.today() - self.due_date).days
if days_left > 0:
return round(self.points / days_left, 2)
else:
return None
``` |
{
"source": "joeblodgett/Snowfakery",
"score": 3
} |
#### File: Snowfakery/tests/test_locales.py
```python
from unittest import mock
from io import StringIO
from snowfakery.data_generator import generate
class TestLocales:
def test_locales(self, generated_rows):
yaml = """
- var: snowfakery_locale
value: no_NO
- object: first
fields:
name:
fake: name
- var: snowfakery_locale
value: fr_FR
- object: second
fields:
name:
fake: name
"""
with mock.patch("snowfakery.utils.template_utils.Faker") as f:
generate(StringIO(yaml))
locale_changes = [c[1][0] for c in f.mock_calls if not c[0]]
assert locale_changes == [None, "no_NO", "fr_FR"]
``` |
{
"source": "joebobbio/ChromeyMcChromeface",
"score": 2
} |
#### File: commands/info/help.py
```python
import traceback
import discord
from discord.ext import commands
class Utilities(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.left_col_length = 17
self.right_col_length = 80
self.mod_only = ["ModUtils", "Filters", "ReactionRoles", "Admin"]
self.nerd_only = ["ModActions", "Nerd", "Tags"]
@commands.command(name="help", hidden=True)
@commands.guild_only()
@commands.has_permissions(add_reactions=True, embed_links=True)
async def help_comm(self, ctx: commands.Context, *, command_arg: str = None):
"""Gets all cogs and commands of mine."""
if not command_arg:
await ctx.message.add_reaction("📬")
header = "Get a detailed description for a specific command with `!help <command name>`\n"
string = ""
for cog_name in self.bot.cogs:
cog = self.bot.cogs[cog_name]
is_mod = self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 2)
is_nerd = self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 1)
if not cog.get_commands() or (cog_name in self.mod_only and not is_mod):
continue
elif not cog.get_commands() or (cog_name in self.nerd_only and not is_nerd):
continue
string += f"== {cog_name} ==\n"
for command in cog.get_commands():
# print(type(command), command)
spaces_left = ' ' * (self.left_col_length - len(command.name))
if command.help is not None:
command.brief = command.help.split("\n")[0]
else:
command.brief = "No description."
cmd_desc = command.brief[0:self.right_col_length] + "..." if len(command.brief) > self.right_col_length else command.brief
if isinstance(command, commands.core.Group):
string += f"\t* {command.name}{spaces_left} :: {cmd_desc}\n"
for c in command.commands:
spaces_left = ' ' * (self.left_col_length - len(c.name)-4)
if c.help is not None:
c.brief = c.help.split("\n")[0]
else:
c.brief = "No description."
cmd_desc = c.brief[0:self.right_col_length] + "..." if len(c.brief) > self.right_col_length else c.brief
string += f"\t\t* {c.name}{spaces_left} :: {cmd_desc}\n"
else:
string += f"\t* {command.name}{spaces_left} :: {cmd_desc}\n"
string += "\n"
try:
parts = string.split("\n")
group_size = 25
if len(parts) <= group_size:
await ctx.author.send(header + "\n```asciidoc\n" + "\n".join(parts[0:group_size]) + "```")
else:
seen = 0
await ctx.author.send(header + "\n```asciidoc\n" + "\n".join(parts[seen:seen+group_size]) + "```")
seen += group_size
while seen < len(parts):
await ctx.author.send("```asciidoc\n" + "\n".join(parts[seen:seen+group_size]) + "```")
seen += group_size
except Exception:
await ctx.message.reply("I tried to DM you but couldn't. Make sure your DMs are enabled.")
else:
command = self.bot.get_command(command_arg.lower())
if command:
# print(str(command.cog))
if command.cog.qualified_name in self.mod_only and not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 2):
raise commands.BadArgument("You don't have permission to view that command.")
elif command.cog.qualified_name in self.nerd_only and not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 1):
raise commands.BadArgument("You don't have permission to view that command.")
else:
await ctx.message.add_reaction("📬")
embed = await self.get_usage_embed(ctx, command)
try:
await ctx.author.send(embed=embed)
except Exception:
await ctx.message.reply("I tried to DM you but couldn't. Make sure your DMs are enabled.")
else:
await ctx.message.reply("Command not found.")
@commands.command(name="usage", hidden=True)
@commands.guild_only()
@commands.has_permissions(add_reactions=True, embed_links=True)
async def usage(self, ctx: commands.Context, *, command_arg: str):
"""Show usage of one command
Parameters
----------
command_arg : str
Name of command
"""
bot_chan = self.bot.settings.guild().channel_offtopic
if not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 2) and ctx.channel.id != bot_chan:
raise commands.BadArgument(
f"Command only allowed in <#{bot_chan}>")
command = self.bot.get_command(command_arg.lower())
if command:
embed = await self.get_usage_embed(ctx, command)
await ctx.message.reply(embed=embed)
else:
await ctx.message.reply("Command not found.")
async def get_usage_embed(self, ctx, command):
if command.cog.qualified_name in self.mod_only and not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 2):
raise commands.BadArgument("You don't have permission to view that command.")
elif command.cog.qualified_name in self.nerd_only and not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 1):
raise commands.BadArgument("You don't have permission to view that command.")
else:
args = ""
for thing in command.clean_params:
args += f"<{str(thing)}> "
if command.full_parent_name:
embed = discord.Embed(title=f"!{command.full_parent_name} {command.name} {args}")
else:
embed = discord.Embed(title=f"!{command.name} {args}")
parts = command.help.split("\n\n")
embed.description = parts[0] + '\n\n'
for part in parts[1:len(parts)]:
embed.description += "```\n"
embed.description += part
embed.description += "\n```"
embed.color = discord.Color.random()
return embed
@usage.error
@help_comm.error
async def info_error(self, ctx, error):
if (isinstance(error, commands.MissingRequiredArgument)
or isinstance(error, commands.BadArgument)
or isinstance(error, commands.BadUnionArgument)
or isinstance(error, commands.MissingPermissions)
or isinstance(error, commands.NoPrivateMessage)):
await self.bot.send_error(ctx, error)
else:
traceback.print_exc()
def setup(bot):
bot.add_cog(Utilities(bot))
```
#### File: commands/misc/admin.py
```python
import datetime as dt
import traceback
import discord
from discord.ext import commands
class Admin(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="setpfp")
@commands.guild_only()
async def setpfp(self, ctx: commands.Context):
"""Set the bot's profile picture (admin only)
"""
if not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 3):
raise commands.BadArgument(
"You do not have permission to use this command.")
if len(ctx.message.attachments) < 1:
raise commands.BadArgument("Please attach an image to use as the profile picture.")
await self.bot.user.edit(avatar=await ctx.message.attachments[0].read())
await ctx.message.reply(embed=discord.Embed(color=discord.Color.blurple(), description="Done!"))
@setpfp.error
async def info_error(self, ctx, error):
await ctx.message.delete(delay=5)
if (isinstance(error, commands.MissingRequiredArgument)
or isinstance(error, commands.BadArgument)
or isinstance(error, commands.BadUnionArgument)
or isinstance(error, commands.MissingPermissions)
or isinstance(error, commands.BotMissingPermissions)
or isinstance(error, commands.CommandOnCooldown)
or isinstance(error, commands.CommandInvokeError)
or isinstance(error, commands.NoPrivateMessage)):
await self.bot.send_error(ctx, error)
else:
await self.bot.send_error(ctx, "A fatal error occured. Tell <@109705860275539968> about this.")
traceback.print_exc()
def setup(bot):
bot.add_cog(Admin(bot))
```
#### File: commands/misc/misc.py
```python
import datetime
import traceback
import typing
from io import BytesIO
import aiohttp
import discord
from discord import mentions
import humanize
import pytimeparse
from discord.ext import commands
from twemoji_parser import emoji_to_url
class Misc(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.spam_cooldown = commands.CooldownMapping.from_cooldown(3, 15.0, commands.BucketType.channel)
@commands.command(name="remindme")
@commands.guild_only()
async def remindme(self, ctx, dur: str, *, reminder: str):
"""Send yourself a reminder after a given time gap
Example usage
-------------
!remindme 1h bake the cake
Parameters
----------
dur : str
After when to send the reminder
reminder : str
What to remind you of
"""
bot_chan = self.bot.settings.guild().channel_offtopic
if not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 2) and ctx.channel.id != bot_chan:
raise commands.BadArgument(f"Command only allowed in <#{bot_chan}>.")
now = datetime.datetime.now()
delta = pytimeparse.parse(dur)
if delta is None:
raise commands.BadArgument("Please give a valid time to remind you! (i.e 1h, 30m)")
time = now + datetime.timedelta(seconds=delta)
if time < now:
raise commands.BadArgument("Time has to be in the future >:(")
reminder = discord.utils.escape_markdown(reminder)
self.bot.settings.tasks.schedule_reminder(ctx.author.id, reminder, time)
natural_time = humanize.naturaldelta(
delta, minimum_unit="seconds")
embed = discord.Embed(title="Reminder set", color=discord.Color.random(), description=f"We'll remind you in {natural_time} ")
await ctx.message.reply(embed=embed)
@commands.command(name="jumbo")
@commands.guild_only()
async def jumbo(self, ctx, emoji: typing.Union[discord.Emoji, discord.PartialEmoji, str]):
"""Post large version of a given emoji
Example usage
-------------
!jumbo :ntwerk:
Parameters
----------
emoji : typing.Union[discord.Emoji, discord.PartialEmoji]
Emoji to post
"""
bot_chan = self.bot.settings.guild().channel_offtopic
if not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 2) and ctx.channel.id != bot_chan:
if await self.ratelimit(ctx.message):
raise commands.BadArgument("This command is on cooldown.")
if isinstance(emoji, str):
emoji_url = await emoji_to_url(emoji)
if emoji_url == emoji :
raise commands.BadArgument("Couldn't find a suitable emoji.")
emoji_bytes = await self.get_emoji_bytes(emoji_url)
if emoji_bytes is None:
raise commands.BadArgument("Couldn't find a suitable emoji.")
_file = discord.File(BytesIO(emoji_bytes), filename="image.png")
await ctx.message.reply(file=_file, mention_author=False)
else:
await ctx.message.reply(emoji.url, mention_author=False)
async def get_emoji_bytes(self, url):
async with aiohttp.ClientSession() as session:
async with session.head(url) as resp:
if resp.status != 200:
return None
elif resp.headers["CONTENT-TYPE"] not in ["image/png", "image/jpeg", "image/gif", "image/webp"]:
return None
else:
async with session.get(url) as resp2:
if resp2.status != 200:
return None
return await resp2.read()
async def ratelimit(self, message):
bucket = self.spam_cooldown.get_bucket(message)
return bucket.update_rate_limit()
@commands.command(name="avatar")
@commands.guild_only()
async def avatar(self, ctx, member: discord.Member = None):
"""Post large version of a given user's avatar
Parameters
----------
member : discord.Member, optional
Member to get avatar of, default to command invoker
"""
if member is None:
member = ctx.author
bot_chan = self.bot.settings.guild().channel_offtopic
if not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 1) and ctx.channel.id != bot_chan:
raise commands.BadArgument(
f"Command only allowed in <#{bot_chan}>")
embed = discord.Embed(title=f"{member}'s avatar")
embed.set_image(url=member.avatar_url)
embed.color = discord.Color.random()
embed.set_footer(text=f"Requested by {ctx.author}")
await ctx.message.reply(embed=embed)
@commands.command(name='helpers')
@commands.cooldown(type=commands.BucketType.member, rate=1, per=86400)
async def helpers(self, ctx):
"""Tag helpers, usable in #support once every 24 hours per user"""
if ctx.channel.id != self.bot.settings.guild().channel_support:
self.helpers.reset_cooldown(ctx)
raise commands.BadArgument(f'This command is only usable in <#{self.bot.settings.guild().channel_support}>!')
helper_role = ctx.guild.get_role(self.bot.settings.guild().role_helpers)
await ctx.message.reply(f'<@{ctx.author.id}> pinged {helper_role.mention}', allowed_mentions=discord.AllowedMentions(roles=True))
@helpers.error
@jumbo.error
@remindme.error
@avatar.error
async def info_error(self, ctx, error):
await ctx.message.delete(delay=5)
if (isinstance(error, commands.MissingRequiredArgument)
or isinstance(error, commands.BadArgument)
or isinstance(error, commands.BadUnionArgument)
or isinstance(error, commands.MissingPermissions)
or isinstance(error, commands.BotMissingPermissions)
or isinstance(error, commands.MaxConcurrencyReached)
or isinstance(error, commands.NoPrivateMessage)):
await self.bot.send_error(ctx, error)
elif isinstance(error, commands.CommandOnCooldown):
await self.bot.send_error(ctx, "You can only use this command once every 24 hours.")
else:
await self.bot.send_error(ctx, "A fatal error occured. Tell <@109705860275539968> about this.")
traceback.print_exc()
def setup(bot):
bot.add_cog(Misc(bot))
```
#### File: commands/mod/modactions.py
```python
import datetime
import traceback
import typing
import cogs.utils.logs as logging
import discord
import humanize
import pytimeparse
from data.case import Case
from discord.ext import commands
class ModActions(commands.Cog):
"""This cog handles all the possible moderator actions.
- Kick
- Ban
- Unban
- Warn
- Liftwarn
- Mute
- Unmute
- Purge
"""
def __init__(self, bot):
self.bot = bot
async def check_permissions(self, ctx, user: typing.Union[discord.Member, int] = None):
if isinstance(user, discord.Member):
if user.id == ctx.author.id:
await ctx.message.add_reaction("🤔")
raise commands.BadArgument("You can't call that on yourself.")
if user.bot:
await ctx.message.add_reaction("🤔")
raise commands.BadArgument("You can't call that on bots :(")
# must be at least a mod
if not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 2):
raise commands.BadArgument(
"You do not have permission to use this command.")
if user:
if isinstance(user, discord.Member):
if user.top_role >= ctx.author.top_role:
raise commands.BadArgument(
message=f"{user.mention}'s top role is the same or higher than yours!")
@commands.guild_only()
@commands.bot_has_guild_permissions(kick_members=True, ban_members=True)
@commands.command(name="warn")
async def warn(self, ctx: commands.Context, user: typing.Union[discord.Member, int], *, reason: str = "No reason.") -> None:
"""Warn a user (nerds and up)
Example usage:
--------------
`!warn <@user/ID> <reason (optional)>
Parameters
----------
user : discord.Member
The member to warn
reason : str, optional
Reason for warning, by default "No reason."
"""
if user.id == ctx.author.id:
await ctx.message.add_reaction("🤔")
raise commands.BadArgument("You can't call that on yourself.")
if user.bot:
await ctx.message.add_reaction("🤔")
raise commands.BadArgument("You can't call that on bots :(")
if not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 1):
raise commands.BadArgument(
"You do not have permission to use this command.")
# if the ID given is of a user who isn't in the guild, try to fetch the profile
if isinstance(user, int):
try:
user = await self.bot.fetch_user(user)
except discord.NotFound:
raise commands.BadArgument(
f"Couldn't find user with ID {user}")
guild = self.bot.settings.guild()
reason = discord.utils.escape_markdown(reason)
reason = discord.utils.escape_mentions(reason)
# prepare the case object for database
case = Case(
_id=guild.case_id,
_type="WARN",
mod_id=ctx.author.id,
mod_tag=str(ctx.author),
reason=reason,
punishment="WARN"
)
# increment case ID in database for next available case ID
await self.bot.settings.inc_caseid()
# add new case to DB
await self.bot.settings.add_case(user.id, case)
# prepare log embed, send to user, channel where invoked
log = await logging.prepare_warn_log(ctx.author, user, case)
dmed = True
if isinstance(user, discord.Member):
try:
await user.send(f"You were warned in {ctx.guild.name}.", embed=log)
except Exception:
dmed = False
# also send response in channel where command was called
await ctx.message.reply(user.mention if not dmed else "", embed=log)
modlog_chan = ctx.guild.get_channel(
self.bot.settings.guild().channel_modlogs)
if modlog_chan:
log.remove_author()
log.set_thumbnail(url=user.avatar_url)
await modlog_chan.send(embed=log)
@commands.guild_only()
@commands.command(name="liftwarn")
async def liftwarn(self, ctx: commands.Context, user: discord.Member, case_id: int, *, reason: str = "No reason.") -> None:
"""Mark a warn as lifted. (mod only)
Example usage:
--------------
`!liftwarn <@user/ID> <case ID> <reason (optional)>`
Parameters
----------
user : discord.Member
User to remove warn from
case_id : int
The ID of the case for which lift
reason : str, optional
Reason for lifting warn, by default "No reason."
"""
await self.check_permissions(ctx, user)
# retrieve user's case with given ID
cases = await self.bot.settings.get_case(user.id, case_id)
case = cases.cases.filter(_id=case_id).first()
reason = discord.utils.escape_markdown(reason)
reason = discord.utils.escape_mentions(reason)
# sanity checks
if case is None:
raise commands.BadArgument(
message=f"{user} has no case with ID {case_id}")
elif case._type != "WARN":
raise commands.BadArgument(
message=f"{user}'s case with ID {case_id} is not a warn case.")
elif case.lifted:
raise commands.BadArgument(
message=f"Case with ID {case_id} already lifted.")
# passed sanity checks, so update the case in DB
case.lifted = True
case.lifted_reason = reason
case.lifted_by_tag = str(ctx.author)
case.lifted_by_id = ctx.author.id
case.lifted_date = datetime.datetime.now()
cases.save()
dmed = True
# prepare log embed, send to user, channel where invoked
log = await logging.prepare_liftwarn_log(ctx.author, user, case)
try:
await user.send(f"Your warn was lifted in {ctx.guild.name}.", embed=log)
except Exception:
dmed = False
await ctx.message.reply(user.mention if not dmed else "", embed=log)
modlog_chan = ctx.guild.get_channel(
self.bot.settings.guild().channel_modlogs)
if modlog_chan:
log.remove_author()
log.set_thumbnail(url=user.avatar_url)
await modlog_chan.send(embed=log)
@commands.guild_only()
@commands.command(name="editreason")
async def editreason(self, ctx: commands.Context, user: typing.Union[discord.Member,int], case_id: int, *, new_reason: str) -> None:
"""Edit case reason for a case (mod only)
Example usage:
--------------
`!editreason <@user/ID> <case ID> <reason>`
Parameters
----------
user : discord.Member
User to edit case of
case_id : int
The ID of the case for which we want to edit reason
new_reason : str
New reason
"""
if isinstance(user, int):
try:
user = await self.bot.fetch_user(user)
except discord.NotFound:
raise commands.BadArgument(
f"Couldn't find user with ID {user}")
await self.check_permissions(ctx, user)
# retrieve user's case with given ID
cases = await self.bot.settings.get_case(user.id, case_id)
case = cases.cases.filter(_id=case_id).first()
new_reason = discord.utils.escape_markdown(new_reason)
new_reason = discord.utils.escape_mentions(new_reason)
# sanity checks
if case is None:
raise commands.BadArgument(
message=f"{user} has no case with ID {case_id}")
old_reason = case.reason
case.reason = new_reason
case.date = datetime.datetime.now()
cases.save()
dmed = True
log = await logging.prepare_editreason_log(ctx.author, user, case, old_reason)
if isinstance(user, discord.Member):
try:
await user.send(f"Your case was updated in {ctx.guild.name}.", embed=log)
except Exception:
dmed = False
await ctx.message.reply(f"The case has been updated.", embed=log)
modlog_chan = ctx.guild.get_channel(
self.bot.settings.guild().channel_modlogs)
if modlog_chan:
log.remove_author()
log.set_thumbnail(url=user.avatar_url)
await modlog_chan.send(embed=log)
@commands.guild_only()
@commands.bot_has_guild_permissions(kick_members=True)
@commands.command(name="kick")
async def kick(self, ctx: commands.Context, user: discord.Member, *, reason: str = "No reason.") -> None:
"""Kick a user (mod only)
Example usage:
--------------
`!kick <@user/ID> <reason (optional)>`
Parameters
----------
user : discord.Member
User to kick
reason : str, optional
Reason for kick, by default "No reason."
"""
await self.check_permissions(ctx, user)
reason = discord.utils.escape_markdown(reason)
reason = discord.utils.escape_mentions(reason)
log = await self.add_kick_case(ctx, user, reason)
try:
await user.send(f"You were kicked from {ctx.guild.name}", embed=log)
except Exception:
pass
await user.kick(reason=f'{ctx.author}: {reason}')
await ctx.message.reply(embed=log)
modlog_chan = ctx.guild.get_channel(
self.bot.settings.guild().channel_modlogs)
if modlog_chan:
log.remove_author()
log.set_thumbnail(url=user.avatar_url)
await modlog_chan.send(embed=log)
async def add_kick_case(self, ctx, user, reason):
# prepare case for DB
case = Case(
_id=self.bot.settings.guild().case_id,
_type="KICK",
mod_id=ctx.author.id,
mod_tag=str(ctx.author),
reason=reason,
)
# increment max case ID for next case
await self.bot.settings.inc_caseid()
# add new case to DB
await self.bot.settings.add_case(user.id, case)
return await logging.prepare_kick_log(ctx.author, user, case)
@commands.guild_only()
@commands.bot_has_guild_permissions(ban_members=True)
@commands.command(name="ban")
async def ban(self, ctx: commands.Context, user: typing.Union[discord.Member, int], *, reason: str = "No reason."):
"""Ban a user (mod only)
Example usage:
--------------
`!ban <@user/ID> <reason (optional)>`
Parameters
----------
user : typing.Union[discord.Member, int]
The user to be banned, doesn't have to be part of the guild
reason : str, optional
Reason for ban, by default "No reason."
"""
await self.check_permissions(ctx, user)
reason = discord.utils.escape_markdown(reason)
reason = discord.utils.escape_mentions(reason)
# if the ID given is of a user who isn't in the guild, try to fetch the profile
if isinstance(user, int):
try:
user = await self.bot.fetch_user(user)
previous_bans = [user for _, user in await ctx.guild.bans()]
if user in previous_bans:
raise commands.BadArgument("That user is already banned!")
except discord.NotFound:
raise commands.BadArgument(
f"Couldn't find user with ID {user}")
log = await self.add_ban_case(ctx, user, reason)
try:
await user.send(f"You were banned from {ctx.guild.name}", embed=log)
except Exception:
pass
if isinstance(user, discord.Member):
await user.ban(reason=f'{ctx.author}: {reason}')
else:
# hackban for user not currently in guild
await ctx.guild.ban(discord.Object(id=user.id), reason=f'{ctx.author}: {reason}')
await ctx.message.reply(embed=log)
modlog_chan = ctx.guild.get_channel(
self.bot.settings.guild().channel_modlogs)
if modlog_chan:
log.remove_author()
log.set_thumbnail(url=user.avatar_url)
await modlog_chan.send(embed=log)
async def add_ban_case(self, ctx, user, reason):
# prepare the case to store in DB
case = Case(
_id=self.bot.settings.guild().case_id,
_type="BAN",
mod_id=ctx.author.id,
mod_tag=str(ctx.author),
punishment="PERMANENT",
reason=reason,
)
# increment DB's max case ID for next case
await self.bot.settings.inc_caseid()
# add case to db
await self.bot.settings.add_case(user.id, case)
# prepare log embed to send to user and context
return await logging.prepare_ban_log(ctx.author, user, case)
@commands.guild_only()
@commands.bot_has_guild_permissions(ban_members=True)
@commands.command(name="unban")
async def unban(self, ctx: commands.Context, user: int, *, reason: str = "No reason.") -> None:
"""Unban a user (must use ID) (mod only)
Example usage:
--------------
`!unban <user ID> <reason (optional)> `
Parameters
----------
user : int
ID of the user to unban
reason : str, optional
Reason for unban, by default "No reason."
"""
await self.check_permissions(ctx)
reason = discord.utils.escape_markdown(reason)
reason = discord.utils.escape_mentions(reason)
try:
user = await self.bot.fetch_user(user)
previous_bans = [user for _, user in await ctx.guild.bans()]
if user not in previous_bans:
raise commands.BadArgument("That user isn't banned!")
except discord.NotFound:
raise commands.BadArgument(f"Couldn't find user with ID {user}")
try:
await ctx.guild.unban(discord.Object(id=user.id), reason=f'{ctx.author}: {reason}')
except discord.NotFound:
raise commands.BadArgument(f"{user} is not banned.")
case = Case(
_id=self.bot.settings.guild().case_id,
_type="UNBAN",
mod_id=ctx.author.id,
mod_tag=str(ctx.author),
reason=reason,
)
await self.bot.settings.inc_caseid()
await self.bot.settings.add_case(user.id, case)
log = await logging.prepare_unban_log(ctx.author, user, case)
await ctx.message.reply(embed=log)
modlog_chan = ctx.guild.get_channel(
self.bot.settings.guild().channel_modlogs)
if modlog_chan:
log.remove_author()
log.set_thumbnail(url=user.avatar_url)
await modlog_chan.send(embed=log)
@commands.guild_only()
@commands.bot_has_guild_permissions(manage_messages=True)
@commands.command(name="purge")
async def purge(self, ctx: commands.Context, limit: int = 0) -> None:
"""Purge messages from current channel (mod only)
Example usage:
--------------
`!purge <number of messages>`
Parameters
----------
limit : int, optional
Number of messages to purge, must be > 0, by default 0 for error handling
"""
await self.check_permissions(ctx)
if limit <= 0:
raise commands.BadArgument(
"Number of messages to purge must be greater than 0")
elif limit > 100:
limit = 100 # safety mechanism to not accidentally purge a ton of messsages if someone screws this up
msgs = await ctx.channel.history(limit=limit+1).flatten()
await ctx.channel.purge(limit=limit+1)
await ctx.send(f'Purged {len(msgs)} messages.', delete_after=5)
@commands.guild_only()
@commands.bot_has_guild_permissions(manage_roles=True)
@commands.command(name="mute")
async def mute(self, ctx: commands.Context, user: discord.Member, dur: str = "", *, reason: str = "No reason.") -> None:
"""Mute a user (nerds and up)
Example usage:
--------------
`!mute <@user/ID> <duration> <reason (optional)>`
Parameters
----------
user : discord.Member
Member to mute
dur : str
Duration of mute (i.e 1h, 10m, 1d)
reason : str, optional
Reason for mute, by default "No reason."
"""
if user.id == ctx.author.id:
await ctx.message.add_reaction("🤔")
raise commands.BadArgument("You can't call that on yourself.")
if user.bot:
await ctx.message.add_reaction("🤔")
raise commands.BadArgument("You can't call that on bots :(")
if not self.bot.settings.permissions.hasAtLeast(ctx.guild, ctx.author, 1):
raise commands.BadArgument(
"You do not have permission to use this command.")
reason = discord.utils.escape_markdown(reason)
reason = discord.utils.escape_mentions(reason)
now = datetime.datetime.now()
delta = pytimeparse.parse(dur)
if delta is None:
if reason == "No reason." and dur == "":
reason = "No reason."
elif reason == "No reason.":
reason = dur
else:
reason = f"{dur} {reason}"
mute_role = self.bot.settings.guild().role_mute
mute_role = ctx.guild.get_role(mute_role)
if mute_role in user.roles:
raise commands.BadArgument("This user is already muted.")
case = Case(
_id=self.bot.settings.guild().case_id,
_type="MUTE",
date=now,
mod_id=ctx.author.id,
mod_tag=str(ctx.author),
reason=reason,
)
if delta:
try:
time = now + datetime.timedelta(seconds=delta)
case.until = time
case.punishment = humanize.naturaldelta(
time - now, minimum_unit="seconds")
self.bot.settings.tasks.schedule_unmute(user.id, time)
except Exception:
raise commands.BadArgument(
"An error occured, this user is probably already muted")
else:
case.punishment = "PERMANENT"
await self.bot.settings.inc_caseid()
await self.bot.settings.add_case(user.id, case)
u = await self.bot.settings.user(id=user.id)
u.is_muted = True
u.save()
await user.add_roles(mute_role)
log = await logging.prepare_mute_log(ctx.author, user, case)
dmed = True
try:
await user.send(f"You have been muted in {ctx.guild.name}", embed=log)
except Exception:
dmed = False
await ctx.message.reply(embed=log)
modlog_chan = ctx.guild.get_channel(
self.bot.settings.guild().channel_modlogs)
if modlog_chan:
log.remove_author()
log.set_thumbnail(url=user.avatar_url)
await modlog_chan.send(embed=log)
@commands.guild_only()
@commands.bot_has_guild_permissions(manage_roles=True)
@commands.command(name="unmute")
async def unmute(self, ctx: commands.Context, user: discord.Member, *, reason: str = "No reason.") -> None:
"""Unmute a user (mod only)
Example usage:
--------------
` !unmute <@user/ID> <reason (optional)>`
Parameters
----------
user : discord.Member
Member to unmute
reason : str, optional
Reason for unmute, by default "No reason."
"""
await self.check_permissions(ctx, user)
mute_role = self.bot.settings.guild().role_mute
mute_role = ctx.guild.get_role(mute_role)
await user.remove_roles(mute_role)
u = await self.bot.settings.user(id=user.id)
u.is_muted = False
u.save()
try:
self.bot.settings.tasks.cancel_unmute(user.id)
except Exception:
pass
case = Case(
_id=self.bot.settings.guild().case_id,
_type="UNMUTE",
mod_id=ctx.author.id,
mod_tag=str(ctx.author),
reason=reason,
)
await self.bot.settings.inc_caseid()
await self.bot.settings.add_case(user.id, case)
log = await logging.prepare_unmute_log(ctx.author, user, case)
dmed = True
try:
await user.send(f"You have been unmuted in {ctx.guild.name}", embed=log)
except Exception:
dmed = False
await ctx.message.reply(embed=log)
modlog_chan = ctx.guild.get_channel(
self.bot.settings.guild().channel_modlogs)
if modlog_chan:
log.remove_author()
log.set_thumbnail(url=user.avatar_url)
await modlog_chan.send(embed=log)
@unmute.error
@mute.error
@liftwarn.error
@unban.error
@ban.error
@warn.error
@purge.error
@kick.error
@editreason.error
async def info_error(self, ctx, error):
await ctx.message.delete(delay=5)
if (isinstance(error, commands.MissingRequiredArgument)
or isinstance(error, commands.BadArgument)
or isinstance(error, commands.BadUnionArgument)
or isinstance(error, commands.BotMissingPermissions)
or isinstance(error, commands.MissingPermissions)
or isinstance(error, commands.NoPrivateMessage)):
await self.bot.send_error(ctx, error)
else:
await self.bot.send_error(ctx, error)
traceback.print_exc()
def setup(bot):
bot.add_cog(ModActions(bot))
```
#### File: cogs/utils/tasks.py
```python
import logging
from datetime import datetime
import discord
import random
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from cogs.utils.logs import prepare_unmute_log
from data.case import Case
jobstores = {
'default': MongoDBJobStore(database="chromey", collection="jobs", host="127.0.0.1"),
}
executors = {
'default': ThreadPoolExecutor(20)
}
job_defaults = {
# 'coalesce': True
}
BOT_GLOBAL = None
class Tasks():
"""Job scheduler for unmute, using APScheduler
"""
def __init__(self, bot: discord.Client):
"""Initialize scheduler
Parameters
----------
bot : discord.Client
instance of Discord client
"""
global BOT_GLOBAL
BOT_GLOBAL = bot
logging.basicConfig()
logging.getLogger('apscheduler').setLevel(logging.DEBUG)
self.tasks = AsyncIOScheduler(
jobstores=jobstores, executors=executors, job_defaults=job_defaults, event_loop=bot.loop)
self.tasks.start()
def schedule_unmute(self, id: int, date: datetime) -> None:
"""Create a task to unmute user given by ID `id`, at time `date`
Parameters
----------
id : int
User to unmute
date : datetime.datetime
When to unmute
"""
self.tasks.add_job(unmute_callback, 'date', id=str(
id), next_run_time=date, args=[id], misfire_grace_time=3600)
def schedule_unrules(self, id: int, date: datetime) -> None:
"""Create a task to remove rules for user given by ID `id`, at time `date`
Parameters
----------
id : int
User to unrules
date : datetime.datetime
When to unrules
"""
self.tasks.add_job(unrules_callback, 'date', id=str(
id+3), next_run_time=date, args=[id], misfire_grace_time=3600)
def schedule_untimeout(self, id: int, date: datetime) -> None:
"""Create a task to remove timeout for user given by ID `id`, at time `date`
Parameters
----------
id : int
User to untimeout
date : datetime.datetime
When to untimeout
"""
self.tasks.add_job(untimeout_callback, 'date', id=str(
id+5), next_run_time=date, args=[id], misfire_grace_time=3600)
def schedule_remove_bday(self, id: int, date: datetime) -> None:
"""Create a task to remove birthday role from user given by ID `id`, at time `date`
Parameters
----------
id : int
User to remove role
date : datetime.datetime
When to remove role
"""
self.tasks.add_job(remove_bday_callback, 'date', id=str(
id+1), next_run_time=date, args=[id], misfire_grace_time=3600)
def cancel_unmute(self, id: int) -> None:
"""When we manually unmute a user given by ID `id`, stop the task to unmute them.
Parameters
----------
id : int
User whose unmute task we want to cancel
"""
self.tasks.remove_job(str(id), 'default')
def schedule_reminder(self, id: int, reminder: str, date: datetime) -> None:
"""Create a task to remind someone of id `id` of something `reminder` at time `date`
Parameters
----------
id : int
User to remind
reminder : str
What to remind them of
date : datetime.datetime
When to remind
"""
self.tasks.add_job(reminder_callback, 'date', id=str(
id+random.randint(5, 100)), next_run_time=date, args=[id, reminder], misfire_grace_time=3600)
def unmute_callback(id: int) -> None:
"""Callback function for actually unmuting. Creates asyncio task
to do the actual unmute.
Parameters
----------
id : int
User who we want to unmute
"""
BOT_GLOBAL.loop.create_task(remove_mute(id))
async def remove_mute(id: int) -> None:
"""Remove the mute role of the user given by ID `id`
Parameters
----------
id : int
User to unmute
"""
guild = BOT_GLOBAL.get_guild(BOT_GLOBAL.settings.guild_id)
if guild is not None:
mute_role = BOT_GLOBAL.settings.guild().role_mute
mute_role = guild.get_role(mute_role)
if mute_role is not None:
user = guild.get_member(id)
if user is not None:
await user.remove_roles(mute_role)
case = Case(
_id=BOT_GLOBAL.settings.guild().case_id,
_type="UNMUTE",
mod_id=BOT_GLOBAL.user.id,
mod_tag=str(BOT_GLOBAL.user),
reason="Temporary mute expired.",
)
await BOT_GLOBAL.settings.inc_caseid()
await BOT_GLOBAL.settings.add_case(user.id, case)
u = await BOT_GLOBAL.settings.user(id=user.id)
u.is_muted = False
u.save()
log = await prepare_unmute_log(BOT_GLOBAL.user, user, case)
log.remove_author()
log.set_thumbnail(url=user.avatar_url)
dmed = True
try:
await user.send(embed=log)
except Exception:
pass
else:
case = Case(
_id=BOT_GLOBAL.settings.guild().case_id,
_type="UNMUTE",
mod_id=BOT_GLOBAL.user.id,
mod_tag=str(BOT_GLOBAL.user),
reason="Temporary mute expired.",
)
await BOT_GLOBAL.settings.inc_caseid()
await BOT_GLOBAL.settings.add_case(id, case)
u = await BOT_GLOBAL.settings.user(id=id)
u.is_muted = False
u.save()
def reminder_callback(id: int, reminder: str):
BOT_GLOBAL.loop.create_task(remind(id, reminder))
async def remind(id, reminder):
"""Remind the user callback
Parameters
----------
id : int
ID of user to remind
reminder : str
body of reminder
"""
guild = BOT_GLOBAL.get_guild(BOT_GLOBAL.settings.guild_id)
if guild is None:
return
member = guild.get_member(id)
if member is None:
return
embed = discord.Embed(title="Reminder!", description=f"*You wanted me to remind you something... What was it... Oh right*:\n\n{reminder}", color=discord.Color.random())
try:
await member.send(embed=embed)
except Exception:
channel = guild.get_channel(BOT_GLOBAL.settings.guild().channel_offtopic)
await channel.send(member.mention, embed=embed)
def remove_bday_callback(id: int) -> None:
"""Callback function for actually unmuting. Creates asyncio task
to do the actual unmute.
Parameters
----------
id : int
User who we want to unmute
"""
BOT_GLOBAL.loop.create_task(remove_bday(id))
async def remove_bday(id: int) -> None:
"""Remove the bday role of the user given by ID `id`
Parameters
----------
id : int
User to remove role of
"""
guild = BOT_GLOBAL.get_guild(BOT_GLOBAL.settings.guild_id)
if guild is None:
return
bday_role = BOT_GLOBAL.settings.guild().role_birthday
bday_role = guild.get_role(bday_role)
if bday_role is None:
return
user = guild.get_member(id)
await user.remove_roles(bday_role)
def unrules_callback(id: int) -> None:
"""Callback function for actually unrules. Creates asyncio task
to do the actual unrules.
Parameters
----------
id : int
User who we want to unrules
"""
BOT_GLOBAL.loop.create_task(remove_rules(id))
async def remove_rules(id: int) -> None:
"""Remove the rules role of the user given by ID `id`
Parameters
----------
id : int
User to unmute
"""
guild = BOT_GLOBAL.get_guild(BOT_GLOBAL.settings.guild_id)
if guild is None:
return
member = guild.get_member(id)
if member is None:
return
role = guild.get_role(BOT_GLOBAL.settings.guild().role_rules)
if role is None:
return
embed=discord.Embed(title="Timeout finished.", color=discord.Color(value=0x37b83b), description='Removed your timeout role. Please behave, or we will have to take further action.')
try:
await member.send(embed=embed)
await member.remove_roles(role)
except discord.Forbidden:
channel = guild.get_channel(BOT_GLOBAL.settings.guild().channel_offtopic)
await channel.send(f'{member.mention} I tried to DM this to you, but your DMs are closed!', embed=embed)
await member.remove_roles(role)
def untimeout_callback(id: int) -> None:
"""Callback function for actually untimeout. Creates asyncio task
to do the actual untimeout.
Parameters
----------
id : int
User who we want to untimeout
"""
BOT_GLOBAL.loop.create_task(remove_timeout(id))
async def remove_timeout(id: int) -> None:
"""Remove the timeout role of the user given by ID `id`
Parameters
----------
id : int
User to unmute
"""
guild = BOT_GLOBAL.get_guild(BOT_GLOBAL.settings.guild_id)
if guild is None:
return
member = guild.get_member(id)
if member is None:
return
role = guild.get_role(BOT_GLOBAL.settings.guild().role_timeout)
print(role)
if role is None:
return
embed=discord.Embed(title="Timeout finished.", color=discord.Color(value=0x37b83b), description='Removed your timeout role. Please behave, or we will have to take further action.')
try:
await member.send(embed=embed)
await member.remove_roles(role)
except discord.Forbidden:
channel = discord.utils.get(guild.channels, name="general" if os.environ.get('PRODUCTION') == "false" else "off-topic")
await channel.send(f'{member.mention} I tried to DM this to you, but your DMs are closed!', embed=embed)
await member.remove_roles(role)
```
#### File: joebobbio/ChromeyMcChromeface/migrate.py
```python
import asyncio
import os
import mongoengine
from dotenv import find_dotenv, load_dotenv
import sqlite3
from data.user import User
from data.guild import Guild
from data.tag import Tag
from os.path import dirname, abspath
import os
import dateutil.parser
load_dotenv(find_dotenv())
async def setup():
print("STARTING SETUP...")
guild = Guild.objects(_id=int(os.environ.get("CHROMEY_MAINGUILD"))).first()
BASE_DIR = dirname(dirname(abspath(__file__)))
db_path = os.path.join(BASE_DIR, "ChromeyMcChromeface/commands.sqlite")
commands = None
users = None
try:
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute("SELECT * FROM commands ORDER BY command_name")
# c.execute("SELECT * FROM commands WHERE server_id = ? ORDER BY command_name", (int(os.environ.get("CHROMEY_MAINGUILD")),))
commands = c.fetchall()
c.execute("SELECT * FROM users")
users = c.fetchall()
finally:
conn.close()
for command in commands:
tag = Tag()
tag._id = command[0]
user_tag = None
for user in users:
if user[0] == int(command[2]):
user_tag = user[1]
tag.added_by_tag = user[1]
if user_tag is None:
tag.added_by_tag = "Unknown"
tag.added_by_id = command[2]
tag.name = command[3]
tag.use_count = command[4]
tag.content = command[5]
tag.args = command[6] == "true"
guild.tags.append(tag)
# print(command[3], command[6])
# you should have this setup in the .env file beforehand
guild.save()
karma = None
karma_history = None
try:
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute("SELECT * FROM karma_history")
karma_history = c.fetchall()
c.execute("SELECT * FROM karma")
karma = c.fetchall()
finally:
conn.close()
for user in karma:
u = User.objects(_id=user[0]).first()
# first we ensure this user has a User document in the database before continuing
if not u:
u = User()
u._id = user[0]
u.karma = user[2]
u.save()
for hist in karma_history:
receiver = User.objects(_id=hist[2]).first()
if not receiver:
receiver = User()
receiver._id = user[0]
giver = User.objects(_id=hist[3]).first()
if not giver:
giver = User()
giver._id = user[0]
give_action = {
"amount": hist[4],
"to": hist[2],
"date": dateutil.parser.parse(hist[5]),
"reason": hist[6]
}
giver.karma_given_history.append(give_action)
giver.save()
receive_action = {
"amount": hist[4],
"from": hist[3],
"date": dateutil.parser.parse(hist[5]),
"reason": hist[6]
}
receiver.karma_received_history.append(receive_action)
receiver.save()
print("DONE")
if __name__ == "__main__":
mongoengine.register_connection(alias="default", name="chromey")
res = asyncio.get_event_loop().run_until_complete( setup() )
``` |
{
"source": "joebobs0n/Eagle-Library-Tool",
"score": 3
} |
#### File: Eagle-Library-Tool/src/lbrHandler.py
```python
import xml.etree.ElementTree as et
import os
from PyQt5.QtWidgets import QGraphicsScene
xml_header = '<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE eagle SYSTEM "eagle.dtd">\n'
class EagleLibrary:
def __init__(self, path):
self.tree = et.parse(path)
self.root = self.tree.getroot()
def getDevices(self, select=None):
devices = list(self.root.iter('deviceset'))
if select:
try:
devices = [device for device in devices if device.attrib['name'] == select][0]
except:
return []
return devices
def getConnections(self, device, select=None):
connections = list(device.iter('device'))
if select != None:
connections = [obj for obj in connections if obj.attrib['package'] == select]
return connections
def getSymbols(self, device):
symbols = []
gates = list(device.iter('gate'))
for gate in gates:
symbol = [obj for obj in self.root.iter('symbol') if obj.attrib['name'] == gate.attrib['symbol']]
if len(symbol) == 1:
symbol = symbol[0]
symbols.append((gate, symbol))
else:
return []
return symbols
def getFootprints(self, device, select=None):
footprints = []
devices = list(device.iter('device'))
for device in devices:
try:
footprint = [obj for obj in self.root.iter('package') if obj.attrib['name'] == device.attrib['package']]
if len(footprint) == 1:
footprint = footprint[0]
footprints.append((device, footprint))
else:
return []
except:
return []
if select:
try:
footprints = [tupl for tupl in footprints if tupl[1].attrib['name'] == select]
except:
return []
return footprints
def getLayers(self, number=None, name=None):
layers = list(self.root.iter('layer'))
if number:
layers = [layer for layer in layers if layer.attrib['number'] == number]
if name:
layers = [layer for layer in layers if layer.attrib['name'] == name]
if len(layers) == 1:
layers = layers[0]
return layers
def getElement(self, element):
elements = list(self.root.iter(element))
return elements
def __recurse(self, element, depth=0):
# tmp = f'{depth:2d}: {". " * depth}{element.tag}{("-->" + str(element.attrib)) if len(element.attrib) > 0 else ""}\n'
tagAndText = f'{element.tag} [{element.text}]' if element.text != None and len(element.text) > 1 else f'{element.tag}'
tmp = f'{" | " * depth}{tagAndText}{(" --> " + str(element.attrib)) if len(element.attrib) > 0 else ""}\n'
self.__printMessage += tmp
children = list(element)
for child in children:
self.__recurse(child, depth+1)
def printLibraryStructure(self, element=None):
self.__printMessage = ''
if element == None:
self.__recurse(self.root)
else:
self.__recurse(element)
return self.__printMessage
def exportLibrary(self, filename):
with open(filename, 'w') as f:
f.write(xml_header)
self.tree.write(open(filename, 'ab'), encoding='UTF-8')
``` |
{
"source": "joebobs0n/python-nn",
"score": 3
} |
#### File: python-nn/src/helpers.py
```python
from time import time
from pathlib import Path
import json
#? --- CLASSES ------------------------------------------------------------------------------------
#? ------------------------------------------------------------------------------------------------
class Timer:
def __init__(self, name=''):
self.__name = name
def __enter__(self):
self.__tstart = time()
def __exit__(self, type, value, tb):
t = time() - self.__tstart
print(f'{Format.GREEN}{self.__name}{Format.END} elapsed time: {t:.3f} second(s)')
#? --- METHODS ------------------------------------------------------------------------------------
#? ------------------------------------------------------------------------------------------------
def loadDefaults(key):
defaults_path = Path(__file__).resolve().parent / 'defaults.json'
with open(defaults_path, 'r') as f:
data = json.load(f)[key]
return data
#? --- VARIABLES ----------------------------------------------------------------------------------
#? ------------------------------------------------------------------------------------------------
Format = {
'GREEN': '\033[92m',
'RED': '\033[91m',
'BOLD': '\033[1m',
'END': '\033[0m'
}
```
#### File: python-nn/src/neuron.py
```python
r'''
* --- NEURON CLASS (NEURAL NETWORK BOTTOM LEVEL) --------------------------------------------------
* -------------------------------------------------------------------------------------------------
* The class describing a single neuron within a neural network.
* The network would likely run faster if it weren't abstracted out like this since this way, due to
* the individual neuron calculation rather than doing matrix multiplication at the layer level.
* Perhaps some timing analasys will be done in the future and revisions made. Perhaps...
*
* Author: joebobs0n
* Last Edited: 25 Jun 2021
* -------------------------------------------------------------------------------------------------
'''
from copy import deepcopy
import numpy as np
import json
try:
import src.helpers as helpers
except ModuleNotFoundError:
import helpers
class Neuron:
#? --- HOOK METHODS ---------------------------------------------------------------------------
#? --------------------------------------------------------------------------------------------
def __init__(self, config=None, n_inputs=None, act_f=None, q=None, q_scalar=None, bias=None):
args = {key:val for key, val in locals().items() if key != 'self' and key != 'config'}
self.__defaults = helpers.loadDefaults('neuron')
self.__fatals = []
self.__data = deepcopy(self.__defaults)
tempConfig = {}
for key, val in {key:val for key, val in args.items() if val != None}.items():
tempConfig[key] = val
if config is not None:
for key, val in {key:val for key, val in config.items() if val != None}.items():
tempConfig[key] = val
self.setConfig(tempConfig)
def __str__(self):
ret = deepcopy(self.__data)
ret['act_f'] = ret['act_f'].__name__[2:]
return json.dumps(ret, indent=4)
def __getitem__(self, key):
return self.__data[key]
#? --- HIDDEN METHODS -------------------------------------------------------------------------
#? --------------------------------------------------------------------------------------------
def __patchConfig(self, config):
prev_config = deepcopy(self.__data)
patched = deepcopy(self.__data)
for key, val in {key:val for key, val in config.items()}.items():
patched[key] = val
for key in self.__defaults.keys():
if key not in config.keys():
config[key] = None
if config['n_inputs'] is not None and config['q'] is None:
patched['q'] = []
elif config['n_inputs'] is None and config['q'] is not None:
patched['n_inputs'] = -1
elif config['n_inputs'] is None and config['q'] is None and config['q_scalar'] is not None:
scalar_temp = patched['q_scalar'] / prev_config['q_scalar']
patched['q'] = [scalar_temp * q for q in patched['q']]
if patched['q'] == []:
patched['q'] = self.__genRandQ(patched)
if patched['n_inputs'] == -1:
patched['n_inputs'] = len(patched['q'])
return patched
def __validateConfig(self, config):
if len(config['q']) != config['n_inputs']:
self.__fatals.append('{}-F-{} {}n_inputs{} and {}q length{} mismatch'.format(
helpers.Format['RED'], helpers.Format['END'],
helpers.Format['BOLD'], helpers.Format['END'],
helpers.Format['BOLD'], helpers.Format['END'],
))
if not callable(config['act_f']):
self.__fatals.append('{}-F-{} {}{}{} is invalid selection for {}act_f{}'.format(
helpers.Format['RED'], helpers.Format['END'],
helpers.Format['BOLD'], config['act_f'], helpers.Format['END'],
helpers.Format['BOLD'], helpers.Format['END']
))
self.__qualify()
def __qualify(self):
if len(self.__fatals) > 0:
print('', *self.__fatals, sep='\n')
exit(len(self.__fatals))
def __getActivationFunc(self, config):
act_f = config['act_f'].lower()
if act_f in self.actFunctions.keys():
return self.actFunctions[act_f]
def __genRandQ(self, config):
n = config['n_inputs']
q = np.random.randn(1, n)[0]
q = config['q_scalar'] * q
return list(q)
def __normalizeQ(self, config):
return [np.float64(q) for q in config['q']]
#? --- ACTIVATION FUNCTIONS -------------------------------------------------------------------
#? --------------------------------------------------------------------------------------------
def __identity(self, data):
self.__data['output'] = data
def __step(self, data):
self.__data['output'] = [1 if y > 0 else 0 for y in data]
def __sigmoid(self, data):
self.__data['output'] = [1/(1+np.exp(-y)) for y in data]
def __tanh(self, data):
self.__data['output'] = [(np.exp(y) - np.exp(-y))/(np.exp(y) + np.exp(-y)) for y in data]
def __relu(self, data):
self.__data['output'] = [y if y > 0 else 0 for y in data]
actFunctions = {
'identity': __identity,
'step': __step,
'sigmoid': __sigmoid,
'tanh': __tanh,
'relu': __relu
}
#? --- PUBLIC METHODS -------------------------------------------------------------------------
#? --------------------------------------------------------------------------------------------
def editConfig(self, n_inputs=None, act_f=None, q=None, q_scalar=None, bias=None):
args = {key:val for key, val in locals().items() if key != 'self' and val != None}
self.setConfig(args)
def setConfig(self, config):
if len(config.keys()) < len(self.__defaults.keys()):
config = self.__patchConfig(config)
if not callable(config['act_f']):
config['act_f'] = self.__getActivationFunc(config)
config['q'] = self.__normalizeQ(config)
self.__validateConfig(config)
self.__data = deepcopy(config)
def forward(self, batch):
if type(batch[0]) == float:
batch = [batch]
calc = [float(np.dot(self.__data['q'], sample) + self.__data['bias']) for sample in batch]
self.__data['act_f'](self, calc)
return self.output
#? --- PROPERTIES -----------------------------------------------------------------------------
#? --------------------------------------------------------------------------------------------
@property
def available_activation_functions(self):
return list(self.actFunctions.keys())
@property
def config(self):
return {key:val for key, val in self.__data.items() if key != 'output'}
@property
def output(self):
return self.__data['output']
```
#### File: python-nn/src/_ut_network.py
```python
r'''
* --- NETWORK CLASS UNIT TEST ---------------------------------------------------------------------
* -------------------------------------------------------------------------------------------------
* Unit testing to cover trivial and non-trivial features of Network class.
*
* Author: joebobs0n
* Last Edited: 25 Jun 2021
* -------------------------------------------------------------------------------------------------
'''
from network import Network
from copy import deepcopy
import helpers
import unittest
class TestLayer(unittest.TestCase):
def setUp(self):
pass
if __name__ == '__main__':
print('{}-I-{} Running unit tests on {}Layer{} class...'.format(
helpers.Format['GREEN'], helpers.Format['END'],
helpers.Format['BOLD'], helpers.Format['END']
))
print('----------------------------------------------------------------------')
unittest.main(verbosity=2)
``` |
{
"source": "joebobs0n/rpi_ip_mailer",
"score": 3
} |
#### File: joebobs0n/rpi_ip_mailer/startup_mailer.py
```python
import subprocess
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
import time
import http.client as httplib
throwaway_email = '<EMAIL>'
email_password = '<PASSWORD>'
# function to check if internet connection is available
def have_internet():
conn = httplib.HTTPConnection("www.google.com", timeout=5)
try:
conn.request("HEAD", "/")
conn.close()
return True
except:
conn.close()
return False
# do not continue until internet is available
while not have_internet():
pass
gmail_user = throwaway_email # throwaway email
gmail_password = <PASSWORD> # throwaway email password
to = [throwaway_email] # target email (same as throwaway)
smtpserver = smtplib.SMTP('smtp.gmail.com', 587) # Server to use.
arg = 'hostname' # Linux command to retrieve device's name
# Runs 'arg' in a hidden terminal.
p = subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE)
data = p.communicate() # Get data from 'p terminal'.
# Parse out device name
name_lines = data[0].splitlines()
name_line = name_lines[0].split()
name = name_line[0]
device = '%s' % (name.decode())
arg = 'hostname -I' # Linux command to retrieve ip addresses
# Runs 'arg' in a hidden terminal.
p = subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE)
data = p.communicate() # Get data from 'p terminal'.
# Parse out ip address of device
ip_lines = data[0].splitlines()
split_line = ip_lines[0].split()
ipaddr = split_line[0]
my_ip = '%s' % (ipaddr.decode())
# start communication with server with TLS encryption
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(gmail_user, gmail_password) # log into server
# Creates the text, subject, 'from', and 'to' of the message.
for recipient in to:
msg = MIMEText(my_ip)
msg['Subject'] = 'IP Addr - %s (%s)' % (device, datetime.now().strftime('%d %b %Y at %H:%M:%S'))
msg['From'] = gmail_user
msg['To'] = recipient
# Sends the message
smtpserver.sendmail(gmail_user, [recipient], msg.as_string())
# Closes the smtp server.
smtpserver.quit()
``` |
{
"source": "joebobs0n/StupidHelmet",
"score": 3
} |
#### File: StupidHelmet/other/AndyScratch.py
```python
import numpy as np # used for calculations and array manipulations
import cv2 as cv # used for camera interface and robotic vision
import imutils # used for frame manipulations
# from matplotlib import pyplot as plt
import os # used to change working directory
import sys # used to find working path
import stupid_helmet_helpers as stpdhh # custom supplemental functions/classes
os.chdir(sys.path[0]) # change working directory to script path
# function to close all things and exit script
def quitScript():
cv.destroyAllWindows()
cam_l.release()
cam_r.release()
exit()
# initialize left and right cameras (comment out video feed or camera feed to disable)
cam_l = cv.VideoCapture('test_footage_left.avi')
cam_r = cv.VideoCapture('test_footage_right.avi')
# cam_l = cv.VideoCapture(3)
# cam_r = cv.VideoCapture(2)
# read in left camera intrinsic and distortion parameters
left_params = np.load('stereo_params/left_params.npz')
mat_l = left_params['mat']
dist_l = left_params['dist']
# read in right camera intrinsic and distortion paramters
right_params = np.load('stereo_params/right_params.npz')
mat_r = right_params['mat']
dist_r = right_params['dist']
# read in stereo rectification paramters
rectify = np.load('stereo_params/rectify_params.npz')
R1 = rectify['R1']
R2 = rectify['R2']
P1 = rectify['P1']
P2 = rectify['P2']
# read in one frame from left and right cameras
ret_l, frame_l = cam_l.read()
ret_r, frame_r = cam_r.read()
# check to see if a frame was received --> if not quit script
if ret_l == False:
print('Cannot get frame from left camera. Exiting...')
quitScript()
if ret_r == False:
print('Cannot get frame from right camera. Exiting...')
quitScript()
# frame_l = imutils.rotate_bound(frame_l, 90 * 3) # uncomment if using video feed
# frame_r = imutils.rotate_bound(frame_r, 90 * 1) # uncomment if using video feed
# save shape of read frames
shape_l = tuple(np.flip(np.shape(frame_l)[0:2]))
shape_r = tuple(np.flip(np.shape(frame_r)[0:2]))
# calculate left and right camera remapping
l1, l2 = cv.initUndistortRectifyMap(
mat_l, dist_l, R1, P1, shape_l, cv.CV_32FC1)
r1, r2 = cv.initUndistortRectifyMap(
mat_r, dist_r, R2, P2, shape_r, cv.CV_32FC1)
# create stereo depth map object
stereo = cv.StereoBM_create()
# set parameters
stereo.setBlockSize(21) # size of disparity block detection
stereo.setMinDisparity(4) # minimum disparity. Most use 0.
# the range of allowable disparities -> multiples of 16
stereo.setNumDisparities(112)
# stereo.setPreFilterType(1) # 0 = prefilter to a normalized response, 1 is a x sobel filter
# stereo.setPreFilterSize(21) # The block used for the prefilter
# stereo.setPreFilterCap(32) # Saturation applied after prefiltering
# stereo.setTextureThreshold(1) # The amount of texture necessary for a disparity to be determined (otherwise => blank/black)
# stereo.setUniquenessRatio(1) # The amount of uniqueness required for two competing results for a "winner" to be declared
# Maximum size of a dettached blob to be considered as a "speckle"
stereo.setSpeckleWindowSize(10)
# maximum allowable difference between disparities within speckle window
stereo.setSpeckleRange(45)
while True:
# read out left and right frames
ret_l, frame_l = cam_l.read()
ret_r, frame_r = cam_r.read()
# frame_l = imutils.rotate_bound(frame_l, 90 * 3) # uncomment if using video feed
# frame_r = imutils.rotate_bound(frame_r, 90 * 1) # uncomment if using video feed
# convert left and right frames to grayscale
gray_l = cv.cvtColor(frame_l, cv.COLOR_BGR2GRAY)
gray_r = cv.cvtColor(frame_r, cv.COLOR_BGR2GRAY)
# exit script if either left or right frame not read
if ret_l == False or ret_r == False:
break
# make left and right frames cononical
rectify_l = cv.remap(gray_l, l1, l2, cv.INTER_LINEAR)
rectify_r = cv.remap(gray_r, r1, r2, cv.INTER_LINEAR)
# stack rectified frames side by side for viewing
undistort_hstack = np.hstack([rectify_l, rectify_r])
# show rectified frames
cv.imshow('stereo frames', undistort_hstack)
# calculate depth map in terms of disparity
disparity = stereo.compute(rectify_l, rectify_r)
# display disparity map
cv.imshow('preview', disparity/1024)
# calculate rgb representation to send
ret, rgb_representation = stpdhh.parseDisparityMap(disparity)
# calculate viewer and display
c = 20
disp_partitioned = np.zeros(
(rgb_representation.shape[0]*c, rgb_representation.shape[1]*c, 3))
if ret == True:
for y in range(rgb_representation.shape[0]):
for x in range(rgb_representation.shape[1]):
disp_partitioned[y*c:(y+1)*c-1, x*c:(x+1)*c-1] = np.ones((c-1, c-1, 3)) * np.flip(rgb_representation[y][x])
cv.imshow('led representation', disp_partitioned)
# wait maximum 1 ms to read keystroke
k = cv.waitKey(1) & 0xff
# if escape key read, exit script
if k == 27:
break
# close up and quit
quitScript()
``` |
{
"source": "joebonneau/portfolio_website",
"score": 3
} |
#### File: portfolio_website/api/api.py
```python
import os
from time import time
from datetime import datetime
import json
from github import Github
from dotenv import load_dotenv
import flask
from flask import Flask
load_dotenv()
GITHUB_PAT = os.environ.get("GITHUB_PAT")
app = Flask(__name__)
@app.route("/api/repo")
def get_github_repos():
gh = Github(GITHUB_PAT)
repos = []
for repo in gh.get_user().get_repos():
repos.append(repo.full_name)
return {"repos": repos}
# pygithub for displaying github data?
``` |
{
"source": "joebonneau/spoticli",
"score": 2
} |
#### File: spoticli/spoticli/util.py
```python
import re
import time
from configparser import ConfigParser
from datetime import datetime
from os import mkdir
from pathlib import Path
from time import sleep
from typing import Any, Generator, Optional
import click
from appdirs import user_config_dir
from click.termui import style
from click.types import Choice
from spotipy.client import Spotify
from tabulate import tabulate
from tqdm import tqdm
def add_playlist_to_queue(sp_auth, uri: str, device: Optional[str] = None) -> None:
"""
Adds all tracks from a playlist to the queue.
"""
offset = 0
click.secho("Adding playlist tracks to queue...", fg="magenta")
while True:
playlists_res = sp_auth.playlist_items(
uri, limit=100, fields="items.track.uri", offset=offset
)
for item in tqdm(playlists_res["items"]):
sp_auth.add_to_queue(item["track"]["uri"], device_id=device)
if len(playlists_res) < 100:
break
offset += 100
click.secho("All playlist tracks added successfully!", fg="green")
def add_album_to_queue(
sp_auth: Spotify, uri: str, device: Optional[str] = None
) -> None:
"""
Adds all tracks of an album to the queue.
"""
while True:
tracks_res = sp_auth.album_tracks(uri, limit=50, offset=0)
for track in tqdm(tracks_res["items"]):
sp_auth.add_to_queue(track["uri"], device_id=device)
if len(tracks_res) < 50:
break
click.secho("Album successfully added to the queue.", fg="green")
def get_artist_names(res: dict[str, Any]) -> str:
"""
Retrieves all artist names for a given input to the "album" key of a response.
"""
artists = []
for artist in res["artists"]:
artists.append(artist["name"])
artists_str = ", ".join(artists)
return artists_str
def get_current_playback(res: dict[str, Any], display: bool) -> Optional[dict]:
"""
Retrieves current playback information, parses the json response, and optionally displays
information about the current playback.
"""
playback = None
try:
playback_items = res["item"]
playback_album = playback_items["album"]
playback = {
"artists": get_artist_names(playback_album),
"track_name": playback_items["name"],
"track_uri": playback_items["uri"],
"track_url": playback_items["external_urls"].get("spotify"),
"album_name": playback_album["name"],
"album_type": playback_album["album_type"],
"album_uri": playback_album["uri"],
"album_url": playback_album["external_urls"].get("spotify"),
"release_date": playback_album["release_date"],
"duration": convert_ms(playback_items["duration_ms"]),
"volume": res["device"]["volume_percent"],
"shuffle_state": res["shuffle_state"],
"resuming_disallowed": res["actions"]["disallows"].get("resuming"),
"pausing_disallowed": res["actions"]["disallows"].get("pausing"),
"skip_prev_disallowed": res["actions"]["disallows"].get("skipping_prev"),
}
if display:
track_name = style(playback["track_name"], fg="magenta")
artists_name = style(playback["artists"], fg="green")
album_name = style(playback["album_name"], fg="blue")
album_type = playback["album_type"]
click.secho(
f"Now playing: {track_name} by {artists_name} from the {album_type} {album_name}"
)
click.echo(
f"Duration: {playback['duration']}, Released: {playback['release_date']}"
)
except TypeError:
click.secho("Nothing is currently playing!", fg="red")
return playback
def search_parse(res: dict[str, Any], k: str) -> tuple[list[dict[str, Any]], list[str]]:
items = res[k]["items"]
uris = []
results = []
if k == "albums":
for i, item in enumerate(items):
artists = get_artist_names(item)
name = item["name"]
uris.append(item["uri"])
results.append(
{
"index": i,
"artist(s)": truncate(artists),
"album title": name,
"release date": item["release_date"],
}
)
elif k == "artists":
results = []
for i, item in enumerate(items):
results.append({"index": i, "artist": truncate(item["name"])})
uris.append(item["uri"])
elif k == "playlists":
results = []
for i, item in enumerate(items):
desc = item["description"]
uris.append(item["uri"])
results.append(
{
"index": i,
"name": truncate(item["name"]),
"creator": item["owner"]["display_name"],
"description": truncate(desc),
"tracks": item["tracks"]["total"],
}
)
elif k == "tracks":
results = []
uris = []
for i, item in enumerate(items):
artists = get_artist_names(item)
name = item["name"]
uris.append(item["uri"])
results.append(
{
"index": i,
"name": name,
"duration": convert_ms(item["duration_ms"]),
"artist(s)": truncate(artists),
"album title": item["album"]["name"],
"release date": item["album"]["release_date"],
}
)
return results, uris
def search_proceed(
sp_auth: Spotify,
type_: str,
results: list[dict[str, Any]],
uris: list[str],
device: Optional[str] = None,
) -> None:
click.secho(tabulate(results, headers="keys", tablefmt="github"))
choices = (str(num) for num in range(len(results)))
index = int(
click.prompt(
"Enter the index",
type=Choice(choices), # type: ignore
show_choices=False,
)
)
if type_ != "artist":
action = click.prompt(
"Play now or add to queue?",
type=Choice(("p", "q"), case_sensitive=False),
show_choices=True,
)
if action == "p":
sp_auth.start_playback(uris=[uris[index]], device_id=device)
sleep(0.5)
current_playback = sp_auth.current_playback()
get_current_playback(current_playback, display=True)
else:
if type_ == "album":
add_album_to_queue(sp_auth, uris[index], device=device)
elif type_ == "playlist":
confirmation = click.prompt(
f"Are you sure you want to add all {results[index]['tracks']} tracks?",
type=Choice(("y", "n"), case_sensitive=False),
show_choices=True,
)
if confirmation == "y":
add_playlist_to_queue(sp_auth, uris[index], device=device)
else:
click.secho("Operation aborted.", fg="red")
elif type_ == "track":
sp_auth.add_to_queue(uris[index], device_id=device)
click.secho("Track added to queue successfully!", fg="green")
elif type_ == "artist":
album_or_track = click.prompt(
"View artist albums or most popular tracks?",
type=Choice(("a", "t"), case_sensitive=False),
show_choices=True,
)
if album_or_track == "a":
artist_albums_res = sp_auth.artist_albums(
uris[index], album_type="album,single"
)
uris, choices = parse_artist_albums(artist_albums_res)
else:
artist_tracks_res = sp_auth.artist_top_tracks(uris[index])
uris, choices = parse_artist_top_tracks(artist_tracks_res)
index = int(
click.prompt(
"Enter the index",
type=Choice(choices), # type: ignore
show_choices=False,
)
)
play_or_queue = click.prompt(
"Play now or add to queue?",
type=Choice(("p", "q"), case_sensitive=False),
show_choices=True,
)
if play_or_queue == "p":
play_content(
sp_auth=sp_auth,
uri=uris[index],
album_or_track=album_or_track,
device_id=device,
)
sleep(0.5)
playback = sp_auth.current_playback()
get_current_playback(playback, display=True)
else:
if album_or_track == "a":
add_album_to_queue(sp_auth, uris[index], device=device)
else:
sp_auth.add_to_queue(uris[index], device_id=device)
click.secho("Successfully added to queue!", fg="green")
def play_content(
sp_auth: Spotify,
uri: str,
album_or_track: str,
device_id: str = None,
):
if album_or_track == "t":
sp_auth.start_playback(uris=[uri], device_id=device_id)
elif album_or_track == "a":
sp_auth.start_playback(context_uri=uri, device_id=device_id)
def convert_ms(duration_ms: int) -> str:
"""
Converts milliseconds to a string representation of a timestamp (MM:SS).
"""
minutes, seconds = divmod(duration_ms / 1000, 60)
rounded_seconds = int(round(seconds, 0))
if rounded_seconds - 10 < 0:
rounded_seconds = "0" + str(rounded_seconds) # type: ignore
duration = f"{int(minutes)}:{rounded_seconds}"
return duration
def convert_timestamp(timestamp: str) -> int:
"""
Converts a timestamp (MM:SS) to milliseconds.
"""
timestamp_list = timestamp.split(":")
minutes = timestamp_list[0]
seconds = timestamp_list[1]
minutes_in_ms = int(minutes) * 60 * 1000
seconds_in_ms = int(seconds) * 1000
total_ms = minutes_in_ms + seconds_in_ms
if any((len(seconds) > 2, len(seconds) < 2, minutes_in_ms < 0, seconds_in_ms < 0)):
raise ValueError("Invalid format. Proper format is MM:SS.")
return total_ms
def convert_datetime(datetime_str: str) -> int:
"""
Converts a string representation of a datetime (YYYYMMDD HH:MM) to milliseconds
"""
datetime_pattern = "%Y%m%d %H:%M"
datetime_obj = datetime.strptime(datetime_str, datetime_pattern)
unix_timestamp = time.mktime(datetime_obj.timetuple()) * 1000
return int(unix_timestamp)
def truncate(name: str, length: int = 50) -> str:
"""
Truncates a string and adds an elipsis if it exceeds the specified length. Otherwise, return the unmodified string.
"""
if len(name) > length:
name = name[0:length] + "..."
return name
def check_url_format(url: str) -> str:
"""
Performs a simple URL validation check. Definitely won't catch all errors, but will eliminate most.
"""
pattern = r"open.spotify.com/[a-z]{5,8}/\w{22}"
match = re.search(pattern, url)
if not match:
raise ValueError
return "https://" + match.group()
def parse_recent_playback(
res: dict[str, Any]
) -> tuple[list[int], dict[str, list], list[str]]:
"""
Parses the response returned by Spotify.current_user_recently_played and displays a table of information.
"""
positions = []
track_names = []
track_uris = []
album_names = []
album_uris = []
album_types = []
timestamps = []
playback_items = res["items"]
for i, item in enumerate(playback_items):
positions.append(i)
track_names.append(item["track"]["name"])
track_uris.append(item["track"]["uri"])
album_names.append(item["track"]["album"]["name"])
album_uris.append(item["track"]["album"]["uri"])
album_types.append(item["track"]["album"]["album_type"])
timestamps.append(item["played_at"])
recent_dict = {
"index": positions,
"track_name": track_names,
"track_uri": track_uris,
"album_name": album_names,
"album_uri": album_uris,
"album_type": album_types,
"timestamp": timestamps,
}
display_dict = dict(
(k, recent_dict[k])
for k in ("index", "track_name", "album_type", "album_name", "timestamp")
)
click.echo(tabulate(display_dict, headers="keys", tablefmt="github"))
return positions, recent_dict, track_uris
def parse_artist_top_tracks(
res: dict[str, Any]
) -> tuple[list[str], Generator[str, None, None]]:
"""
Parses the response returned by Spotify.artist_top_tracks and displays a table of information.
"""
tracks = []
uris = []
for i, track in enumerate(res["tracks"]):
tracks.append(
{
"index": i,
"name": track["name"],
"artists": get_artist_names(track["album"]),
"popularity": track["popularity"],
}
)
uris.append(track["uri"])
click.echo(tabulate(tracks, headers="keys", tablefmt="github"))
choices = (str(num) for num in range(len(tracks)))
return uris, choices
def parse_artist_albums(
res: dict[str, Any]
) -> tuple[list[str], Generator[str, None, None]]:
"""
Parses the response returned by Spotify.artist_albums and displays a table of information.
"""
albums = []
uris = []
for i, item in enumerate(res["items"]):
album_type = item["album_type"]
artists = truncate(get_artist_names(item))
album_name = item["name"]
release_date = item["release_date"]
total_tracks = item["total_tracks"]
uris.append(item["uri"])
albums.append(
{
"index": i,
"artist(s)": artists,
"album name": album_name,
"album type": album_type,
"tracks": total_tracks,
"release date": release_date,
}
)
click.echo(tabulate(albums, headers="keys", tablefmt="github"))
choices = (str(num) for num in range(len(albums)))
return uris, choices
def generate_config():
config_dir = Path(user_config_dir()) / "spoticli"
config_file = config_dir / "spoticli.ini"
config = ConfigParser()
if not config_dir.exists():
mkdir(config_dir)
client_id = click.prompt(
"Provide the Spotify client ID from the developer dashboard"
)
client_secret = click.prompt(
"Provide the Spotify client secret from the developer dashboard"
)
redirect_uri = click.prompt("Provide the redirect uri specified in the Spotify app")
user_id = click.prompt("Provide the Spotify user ID")
config["auth"] = {
"SPOTIFY_CLIENT_ID": client_id,
"SPOTIFY_CLIENT_SECRET": client_secret,
"SPOTIFY_USER_ID": user_id,
"SPOTIFY_REDIRECT_URI": redirect_uri,
}
with open(config_file, "w") as cfg:
config.write(cfg)
click.secho("Config file created successfully!", fg="green")
```
#### File: tests/integration/test_commands.py
```python
import os
from click.testing import CliRunner
from spoticli.spoticli import main
SPOTIFY_DEVICE_ID = os.environ.get("SPOTIFY_DEVICE_ID")
def test_play():
runner = CliRunner()
result = runner.invoke(main, ["play", f"--device={SPOTIFY_DEVICE_ID}"])
assert "Now playing:" in result.output
def test_next_track():
runner = CliRunner()
result = runner.invoke(main, ["next", f"--device={SPOTIFY_DEVICE_ID}"])
assert "Now playing:" in result.output
def test_previous_track():
runner = CliRunner()
result = runner.invoke(main, ["prev", f"--device={SPOTIFY_DEVICE_ID}"])
assert "Now playing:" in result.output
def test_seek():
runner = CliRunner()
result = runner.invoke(main, ["seek", "00:10", f"--device={SPOTIFY_DEVICE_ID}"])
assert result.output == ""
def test_pause():
runner = CliRunner()
result = runner.invoke(main, ["pause", f"--device={SPOTIFY_DEVICE_ID}"])
assert "Playback paused." in result.output
def test_voldown():
runner = CliRunner()
result = runner.invoke(main, ["volup", "50", f"--device={SPOTIFY_DEVICE_ID}"])
assert "New volume:" in result.output
def test_volup():
runner = CliRunner()
result = runner.invoke(main, ["volup", "50", f"--device={SPOTIFY_DEVICE_ID}"])
assert "New volume:" in result.output
def test_now():
runner = CliRunner()
result = runner.invoke(main, ["now"])
assert "Released:" in result.output
def test_now_verbose():
runner = CliRunner()
result = runner.invoke(main, ["now", "-v"])
assert "Time signature:" in result.output
def test_add_current_track_to_playlist():
runner = CliRunner()
result = runner.invoke(main, ["actp"], input="0, 1")
assert "was successfully added to all specified playlists!" in result.output
def test_recent_action_play_track():
runner = CliRunner()
inputs = ("y", "p", "0", "t")
result = runner.invoke(
main, ["recent", f"--device={SPOTIFY_DEVICE_ID}"], input="\n".join(inputs)
)
assert "Now playing:" in result.output
def test_recent_action_play_album():
runner = CliRunner()
inputs = ("y", "p", "0", "a")
result = runner.invoke(
main, ["recent", f"--device={SPOTIFY_DEVICE_ID}"], input="\n".join(inputs)
)
assert "Now playing:" in result.output
def test_recent_action_queue_track():
runner = CliRunner()
inputs = ("y", "q", "0", "t")
result = runner.invoke(
main, ["recent", f"--device={SPOTIFY_DEVICE_ID}"], input="\n".join(inputs)
)
assert "Track successfully added to the queue." in result.output
def test_recent_action_queue_album():
runner = CliRunner()
inputs = ("y", "q", "0", "a")
result = runner.invoke(
main, ["recent", f"--device={SPOTIFY_DEVICE_ID}"], input="\n".join(inputs)
)
assert "Album successfully added to the queue." in result.output
def test_recent_action_create_playlist():
runner = CliRunner()
inputs = ("y", "cp", "0, 5", "recent_test")
result = runner.invoke(
main, ["recent", f"--device={SPOTIFY_DEVICE_ID}"], input="\n".join(inputs)
)
assert "Playlist 'recent_test' created successfully!" in result.output
def test_shuffle_on():
runner = CliRunner()
result = runner.invoke(main, ["shuffle", "-on", f"--device={SPOTIFY_DEVICE_ID}"])
assert "Shuffle toggled on" in result.output
def test_shuffle_off():
runner = CliRunner()
result = runner.invoke(main, ["shuffle", "-off", f"--device={SPOTIFY_DEVICE_ID}"])
assert "Shuffle toggled off" in result.output
def test_create_playlist_valid_inputs():
runner = CliRunner()
playlist_name = "test_playlist"
result = runner.invoke(main, ["cp", "-pub", "-i", playlist_name])
assert f"Playlist '{playlist_name}' created successfully!" in result.output
def test_create_playlist_invalid_inputs():
runner = CliRunner()
playlist_name = "test_playlist"
result = runner.invoke(main, ["cp", "-pub", "-c", playlist_name])
assert "Collaborative playlists can only be private." in result.output
```
#### File: tests/unit/test_util.py
```python
import json
from pathlib import Path
import pytest
from spoticli.util import (
check_url_format,
convert_datetime,
convert_ms,
convert_timestamp,
get_artist_names,
get_current_playback,
search_parse,
truncate,
)
@pytest.fixture(scope="module")
def example_response_data():
path = Path("tests/unit/artifacts/current_playback_res.json")
with open(path) as f:
res = json.load(f)
return res
def test_get_artist_names(example_response_data):
artist_names = get_artist_names(example_response_data["item"])
assert artist_names == "Durand Jones & The Indications, <NAME>"
def test_get_current_playback(example_response_data):
playback = get_current_playback(example_response_data, False)
response = {
"album_name": "Private Space",
"album_type": "album",
"album_uri": "spotify:album:4ogV05oprfriua7n9icbvN",
"album_url": "https://open.spotify.com/album/4ogV05oprfriua7n9icbvN",
"artists": "Durand Jones & The Indications",
"duration": "3:45",
"pausing_disallowed": None,
"release_date": "2021-07-30",
"resuming_disallowed": True,
"shuffle_state": False,
"skip_prev_disallowed": True,
"track_name": "Love Will Work It Out",
"track_uri": "spotify:track:6qXQYEZeRSgmAvDm4ZEAUZ",
"track_url": "https://open.spotify.com/track/6qXQYEZeRSgmAvDm4ZEAUZ",
"volume": 100,
}
assert playback == response
def test_convert_ms():
assert convert_ms(225461) == "3:45"
assert convert_ms(600000) == "10:00"
def test_convert_timestamp():
assert convert_timestamp("3:45") == 225000
assert convert_timestamp("10:00") == 600000
@pytest.mark.xfail(reason="returns the wrong value in CI for some reason")
def test_convert_datetime():
assert convert_datetime("20210813 20:01") == 1628910060000
assert convert_datetime("20200403 13:37") == 1585946220000
def test_truncate():
artists_str = "<NAME> & The Indications, <NAME>"
assert truncate(artists_str, 40) == "<NAME> & The Indications, <NAME>..."
assert truncate(artists_str, 35) == "<NAME> & The Indications, Aar..."
assert truncate(artists_str) == "<NAME> & The Indications, <NAME>"
def test_search_parse_album():
path = Path("tests/unit/artifacts/search_album_res.json")
f = open(path)
res = json.load(f)
actual_results, actual_uris = search_parse(res, "albums")
results = [
{
"index": 0,
"artist(s)": "Nas",
"album title": "Illmatic",
"release date": "1994-04-19",
},
{
"index": 1,
"artist(s)": "Nas",
"album title": "Illmatic XX",
"release date": "2014-04-15",
},
{
"index": 2,
"artist(s)": "Nas",
"album title": "Illmatic",
"release date": "1994-04-19",
},
{
"index": 3,
"artist(s)": "Nas",
"album title": "Illmatic: Live from the Kennedy Center with the National Symphony Orchestra",
"release date": "2018-04-20",
},
{
"index": 4,
"artist(s)": "golden era",
"album title": "illmatic (lofi beats)",
"release date": "2020-03-13",
},
{
"index": 5,
"artist(s)": "Various Artists",
"album title": "10 Year Anniversary Illmatic Platinum Series",
"release date": "2004",
},
{
"index": 6,
"artist(s)": "<NAME>, <NAME>",
"album title": "TOP OF TOKYO/TT2 オワリのうた",
"release date": "2006-11-29",
},
{
"index": 7,
"artist(s)": "<NAME>",
"album title": "L.S.D",
"release date": "2021-04-09",
},
{
"index": 8,
"artist(s)": "Nas",
"album title": "Stillmatic",
"release date": "2001-12-18",
},
{
"index": 9,
"artist(s)": "Nas",
"album title": "From Illmatic To Stillmatic The Remixes",
"release date": "2002-07-02",
},
]
uris = [
"spotify:album:3kEtdS2pH6hKcMU9Wioob1",
"spotify:album:6oSHgr3TZJPCFshYUfBDqE",
"spotify:album:4Ylo6qvhUY2h7VqEJHfYcy",
"spotify:album:1Xd9sCWxvNx02wCTZbKoek",
"spotify:album:6YiJxfK69jd89oUyk7CeQ3",
"spotify:album:6rXstoVf7abF1VyuYRzxBw",
"spotify:album:68ug5BwUWtP1OAzq8AlMUT",
"spotify:album:7iDV5POx4lTm2LHHxSSgyT",
"spotify:album:0cLzuJG2UDa0axMQkF7JR6",
"spotify:album:32zX5u2pOCNNxzO2BAyGfd",
]
assert actual_uris == uris
assert actual_results == results
def test_search_parse_artist():
path = Path("tests/unit/artifacts/search_artist_res.json")
f = open(path)
res = json.load(f)
actual_results, actual_uris = search_parse(res, "artists")
results = [
{"index": 0, "artist": "A Tribe Called Quest"},
{"index": 1, "artist": "A Tribe Called Quest"},
]
uris = [
"spotify:artist:09hVIj6vWgoCDtT03h8ZCa",
"spotify:artist:2NQZmi2vNrB09no3wbNuJC",
]
assert actual_uris == uris
assert actual_results == results
def test_search_parse_playlist():
path = Path("tests/unit/artifacts/search_playlist_res.json")
f = open(path)
res = json.load(f)
actual_results, actual_uris = search_parse(res, "playlists")
results = [
{
"index": 0,
"name": "Groovin', Pt. 1 (2020)",
"creator": "Soul Dialect",
"description": "",
"tracks": 18,
},
{
"index": 1,
"name": "Groovin on a Sunday Afternoon",
"creator": "<NAME>",
"description": "",
"tracks": 635,
},
{
"index": 2,
"name": "<NAME>",
"creator": "Spotify",
"description": "R&Bの最新話題曲をまとめてお届けします。cover: ティナーシェ",
"tracks": 60,
},
{
"index": 3,
"name": "Groovin', Pt. 2 (2020)",
"creator": "Soul Dialect",
"description": "",
"tracks": 93,
},
{
"index": 4,
"name": "<NAME>",
"creator": "<NAME>",
"description": "Grooving Tunes to get you through the weekend! Fea...",
"tracks": 154,
},
{
"index": 5,
"name": "Cruise And Play: Groovin' Soul Classics",
"creator": "PlayStation®️",
"description": "The greatest old school jams. Cruise down the virt...",
"tracks": 201,
},
{
"index": 6,
"name": "<NAME> - Groovin' – Desconocidos",
"creator": "Acarlosbriones",
"description": "",
"tracks": 37,
},
{
"index": 7,
"name": "Groovin', Pt. 2 - Proto",
"creator": "Soul Dialect",
"description": "",
"tracks": 90,
},
{
"index": 8,
"name": "Groovin' ",
"creator": "<NAME>",
"description": "",
"tracks": 186,
},
{
"index": 9,
"name": "Groovin', Pt. 3 (2020)",
"creator": "Soul Dialect",
"description": "",
"tracks": 80,
},
]
uris = [
"spotify:playlist:0oQE11XvrxWXK2a4CVRN3q",
"spotify:playlist:4ATaA5T1ZUmY1fzJyMBr3P",
"spotify:playlist:37i9dQZF1DX4CB6zI8FWXS",
"spotify:playlist:1qQFW19QP5LqZFSeJtl0NH",
"spotify:playlist:1W0lsTd8R0WbmnZg3rQmcg",
"spotify:playlist:6y5ldR0UFhVs1lqWhy6Pva",
"spotify:playlist:2mkeaNza52gcLpg5YrW9bg",
"spotify:playlist:2EKsFAissZHtRZkSv3oa7H",
"spotify:playlist:0J1euUuaGror5gPvQ8UIyY",
"spotify:playlist:5SmXvDdhGY7VOQNrMMZqRq",
]
assert actual_uris == uris
assert actual_results == results
def test_search_parse_track():
path = Path("tests/unit/artifacts/search_track_res.json")
f = open(path)
res = json.load(f)
actual_results, actual_uris = search_parse(res, "tracks")
results = [
{
"index": 0,
"name": "September",
"duration": "3:35",
"artist(s)": "Earth, Wind & Fire",
"album title": "The Best Of Earth, Wind & Fire Vol. 1",
"release date": "1978-11-23",
},
{
"index": 1,
"name": "September",
"duration": "3:41",
"artist(s)": "<NAME>",
"album title": "September",
"release date": "2021-06-11",
},
{
"index": 2,
"name": "<NAME>",
"duration": "3:40",
"artist(s)": "<NAME>",
"album title": "Raised Under Grey Skies (Deluxe)",
"release date": "2017-10-06",
},
{
"index": 3,
"name": "Wake Me up When September Ends",
"duration": "4:46",
"artist(s)": "Green Day",
"album title": "American Idiot",
"release date": "2004-09-21",
},
{
"index": 4,
"name": "September Rain - 2020 Remaster",
"duration": "4:32",
"artist(s)": "<NAME>",
"album title": "COLLECTION",
"release date": "2020-03-25",
},
{
"index": 5,
"name": "<NAME> - <NAME>",
"duration": "3:32",
"artist(s)": "<NAME>",
"album title": "Sleepy Sleep",
"release date": "2021-08-13",
},
{
"index": 6,
"name": "September",
"duration": "3:35",
"artist(s)": "Earth, Wind & Fire",
"album title": "September",
"release date": "2018-04-17",
},
{
"index": 7,
"name": "<NAME>",
"duration": "4:10",
"artist(s)": "Russ",
"album title": "September 16",
"release date": "2018-07-20",
},
{
"index": 8,
"name": "<NAME> (Live at Tushino Airfield, Moscow, Russia - September 28th, 1991)",
"duration": "5:21",
"artist(s)": "Metallica",
"album title": "Nothing Else Matters (Orchestra/Clean Guitar/Vocal Mix - July 8th, 1991)",
"release date": "2021-08-12",
},
{
"index": 9,
"name": "September",
"duration": "4:04",
"artist(s)": "Daughtry",
"album title": "It's Not Over....The Hits So Far",
"release date": "2016-02-12",
},
]
uris = [
"spotify:track:2grjqo0Frpf2okIBiifQKs",
"spotify:track:0exZ0YogJPbjGzblpcZaw7",
"spotify:track:0zbzrhfVS9S2TszW3wLQZ7",
"spotify:track:3ZffCQKLFLUvYM59XKLbVm",
"spotify:track:6A9YFkei6zWfPSxWxlBecY",
"spotify:track:3W116J45gzALWG50HZngHl",
"spotify:track:7Cuk8jsPPoNYQWXK9XRFvG",
"spotify:track:7a5RvlW5tMU0AZ4tvbGLhn",
"spotify:track:3tsxiCcQiPL5Ay8Sw4w3tu",
"spotify:track:2ikUwLex9wXpIOEgY45Wk7",
]
assert actual_uris == uris
assert actual_results == results
def test_check_url_format_valid():
track_url = (
"https://open.spotify.com/track/464BrxdI2djpYOUoXol3cQ?si=8757bf6f2e5a4120"
)
album_url = "https://open.spotify.com/album/4XF4TSU1Z8FvA52wvZqrQ5?si=0l5T5q6BQfKacmPF9hjpXg&dl_branch=1"
playlist_url = (
"https://open.spotify.com/playlist/5fArw51CQey2sVuS6SULxl?si=9b4f62b39b3a4a6d"
)
assert check_url_format(track_url)
assert check_url_format(album_url)
assert check_url_format(playlist_url)
def test_check_url_format_invalid():
url_1 = "https://open.spotify.com/track/464Br"
url_2 = "https://close.spotify.com/album/4XF4TSU1Z8FvA52wvZqrQ5?si=0l5T5q6BQfKacmPF9hjpXg&dl_branch=1"
with pytest.raises(ValueError):
check_url_format(url_1)
with pytest.raises(ValueError):
check_url_format(url_2)
``` |
{
"source": "joebonomo/flask-sherlock-1",
"score": 4
} |
#### File: flask-sherlock-1/app/rengine.py
```python
import random
class Sherlock():
"""
Movies recommendation engine.
"""
def __init__(self, movies, features):
self.movies = movies
self.title = features.get("title")
self.features = ["genre", "stars"]
def recommend(self):
"""
Algorithm recommends movies based on default movie features.
The algorithm uses partial match as search criteria and returns sorted list of movie(s).
"""
ref_movie = self.__get_movie(self.title)
if not ref_movie:
return self.__lucky_recommendation(self.movies)
ref_movie = ref_movie[0]
movies = []
for movie in self.movies:
if movie["title"] != self.title:
for feature in self.features:
feature_match = [fm in movie[feature] for fm in ref_movie[feature]]
if any(feature_match):
movies.append(movie)
break
return sorted(movies, key=lambda movie: movie["rating"], reverse=True)
def __lucky_recommendation(self, movies):
"""
I feel lucky - random choice.
"""
return [random.choice(movies)]
def __get_movie(self, title):
"""
Find movie by title.
"""
movie = [movie for movie in self.movies if movie["title"] == title]
return movie if movie else []
``` |
{
"source": "joebordes/ADOdb",
"score": 2
} |
#### File: ADOdb/scripts/buildrelease.py
```python
import errno
import getopt
import re
import os
from os import path
import shutil
import subprocess
import sys
import tempfile
import updateversion
# ADOdb Repository reference
origin_repo = "https://github.com/ADOdb/ADOdb.git"
release_branch = "master"
release_prefix = "adodb"
# Directories and files to exclude from release tarballs
# For consistency, this should match the list in .gitattributes
exclude_list = (".git*",
".mailmap",
"replicate",
"scripts",
"tests",
"cute_icons_for_site",
".idea",
)
# Command-line options
options = "hb:dfk"
long_options = ["help", "branch=", "debug", "fresh", "keep"]
# Global flags
debug_mode = False
fresh_clone = False
cleanup = True
def usage():
"""
Print script's command-line arguments help.
"""
print('''Usage: {} [options] version release_path
Parameters:
version ADOdb version to bundle (e.g. v5.19)
release_path Where to save the release tarballs
Options:
-h | --help Show this usage message
-b | --branch <branch> Use specified branch (defaults to '{}' for '.0'
releases, or 'hotfix/<version>' for patches)
-d | --debug Debug mode (ignores upstream: no fetch, allows
build even if local branch is not in sync)
-f | --fresh Create a fresh clone of the repository
-k | --keep Keep build directories after completion
(useful for debugging)
'''.format(
path.basename(__file__),
release_branch
))
# end usage()
def set_version_and_tag(version):
global release_branch, debug_mode, fresh_clone, cleanup
# Delete existing tag to force creation in debug mode
if debug_mode:
try:
updateversion.tag_delete(version)
except subprocess.CalledProcessError:
pass
# Checkout release branch
subprocess.call("git checkout {}".format(release_branch), shell=True)
if not debug_mode:
# Make sure we're up-to-date, ignore untracked files
ret = subprocess.check_output(
"git status --branch --porcelain --untracked-files=no",
text=True,
shell=True
)
if not re.search(release_branch + "$", ret):
print("\nERROR: branch must be aligned with upstream")
sys.exit(4)
# Update the code, create commit and tag
updateversion.version_set(version)
# Make sure we don't delete the modified repo
if fresh_clone:
cleanup = False
def main():
global release_branch, debug_mode, fresh_clone, cleanup
# Get command-line options
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], options, long_options)
except getopt.GetoptError as err:
print(str(err))
usage()
sys.exit(2)
if len(args) < 2:
usage()
print("ERROR: please specify the version and release_path")
sys.exit(1)
for opt, val in opts:
if opt in ("-h", "--help"):
usage()
sys.exit(0)
elif opt in ("-b", "--branch"):
release_branch = val
elif opt in ("-d", "--debug"):
debug_mode = True
elif opt in ("-f", "--fresh"):
fresh_clone = True
elif opt in ("-k", "--keep"):
cleanup = False
# Mandatory parameters
version = updateversion.version_check(args[0])
release_path = args[1]
# Default release branch
if updateversion.version_is_patch(version):
release_branch = 'hotfix/' + version.rsplit('.', 1)[0]
# -------------------------------------------------------------------------
# Start the build
#
global release_prefix
print("Building ADOdb release {} into '{}'\n".format(
version,
release_path
))
if debug_mode:
print("DEBUG MODE: ignoring upstream repository status")
if fresh_clone:
# Create a new repo clone
print("Cloning a new repository")
repo_path = tempfile.mkdtemp(prefix=release_prefix + "-",
suffix=".git")
subprocess.call(
"git clone {} {}".format(origin_repo, repo_path),
shell=True
)
os.chdir(repo_path)
else:
# Git repo's root directory
repo_path = updateversion.git_root()
os.chdir(repo_path)
# Check for any uncommitted changes
try:
subprocess.check_output(
"git diff --exit-code && "
"git diff --cached --exit-code",
shell=True
)
except subprocess.CalledProcessError:
print("ERROR: there are uncommitted changes in the repository")
sys.exit(3)
# Update the repository
if not debug_mode:
print("Updating repository in '{}'".format(os.getcwd()))
try:
subprocess.check_output("git fetch", shell=True)
except subprocess.CalledProcessError:
print("ERROR: unable to fetch\n")
sys.exit(3)
# Check existence of Tag for version in repo, create if not found
try:
updateversion.tag_check(version)
if debug_mode:
set_version_and_tag(version)
except subprocess.CalledProcessError:
set_version_and_tag(version)
# Copy files to release dir
release_files = release_prefix + version.split(".")[0]
release_tmp_dir = path.join(release_path, release_files)
print("Copying release files to '{}'".format(release_tmp_dir))
retry = True
while True:
try:
shutil.copytree(
repo_path,
release_tmp_dir,
ignore=shutil.ignore_patterns(*exclude_list)
)
break
except OSError as err:
# First try and file exists, try to delete dir
if retry and err.errno == errno.EEXIST:
print("WARNING: Directory '{}' exists, delete it and retry"
.format(release_tmp_dir))
shutil.rmtree(release_tmp_dir)
retry = False
continue
else:
# We already tried to delete or some other error occurred
raise
# Create tarballs
print("Creating release tarballs...")
release_name = release_prefix + '-' + version
os.chdir(release_path)
print("- tar")
subprocess.call(
"tar -czf {}.tar.gz {}".format(release_name, release_files),
shell=True
)
print("- zip")
subprocess.call(
"zip -rq {}.zip {}".format(release_name, release_files),
shell=True
)
if cleanup:
print("Deleting working directories")
shutil.rmtree(release_tmp_dir)
if fresh_clone:
shutil.rmtree(repo_path)
else:
print("\nThe following working directories were kept:")
if fresh_clone:
print("- '{}' (repo clone)".format(repo_path))
print("- '{}' (release temp dir)".format(release_tmp_dir))
print("Delete them manually when they are no longer needed.")
# Done
print("\nADOdb release {} build complete, files saved in '{}'.".format(
version,
release_path
))
print("Don't forget to generate a README file with the changelog")
# end main()
if __name__ == "__main__":
main()
``` |
{
"source": "joebos/django-allauth",
"score": 3
} |
#### File: providers/etsy/views.py
```python
import json
from allauth.socialaccount.providers.oauth.client import OAuth
from allauth.socialaccount.providers.oauth.views import (OAuthAdapter,
OAuthLoginView,
OAuthCallbackView)
from .provider import EtsyProvider
class EtsyAPI(OAuth):
"""
Verifying twitter credentials
"""
url = 'https://openapi.etsy.com/v2/users/__SELF__'
url_avatar = 'https://openapi.etsy.com/v2/users/__SELF__/avatar/src'
url_shops = 'https://openapi.etsy.com/v2/users/__SELF__/shops'
url_profile = 'https://openapi.etsy.com/v2/users/__SELF__/profile'
def get_user_info(self):
user = json.loads(self.query(self.url))
#user_avatar = json.loads(self.query(self.url_avatar))
user_shops = json.loads(self.query(self.url_shops))
user_profile = json.loads(self.query(self.url_profile))
data = {"user": user["results"][0], "profile": user_profile["results"][0], "shops": user_shops["results"]}
return data
class EtsyOAuthAdapter(OAuthAdapter):
provider_id = EtsyProvider.id
request_token_url = 'https://openapi.etsy.com/v2/oauth/request_token'
access_token_url = 'https://openapi.etsy.com/v2/oauth/access_token'
# Issue #42 -- this one authenticates over and over again...
# authorize_url = 'https://api.twitter.com/oauth/authorize'
authorize_url = 'https://www.etsy.com/oauth/signin'
def complete_login(self, request, app, token):
client = EtsyAPI(request, app.client_id, app.secret,
self.request_token_url)
extra_data = client.get_user_info()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth_login = OAuthLoginView.adapter_view(EtsyOAuthAdapter)
oauth_callback = OAuthCallbackView.adapter_view(EtsyOAuthAdapter)
``` |
{
"source": "joebos/django-cbv-contact-form",
"score": 2
} |
#### File: contact_form/models/subject.py
```python
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.models import Site
from django.utils.encoding import python_2_unicode_compatible
from contact_form.conf import settings
from contact_form.models.department import Department
@python_2_unicode_compatible
class Subject(models.Model):
title = models.CharField(max_length=settings.CONTACT_FORM_SUBJECT_MAX_LENGTH)
department = models.ForeignKey(Department)
description = models.TextField(blank=True)
site = models.ForeignKey(Site, null=True, blank=True)
def __str__(self):
return self.title
class Meta:
app_label = 'contact_form'
verbose_name = _('Subject')
verbose_name_plural = _('Subjects')
``` |
{
"source": "joebos/django-cookies-samesite",
"score": 2
} |
#### File: django-cookies-samesite/tests/test_middleware.py
```python
import unittest
from mock import patch
import django
from ddt import ddt, data
from django.test import TestCase
from django_cookies_samesite.middleware import DJANGO_SUPPORTED_VERSION
@ddt
class CookiesSamesiteTests(TestCase):
@unittest.skipIf(django.get_version() >= DJANGO_SUPPORTED_VERSION, 'should skip if Django already supports')
def test_cookie_samesite_strict(self):
with self.settings(SESSION_COOKIE_SAMESITE='strict'):
response = self.client.get('/cookies-test/')
self.assertEqual(response.cookies['sessionid']['samesite'], 'strict')
self.assertEqual(response.cookies['csrftoken']['samesite'], 'strict')
csrf_token = response.cookies['csrftoken']
session_id = response.cookies['sessionid']
cookies_string = sorted(response.cookies.output().split('\r\n'))
self.assertTrue('csrftoken=', cookies_string[0])
self.assertTrue('; SameSite=strict', cookies_string[0])
self.assertTrue('sessionid=', cookies_string[2])
self.assertTrue('; SameSite=strict', cookies_string[2])
@unittest.skipIf(django.get_version() >= DJANGO_SUPPORTED_VERSION, 'should skip if Django already supports')
def test_cookie_samesite_lax(self):
with self.settings(SESSION_COOKIE_SAMESITE='lax'):
response = self.client.get('/cookies-test/')
self.assertEqual(response.cookies['sessionid']['samesite'], 'lax')
self.assertEqual(response.cookies['csrftoken']['samesite'], 'lax')
cookies_string = sorted(response.cookies.output().split('\r\n'))
self.assertTrue('csrftoken=' in cookies_string[0])
self.assertTrue('; SameSite=lax' in cookies_string[0])
self.assertTrue('sessionid=' in cookies_string[2])
self.assertTrue('; SameSite=lax' in cookies_string[2])
@unittest.skipIf(django.get_version() >= DJANGO_SUPPORTED_VERSION, 'should skip if Django already supports')
def test_cookie_samesite_none(self):
with self.settings(SESSION_COOKIE_SAMESITE='none'):
response = self.client.get('/cookies-test/')
self.assertEqual(response.cookies['sessionid']['samesite'], 'none')
self.assertEqual(response.cookies['csrftoken']['samesite'], 'none')
cookies_string = sorted(response.cookies.output().split('\r\n'))
self.assertTrue('csrftoken=' in cookies_string[0])
self.assertTrue('; SameSite=none' in cookies_string[0])
self.assertTrue('sessionid=' in cookies_string[2])
self.assertTrue('; SameSite=none' in cookies_string[2])
with self.settings(SESSION_COOKIE_SAMESITE='none', SESSION_COOKIE_SAMESITE_FORCE_ALL=True):
response = self.client.get('/cookies-test/')
self.assertEqual(response.cookies['sessionid']['samesite'], 'none')
self.assertEqual(response.cookies['csrftoken']['samesite'], 'none')
self.assertEqual(response.cookies['custom_cookie']['samesite'], 'none')
self.assertEqual(response.cookies['zcustom_cookie']['samesite'], 'none')
cookies_string = sorted(response.cookies.output().split('\r\n'))
self.assertTrue('custom_cookie=' in cookies_string[1])
self.assertTrue('; SameSite=none' in cookies_string[1])
self.assertTrue('csrftoken=' in cookies_string[0])
self.assertTrue('; SameSite=none' in cookies_string[0])
self.assertTrue('sessionid=' in cookies_string[2])
self.assertTrue('; SameSite=none' in cookies_string[2])
self.assertTrue('zcustom_cookie=' in cookies_string[3])
self.assertTrue('; SameSite=none' in cookies_string[3])
@unittest.skipIf(django.get_version() < DJANGO_SUPPORTED_VERSION, 'should skip if Django does not support')
def test_cookie_samesite_django30(self):
# Raise DeprecationWarning for newer versions of Django
with patch('django.get_version', return_value=DJANGO_SUPPORTED_VERSION):
with self.assertRaises(DeprecationWarning) as exc:
self.client.get('/cookies-test/')
# print(exc.exception.args)
self.assertEqual(exc.exception.args[0], (
'Your version of Django supports SameSite flag in the cookies mechanism. '
'You should remove django-cookies-samesite from your project.'
))
with patch('django_cookies_samesite.middleware.django.get_version', return_value=DJANGO_SUPPORTED_VERSION):
with self.assertRaises(DeprecationWarning) as exc:
self.client.get('/cookies-test/')
self.assertEqual(exc.exception.args[0], (
'Your version of Django supports SameSite flag in the cookies mechanism. '
'You should remove django-cookies-samesite from your project.'
))
@unittest.skipIf(django.get_version() >= DJANGO_SUPPORTED_VERSION, 'should skip if Django already supports')
def test_cookie_samesite_custom_cookies(self):
# Middleware shouldn't accept malformed settings
with self.settings(
SESSION_COOKIE_SAMESITE='lax',
SESSION_COOKIE_SAMESITE_KEYS='something'
):
with self.assertRaises(ValueError) as exc:
self.client.get('/cookies-test/')
self.assertEqual(exc.exception.args[0], 'SESSION_COOKIE_SAMESITE_KEYS should be a list, set or tuple.')
# Test if SameSite flags is set to custom cookies
with self.settings(
SESSION_COOKIE_SAMESITE='lax',
SESSION_COOKIE_SAMESITE_KEYS=('custom_cookie',)
):
response = self.client.get('/cookies-test/')
self.assertEqual(response.cookies['sessionid']['samesite'], 'lax')
self.assertEqual(response.cookies['csrftoken']['samesite'], 'lax')
self.assertEqual(response.cookies['custom_cookie']['samesite'], 'lax')
self.assertEqual(response.cookies['zcustom_cookie']['samesite'], '')
cookies_string = sorted(response.cookies.output().split('\r\n'))
self.assertTrue('custom_cookie=' in cookies_string[1])
self.assertTrue('; SameSite=lax' in cookies_string[1])
self.assertTrue('csrftoken=' in cookies_string[0])
self.assertTrue('; SameSite=lax' in cookies_string[0])
self.assertTrue('sessionid=' in cookies_string[2])
self.assertTrue('; SameSite=lax' in cookies_string[2])
self.assertTrue('zcustom_cookie=' in cookies_string[3])
self.assertTrue('; SameSite=lax' not in cookies_string[3])
@unittest.skipIf(django.get_version() >= DJANGO_SUPPORTED_VERSION, 'should skip if Django already supports')
def test_cookie_samesite_invalid(self):
with self.settings(SESSION_COOKIE_SAMESITE='invalid'):
with self.assertRaises(ValueError) as exc:
self.client.get('/cookies-test/')
self.assertEqual(exc.exception.args[0], 'samesite must be "lax", "none", or "strict".')
@unittest.skipIf(django.get_version() >= DJANGO_SUPPORTED_VERSION, 'should skip if Django already supports')
def test_cookie_samesite_unset(self):
with self.settings(SESSION_COOKIE_SAMESITE=None):
response = self.client.get('/cookies-test/')
print(response.cookies)
self.assertEqual(response.cookies['sessionid'].get('samesite'), '')
self.assertEqual(response.cookies['csrftoken'].get('samesite'), '')
cookies_string = sorted(response.cookies.output().split('\r\n'))
self.assertTrue('csrftoken=' in cookies_string[0])
self.assertTrue('; SameSite=lax' not in cookies_string[0])
self.assertTrue('; SameSite=strict' not in cookies_string[0])
self.assertTrue('sessionid=' in cookies_string[2])
self.assertTrue('; SameSite=lax' not in cookies_string[2])
self.assertTrue('; SameSite=strict' not in cookies_string[2])
@unittest.skipIf(django.get_version() >= DJANGO_SUPPORTED_VERSION, 'should skip if Django already supports')
def test_cookie_names_changed(self):
session_name = 'sessionid-test'
csrf_name = 'csrftoken-test'
with self.settings(
SESSION_COOKIE_NAME=session_name,
CSRF_COOKIE_NAME=csrf_name,
SESSION_COOKIE_SAMESITE='lax'
):
response = self.client.get('/cookies-test/')
self.assertEqual(response.cookies[session_name]['samesite'], 'lax')
self.assertEqual(response.cookies[csrf_name]['samesite'], 'lax')
cookies_string = sorted(response.cookies.output().split('\r\n'))
self.assertTrue(csrf_name + '=' in cookies_string[0])
self.assertTrue('; SameSite=lax' in cookies_string[0])
self.assertTrue(session_name + '=' in cookies_string[2])
self.assertTrue('; SameSite=lax' in cookies_string[2])
@unittest.skipIf(django.get_version() >= DJANGO_SUPPORTED_VERSION, 'should skip if Django already supports')
@data(
# Chrome
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
)
def test_unsupported_browsers(self, ua_string):
session_name = 'sessionid-test'
csrf_name = 'csrftoken-test'
with self.settings(
SESSION_COOKIE_NAME=session_name,
CSRF_COOKIE_NAME=csrf_name,
SESSION_COOKIE_SAMESITE='lax'
):
response = self.client.get(
'/cookies-test/',
HTTP_USER_AGENT=ua_string,
)
self.assertEqual(response.cookies[session_name]['samesite'], '')
self.assertEqual(response.cookies[csrf_name]['samesite'], '')
cookies_string = sorted(response.cookies.output().split('\r\n'))
self.assertTrue('; SameSite=lax' not in cookies_string[0])
self.assertTrue('; SameSite=lax' not in cookies_string[1])
@data(
# Chrome
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.2704.103 Safari/537.36",
# Firefox
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0",
# Internet Explorer
"Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)",
# Safari
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1"
)
@unittest.skipIf(django.get_version() >= DJANGO_SUPPORTED_VERSION, 'should skip if Django already supports')
def test_supported_browsers(self, ua_string):
session_name = 'sessionid-test'
csrf_name = 'csrftoken-test'
with self.settings(
SESSION_COOKIE_NAME=session_name,
CSRF_COOKIE_NAME=csrf_name,
SESSION_COOKIE_SAMESITE='lax'
):
response = self.client.get(
'/cookies-test/',
HTTP_USER_AGENT=ua_string,
)
self.assertEqual(response.cookies[session_name]['samesite'], 'lax')
self.assertEqual(response.cookies[csrf_name]['samesite'], 'lax')
cookies_string = sorted(response.cookies.output().split('\r\n'))
self.assertTrue('; SameSite=lax' in cookies_string[0])
self.assertTrue('; SameSite=lax' in cookies_string[2])
``` |
{
"source": "joebos/django-feedback-form",
"score": 2
} |
#### File: django-feedback-form/feedback_form/forms.py
```python
from django import forms
from django.conf import settings
from django.core.urlresolvers import reverse
#from django_libs.utils_email import send_email
from .models import Feedback
from django.template.loader import render_to_string
from django.template import TemplateDoesNotExist
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.core.mail import get_connection
class FeedbackForm(forms.ModelForm):
"""
A feedback form with modern spam protection.
:url: Field to trap spam bots.
"""
url = forms.URLField(required=False)
def __init__(self, user=None, url=None, prefix='feedback',
content_object=None, *args, **kwargs):
self.content_object = content_object
super(FeedbackForm, self).__init__(prefix='feedback', *args, **kwargs)
if url:
self.instance.current_url = url
if user:
self.instance.user = user
del self.fields['email']
self.instance.email = str(user.email) if hasattr(user, "email") else settings.FROM_EMAIL
else:
self.fields['email'].required = True
def save(self):
if not self.cleaned_data.get('url'):
self.instance.content_object = self.content_object
obj = super(FeedbackForm, self).save()
context = {
'url': reverse('admin:feedback_form_feedback_change',
args=(obj.id, )),
'feedback': obj,
}
self.send_mail(
'feedback_form/email/subject.html',
'feedback_form/email/body.html',
self.instance.email,
[support[1] for support in settings.SUPPORT],
[],
context
)
return obj
class Media:
css = {'all': ('feedback_form/css/feedback_form.css'), }
js = ('feedback_form/js/feedback_form.js', )
class Meta:
model = Feedback
fields = ('email', 'message')
def render_mail_with_template(self, subject_template, body_template, from_email, tos, bccs, context):
"""
Renders an e-mail to `email`. `template_prefix` identifies the
e-mail that is to be sent, e.g. "account/email/email_confirmation"
"""
subject = render_to_string(subject_template, context)
# remove superfluous line breaks
subject = " ".join(subject.splitlines()).strip()
#subject = self.format_email_subject(subject)
bodies = {}
for ext in ['html', 'txt']:
try:
template_name = body_template
bodies[ext] = render_to_string(template_name, context).strip()
except TemplateDoesNotExist:
if ext == 'txt' and not bodies:
# We need at least one body
raise
if 'txt' in bodies:
msg = EmailMultiAlternatives(subject,
bodies['txt'],
from_email=from_email,
to=tos,
bcc=bccs)
if 'html' in bodies:
msg.attach_alternative(bodies['html'], 'text/html')
else:
msg = EmailMessage( subject,
bodies['html'],
from_email=from_email,
to=tos,
bcc=bccs)
msg.content_subtype = 'html' # Main content is now text/html
return msg
def send_mail(self, subject_template, body_template, from_email, tos, bccs, context):
msg = self.render_mail_with_template(subject_template, body_template, from_email, tos, bccs, context)
msg.connection = get_connection('django.core.mail.backends.smtp.EmailBackend')
msg.send()
msg.connection.close()
```
#### File: feedback_form/tests/models_tests.py
```python
from django.test import TestCase
from ..models import Feedback
class FeedbackTestCase(TestCase):
"""Tests for the ``Feedback`` model class."""
longMessage = True
def test_instantiation(self):
"""Test if the ``Feedback`` model instantiates."""
feedback = Feedback()
self.assertTrue(feedback, msg='Should be correctly instantiated.')
``` |
{
"source": "joebowen/channelwormdjango",
"score": 3
} |
#### File: ChannelWorm/cwFitter/Initiator.py
```python
import matplotlib.pyplot as plt
class Initiator(object):
def __init__(self, userData):
"""Initializes variables for other modules
:param user: parameters related to user profile
"""
#TODO: Initialize data provided by user (directly from interface or from DB)
self.sampleData = userData['samples']
self.sim_params = dict() #userData['sim_params']
self.evol_params = dict() # userData['evol_opts']
self.bio_params = dict() #userData['bio_params']
def getBioParameters(self):
"""
Get parameters for cell and channel from user / DB and initialize variables.
"""
#TODO: Get values from pyOW
self.bio_params['cell_type'] = 'ADAL'
self.bio_params['channel_type'] = 'EGL-19'
self.bio_params['ion_type'] = 'Ca'
#Standard spec_cap = 0.01 F/m2
#From <NAME> 2008
self.bio_params['cell_params'] = ['C_mem','area','spec_cap']
self.bio_params['unit_cell_params'] = ['F','m2','F/m2']
self.bio_params['val_cell_params'] = [7.23653e-11,7.23653e-9,0.01]
#self.bio_params['cell_channel_params'] = ['channel_density']
#self.bio_params['unit_cell_channel_params'] = ['1/m2']
#self.bio_params['val_cell_channel_params'] = []
# g (S) = (g_dens (S/m2) / spec_cap (F/m2)) * C_mem (F)
self.bio_params['channel_params'] = ['g',
'e_rev',
'v_half_a',
'v_half_i',
'k_a',
'k_i',
'T_a',
'T_i',
'a_power',
'i_power']
self.bio_params['unit_chan_params'] = ['S/F',
'V',
'V',
'V',
'V',
'V',
'S',
'S',
' ',
' ']
self.bio_params['min_val_channel'] = [100 , 0.01, -0.01, 0.01, 0.0001, -0.001, 0.00001, 0.01, 2, 1]
# self.bio_params['min_val_channel'] = [1 , -0.01, -0.1, -0.1, 0.000001, -0.1, 0.00001, 0.00001, 2, 1]
self.bio_params['max_val_channel'] = [500 , 0.1,-0.001, 0.1, 0.001, -0.0001, 0.001, 1, 2, 1]
# self.bio_params['max_val_channel'] = [1000 , 0.01, -0.1, 0.1, 0.1, -0.00001, 1, 1, 2, 1]
# self.bio_params['min_val_channel'] = [220, 0.049, -0.0033, 0.025, 0.006, -0.005, 0.00010, 0.150, 2, 1]
# self.bio_params['max_val_channel'] = [220, 0.049, -0.0033, 0.025, 0.006, -0.005, 0.00010, 0.150, 2, 1]
if self.bio_params['ion_type'] == 'Ca':
self.bio_params['cell_params'].extend(['ca_con'])
self.bio_params['unit_cell_params'].extend(['M'])
self.bio_params['val_cell_params'].extend([6.1e-6])
#Parameters for Ca-dependent inactivation (Boyle & Cohen 2008)
self.bio_params['channel_params'].extend(['ca_half_i','alpha_ca','k_ca','T_ca','cdi_power'])
self.bio_params['unit_chan_params'].extend(['M',' ','M','S',' '])
self.bio_params['min_val_channel'].extend([10e-9, 0.1, -10e-9, 0.5e-3, 1])
self.bio_params['max_val_channel'].extend([300e-9, 0.4, -150e-9, 20e-3, 1])
# self.bio_params['min_val_channel'].extend([6.41889e-08, 0.282473, -1.00056e-08, 0.0115, 1])
# self.bio_params['max_val_channel'].extend([6.41889e-08, 0.282473, -1.00056e-08, 0.0115, 1])
# Boyle & Cohen: thiCa = 6.1e-6/(T_Ca*gCa)
# NeuroML: thiCa = ca_rho / area_m2
return self.bio_params
def getSimParameters(self,type='VClamp'):
"""
Get simulation parameters from user / DB and initialize variables.
"""
#TODO: Get values from pyOW
self.sim_params['v_init'] = -75e-3
self.sim_params['deltat'] = 1e-5
self.sim_params['duration'] = 0.3
self.sim_params['start_time'] = 0.02
self.sim_params['end_time'] = 0.22
self.sim_params['protocol_start'] = -40e-3
self.sim_params['protocol_end'] = 80e-3
self.sim_params['protocol_steps'] = 10e-3
self.sim_params['ion_type'] = 'Ca'
if type == 'IClamp':
self.sim_params['v_init_I'] = -75e-3
self.sim_params['deltat_I'] = 1e-5
self.sim_params['duration_I'] = 0.045
self.sim_params['start_time_I'] = 0.005
self.sim_params['end_time_I'] = 0.025
self.sim_params['protocol_start_I'] = 100e-12
self.sim_params['protocol_end_I'] = 400e-12
self.sim_params['protocol_steps_I'] = 100e-12
self.sim_params['ion_type_I'] = 'Ca'
return self.sim_params
def getSampleParameters(self):
"""
Get experimental parameters from user / DB and initialize variables.
Data structure for sampleData:
['VClamp']
['ref']
['fig'] e.g. 2A
['doi'] e.g. 10.1371/journal.pcbi.0030169.
['traces']
['vol'] e.g. -30 --> ['amp'] in case of IClamp
['csv_path'] e.g. data/user1/vclampM30.csv
['x_var']
['y_var']
['type'] e.g. current
['unit'] e.g. nA
['toSI'] e.g. e-9
['t']
['I']
[] e.g. -50.5,-49.8,...
['IClamp']
['IV']
"""
#TODO: Get values from pyOW
#For loop to extract all csv files from user's profile path
# 1: csv files: IClamp, VClamp, IV, G/Gmax, mtau, minf, htau, hinf, etc
# 1.1: info related to figures, and experiment: x,y variables, references (paper DOI, plot ref), experimental conditions (voltage/current clamped, temprature, etc)
if 'VClamp' in self.sampleData:
i = 0
for trace in self.sampleData['VClamp']['traces']:
self.sampleData['VClamp']['traces'][i]['t'],self.sampleData['VClamp']['traces'][i]['I'] = self.csv_to_XY(trace['csv_path'], trace['x_var'], trace['y_var'], self.sampleData['VClamp']['ref'])
i += 1
if 'IClamp' in self.sampleData:
i = 0
for trace in self.sampleData['IClamp']['traces']:
self.sampleData['IClamp']['traces'][i]['t'],self.sampleData['IClamp']['traces'][i]['V'] = self.csv_to_XY(trace['csv_path'], trace['x_var'], trace['y_var'], self.sampleData['IClamp']['ref'])
i += 1
if 'IV' in self.sampleData:
self.sampleData['IV']['V'],self.sampleData['IV']['I'] = self.csv_to_XY(self.sampleData['IV']['csv_path'], self.sampleData['IV']['x_var'], self.sampleData['IV']['y_var'], self.sampleData['IV']['ref'])
return self.sampleData
def csv_to_XY(self,path,x_var,y_var,ref,plot=False):
"""Extracts X,Y data from a csv file and convert to array
Data must be in a csv and in two columns, (e.g. time and
voltage, and units should be SI (e.g. Volts and Seconds)).
:param path: Path to csv file e.g data/user1/vt.csv
:param x_var: Variable type and unit for the first column parameter of csv file
:param y_var: Variable type and unit for the second column parameter of csv file
:param ref: Paper reference including figure
:param plot: If plot = TRUE, then plot raw data
:return: two lists - X and Y
"""
import csv
x=[]
y=[]
with open(path) as f:
reader = csv.reader(f)
for row in reader:
x_value = float(row[0])
y_value = float(row[1])
x.append(x_value * x_var['toSI'])
y.append(y_value * y_var['toSI'])
if plot:
plt.plot(x,y)
plt.title('Raw data from Fig.%s, DOI: %s'%(ref['fig'],ref['doi']))
plt.xlabel('%s (%s)'%(x_var['type'],x_var['unit']))
plt.ylabel('%s (%s)'%(y_var['type'],y_var['unit']))
plt.show()
return x,y
```
#### File: ChannelWorm/cwFitter/Modelator.py
```python
import matplotlib.pyplot as plt
class Modelator(object):
def __init__(self, bio_params, sim_params):
self.cell_params = bio_params['cell_params']
self.channel_params = bio_params['channel_params']
self.sim_params = sim_params
def compare_plots(self,sampleData,simData,show=False):
"""
Generates originals vs simulated plots
"""
#TODO: Add path and GUID to saved plotes
if 'VClamp' in sampleData:
ref = sampleData['VClamp']['ref']
for trace in sampleData['VClamp']['traces']:
sample_plot, = plt.plot(trace['t'],trace['I'], label = '%i (V)'%trace['vol'])
voltage = self.sim_params['protocol_start']
for trace in simData['VClamp']['I']:
model_plot, = plt.plot(simData['VClamp']['t'],trace, label = '%i (V)'%voltage)
voltage -= self.sim_params['protocol_steps']
plt.legend([sample_plot,model_plot], ["Original data from Fig.%s, DOI: %s"%(ref['fig'],ref['doi']),"Best model"])
#plt.ylim(-80.0,80.0)
#plt.xlim(0.0,1000.0)
plt.title("The Best Model fitted to data for voltage-clamp using GA")
plt.xlabel("Time (s)")
plt.ylabel("Current (A)")
plt.savefig("data_vs_candidate-VClamp.png",bbox_inches='tight',format='png')
if show:
plt.show()
if 'IClamp' in sampleData:
ref = sampleData['IClamp']['ref']
for trace in sampleData['IClamp']['traces']:
sample_plot, = plt.plot(trace['t'],trace['V'], label = '%i (A)'%trace['amp'])
amp = self.sim_params['protocol_start_I']
for trace in simData['IClamp']['V']:
model_plot, = plt.plot(simData['IClamp']['t'],trace, label = '%i (A)'%amp)
amp -= self.sim_params['protocol_steps_I']
plt.legend([sample_plot,model_plot], ["Original data from Fig.%s, DOI: %s"%(ref['fig'],ref['doi']),"Best model"])
#plt.ylim(-80.0,80.0)
#plt.xlim(0.0,1000.0)
plt.title("The Best Model fitted to data for current-clamp using GA")
plt.xlabel("Time (s)")
plt.ylabel("Voltage (V)")
plt.savefig("data_vs_candidate-IClamp.png",bbox_inches='tight',format='png')
if show:
plt.show()
if 'IV' in sampleData:
ref = sampleData['IV']['ref']
sample_plot, = plt.plot([round(x*1e3) for x in sampleData['IV']['V']],sampleData['IV']['I'])
if 'VClamp' in simData:
model_plot, = plt.plot([round(x*1e3) for x in simData['VClamp']['V_max']],simData['VClamp']['I_max'])
else:
model_plot, = plt.plot([round(x*1e3) for x in simData['IClamp']['V_max']],simData['IClamp']['I_max'])
plt.legend([sample_plot,model_plot], ["Original data from Fig.%s, DOI: %s"%(ref['fig'],ref['doi']),"Best model"])
#plt.ylim(-80.0,80.0)
#plt.xlim(0.0,1000.0)
plt.title("The Best Model fitted to data for I/V curve using GA")
plt.xlabel("Voltage (mV)")
plt.ylabel("Current (A/F)")
plt.savefig("data_vs_candidate-IV.png",bbox_inches='tight',format='png')
if show:
plt.show()
def generate_nml2(self):
"""
:return:
"""
def run_nml2(self):
"""
:return:
"""
``` |
{
"source": "joe-bowman/docker-formula",
"score": 2
} |
#### File: default/testinfra/test_docker.py
```python
import testinfra
def test_service_is_running_and_enabled(Service):
docker = Service('docker')
assert docker.is_running
assert docker.is_enabled
``` |
{
"source": "Joeboyc2/pi-eco-indicator",
"score": 3
} |
#### File: Joeboyc2/pi-eco-indicator/store_data.py
```python
import sqlite3
import os
import sys
import time
from reprlib import Repr
from datetime import datetime
from urllib.request import pathname2url
import pytz
import requests
import argparse
import eco_indicator
AGILE_API_BASE = (
'https://api.octopus.energy/v1/products/'
'AGILE-18-02-21/electricity-tariffs/E-1R-AGILE-18-02-21-')
AGILE_REGIONS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'P', 'N', 'J', 'H', 'K', 'L', 'M']
AGILE_API_TAIL = "/standard-unit-rates/"
CARBON_API_BASE = ('https://api.carbonintensity.org.uk')
CARBON_REGIONS = {'A': '/regional/intensity/{from_time}/fw48h/regionid/10',
'B': '/regional/intensity/{from_time}/fw48h/regionid/9',
'C': '/regional/intensity/{from_time}/fw48h/regionid/13',
'D': '/regional/intensity/{from_time}/fw48h/regionid/6',
'E': '/regional/intensity/{from_time}/fw48h/regionid/8',
'F': '/regional/intensity/{from_time}/fw48h/regionid/4',
'G': '/regional/intensity/{from_time}/fw48h/regionid/3',
'P': '/regional/intensity/{from_time}/fw48h/regionid/1',
'N': '/regional/intensity/{from_time}/fw48h/regionid/2',
'J': '/regional/intensity/{from_time}/fw48h/regionid/14',
'H': '/regional/intensity/{from_time}/fw48h/regionid/12',
'K': '/regional/intensity/{from_time}/fw48h/regionid/7',
'L': '/regional/intensity/{from_time}/fw48h/regionid/11',
'M': '/regional/intensity/{from_time}/fw48h/regionid/5',
'Z': '/intensity/{from_time}/fw48h'}
MAX_RETRIES = 15 # give up once we've tried this many times to get the prices from the API
parser = argparse.ArgumentParser(description=('Read data from a remote API and store it in a local SQlite database'))
parser.add_argument('--conf', '-c', default='config.yaml', help='specify config file')
parser.add_argument('--print', '-p', action='store_true', help='print data which was retrieved (JSON format)')
args = parser.parse_args()
conf_file = args.conf
def get_data_from_api(_request_uri: str) -> dict:
"""using the provided URI, request data from the API and return a JSON object.
Try to handle errors gracefully with retries when appropriate."""
# Try to handle issues with the API - rare but do happen, using an
# exponential sleep time up to 2**14 (16384) seconds, approx 4.5 hours.
# We will keep trying for over 9 hours and then give up.
retry_count = 0
my_repr = Repr()
my_repr.maxstring = 80 # let's avoid truncating our error messages too much
while retry_count <= MAX_RETRIES:
if retry_count == MAX_RETRIES:
raise SystemExit('API retry limit exceeded.')
try:
success = False
response = requests.get(_request_uri, timeout=5)
response.raise_for_status()
if response.status_code // 100 == 2:
success = True
except requests.exceptions.HTTPError as error:
print(('API HTTP error ' + str(response.status_code) +
',retrying in ' + str(2**retry_count) + 's'))
time.sleep(2**retry_count)
retry_count += 1
except requests.exceptions.ConnectionError as error:
print(('API connection error: ' + my_repr.repr(str(error)) +
', retrying in ' + str(2**retry_count) + 's'))
time.sleep(2**retry_count)
retry_count += 1
except requests.exceptions.Timeout:
print('API request timeout, retrying in ' + str(2**retry_count) + 's')
time.sleep(2**retry_count)
retry_count += 1
except requests.exceptions.RequestException as error:
raise SystemExit('API Request error: ' + str(error)) from error
if success:
print('API request successful, status ' + str(response.status_code) + '.')
if args.print: print(response.json())
return response.json()
def insert_data(data: dict):
"""Insert our data records one by one, keep track of how many were successfully inserted
and print the results of the insertion."""
num_rows_inserted = 0
if config['Mode'] == 'agile_price':
for result in data['results']:
# insert_record returns false if it was a duplicate record
# or true if a record was successfully entered.
if insert_record(result['valid_from'], result['value_inc_vat']):
num_rows_inserted += 1
if num_rows_inserted > 0:
lastslot = datetime.strftime(datetime.strptime(
data['results'][0]['valid_to'], "%Y-%m-%dT%H:%M:%SZ"), "%H:%M on %A %d %b")
print(str(num_rows_inserted) + ' prices were inserted, ending at ' + lastslot + '.')
else:
print('No prices were inserted - maybe we have them'
' already, or Octopus are late with their update.')
if config['Mode'] == 'carbon':
if config['DNORegion'] == 'Z':
carbon_data = data['data']
else:
carbon_data = data['data']['data']
for result in carbon_data:
if insert_record(result['from'], result['intensity']['forecast']):
num_rows_inserted += 1
if num_rows_inserted > 0:
lastslot = datetime.strftime(datetime.strptime(
carbon_data[47]['from'], "%Y-%m-%dT%H:%MZ"), "%H:%M on %A %d %b")
print(str(num_rows_inserted) + ' intensities were inserted, '
'ending at ' + lastslot + '.')
else:
print('No values were inserted - maybe we have them'
' already, or carbonintensity.org.uk are late with their update.')
def insert_record(valid_from: str, data_value: float) -> bool:
"""Assuming we still have a cursor, take a tuple and stick it into the database.
Return False if it was a duplicate record (not inserted) and True if a record
was successfully inserted."""
if not cursor:
raise SystemExit('Database connection lost!')
if config['Mode'] == 'agile_price':
# make the date/time work for SQLite, it's picky about the format,
# easier to use the built in SQLite datetime functions
# when figuring out what records we want rather than trying to roll our own
valid_from_formatted = datetime.strftime(
datetime.strptime(valid_from, "%Y-%m-%dT%H:%M:%SZ"), "%Y-%m-%d %H:%M:%S")
data_tuple = (valid_from_formatted, data_value)
# print(data_tuple) # debug
try:
cursor.execute(
"INSERT INTO 'eco'('valid_from', 'value_inc_vat') VALUES (?, ?) ON CONFLICT(valid_from) DO UPDATE SET value_inc_vat=excluded.value_inc_vat;", data_tuple)
except sqlite3.Error as error:
raise SystemError('Database error: ' + str(error)) from error
else:
return True # the record was inserted
if config['Mode'] == 'carbon':
valid_from_formatted = datetime.strftime(
datetime.strptime(valid_from, "%Y-%m-%dT%H:%MZ"), "%Y-%m-%d %H:%M:%S")
data_tuple = (valid_from_formatted, data_value)
# print(data_tuple) # debug
try:
cursor.execute(
"INSERT INTO 'eco'('valid_from', 'intensity') VALUES (?, ?) ON CONFLICT(valid_from) DO UPDATE SET intensity=excluded.intensity;", data_tuple)
except sqlite3.Error as error:
raise SystemError('Database error: ' + str(error)) from error
else:
return True # the record was inserted
return False
def remove_old_data(age: str):
"""Delete old data from the database, we don't want to display those and we don't want it
to grow too big. 'age' must be a string that SQLite understands"""
if not cursor:
raise SystemExit('Database connection lost before pruning data!')
try:
cursor.execute("SELECT COUNT(*) FROM eco "
"WHERE valid_from < datetime('now', '-" + age + "')")
selected_rows = cursor.fetchall()
num_old_rows = selected_rows[0][0]
# I don't know why this doesn't just return an int rather than a list of a list of an int
if num_old_rows > 0:
cursor.execute("DELETE FROM eco WHERE valid_from < datetime('now', '-" + age + "')")
print(str(num_old_rows) + ' unneeded data points from the past were deleted.')
else:
print('There were no old data points to delete.')
except sqlite3.Error as error:
print('Failed while trying to remove old data points from database: ', error)
os.chdir(os.path.dirname(sys.argv[0]))
config = eco_indicator.get_config(conf_file)
if config['Mode'] == 'agile_price':
DNO_REGION = config['DNORegion']
if DNO_REGION in AGILE_REGIONS:
print('Selected region ' + DNO_REGION)
else:
raise SystemExit('Error: DNO region ' + DNO_REGION + ' is not a valid choice.')
# Build the API for the request - public API so no authentication required
request_uri = (AGILE_API_BASE + DNO_REGION + AGILE_API_TAIL)
elif config['Mode'] == 'carbon':
DNO_REGION = config['DNORegion']
if DNO_REGION in CARBON_REGIONS:
print('Selected region ' + DNO_REGION)
else:
raise SystemExit('Error: DNO region ' + DNO_REGION + ' is not a valid choice.')
# Build the API for the request - public API so no authentication required
request_time = datetime.now().astimezone(pytz.utc).isoformat()
request_uri = (CARBON_API_BASE + CARBON_REGIONS[DNO_REGION])
request_uri = request_uri.format(from_time=request_time)
try:
# connect to the database in rw mode so we can catch the error if it doesn't exist
DB_URI = 'file:{}?mode=rw'.format(pathname2url('eco_indicator.sqlite'))
conn = sqlite3.connect(DB_URI, uri=True)
cursor = conn.cursor()
print('Connected to database...')
except sqlite3.OperationalError:
# handle missing database case
print('No database found. Creating a new one...')
conn = sqlite3.connect('eco_indicator.sqlite')
cursor = conn.cursor()
# UNIQUE constraint prevents duplication of data on multiple runs of this script
# ON CONFLICT FAIL allows us to count how many times this happens
cursor.execute('CREATE TABLE eco (valid_from STRING PRIMARY KEY ON CONFLICT REPLACE, '
'value_inc_vat REAL, intensity REAL)')
conn.commit()
print('Database created... ')
data_rows = get_data_from_api(request_uri)
insert_data(data_rows)
remove_old_data('2 days')
# finish up the database operation
if conn:
conn.commit()
conn.close()
``` |
{
"source": "joebrands/Suspension-Project",
"score": 3
} |
#### File: joebrands/Suspension-Project/GROUND.py
```python
import numpy as np
import scipy.interpolate as interpolate
import matplotlib.pyplot as plt
import VEHICLE
class Ground:
def __init__(self):
# self.car = q_car()
self.tracklength = None
self.resolution = None
self.xdata = []
self.ydata = []
def getdata(self, data): # interpret the ground .txt and plot ground profile
n = len(data)
for lineN in data:
self.xdata.append(lineN[0])
self.ydata.append(lineN[1])
self.tracklength = data[n - 1][0]
self.resolution = self.xdata[1] - self.xdata[0]
def graphtrack(self):
plt.plot(self.xdata, self.ydata)
plt.show()
print('GROUND DATA PLOTTED SUCESSFULLY')
# Polynomial Fit
# -------------------------------------------------------------------
def polyfitgraph(self):
file = list(VEHICLE.q_car.file)
n = len(file)
u = np.zeros(n)
r = np.zeros(n)
for i in range(n):
u[i] = file[i][0]
r[i] = file[i][1]
y = np.zeros(n)
t = np.linspace(0, u[n - 1], n)
z = np.polyfit(u, r, 20)
def f(z, t):
return (z[0] * t**20) + (z[1] * t**19) + (z[2] * t**18) + (z[3] * t**17) + (z[4] * t**16) + (z[5] * t**15) + (z[6] * t**14) + (z[7] * t**13) + (
z[8] * t**12) + (z[9] * t**11) + (z[10] * t**10) + (z[11] * t**9) + (z[12] * t**8) + (z[13] * t**7) + (z[14] * t**6) + (z[15] * t**5) + (
z[16] * t**4) + (z[17] * t**3) + (z[18] * t**2) + (z[19] * t) + z[20]
for i in range(len(t)):
y[i] = (f(z, t[i]))
plt.plot(t, y)
plt.show()
print('GROUND DATA PLOTTED SUCESSFULLY')
# --------------------------------------------------------------------
def main():
file = np.loadtxt('GroundDataExample1.txt', delimiter = ',', skiprows = 1, unpack = False)
file = file.tolist()
# print(file[0:3])
Ground.getdata(file)
# main() # uncomment to test this file only
``` |
{
"source": "JoeBugajski/python-examples",
"score": 3
} |
#### File: python-examples/Chapter 2/function-copy.py
```python
def function(n = 1):
print(n)
return n * 2
x = function(69)
print(x)
```
#### File: python-examples/Chapter 7/generator-copy.py
```python
def main():
for i in inclusive_range(25): # you can feed this (start, stop, step)
print(i, end = ' ')
print()
# This version of range includes 0-25, not 0-24
# range is actually a generator
def inclusive_range(*args): # variable argument list
numargs = len(args)
start = 0 # default start val if no start arg
step = 1 # default step val if no step arg
# initialize parameters
if numargs < 1:
raise TypeError(f'expected at least 1 argument, got {numargs}')
elif numargs == 1:
stop = args[0] # if 1 arg, that arg is assigned to stop
elif numargs == 2:
(start, stop) = args # if 2, args are assigned to start and stop
elif numargs == 3:
(start, stop, step) = args # if 3, args assigned to start, stop, step
else: raise TypeError(f'expected at most 3 arguments, got {numargs}') # 4 is right out
# generator
i = start
while i <= stop: # this while loop continues until it hits stop val
yield i # yield is like return except it's for a generator
# It yields a value and then after it yields the value the
# function continues until it yields the next value.
i += step
if __name__ == '__main__': main()
```
#### File: python-examples/Chapter 8/dict-copy.py
```python
def main():
# You can just create a dictionary like this:
# animals = { 'kitten': 'meow', 'puppy': 'ruff!', 'lion': 'grrr',
# 'giraffe': 'I am a giraffe!', 'dragon': 'rawr' }
# You can also create a dictionary using the dictionary constructor
# This looks a bit cleaner
animals = dict(kitten = 'meow', puppy = 'ruff!', lion = 'grrr', giraffe = 'I am giraffe!', dragon = 'rawr')
# Keys and Values can be any type
# keys and values are immutable, so to alter values you have to create
# a new seq, either a dictionary or some other seq
# items() is a good method for printing out key value pairs
print('''
Key-Value pairs:
''')
for k, v in animals.items(): print(f'{k}: {v}')
# this returns the same as below:
# print_dict(animals)
# You can also print keys like this:
print('''
Just keys:
''')
for k in animals.keys(): print(k)
# Same goes for values
print('''
Just values:
''')
for v in animals.values(): print(v)
# A dictionary is indexed by its keys, so you can access values
# by simply calling dictionary['key']
print(animals['puppy'])
# You can search for a key in a dictionary like so:
print('lion' in animals) # This way will return True
print('Found it!' if 'lion' in animals else 'nope!') # Return specified strings
# If you try to access a key directly that doesn't exist, you'll get a KeyError
# That's why it's probably a better idea to use a ternary as above
# Or you can use this get() method below:
print(animals.get('godzilla')) # Returns None instead of error
# You can add an item to a dictionary like so:
animals['monkey'] = 'haha'
print(animals['monkey'])
def print_dict(o):
for k, v in o.items(): print(f'{k}: {v}')
if __name__ == '__main__': main()
```
#### File: python-examples/Chapter 8/sets copy.py
```python
def main():
a = set("We're gonna need a bigger boat.")
b = set("I'm sorry, Dave. I'm afraid I can't do that.")
print_set(a) # If you really want them sorted, you can do print_set(sorted(a))
print_set(b) # otherwise, they'll be in a different order every time you run
# But if you really wanted an ordered list, you'd use list
# For the most parts, you'd use a set to compare two or more collections
# for example, I can check for the members that are in set a but not in set b
# by using the minus operator as seen here:
print('''
a - b?
''')
print_set(sorted(a - b))
# I can find the members that are in set a or set b or both by using the vertical
# bar operator and that's all of the members that are in one or both of the sets.
print('''
a, b, or both?
''')
print_set(sorted(a | b)) # use the vertical bar operator
# Or I can look for the exclusive or using the caret operator.
# So that's a or b, but not both
print('''
a or b, but not both
''')
print_set(sorted(a ^ b))
# Or I can look for only the members that are in both
print('''
both a and b
''')
print_set(sorted(a & b))
def print_set(o):
print('{', end = '')
for x in o: print(x, end = '')
print('}')
if __name__ == '__main__': main()
``` |
{
"source": "JoeBuzh/DeepWater",
"score": 2
} |
#### File: dao/orm/db_orm.py
```python
import sys
sys.path.append('../../')
from sqlalchemy import create_engine
from sqlalchemy.schema import MetaData
from sqlalchemy.orm import sessionmaker
class DataBaseORM:
"""
ORM Tool Class.
"""
__db_charset = 'utf-8'
matedata = MetaData()
def __init__(self, name: str, engine_cmd: str):
self.name = name
self.engine = create_engine(engine_cmd, encoding=DataBaseORM.__db_charset)
def create_session(self):
Session = sessionmaker(bind=self.engine)
return Session()
def _test_session(self, test_sql: str):
assert self.session is not None and self.engine is not None
with self.engine.connect() as connection:
result = connection.execute(test_sql)
for row in result:
print(row)
```
#### File: DeepWater/dao/test.py
```python
""" ORM Test """
import sys
sys.path.append('../')
import traceback
import pandas as pd
from dao.orm.SQLite_dynamic import orm
from dao.orm.SQLite_dynamic import AutoStation, MonSection
from dao.orm.SQLite_dynamic import ObsDataRaw, ObsDataQcLinear
def test():
try:
session = orm.create_session()
# orm test
auto_stat_records = session.query(AutoStation.name, AutoStation.lon, AutoStation.lat).filter_by(provincename='北京市').all()
moni_sect_records = session.query(MonSection.rb_name, MonSection.riverlak, MonSection.rb_code).filter_by(provincename='河北省').all()
raw_records = session.query(ObsDataRaw.time, ObsDataRaw.name, ObsDataRaw.pH, ObsDataRaw.codmn).filter_by(time='2020-08-08 12:00:00').all()
qc_records = session.query(ObsDataQcLinear.time, ObsDataQcLinear.pH, ObsDataQcLinear.tp).filter_by(time='2020-08-08 12:00:00').all()
print(pd.DataFrame(auto_stat_records))
print("*"*66)
print(pd.DataFrame(moni_sect_records))
print("*"*66)
print(pd.DataFrame(raw_records))
print("*"*66)
print(pd.DataFrame(qc_records))
except Exception as e:
traceback.print_exc()
if __name__ == '__main__':
test()
```
#### File: lib/machineL/LinearModel.py
```python
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge
from sklearn.linear_model import ElasticNet
""" 线性模型 """
def lr():
return LinearRegression(fit_intercept=True, normalize=True)
def lasso():
return Lasso(alpha=0.8, fit_intercept=True, normalize=True)
def ridge():
return Ridge(alpha=0.8, fit_intercept=True, normalize=True)
def elasticNet():
return ElasticNet(alpha=0.8, fit_intercept=True, normalize=True)
```
#### File: scripts/.ipynb_checkpoints/run_forecast-checkpoint.py
```python
import sys
sys.path.append("../")
from utils.ConfigParseUtils import ConfigParser
from src.DataForecast.run import forecast_arima
from src.DataForecast.run import forecast_fbprophet
from src.DataForecast.run import forecast_lstm
from src.DataForecast.run import forecast_gru
def main():
"""
Forecast Workflow.
"""
cfp = ConfigParser()
if cfp.start is not None and cfp.end is not None:
assert cfp.start <= cfp.end
if cfp.model == "Arima":
forecast_arima(station=cfp.name, index=cfp.index, start=cfp.start, end=cfp.end)
elif cfp.model == "Fbprophet":
forecast_fbprophet(station=cfp.name, index=cfp.index, start=cfp.start, end=cfp.end)
elif cfp.model == "LSTM":
forecast_lstm(station=cfp.name, index=cfp.index, start=cfp.start, end=cfp.end)
elif cfp.model == "GRU":
forecast_gru(station=cfp.name, index=cfp.index, start=cfp.start, end=cfp.end)
else:
print("Wrong model with {}".format(cfp.model))
sys.exit()
if __name__ == "__main__":
main()
```
#### File: scripts/.ipynb_checkpoints/run_qc-checkpoint.py
```python
import os
import sys
sys.path.append("../")
from utils.ConfigParseUtils import ConfigParser
from src.DataQC.run import qc_entrance
def main():
"""
Quality Control Workflow.
"""
cfp = ConfigParser()
if cfp.start is not None and cfp.end is not None:
assert cfp.start <= cfp.end
else:
print("Error Start or End Time.")
sys.exit()
if cfp.index != "all":
print("Index should be [ all ].")
sys.exit()
if cfp.model == "qc":
qc_entrance(station=cfp.name, index=cfp.index, start=cfp.start, end=cfp.end)
else:
print("Index should be [ qc ].")
sys.exit()
if __name__ == "__main__":
main()
```
#### File: DataEvaluate/.ipynb_checkpoints/forward_evaluate-checkpoint.py
```python
""" 正向模拟评价功能类 """
import os
import sys
sys.path.append('../../')
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from src.DataEvaluate.settings import *
from src.DataEvaluate.utils import *
class ForwardEvaluate:
"""
Forecast Data Foreword Evaluation Class.
"""
def __init__(
self,
real_df: pd.DataFrame,
pred_df: pd.DataFrame,
eval_start: datetime,
eval_end: datetime,
save_dir: str
):
self.real_df = real_df
self.pred_df = pred_df
self.start = eval_start
self.end = eval_end
self.save_dir = checkdir(save_dir)
def forward_search(self, this_time: datetime) -> pd.DataFrame:
"""
Forword Search Ture Value.
"""
this_start = this_time + timedelta(hours=FREQ)
this_end = this_time + timedelta(hours=EVALUATE_SCALE*FREQ)
return self.real_df[
this_start.strftime("%Y-%m-%d %H:00:00"):this_end.strftime("%Y-%m-%d %H:00:00")]
def evaluate_duration(self):
"""
Evaluate From Start to End.
"""
eval_start = self.start
eval_end = self.end
print(eval_start, eval_end)
time_list = []
mae_list = []
mse_list = []
nash_list = []
accuracy_list = []
while eval_start <= eval_end:
print('Evaluating: {}'.format(eval_start.strftime("%Y-%m-%d %H")))
this_real = self.forward_search(eval_start)
this_pred = self.pred_df.loc[self.pred_df.index==eval_start.strftime("%Y-%m-%d %H:00:00")]
this_real['{}_P'.format(INDEX)] = this_pred.values[0][:EVALUATE_SCALE]
this_real['err_rate'] = abs(this_real[INDEX]-this_real['{}_P'.format(INDEX)]) / this_real[INDEX]
# print(this_real)
mae = calc_mae(this_real[INDEX], this_real['{}_P'.format(INDEX)])
mse = calc_mse(this_real[INDEX], this_real['{}_P'.format(INDEX)])
nash = calc_nash(this_real[INDEX], this_real['{}_P'.format(INDEX)])
accuracy = this_real[this_real['err_rate']<=0.3].shape[0] / this_real.shape[0]
print(mae, mse, nash, accuracy)
time_list.append(eval_start)
mae_list.append(mae)
mse_list.append(mse)
nash_list.append(nash)
accuracy_list.append(accuracy)
# self.forward_plot(this_real)
# loop
eval_start += timedelta(hours=FREQ)
index_df = pd.DataFrame({
'Time': time_list, 'mae': mae_list, 'mse': mse_list, 'nash': nash_list, 'accuracy': accuracy_list
}).set_index('Time')
print(index_df)
self.index_plot(index_df)
print(index_df.describe().T)
def forward_plot(self, data: pd.DataFrame):
"""
Plot One Moment Forward Search Forecast.
"""
plt.figure(figsize=(20,5))
plt.plot(data.index, data[INDEX], label='Forecast', color='b', marker='o', linestyle='--')
plt.plot(data.index, data['{}_P'.format(INDEX)], label='Truth', color='g', marker='*', linestyle='--')
plt.legend(loc='best')
plt.title("{0} ({1}) Forward Evaluation".format(data.index[0], INDEX), fontsize=15)
plt.savefig(os.path.join(
self.save_dir,
'{0}_{1}_Forward_Evaluation.png'.format(data.index[0], INDEX)
))
def index_plot(self, data: pd.DataFrame):
"""
Plot Forward Evaluation Indexs.
"""
fig = plt.figure(figsize=(15, 8))
plt.subplot(2, 1, 1)
plt.plot(data.index, data['nash'], label='Nash', color='b', marker='o')
plt.ylabel('Nash')
plt.title("{0} to {1} ({2}) [{3}] Forward Evaluation".format(data.index[0], data.index[0], INDEX, EVALUATE_SCALE), fontsize=15)
plt.subplot(2, 1, 2)
plt.plot(data.index, data['accuracy'], label='Accuracy', color='g', marker='*')
plt.ylabel('Accuracy')
# plt.title("{0} to {1} ({2}) Forward Evaluation".format(data.index[0], data.index[0], INDEX), fontsize=15)
plt.savefig(os.path.join(
self.save_dir,
'{0}_{1}_{2}_{3}_Forward_Evaluation.png'.format(data.index[0], data.index[0], INDEX, EVALUATE_SCALE)))
```
#### File: src/DataEvaluate/utils.py
```python
""" 评价辅助工具 """
import os
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
def calc_accuracy():
pass
def calc_mae(y_true, y_pred) -> float:
"""
Calculate Mean Absolute Error.
y_true: Ture Observation.
y_pred: Forecast Value.
"""
return mean_absolute_error(y_true, y_pred)
def calc_mse(y_true, y_pred) -> float:
"""
Calculate Mean Squared Error.
y_true: Ture Observation.
y_pred: Forecast Value.
"""
return mean_squared_error(y_true, y_pred)
def calc_nash(y_true, y_pred) -> float:
"""
Calculate Nash Correlation Index.
y_true: Ture Observation.
y_pred: Forecast Value.
"""
return r2_score(y_true, y_pred)
```
#### File: DeepWater/utils/ConfigParseUtils.py
```python
import argparse
from argparse import OPTIONAL
from datetime import datetime
class ConfigParser:
"""
Command Line Parameters Parser Utility.
"""
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument(
"-n", type=str, default=None, help="forecast station name")
self.parser.add_argument(
"-m", type=str, default=None, help="forecast method [Arima|Fbprophet|LSTM|Ensemble] ")
self.parser.add_argument(
"-i", type=str, default=None, help="forecast index [codmn|nh3n|tp|tn] ")
self.parser.add_argument(
"-s", type=str, default=None, help="forecast start time [%Y%m%d%H]")
self.parser.add_argument(
"-e", type=str, default=None, help="forecast end time [%Y%m%d%H]")
self.args = self.parser.parse_args()
@property
def name(self) -> str:
return self.args.n
@property
def model(self) -> str:
return self.args.m
@property
def index(self):
return self.args.i
@property
def start(self):
return datetime.strptime(self.args.s, "%Y%m%d%H") if self.args.s is not None else None
@property
def end(self):
return datetime.strptime(self.args.e, "%Y%m%d%H") if self.args.e is not None else None
```
#### File: DeepWater/utils/LogUtils.py
```python
import os
import logging
def init_logger(log_path: str):
"""
Init Logger instance.
"""
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)
# FileHandler
handler = logging.FileHandler(log_path)
handler.setLevel(level=logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
def test():
logger = init_logger('out.log')
if __name__ == "__main__":
test()
``` |
{
"source": "JoeBuzh/EmisPrep",
"score": 2
} |
#### File: src/links/wrfclinker.py
```python
import os
import sys
from datetime import datetime, timedelta
import numpy as np
import xarray as xr
from links.baselink import baseLink
class wrfcLink(baseLink):
'''
Wrf-Chem Emission Data Pre_processing Class.
Function
0. Modify src wrfchemi_d0{1|2|3}_2018_MM_15_HH:00:00;
1. rename filename
2. change 'Times'
3. Copy dst to output
'''
def __init__(self, name: str, this_time: datetime, cfg: dict, in_path: str, out_path: str):
'''
Init.
'''
super().__init__(name=name, this_time=this_time)
# base cfg
# TODO: dict loop
self.base_year = cfg.get('base_year')
self.base_day = cfg.get('base_day')
self.domains = cfg.get('domains')
self.dt_format = cfg.get('dt_format')
self.pred_seq = cfg.get('pred_seq')
# data dir
self.data_in = os.path.join(in_path, self.name)
self.data_out = os.path.join(out_path, self.name)
def _check_domain(self):
'''
Domain Loop.
'''
assert isinstance(self.domains, list) and len(self.domains)>=1
for domain in self.domains:
self._check_time(domain)
def _check_time(self, domain):
'''
Predict Sequence Loop.
'''
start = self.this_time
end = start + timedelta(hours=self.pred_seq)
while start <= end:
src_file = 'wrfchemi_d0{0}_{1}-{2}-{3}_{4}:00:00'.format(
domain,
self.base_year,
start.strftime("%m"),
self.base_day,
start.strftime("%H")
)
dst_file = 'wrfchemi_d0{0}_{1}'.format(
domain,
start.strftime(self.dt_format)
)
src = os.path.join(self.data_in, src_file)
dst = os.path.join(self.data_out, dst_file)
# workflow
self._gen_file(src, dst, start)
start += timedelta(hours=1)
def _gen_file(self, src: str, dst: str, dt: datetime):
'''
Generate dst file based on src file.
0. Open src file
1. Change varibales-Times
2. Rename filename and save to dst_file.
3. Make sure dst file exist.
'''
assert os.path.exists(src)
dataset = xr.open_dataset(src)
dt_new = dt.strftime(self.dt_format)
dataset['Times'].values[0] = dt_new.encode('utf-8')
dataset.to_netcdf(dst)
assert os.path.exists(dst)
def _step_control(self):
'''
Inner process control.
0. Check output dir mainly focus on ${output}/${model_name}/${date}.
1. Execute domain loop within predict sequence loop.
'''
# self.tmp_dst = os.path.join(self.data_out, self.this_time.strftime("%Y%m%d"))
self.checkdir(self.data_out)
self._check_domain()
``` |
{
"source": "JoeBuzh/Pm_Composition_Quallity_Control",
"score": 3
} |
#### File: Pm_Composition_Quallity_Control/check/check_hourly_format.py
```python
import os
import sys
STD_NUM=46
def dig_obs(lines: list):
'''
Calc line split num.
'''
flag = 0
for line in lines:
items = line.split(',')
if len(items) != STD_NUM:
# print(len(items))
# print(line)
flag += 1
return flag
def loop_dir(dirname):
'''
Main Dir Looping.
'''
assert os.path.exists(dirname)
for _, filename in enumerate(os.listdir(dirname)):
# print(i, filename)
with open(os.path.join(dirname, filename), 'r') as f:
lines = f.readlines()
res = dig_obs(lines)
if res != 0:
print(filename)
else:
continue
def parse_err_time(filename):
'''
获取发生错误的站点
'''
assert os.path.exists(filename)
with open(filename, 'r') as f:
cont = f.readlines()
t = [f.split('_')[-1].split('.')[0] for f in cont]
print('\n'.join(t))
def main():
'''
Main
'''
src = r'../extract/obs_data'
loop_dir(src)
# err_file = r'./err_hour.txt'
# parse_err_time(err_file)
if __name__ == "__main__":
main()
```
#### File: Pm_Composition_Quallity_Control/extract/getErrTime.py
```python
import os
import sys
STD_NUM=46
def parse_err_time(filename):
'''
获取发生错误的站点
'''
assert os.path.exists(filename)
with open(filename, 'r') as f:
cont = f.readlines()
err_time = [f.split('_')[-1].split('.')[0] for f in cont]
# print('\n'.join(err_time))
return err_time
def main():
'''
Main
'''
err_file = r'./err_hour.txt'
parse_err_time(err_file)
if __name__ == "__main__":
main()
```
#### File: Pm_Composition_Quallity_Control/fill_pm/Extractor.py
```python
import os
import sys
import traceback
import configparser
from datetime import datetime, timedelta
def getStationId(filename):
assert os.path.exists(filename)
with open(filename, 'r') as f:
cont = f.readlines()
ids = [x.split(' ')[0] for x in cont[1:]]
return ids
def getData(config: dict):
start = config['start']
while start <= config['end']:
year = start.strftime("%Y")
if config['type'] == 'mete':
filename = os.path.join(os.path.join(config['mete_dir'], year),
'obs_{}_'.format(config['type']) + start.strftime("%Y%m%d%H")+'.txt')
elif config['type'] == 'envi':
filename = os.path.join(os.path.join(config['envi_dir'], year),
'obs_{}_'.format(config['type']) + start.strftime("%Y%m%d%H")+'.txt')
else:
print("Error type.")
sys.exit()
print(filename)
assert os.path.exists(filename)
extr_cmd = extract_cmd(config, filename, start)
# print(extr_cmd)
# '''
try:
os.system(extr_cmd)
except Exception as err0:
traceback.print_exc(err0)
# '''
start += timedelta(hours=1)
add_header = add_cmd(config)
# print(add_header)
try:
os.system(add_header)
except Exception as err1:
traceback.print_exc(err1)
def extract_cmd(config: dict, filename: str, start) -> str:
return "grep -E '{0}' {1} | sed 's/^/{2},/g' >> {3}.txt".format(
'|'.join(config['ids']),
filename,
start.strftime("%Y%m%d%H"),
'{}/{}_{}_{}'.format(config['savedir'],
config['start'].strftime("%Y%m%d%H"),
config['end'].strftime("%Y%m%d%H"),
config['type']))
def add_cmd(config: dict) -> str:
if config['type'] == 'mete':
return r'''sed -i "1i\时间,站点编号,2分钟平均风向,2分钟平均风速,气温,本站气压,海平面气压,露点温度,相对湿度,小时降水量,能见度,总云量" {}
'''.format('{}/{}_{}_{}.txt'.format(config['savedir'],
config['start'].strftime("%Y%m%d%H"),
config['end'].strftime("%Y%m%d%H"),
config['type']))
elif config['type'] == 'envi':
return r'''sed -i "1i\时间,站点编号,PM2.5浓度,PM10浓度,CO浓度,NO2浓度,SO2浓度,O3浓度,O3 8小时浓度,AQI,空气质量等级,首要污染物" {}
'''.format('{}/{}_{}_{}.txt'.format(config['savedir'],
config['start'].strftime("%Y%m%d%H"),
config['end'].strftime("%Y%m%d%H"),
config['type']))
else:
print('Error type')
sys.exit()
def parseConfig(path: str) -> dict:
cfg = configparser.ConfigParser()
cfg.read(path)
config = {}
config['mete_info'] = cfg.get("StationInfo", "mete_info")
config['envi_info'] = cfg.get("StationInfo", "envi_info")
config['mete_dir'] = cfg.get("DataDir", "mete_dir")
config['envi_dir'] = cfg.get("DataDir", "envi_dir")
config['start'] = datetime.strptime(
cfg.get("Duration", "starttime"), "%Y%m%d%H")
config['end'] = datetime.strptime(
cfg.get("Duration", "endtime"), "%Y%m%d%H")
config['savedir'] = cfg.get("SaveDir", "savedir")
config['type'] = cfg.get("Type", "type")
return config
def main():
workdir = os.path.dirname(__file__)
cfgpath = os.path.join(workdir, 'config.ini')
configs = parseConfig(cfgpath)
if configs['type'] == 'mete':
configs['ids'] = getStationId(configs['mete_info'])
elif configs['type'] == 'envi':
configs['ids'] = getStationId(configs['envi_info'])
# for _id in configs['ids']:
# configs['id'] = _id
getData(configs)
if __name__ == "__main__":
main()
```
#### File: Pm_Composition_Quallity_Control/fill_pm/fill_pm.py
```python
import os
import sys
import xlrd
from datetime import datetime, timedelta
import folium
import numpy as np
import pandas as pd
from rtree import index
PM = ['PM10', 'PM25']
IONIC = ['F-','Cl-','NO3-','SO42-','Ca2+','Na+','K+','NH4+','Mg2+']
OCEC = ['OC','EC']
METAL = [
'Hg','Br','As','Si','Se','Te','V','Ca','Ti','Ba','Sc','Pd','Co','Mo','K',
'Fe','Pb','TI','Cu','Al','Cr','Cs','Ag','Zn','Sb','Sn','Mn','Cd','Ni','Ga'
]
def read_txt(filename: str, sep:str=None):
'''
文件读取
'''
assert os.path.exists(filename)
df = pd.read_table(
filename,
sep=sep,
encoding='utf-8',
engine='python',
error_bad_lines=False)
return df
def parse_time(x):
return datetime.strptime(str(x), "%Y%m%d%H").strftime('%Y-%m-%d:%H')
def read_org(filepath: str):
'''
Read *.txt data file.
'''
assert os.path.join(filepath)
data = pd.read_csv(
filepath,
sep=',',
names=['time','stationcode','longitude','latitude']+PM+IONIC+OCEC+METAL,
encoding='utf-8')
data.replace(-999.0, np.nan, inplace=True)
return data
def search(comp_info, idx) -> dict:
'''
匹配最近站点, 返回映射关系。
'''
_map = {}
for _, row in comp_info.iterrows():
lon = row['longitude']
lat = row['latitude']
comp_code = row['stationcode']
nearby = list(idx.nearest((lon, lat, lon, lat), 1, objects=True))[0]
_map[comp_code] = nearby.object
return _map
def insert_idx(envi_info, idx):
for i, row in envi_info.iterrows():
lon = row['经度']
lat = row['纬度']
obj = row['站号']
idx.insert(i, (lon, lat, lon, lat), obj=obj)
return idx
def merge_pm(src, dst, nearby, mapping):
'''
匹配最近站点PM观测数据.
'''
assert os.path.exists(src) and os.path.exists(dst)
for i, (k, val) in enumerate(mapping.items()):
orgfile = os.path.join(src, '{}.txt'.format(k))
org = read_org(orgfile) # -999.0 -> nan
near = nearby.loc[nearby['站点编号']==int(val), ['时间','站点编号','PM2.5浓度','PM10浓度']]
near['time'] = near['时间'].apply(parse_time)
df = org.merge(near, left_on='time', right_on='time', how='outer')
df['PM10'] = np.round(np.mean(df[['PM10', 'PM10浓度']], axis=1), 3)
df['PM25'] = np.round(np.mean(df[['PM25', 'PM2.5浓度']], axis=1), 3)
picked = df.loc[:, ['time','stationcode','longitude','latitude']+PM+IONIC+OCEC+METAL]
picked.replace(np.nan, -999.0, inplace=True)
picked[PM+IONIC+OCEC+METAL].astype(np.float)
picked.to_csv(
os.path.join(dst, '{}.txt'.format(k)),
sep=',',
index=False,
header=False,
float_format='%.3f'
)
print('{}\t{}\n'.format(i+1, '-'*100))
# print(picked.info())
def main():
'''
主程序.
'''
idx = index.Index()
comp_info = read_txt('../data/obs_com_stations.txt', sep=',')
envi_info = pd.read_csv('../data/obs_env_stations.txt', delim_whitespace=True)
# get map
idx = insert_idx(envi_info, idx)
mapping = search(comp_info, idx)
print(mapping)
# data dir
raw_src = '../data/raw_data'
nearby_file = '../data/nearby_envi.txt'
raw_dst = '../data/raw_data_pm'
# read obs envi
nearby = read_txt(nearby_file, sep=',')
nearby.replace(-999.0, np.nan, inplace=True)
# merge PM
merge_pm(raw_src, raw_dst, nearby, mapping)
if __name__ == "__main__":
main()
```
#### File: src/controllers/Controller.py
```python
import os
import sys
sys.path.append('../')
import numpy as np
import pandas as pd
from sklearn.externals import joblib
from pyod.models.abod import ABOD
from pyod.models.cblof import CBLOF
from pyod.models.feature_bagging import FeatureBagging
from pyod.models.hbos import HBOS
from pyod.models.iforest import IForest
from pyod.models.knn import KNN
from pyod.models.pca import PCA
from pyod.models.ocsvm import OCSVM
from pyod.models.lof import LOF
from src.cfg import OUT_FRACTION, RANDOM_STATE
from src.qc_model_train import define_model as define_qc_models
from src.fill_model_train import define_model as define_fill_models
class Controller(object):
'''
Base Controller Class.
Params
name -> identify name
dt -> now time
raw_df -> raw data
context -> last now next
cfp_dir -> .ini file dir
'''
def __init__(self, name, check_time, raw_df, context, cfp_dir):
'''
Base Class Init.
'''
self.name = name
self.check_time = check_time
self.raw = raw_df
self.context = context
self.cfp_dir = cfp_dir
self.qc_msg = {}
self.qc_data = None
self.fill_data = None
self.qc_row = None
def _qc_model_define(self):
'''
Init QC Model Method.
'''
self.qc_models = define_qc_models()
def _fill_model_define(self):
'''
Init Fill Model Method.
'''
self.fill_models = define_fill_models()
def _fill_value(self, data, src: list, dst: list, model):
'''
Predict Method to Fill Value.
'''
if len(src) == 1:
X = data[src].values.reshape(-1,1)
else:
X = data[src]
y_pred = model.predict(X)
return y_pred
def get_name(self):
print(self.name)
def set_name(self, name):
self.name = name
def get_qc_msg(self):
'''
Get qc msg dict.
'''
return self.qc_msg
def get_qc_data(self):
'''
Get qc data.
'''
return self.qc_data
def get_fill_data(self):
'''
Get filled data
'''
return self.fill_data
```
#### File: src/controllers/OcecController.py
```python
import os
import sys
import configparser
from copy import deepcopy
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
from sklearn.externals import joblib
from src.controllers.Controller import Controller
from src.cfg import PM, OCEC, OUT_FRACTION, RANDOM_STATE
class OcecController(Controller):
'''
OCEC Quality Control Class.
'''
def __init__(self, check_time, raw_df, context, cfp_dir, qc_model_dir, fill_model_dir):
super().__init__(
name='ocec_ctl',
check_time=check_time,
raw_df=raw_df,
context=context,
cfp_dir=cfp_dir)
# -> Controller
# self.qc_msg = {}
# self.qc_data = None
# self.qc_row = None
self.thds = {}
self.qc_model_dir = qc_model_dir
self.fill_model_dir = fill_model_dir
def _init_thd(self, stationcode):
'''
初始指定站点的阈值到self.thds
'''
cfp_file = os.path.join(self.cfp_dir, '{}.ini'.format(stationcode))
cfp_tmp = configparser.ConfigParser()
cfp_tmp.read(cfp_file)
for section in cfp_tmp.sections():
self.thds[section] = {}
for k, _ in cfp_tmp.items(section):
self.thds[section][k] = cfp_tmp.getfloat(section, k)
def _check_miss(self):
'''
处理缺失.
'''
self.raw.replace(-999.0, np.nan, inplace=True)
self.context.replace(-999.0, np.nan, inplace=True)
def _calc_index(self, df):
'''
计算相关指标.
'''
print(df)
df['OCEC'] = df[OCEC].apply(lambda x: x.sum(), axis=1)
df['OC/PM25'] = df['OC'] / df['PM25']
df['EC/PM25'] = df['EC'] / df['PM25']
df['OC/EC'] = df['OC'] / df['EC']
df['OCEC/PM25'] = df['OCEC'] / df['PM25']
return df
def _check_balance(self, station, row, context):
'''
检查 OC/EC
'''
# TODO:
tmp_dict = self.thds
self.qc_msg[station]['OC/EC'] = []
if np.isnan(row['OC/EC'].values[0]):
self.qc_msg[station]['OC/EC'].append(u'无OC/EC结果')
else:
val = np.round(row['OC/EC'].values[0], 3)
self.qc_msg[station]['OC/EC'].append(val)
if tmp_dict['OCEC']['exper_balance_lower']!=-999.0 and val < tmp_dict['OCEC']['exper_balance_lower']:
self.qc_msg[station]['OC/EC'].append(
u'{}小于经验斜率阈值下限{}'.format(val, tmp_dict['OCEC']['exper_balance_lower'])
)
if tmp_dict['OCEC']['exper_balance_upper']!=-999.0 and val > tmp_dict['OCEC']['exper_balance_upper']:
self.qc_msg[station]['OC/EC'].append(
u'{}大于经验斜率阈值上限{}'.format(val, tmp_dict['OCEC']['exper_balance_upper'])
)
if tmp_dict['OCEC']['stats_balance_lower']!=-999.0 and val < tmp_dict['OCEC']['stats_balance_lower']:
self.qc_msg[station]['OC/EC'].append(
u'{}小于统计斜率阈值下限{}'.format(val, tmp_dict['OCEC']['stats_balance_lower'])
)
if tmp_dict['OCEC']['stats_balance_upper']!=-999.0 and val > tmp_dict['OCEC']['stats_balance_upper']:
self.qc_msg[station]['OC/EC'].append(
u'{}大于统计斜率阈值上限{}'.format(val, tmp_dict['OCEC']['stats_balance_upper'])
)
def _check_thd(self, station, row, context):
'''
检查 数据浮动 OC/PM25 EC/PM25 OCEC/PM25 超过阈值
'''
# TODO:
tmp_dict = self.thds
self.qc_row = row[['time','stationcode']+PM+OCEC]
for x in ['OC', 'EC', 'OCEC']:
val = row['{}/PM25'.format(x)].values[0]
self.qc_msg[station][x] = []
if np.isnan(val) or val == 0.0:
self.qc_msg[station][x].append(-999.0)
self.qc_msg[station][x].append(u'缺失')
continue
val = np.round(val, 6)
self.qc_msg[station][x].append(val)
# 检查所有 OC/PM25 EC/PM25 阈值
if tmp_dict[x]['exper_ratio_upper']!=-999.0 and val > tmp_dict[x]['exper_ratio_upper']:
self.qc_msg[station][x].append(
u'{}大于占比经验上限{}'.format(val, tmp_dict[x]['exper_ratio_upper']))
if x == 'OCEC':
pass
else:
self.qc_row[x] = np.nan
if tmp_dict[x]['stats_ratio_upper']!=-999.0 and val > tmp_dict[x]['stats_ratio_upper']:
self.qc_msg[station][x].append(
u'{}大于占比统计上限{}'.format(val, tmp_dict[x]['stats_ratio_upper']))
if x == 'OCEC':
pass
else:
self.qc_row[x] = np.nan
# 检查OC EC变化浮动比率
if x == 'OCEC':
continue
if tmp_dict[x]['exper_float_upper']!=-999.0 and abs(context[x].diff().max()) > tmp_dict[x]['exper_float_upper']:
self.qc_msg[station][x].append(
u'{}大于前后浮动经验上限{}'.format(
abs(context[x].diff().max()),
tmp_dict[x]['exper_float_upper']))
self.qc_row[x] = np.nan
def _check_single(self, station):
'''
质控单一站点所有内容
'''
_row = self.raw[self.raw['stationcode']==station]
_context = self.context[self.context['stationcode']==station]
print(_row)
# print(_context)
self._check_thd(station, _row, _context)
self._check_balance(station, _row, _context)
def _model_predict(self, df, model_dir, _type, src=None):
'''
9个异常识别模型综合判别,最后voting取得结果
_type 选择特征项
'''
print(df[_type].shape)
for name, _ in self.qc_models.items():
model_file = os.path.join(model_dir, '{}.pkl'.format(name))
model = joblib.load(model_file)
df[name] = model.predict(df[_type])
df['ensemble'] = df[self.qc_models.keys()].apply(lambda x: x.sum(), axis=1)
df['ensemble'] = [1 if x > 4 else 0 for x in df['ensemble']]
print(df)
for _, row in df.iterrows():
# stationcode
if not self.qc_msg.__contains__(int(row['stationcode'])):
self.qc_msg[int(row['stationcode'])] = {}
# src
if not self.qc_msg[int(row['stationcode'])].__contains__(src):
self.qc_msg[int(row['stationcode'])][src] = []
# Add
self.qc_msg[int(row['stationcode'])][src].append(
u'模型判别异常' if row['ensemble']==1 else u'模型判别正常')
def _check_model(self):
'''
模型异常识别过程
'''
# 初始化模型
self._qc_model_define()
# 单变量模型
for x in OCEC:
df = self.raw[['stationcode', 'PM25', x]]
df.dropna(inplace=True)
if len(df) == 0:
print('No {} data'.format(x))
continue
else:
model_dir = os.path.join(self.qc_model_dir, x)
self._model_predict(df, model_dir, ['PM25', x], src=x)
# 全变量模型
df_ocec = self.raw[['stationcode', 'PM25'] + OCEC]
df_ocec.dropna(inplace=True)
if len(df_ocec) == 0:
print('No Ionic data.')
else:
model_dir = os.path.join(self.qc_model_dir, 'OCEC')
self._model_predict(df_ocec, model_dir, ['PM25','OC','EC'], src='OCEC')
def _model_fill(self):
'''
模型填数.
目前针对 PM25 -> OC EC
'''
self._fill_model_define()
self.fill_data = deepcopy(self.qc_data)
for x in OCEC:
df0 = self.fill_data[self.fill_data[PM[-1]].notna() & self.fill_data[x].isna()]
df1 = self.fill_data.append(df0).drop_duplicates(keep=False)
if len(df0) == 0:
continue
for name, _ in self.fill_models.items():
model_dir = os.path.join(self.fill_model_dir, x)
model_file = os.path.join(model_dir, '{}.pkl'.format(name))
model = joblib.load(model_file)
df0[name] = self._fill_value(df0, PM[-1:], [x], model)
df0[x] = df0[self.fill_models.keys()].apply(lambda x:np.mean(x), axis=1)
df0.drop(columns=self.fill_models.keys(), inplace=True)
self.fill_data = pd.concat([df0, df1])
print(self.fill_data)
print('~'*100)
def _qc_all(self):
'''
质控全部站点
'''
qc_list = []
for station in self.raw['stationcode'].unique():
print(station)
self.qc_msg[station] = {}
self._init_thd(station)
self._check_single(station)
qc_list.append(self.qc_row)
self.qc_data = pd.concat(qc_list, join='outer')
def step_control(self):
'''
内部主流程
'''
print(self.name)
self._check_miss()
if set(OCEC) < set(self.raw.columns):
self.raw = self._calc_index(self.raw)
print(self.raw)
self.context = self._calc_index(self.context)
self._qc_all()
self._check_model()
# 修改key为int类型
self.qc_msg = {int(k): v for k, v in self.qc_msg.items()}
self._model_fill()
return self.get_qc_msg()
else:
print(self.raw)
self.qc_data = self.raw
# self.qc_data['time'] =
self.qc_data['OC'] = np.nan
self.qc_data['EC'] = np.nan
self._model_fill()
print(self.fill_data)
return self.get_qc_msg()
```
#### File: Pm_Composition_Quallity_Control/src/fill_model_train.py
```python
import os
import sys
import joblib
import warnings
warnings.filterwarnings('ignore')
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
from sklearn.svm import SVR
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import BaggingRegressor
from .dao.get_rawdata import read_raw_txt, read_ini
from cfg import paths, PM, IONIC, OCEC, METAL, FILL_SRC, FILL_DST
def get_dataset(raw_file, qc_file):
'''
获取原始与质控后数据.
缺失已替换nan
'''
assert os.path.exists(raw_file) and os.path.exists(qc_file)
cols = ['time','stationcode','longitude','latitude'] + PM + IONIC + OCEC + METAL
raw_df = read_raw_txt(raw_file, header=cols)[1]
qc_df = read_raw_txt(qc_file, header=cols)[1]
raw_df.replace(-999.0, np.nan, inplace=True)
qc_df.replace(-999.0, np.nan, inplace=True)
return raw_df, qc_df
def define_model():
'''
Model Defination.
'''
# 扩展相关性算法
regressors = {
'LR': LinearRegression(fit_intercept=True),
'SVR': SVR(kernel='linear'),
'DTR': DecisionTreeRegressor(max_depth=3),
'RFR': RandomForestRegressor(n_estimators=10, max_depth=3),
'BGR': BaggingRegressor()
}
return regressors
def select_data(param_list: list, train_df):
'''
param_list 选择特征列, 训练不同的模型.
train_df, 选择不同数据源: raw or qc.
'''
df = train_df[param_list]
df.dropna(inplace=True)
print(df.sample(5))
return df
def checkdir(path: str):
'''
检查目录
'''
if not os.path.exists(path):
os.makedirs(path)
assert os.path.exists(path)
def train(data, models, model_dir):
'''
Train.
'''
# TODO: 针对PM25缺失,是否考虑将其加入特征项
# PM25 + param
savedir = os.path.join(model_dir, FILL_DST[0])
checkdir(savedir)
# train multi-models
for i, (reg_name, reg) in enumerate(models.items()):
print('{}.\tfitting:\t{}'.format(i+1, reg_name))
# print(data.shape)
if len(FILL_SRC) == 1:
X = data[FILL_SRC].values.reshape(-1,1)
y = data[FILL_DST].values.reshape(-1,1)
else:
X = data[FILL_SRC]
y = data[FILL_DST]
reg.fit(X, y)
joblib.dump(reg, os.path.join(savedir, '{}.pkl'.format(reg_name)))
def main():
# Dir
raw_dir = paths.get('obs_data_raw')
qc_dir = paths.get('obs_addpm_dir')
model_dir = paths.get('models_fill')
# 基于检测总站的数据进行训练
f = '110000012.txt'
rawfile, qc_file = os.path.join(raw_dir, f), os.path.join(qc_dir, f)
# Normally based on QC data
raw_df, qc_df = get_dataset(rawfile, qc_file)
# train data
print(FILL_SRC+FILL_DST)
train_set = select_data(FILL_SRC+FILL_DST, qc_df)
models = define_model()
assert len(FILL_DST) == 1
train(train_set, models, model_dir)
if __name__ == "__main__":
main()
```
#### File: src/mylog/logger.py
```python
import os
import logging
import logging.handlers
import time
def init_logger(log_file):
dir_path = os.path.dirname(log_file)
try:
if not os.path.exists(dir_path):
os.makedirs(dir_path)
except Exception as e:
pass
handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=30 * 1024 * 1024, backupCount=10)
fmt = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
formatter = logging.Formatter(fmt)
handler.setFormatter(formatter)
#logger_instance = logging.getLogger('logs')
logger_instance = logging.getLogger(log_file.split("/")[-1])
logger_instance.addHandler(handler)
#logger_instance.setLevel(logging.DEBUG)
logger_instance.setLevel(logging.INFO)
return logger_instance
```
#### File: src/utils/utils_main.py
```python
import os
import sys
sys.path.append('../dao')
import numpy as np
import pandas as pd
from dao.get_rawdata import read_raw_txt
IONIC = [
'time', 'stationcode', 'PM10', 'PM25', 'SO42-', 'F-',
'NO3-', 'NH4+', 'Cl-', 'Na+', 'Ca2+', 'Mg2+', 'K+'
]
OCEC = ['time', 'stationcode', 'PM10', 'PM25', 'OC', 'EC']
METAL = [
'time','stationcode','PM10','PM25','Hg','Br','As','Si','Se','Te','V','Ca','Ti','Ba','Sc','Pd','Co',
'Mo','K','Fe','Pb','TI','Cu', 'Al','Cr','Cs','Ag', 'Zn','Sb','Sn','Mn','Cd','Ni','Ga'
]
def split_obs(df):
'''
考虑数据切割时不同列的缺失.
'''
obs_ionic = df[[x for x in IONIC if x in df.columns]]
for x in IONIC:
if x not in obs_ionic.columns:
obs_ionic[x] = np.nan
else:
continue
obs_ocec = df[[x for x in OCEC if x in df.columns]]
for x in OCEC:
if x not in obs_ocec.columns:
obs_ocec[x] = np.nan
else:
continue
obs_metal = df[[x for x in METAL if x in df.columns]]
for x in METAL:
if x not in obs_metal.columns:
obs_metal[x] = np.nan
else:
continue
return obs_ionic, obs_ocec, obs_metal
def concat_data(time_list: list, datadir: str):
'''
数据拼接.
'''
data_list = []
for _, t in enumerate(time_list):
obs_file = 'obs_com_{}.txt'.format(t.strftime("%Y%m%d%H"))
obs_df = read_raw_txt(os.path.join(datadir, obs_file))[1]
obs_df['time'] = t
# print(obs_df)
data_list.append(obs_df)
if len(data_list) > 0:
return pd.concat(data_list, axis=0, join='outer')
else:
return None
def checkdir(path):
'''
判断路径是否存在,不存在则创建.
'''
if not os.path.exists(path):
os.makedirs(path)
assert os.path.exists(path)
``` |
{
"source": "joecai6/lib-search",
"score": 3
} |
#### File: lib-search/search/textsearch.py
```python
import csv
import sys
import pandas as pd
import numpy as np
import time
from fuzzywuzzy import fuzz
import recordlinkage
#https://pbpython.com/record-linking.html
#import fuzzywuzzy
def match_ratio_title(row, query):
title = row['Title'].lower()
words = query.strip().split(' ')
matches = 0
if words[0] == '':
return False
for word in words:
if word.lower() in title:
matches += 1
return (matches >= 1)
def get_file(name):
path = '../parsed_data/authors_pkl/'
file_name = 'author_' + str(name[0].upper()) + '.pkl'
return path + file_name
start = time.time()
#df = pd.read_pickle('../test_data/records_test.pkl')
'''
Record linking using text algorithms
indexer = recordlinkage.Index()
indexer.full()
checks = indexer.index(df, df_q)
print(len(checks))
comp = recordlinkage.Compare()
comp.string('Title', 'Title', method='jarowinkler', threshold=0.85, label='Title')
matched = comp.compute(checks, df, df_q)
#print(matched.sum(axis=1).value_counts().sort_index(ascending=False))
df_matched = matched[matched.sum(axis=1) >= 1].reset_index()
df_matched['Score'] = df_matched.loc[:, 'Title']
print(df_matched)
print(time.time()-start)
print(df.loc[df_matched.iloc[0,0],:])
print(df_q.loc[df_matched.iloc[0,1],:])
'''
'''
Pandas Test
titles = df["Title"]
title_counts = titles.value_counts()
#print(df.count())
#print(df.head(10))
#print(title_counts)
small = df.loc[:,:]
small = small[["Author", "Record", "Title","Publisher","Place","Date","Edition"]]
small = small.sort_values('Author')
'''
'''
Splitting into keywords
small['Words'] = small['Title'].str.strip().str.split('[\W_]+')
new_small = pd.DataFrame(columns=['Title', 'Words'])
for i, row in small.iterrows():
words = row['Words']
for w in words:
new_small = new_small.append({'Words': w.lower(), 'Title': row['Title']}, ignore_index=True)
new_small = new_small[new_small['Words'].str.len() > 0]
print(new_small.tail(10))
res = new_small[new_small['Words'] == 'the']
print(res)
'''
'''
grouped = small.groupby('Author')
grouped = grouped.apply(lambda x: x.sort_values(['Author']))
small.to_excel("out.xlsx")
print(grouped)
'''
while True:
author_last = input('Enter the author\'s last name:')
if(author_last == 'q'):
break
df_auth = pd.read_pickle(get_file(author_last))
df_auth = df_auth[df_auth['Author'].str.contains(author_last, regex=False, case=False)]
print(df_auth)
query = input('Enter the title: ')
df_title = df_auth[df_auth['Title'].str.contains(query, regex=False, case=False)]
print(df_title)
#print(df[df.apply(lambda row: match_ratio_title(row,query), axis=1)])
#print(df[df.apply(lambda row: match_ratio(row, query), axis=1) > 50])
#to optimize use some sort of data structure to have alphabetical order
``` |
{
"source": "Joecakes4u/gcalendar",
"score": 4
} |
#### File: Joecakes4u/gcalendar/Calendar.py
```python
import httplib2
import oauth2client
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
class Calendar:
"""Stores data to make Google Calendar API happy"""
secret_path = ""
application_name = ""
credentials = ""
http = ""
service = ""
def __init__(self, secret_path, application_name):
"""Instantiate Calendar, keep track of secret path"""
self.SCOPES = 'https://www.googleapis.com/auth/calendar'
self.CREDENTIALS_DIR = "credentials/"
self.secret_path = secret_path
self.application_name = application_name
def get_credentials(self):
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
if not os.path.exists(self.CREDENTIALS_DIR):
os.makedirs(self.CREDENTIALS_DIR)
credential_path = os.path.join(self.CREDENTIALS_DIR,'calendar.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(self.secret_path+'/client_secret.json', self.SCOPES)
flow.user_agent = self.application_name
credentials = tools.run_flow(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def set_calendar_vars(self):
self.credentials = self.get_credentials()
self.http = self.credentials.authorize(httplib2.Http())
self.service = discovery.build('calendar', 'v3', http=self.http)
print type(self.service)
``` |
{
"source": "Joecakes4u/yelp_NLP",
"score": 3
} |
#### File: Joecakes4u/yelp_NLP/parse.py
```python
from elasticsearch import Elasticsearch
def parse(file=None):
try:
with open(file, 'r') as myfile:
data=myfile.read().split('\n')
es = Elasticsearch(['localhost:9200'], http_auth=('elastic','<PASSWORD>'))
i = 1
for d in data:
res = es.index(index="yelp", doc_type='review', id=i, body=d)
i += 1
print(str(i)+": "+str(res['created']))
except Exception as e:
print str(e)
if __name__ == "__main__":
# insert file path
file = ""
parse(file)
``` |
{
"source": "JoeCameron1/IndividualProject",
"score": 3
} |
#### File: IndividualProject/KnotClassifier/knotAutoencoder.py
```python
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from keras import backend as K
from keras.preprocessing.image import ImageDataGenerator
from keras.datasets import mnist
from keras.callbacks import TensorBoard
import numpy as np
import matplotlib.pyplot as plt
def tuple_generator(generator):
for batch in generator:
yield (batch, batch)
img_width = 148
img_height = 148
train_data_dir = 'dataResized/train'
validation_data_dir = 'dataResized/validation'
epochs = 50
batch_size = 128
nb_train_samples = 1152
nb_validation_samples = 226
input_img = Input(shape=(img_width, img_height, 3))
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
train_datagen = ImageDataGenerator(rescale=1. / 255)
test_datagen = ImageDataGenerator(rescale=1. / 255)
# TRAINING GENERATOR
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None)
# VALIDATION GENERATOR
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None)
# MODEL FITTING
fit = autoencoder.fit_generator(
tuple_generator(train_generator),
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=tuple_generator(validation_generator),
validation_steps=nb_validation_samples // batch_size,
shuffle=True)
img = next(validation_generator)[:1]
dec = autoencoder.predict(img)
img = img[0]
dec = dec[0]
img = (img*255).astype('uint8')
dec = (dec*255).astype('uint8')
plt.imshow(np.hstack((img, dec)))
plt.title('Original (Validation) and Reconstructed Images')
plt.show()
img = next(train_generator)[:1]
dec = autoencoder.predict(img)
img = img[0]
dec = dec[0]
img = (img*255).astype('uint8')
dec = (dec*255).astype('uint8')
plt.imshow(np.hstack((img, dec)))
plt.title('Original (Train) and Reconstructed Images')
plt.show()
```
#### File: IndividualProject/KnotClassifier/knotClassifier.py
```python
import argparse
parser = argparse.ArgumentParser(description='Train a convolutional neural network to classify knots.')
group = parser.add_mutually_exclusive_group()
group.add_argument('-s', '--small', action='store_true', help='Use small model architecture')
group.add_argument('-l', '--large', action='store_true', help='Use large model architecture')
group2 = parser.add_mutually_exclusive_group()
group2.add_argument('-a', '--augmentation', action='store_true', help='Use data augmentation')
args = parser.parse_args()
# -----------------------------------------------------------
# IMPORT STATEMENTS
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense, BatchNormalization
from keras.layers.noise import GaussianNoise
from keras.utils import np_utils
from keras import backend as K
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.metrics import confusion_matrix
import itertools
# -----------------------------------------------------------
# GLOBAL VARIABLES
# Target dimensions for the images
# (150, 150) has been shown to be an optimal image size for training
img_width, img_height = 150, 150
# Global variables that are directory specific
train_data_dir = 'dataResized/train'
validation_data_dir = 'dataResized/validation'
nb_train_samples = 1170
nb_validation_samples = 274
epochs = 100
batch_size = 32
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
# -----------------------------------------------------------
# CNN MODELS
# SMALL CNN MODEL
if args.small:
print 'You are using the small CNN model architecture'
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(32))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(10))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
print model.summary()
# LARGE CNN MODEL
elif args.large:
print 'You are using the large CNN model architecture'
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(10))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
print model.summary()
# MEDIUM CNN MODEL
else:
print 'You are using the medium CNN model architecture'
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(10))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
print model.summary()
# -----------------------------------------------------------
# DATA AUGMENTATION
if args.augmentation:
print 'You are using data augmentation'
# Training Augmentation Configuration
# Rotates an image for every degree
# Rescales images
# Modifies shear intensity
# Modifies zoom
# Shifts width
# Shifts height
# Flips images horizontally
# Flips images vertically
train_datagen = ImageDataGenerator(
rotation_range=360,
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.3,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True,
vertical_flip=True
)
# Testing Augmentation Configuration
# Only Rescales images
# Very important for the validation data to have no augmentation
# Enables validation on real data, and not augmented data
test_datagen = ImageDataGenerator(
rescale=1. / 255
)
# NO DATA AUGMENTATION
else:
print 'You are not using data augmentation'
# Training Augmentation Configuration
# Only rescales images
# No augmentation
train_datagen = ImageDataGenerator(
rescale=1. /255
)
# Testing Augmentation Configuration
# Only rescales images
# No augmentation
test_datagen = ImageDataGenerator(
rescale=1. /255
)
# -----------------------------------------------------------
# TRAINING GENERATOR
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical')
# VALIDATION GENERATOR
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical')
# MODEL FITTING
fit = model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size,
shuffle=True)
# SAVE MODEL (INCLUDING WEIGHTS)
model.save('first_try.h5')
# -----------------------------------------------------------
# TSNE VISUALISATION
predictions = model.predict_generator(validation_generator,
steps=nb_validation_samples)
# First, reduce to 10 dimensions with PCA
pca = PCA(n_components=10)
pca_results = pca.fit_transform(predictions)
print('Variance PCA: {}'.format(np.sum(pca.explained_variance_ratio_)))
# Next, run t-SNE on the PCA results to obtain a 2D plot
tsne = TSNE(n_components=2, perplexity=30, learning_rate=250, verbose = 1)
tsne_results = tsne.fit_transform(pca_results[:5000])
# Convert to binary class matrix
categoricalClasses = np_utils.to_categorical(validation_generator.classes[:5000], num_classes = 10)
# Create a figure where each class has a unique colour
colour_map = np.argmax(categoricalClasses, axis=1)
tsneFigure = plt.figure(figsize=(10,10))
for colour in range(10):
indices = np.where(colour_map==colour)
indices = indices[0]
plt.scatter(tsne_results[indices,0],
tsne_results[indices,1],
label=colour)
plt.legend()
plt.title('t-SNE Visualisation')
tsneFigure.savefig('tsneVisualisation.jpg')
plt.close()
# -----------------------------------------------------------
# PLOT TRAINING HISTORY
historyFigure, (left, right) = plt.subplots(ncols=2, figsize=(20,10))
# Plot the training history loss
def plotHistoryLoss(fit):
left.plot(fit.history['loss'],label="Training Loss")
left.plot(fit.history['val_loss'],label="Validation Loss")
left.set_title('Model Loss')
left.set_xlabel('Epoch')
left.set_ylabel('Loss')
left.legend(loc='upper left')
# Plot the training history accuracy
def plotHistoryAccuracy(fit):
right.plot(fit.history['acc'],label="Training Accuracy")
right.plot(fit.history['val_acc'],label="Validation Accuracy")
right.set_title('Model Accuracy')
right.set_xlabel('Epoch')
right.set_ylabel('Accuracy')
right.legend(loc='upper left')
plotHistoryLoss(fit)
plotHistoryAccuracy(fit)
historyFigure.savefig('trainingHistory.jpg')
plt.close()
# -----------------------------------------------------------
# PLOT CONFUSION MATRIX
matrix_predictions = model.predict_generator(validation_generator)
matrix_predictions = np.argmax(matrix_predictions, axis=-1)
print validation_generator.classes
print matrix_predictions
confusionMatrix = confusion_matrix(validation_generator.classes, matrix_predictions)
class_names = ['Alpine Butterfly Knot', 'Bowline Knot', 'Clove Hitch', 'Figure-8 Knot', 'Figure-8 Loop',
'Fisherman Knot', 'Flemish Bend', 'Overhand Knot', 'Reef Knot', 'Slip Knot']
# plot_confusion_matrix function obtained from sklearn documentation
# Confusion Matrix Examples
# http://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
np.set_printoptions(precision=2)
# Plot Confusion Matrix
final_confusion_matrix = plt.figure(figsize=(20, 10))
plot_confusion_matrix(confusionMatrix, classes=class_names,
title='Confusion Matrix')
final_confusion_matrix.savefig('confusionMatrix.jpg')
# Plot Normalised Confusion Matrix
final_normalised_confusion_matrix = plt.figure(figsize=(20, 10))
plot_confusion_matrix(confusionMatrix, classes=class_names, normalize=True,
title='Normalised Confusion Matrix')
final_normalised_confusion_matrix.savefig('normalisedConfusionMatrix.jpg')
plt.close()
``` |
{
"source": "JoeCare/flask_geolocation_api",
"score": 2
} |
#### File: flask_geolocation_api/app/__init__.py
```python
import connexion, os
from connexion.resolver import RestyResolver
from flask import json
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
# Globally accessible libraries
db = SQLAlchemy()
mm = Marshmallow()
def init_app():
"""Initialize the Connexion application."""
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
openapi_path = os.path.join(BASE_DIR, "../")
conn_app = connexion.FlaskApp(
__name__, specification_dir=openapi_path, options={
"swagger_ui": True,
"serve_spec": True
}
)
conn_app.add_api("openapi.yaml", resolver=RestyResolver('run'),
strict_validation=True)
# Flask app and getting into app_context
app = conn_app.app
# Load application config
app.config.from_object('config.ProdConfig')
app.json_encoder = json.JSONEncoder
# Initialize Plugins
db.init_app(app)
mm.init_app(app)
with app.app_context():
# Include our Routes/views
import run
# Register Blueprints
# app.register_blueprint(auth.auth_bp)
# app.register_blueprint(admin.admin_bp)
return app
```
#### File: flask_geolocation_api/app/models.py
```python
from sqlalchemy import Column, Integer, Text, JSON, String
from werkzeug.security import generate_password_hash as gpass
from werkzeug.security import check_password_hash as chpass
import ipaddress, uuid
from dotenv import load_dotenv, find_dotenv
from app import db, mm
load_dotenv(find_dotenv())
class Geolocation(db.Model):
__tablename__ = 'geolocation'
id = Column(Integer, primary_key=True, autoincrement=True,
nullable=True)
input_data = Column(Text, nullable=True)
ip = Column(String, nullable=True)
type = Column(String, nullable=True)
continent_code = Column(String, nullable=True)
continent_name = Column(String, nullable=True)
country_code = Column(String, nullable=True)
country_name = Column(String, nullable=True)
region_name = Column(String, nullable=True)
city = Column(String, nullable=True)
latitude = Column(String, nullable=True)
longitude = Column(String, nullable=True)
location = Column(JSON, nullable=True)
visible = Column(Integer, nullable=False, default=1)
def __init__(self, dictionary, user_input='check'):
setattr(self, "input_data", user_input)
for k, v in dictionary.items():
setattr(self, k, v)
def serialize(self):
"""Serialize record fields for list view"""
return {
"id": self.id,
"ip_address": self.ip,
"ip_type": self.type,
"continent_name": self.continent_name,
"country": self.country_name,
"region": self.region_name,
"city": self.city,
"latitude": self.latitude,
"longitude": self.longitude,
}
def short(self):
"""Serialize record output with most essential fields."""
return {
"id": self.id,
"ip_address": self.ip,
"county_code": self.country_code,
"city": self.city,
}
class GeolocationSchema(mm.SQLAlchemyAutoSchema):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class Meta:
model = Geolocation
alchemy_session = db.session
load_instance = True
exclude = ['visible']
class User(db.Model):
__tablename__ = 'user'
id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
public_id = Column(String(50), unique=True)
login = Column(String, nullable=False)
password = Column(Text, nullable=False)
first_name = Column(String, nullable=True)
last_name = Column(String, nullable=True)
email = Column(String, nullable=True)
def __init__(self, login, password):
self.password = <PASSWORD>(password, salt_length=6)
self.login = login
self.public_id = str(uuid.uuid4())
def detailed(self):
"""Serialize record with all available data"""
return {
"user_id": self.id,
"login": self.login,
"password_hash": self.password,
"firstname": self.first_name,
"lastname": self.last_name,
"email": self.email,
"public_id": self.public_id,
}
def serialize(self):
"""Serialize record output without password"""
return {
"user_id": self.id,
"login": self.login,
"firstname": self.first_name,
}
@staticmethod
def login_validation(_password, current_pass=password, usr_id=id):
if current_pass == _password:
return usr_id
elif chpass(current_pass, _password):
return usr_id
else:
return False
class UserSchema(mm.SQLAlchemyAutoSchema):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class Meta:
model = User
alchemy_session = db.session
load_instance = True
exclude = ['password', 'email']
def ip_validator(_ip):
ip = _ip.replace("'","")
try:
return bool(ipaddress.ip_address(ip))
except ValueError:
return False
# def init_db():
# db.create_all()
# db.create_all()
```
#### File: JoeCare/flask_geolocation_api/run.py
```python
from flask import json, request, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import requests, os, time, six, connexion
from connexion.resolver import RestyResolver
from werkzeug.exceptions import Unauthorized
from jose import JWTError, jwt
from app.models import (
db, mm, ip_validator, Geolocation, GeolocationSchema,
User, UserSchema, gpass, chpass,
load_dotenv, find_dotenv)
load_dotenv(find_dotenv())
def main_page():
response = {"Main endpoints":
{
"Geolocations": "/geolocations",
"Users": "/users",
"Login": "/auth/login",
"Swagger UI": "/ui",
"spec file": "/openapi.json",
}
}
return jsonify(response)
def create():
"""
Create a new geolocation record from data object passed with request
:param geolocation: table of which record will be created; instance
class
:return: 201 on success, 406 if instance exists
"""
if request.method == 'POST':
dict_data = request.get_json()
new_loc = Geolocation(dict_data)
db.session.add(new_loc)
db.session.commit()
return jsonify(
201, f"Geolocation created for: {new_loc.id}", dict_data)
def create_with_ip(input_ip):
"""
Create a new geolocation record from data collected basing on given IP
:param input_ip: IPv4 or IPv6 address passed to endpoints URL
:return: 201 on success, 406 if instance exists, 422 on input
unprocessable in geolocalization process
"""
if ip_validator(input_ip):
if request.method == 'POST':
get_details = requests.get(
f'http://api.ipstack.com/{input_ip}?access_key'
f'={os.getenv("IPSTACK_KEY")}&output=json')
if get_details.status_code == 200:
details = json.loads(get_details.content.decode())
# third_set.append(details)
new_loc = Geolocation(details, input_ip)
db.session.add(new_loc)
db.session.commit()
return jsonify(
201, f"Geolocation data collected for: {input_ip}",
details)
else:
return jsonify(
422, "Unprocessable input. Not correct IPv4/IPv6 address.")
def create_with_domain(input_domain):
"""
Create a new geolocation record from data collected basing on given domain
:param input_domain: domain address passed to endpoints URL
:return: 201 on success, 406 if instance exists,
422 on input unprocessable in geolocalization process
"""
if request.method == 'POST':
get_details = requests.get(
f'http://api.ipstack.com/{input_domain}?access_key'
f'={os.getenv("IPSTACK_KEY")}&output=json')
if get_details.status_code == 200:
details = json.loads(get_details.content.decode())
# third_set.append(details)
new_loc = Geolocation(details, input_domain)
db.session.add(new_loc)
db.session.commit()
return jsonify(201, f"Record created for: {input_domain}", details)
else:
return jsonify(
422, "Unable to collect geolocation data. \
Please check your input or try again in a while.")
def retrieve_all():
"""
Retrieve list of all records in data table
:return: list of matching objects
"""
locations = Geolocation.query.filter(Geolocation.visible == 1).all()
if locations:
return jsonify([loc.serialize() for loc in locations])
return jsonify(404, f"Records not found.")
def retrieve_one(loc_id):
"""
Return one record from the collection matching given ID
:param loc_id: record ID for localization data
:return: matching data object
"""
query = Geolocation.query.filter(Geolocation.visible == 1).filter(
Geolocation.id == loc_id).one_or_none()
# query = Geolocation.query.filter_by(id=loc_id)
# print(jsonify(query))
if query is not None:
schema = GeolocationSchema()
data = schema.dump(query)
return data
else:
return jsonify(404, f"Record not found for ID: {loc_id}")
def update_one(loc_id, geolocation):
"""
Update an existing record with given data
:param loc_id: ID of the record to update
:param geolocation: data given to update record
:return: 200, updated record, 404 if ID not found
"""
to_update = Geolocation.query.filter(
Geolocation.id == loc_id).one_or_none()
if to_update:
# # use db model schema
schema = GeolocationSchema()
# geolocation object (dict) -> db model geolocation instance
input_to_db = schema.load(geolocation, session=db.session)
# Set the id to the person we want to update
input_to_db.id = to_update.id
db.session.merge(input_to_db)
db.session.commit()
#
# # return updated person in the response
output_dump = schema.dump(input_to_db)
return jsonify(200, output_dump)
else:
return jsonify(404, f"Person not found for Id: {loc_id}")
def safe_delete(loc_id):
"""
Remove object from main collection but leaving record in a database
:param loc_id: ID of the record to delete
:return: 200 on successful delete, 404 if not found
"""
location = Geolocation.query.filter_by(id=loc_id).one_or_none()
if location:
# db.session.remove(location)
location.visible = 0
db.session.merge(location)
db.session.commit()
return jsonify(
202, f"Removed record from main API for ID: {loc_id}")
else:
jsonify(404, f"Record not found in database for ID: {loc_id}")
def list_deleted():
"""
List of records removed from API by safe_delete
:return: list of records on success, 404 if not found
"""
locations = Geolocation.query.filter(Geolocation.visible == 0).all()
if locations:
schema = GeolocationSchema(many=True)
data = schema.dump(locations)
return jsonify(
200, f"You've {len(locations)} records safely removed from main "
f"collection.", [loc.short() for loc in locations])
else:
return jsonify(404, "No records stored after safe-delete.")
def restore_deleted(loc_id):
"""
PUT request sent to this endpoint restore record of given ID to main API
view. Works on records which were previously removed with default
safe_delete method.
list to
main API
:param loc_id: ID of the record to restore
:return: 200 on success, 404 if not found
"""
location = Geolocation.query.filter(Geolocation.visible == 0).filter_by(
id=loc_id).one_or_none()
if location:
if request.method == 'PUT':
location.visible = 1
db.session.merge(location)
db.session.commit()
return jsonify(
200, f"Record restored for ID: {loc_id}")
else:
return jsonify(405, "Valid methods on that endpoint: PUT, DELETE")
else:
jsonify(404, f"Record not found in database for ID: {loc_id}")
def remove_deleted(loc_id):
"""
Delete permanently record of given ID from safe_deleted list.
:param loc_id: ID of the record to restore
:return: 200 on success, 404 if not found
"""
location = Geolocation.query.filter(Geolocation.visible == 0).filter_by(
id=loc_id).one_or_none()
if location:
if request.method == 'DELETE':
db.session.delete(location)
db.session.commit()
return jsonify(
200, f"Record permanently removed for ID: {loc_id}")
return jsonify(405, "Valid methods on that endpoint: PUT, DELETE")
else:
jsonify(404, f"Record not found in database for ID: {loc_id}")
# AUTH simple JWT with jose
#========================
JWT_ISSUER = 'com.zalando.connexion'
JWT_SECRET = os.getenv("JWT_SECRET")
JWT_LIFETIME_SECONDS = 900
JWT_ALGORITHM = os.getenv("JWT_ALGORITHM")
def generate_token(public_id):
"""
Simple token generator returning encoded JWT
:param public_id: unique string user identification
:return JWT: authorization token for given public_id
"""
# if User.query.filter_by(public_id=public_id).one_or_none() is None:
# return jsonify(404, "ID unverified")
# else:
timestamp = int(time.time())
payload = {
"iss": JWT_ISSUER,
"iat": int(timestamp),
"exp": int(timestamp + JWT_LIFETIME_SECONDS),
"sub": str(public_id),
}
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
def decode_token(token):
try:
return jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
except JWTError as e:
six.raise_from(Unauthorized, e)
def refresh_token(token):
"""Get new token from last stored in cookies"""
try:
token_dict = jwt.decode(
token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
print("expired to refresh:", token_dict)
except JWTError as e:
print("JWTError with dict occured:", e)
else:
user_pub_id = token_dict['sub']
return jsonify({"Refreshed_token": generate_token(user_pub_id)})
def cookie_token():
"""Get new token from last stored in cookies
With cheating - decoder omits token expiration time
and should always return new JWT."""
access_token = request.cookies.get('jwttoken')
try:
jwt_dict = jwt.decode(
access_token, JWT_SECRET,
algorithms=[JWT_ALGORITHM], options={'verify_exp': False}
)
print("!!!!!!!!!",jwt_dict, access_token)
except AttributeError as e:
print("JWTError occurred decoding to dict:", e)
else:
user_pub_id = jwt_dict['sub']
return jsonify(
{"Authenticated": user_pub_id,
"Bearer": generate_token(user_pub_id)})
# USERS
#=======================
def retrieve_all_users():
"""
Retrieve list of all records in Users table
:return: list of matching objects
"""
users = User.query.all()
if users:
return jsonify(200, [usr.serialize() for usr in users])
else:
return jsonify(204, f"Records not found.")
def retrieve_one_user(user_id):
"""
Return one record from the collection matching given ID
:param user_id: user basic ID number
:return: matching data object
"""
query = User.query.filter(User.id == user_id).one_or_none()
if query:
return jsonify(200, query.detailed())
else:
return jsonify(404, f"Record not found for ID: {user_id}")
def register():
"""
Create new User instance from given credentials and optional extra data
:param login: given user login
:param password: given password for authentication
:param first_name: user first name
:param last_name: user last name
:param email: user email address
:return: list of matching objects
"""
login = request.json.get("login", None)
password = request.json.get("password", None)
first_name = request.json.get("first_name")
last_name = request.json.get("last_name")
email = request.json.get("email")
print(login, password, first_name, last_name, email)
query = User.query.filter_by(login=login).one_or_none()
if query:
return jsonify(
201, "Similar instance already exists. Try different login.")
else:
new_user = User(login, password)
if first_name:
new_user.first_name = first_name
if last_name:
new_user.last_name = last_name
if email:
new_user.email = email
# fourth_set.append(new_user.serialize())
db.session.add(new_user)
db.session.commit()
new = User.query.filter_by(login=login).one()
return jsonify({
"Registered with": new_user.public_id,
"Bearer": generate_token(new.public_id)
})
def log_in():
"""
The Simplest API login.
:param requestBody: require passing correct login and password of
existing user
:return JWT: encoded authorization token for given user on success,
401/404 on incorrect credentials
"""
user = request.get_json()
lgn = user['login']
pwd = user['password']
query = User.query.filter_by(login=lgn).one_or_none()
if query:
check = chpass(query.password, pwd)
if check:
# print(f"Credentials correct for {lgn}")
jwt_token = generate_token(query.public_id)
auth_dict = {
"Authenticated as": query.login,
"Bearer": jwt_token
}
response = make_response(jsonify(auth_dict))
# response.headers["Authorization"] = f"Bearer {jwt_token}"
# response.set_cookie(key='jwttoken', value=jwt_token)
return response
else:
jsonify(401, "Wrong password.")
else:
return jsonify(
404,
"Login not found in database. "
"Please check Your input again or register."
)
# conned_app.add_url_rule()
# def to_json():
# third_set.extend(fourth_set)
# data_set = json.dumps(third_set)
# with open('backup.json', 'a') as backup:
# backup.write(third_set)
# if __name__ == '__main__':
# # init_db()
# conned_app.add_api('openapi.yaml') # , resolver=RestyResolver('run'))
# # conned_app.run(host='127.0.0.1', port=5000, debug=True)
# # port = int(os.environ.get('PORT', 5000))
# # conned_app.run(host='0.0.0.0', port=port, debug=False)
# conned_app.run()
``` |
{
"source": "joechainz/salt-ext-modules-vmware",
"score": 2
} |
#### File: unit/modules/test_vmc_security_groups.py
```python
from unittest.mock import patch
import pytest
import saltext.vmware.modules.vmc_security_groups as vmc_security_groups
from saltext.vmware.utils import vmc_constants
@pytest.fixture
def security_groups_data_by_id(mock_vmc_request_call_api):
data = {
"expression": [
{
"member_type": "VirtualMachine",
"key": "OSName",
"operator": "EQUALS",
"value": "Centos",
"resource_type": "Condition",
"id": "306e22a9-0060-4c11-8557-2ed927887e40",
"path": "/infra/domains/cgw/groups/TEST_GROUP/condition-expressions/306e22a9-0060-4c11-8557-2ed927887e40",
"relative_path": "306e22a9-0060-4c11-8557-2ed927887e40",
"parent_path": "/infra/domains/cgw/groups/TEST_GROUP",
"marked_for_delete": False,
"overridden": False,
"_protection": "NOT_PROTECTED",
}
],
"extended_expression": [],
"reference": False,
"resource_type": "Group",
"id": "security_group_id",
"display_name": "security_group_id",
"description": "TEST Secority group",
"path": "/infra/domains/cgw/groups/TEST_GROUP",
"relative_path": "TEST_GROUP",
"parent_path": "/infra/domains/cgw",
"unique_id": "a6722585-da81-4609-be25-25cd7f7a89f2",
"marked_for_delete": False,
"overridden": False,
"_create_time": 1618809345031,
"_create_user": "<EMAIL>",
"_last_modified_time": 1618809345041,
"_last_modified_user": "<EMAIL>",
"_system_owned": False,
"_protection": "NOT_PROTECTED",
"_revision": 0,
}
mock_vmc_request_call_api.return_value = data
yield data
@pytest.fixture
def security_groups_data(mock_vmc_request_call_api, security_groups_data_by_id):
data = {"result_count": 1, "results": [security_groups_data_by_id]}
mock_vmc_request_call_api.return_value = data
yield data
def test_get_security_groups_should_return_api_response(security_groups_data):
assert (
vmc_security_groups.get(
hostname="hostname",
refresh_key="refresh_key",
authorization_host="authorization_host",
org_id="org_id",
sddc_id="sddc_id",
domain_id="domain_id",
verify_ssl=False,
)
== security_groups_data
)
def test_get_security_groups_called_with_url():
expected_url = (
"https://hostname/vmc/reverse-proxy/api/orgs/org_id/sddcs/sddc_id/policy/api/"
"v1/infra/domains/domain_id/groups"
)
with patch("saltext.vmware.utils.vmc_request.call_api", autospec=True) as vmc_call_api:
result = vmc_security_groups.get(
hostname="hostname",
refresh_key="refresh_key",
authorization_host="authorization_host",
org_id="org_id",
sddc_id="sddc_id",
domain_id="domain_id",
verify_ssl=False,
)
call_kwargs = vmc_call_api.mock_calls[0][-1]
assert call_kwargs["url"] == expected_url
assert call_kwargs["method"] == vmc_constants.GET_REQUEST_METHOD
def test_get_security_group_by_id_should_return_single_security_group(security_groups_data_by_id):
result = vmc_security_groups.get_by_id(
hostname="hostname",
refresh_key="refresh_key",
authorization_host="authorization_host",
org_id="org_id",
sddc_id="sddc_id",
domain_id="domain_id",
security_group_id="security_group_id",
verify_ssl=False,
)
assert result == security_groups_data_by_id
def test_get_security_groups_by_id_called_with_url():
expected_url = (
"https://hostname/vmc/reverse-proxy/api/orgs/org_id/sddcs/sddc_id/policy/api/"
"v1/infra/domains/domain_id/groups/security_group_id"
)
with patch("saltext.vmware.utils.vmc_request.call_api", autospec=True) as vmc_call_api:
result = vmc_security_groups.get_by_id(
hostname="hostname",
refresh_key="refresh_key",
authorization_host="authorization_host",
org_id="org_id",
sddc_id="sddc_id",
domain_id="domain_id",
security_group_id="security_group_id",
verify_ssl=False,
)
call_kwargs = vmc_call_api.mock_calls[0][-1]
assert call_kwargs["url"] == expected_url
assert call_kwargs["method"] == vmc_constants.GET_REQUEST_METHOD
def test_delete_security_group_when_api_should_return_api_response(mock_vmc_request_call_api):
data = {"message": "Security group deleted successfully"}
mock_vmc_request_call_api.return_value = data
assert (
vmc_security_groups.delete(
hostname="hostname",
refresh_key="refresh_key",
authorization_host="authorization_host",
org_id="org_id",
sddc_id="sddc_id",
domain_id="domain_id",
security_group_id="security_group_id",
verify_ssl=False,
)
== data
)
def test_delete_security_groups_by_id_called_with_url():
expected_url = (
"https://hostname/vmc/reverse-proxy/api/orgs/org_id/sddcs/sddc_id/policy/api/"
"v1/infra/domains/domain_id/groups/security_group_id"
)
with patch("saltext.vmware.utils.vmc_request.call_api", autospec=True) as vmc_call_api:
result = vmc_security_groups.delete(
hostname="hostname",
refresh_key="refresh_key",
authorization_host="authorization_host",
org_id="org_id",
sddc_id="sddc_id",
domain_id="domain_id",
security_group_id="security_group_id",
verify_ssl=False,
)
call_kwargs = vmc_call_api.mock_calls[0][-1]
assert call_kwargs["url"] == expected_url
assert call_kwargs["method"] == vmc_constants.DELETE_REQUEST_METHOD
def test_create_security_group_when_api_should_return_api_response(mock_vmc_request_call_api):
data = {"message": "Security group created successfully"}
mock_vmc_request_call_api.return_value = data
assert (
vmc_security_groups.create(
hostname="hostname",
refresh_key="refresh_key",
authorization_host="authorization_host",
org_id="org_id",
sddc_id="sddc_id",
domain_id="domain_id",
security_group_id="security_group_id",
verify_ssl=False,
)
== data
)
def test_create_security_groups_by_id_called_with_url():
expected_url = (
"https://hostname/vmc/reverse-proxy/api/orgs/org_id/sddcs/sddc_id/policy/api/"
"v1/infra/domains/domain_id/groups/security_group_id"
)
with patch("saltext.vmware.utils.vmc_request.call_api", autospec=True) as vmc_call_api:
result = vmc_security_groups.create(
hostname="hostname",
refresh_key="refresh_key",
authorization_host="authorization_host",
org_id="org_id",
sddc_id="sddc_id",
domain_id="domain_id",
security_group_id="security_group_id",
verify_ssl=False,
)
call_kwargs = vmc_call_api.mock_calls[0][-1]
assert call_kwargs["url"] == expected_url
assert call_kwargs["method"] == vmc_constants.PUT_REQUEST_METHOD
@pytest.mark.parametrize(
"actual_args, expected_payload",
[
# all actual args are None
(
{},
{
"id": "security_group_id",
"display_name": "security_group_id",
"description": "",
"expression": [],
"tags": [],
},
),
# allow none have values
(
{"tags": [{"tag": "tag1", "scope": "scope1"}]},
{
"id": "security_group_id",
"display_name": "security_group_id",
"description": "",
"expression": [],
"tags": [{"tag": "tag1", "scope": "scope1"}],
},
),
# all args have values
(
{
"description": "VMs Security groups",
"expression": [
{
"member_type": "VirtualMachine",
"key": "OSName",
"operator": "EQUALS",
"value": "Centos",
"resource_type": "Condition",
}
],
"tags": [{"tag": "tag1", "scope": "scope1"}],
},
{
"id": "security_group_id",
"display_name": "security_group_id",
"description": "VMs Security groups",
"expression": [
{
"member_type": "VirtualMachine",
"key": "OSName",
"operator": "EQUALS",
"value": "Centos",
"resource_type": "Condition",
}
],
"tags": [{"tag": "tag1", "scope": "scope1"}],
},
),
],
)
def test_assert_security_groups_create_should_correctly_filter_args(actual_args, expected_payload):
common_actual_args = {
"hostname": "hostname",
"refresh_key": "refresh_key",
"authorization_host": "authorization_host",
"org_id": "org_id",
"sddc_id": "sddc_id",
"domain_id": "domain_id",
"security_group_id": "security_group_id",
"verify_ssl": False,
}
with patch("saltext.vmware.utils.vmc_request.call_api", autospec=True) as vmc_call_api:
actual_args.update(common_actual_args)
vmc_security_groups.create(**actual_args)
call_kwargs = vmc_call_api.mock_calls[0][-1]
assert call_kwargs["data"] == expected_payload
``` |
{
"source": "joechen018/social-ctf",
"score": 3
} |
#### File: joechen018/social-ctf/confound_regression.py
```python
from os.path import join
import numpy as np
# Simple function to compute least-squares residuals
def confound_regression(confounds, signal):
# Manually add intercept
confounds = np.column_stack([confounds, np.ones(confounds.shape[0])])
# Estimate coefficients via least-squares fit
coef, _, _, _ = np.linalg.lstsq(confounds, signal, rcond=None)
# Compute residuals based on least-squares fit
residuals = signal - np.dot(confounds, coef)
return residuals
if __name__ == 'main':
# Load helper function(s) for interacting with CTF dataset
from ctf_dataset.load import create_wrapped_dataset
base_dir = '/mnt/bucket/labs/hasson/snastase/social-ctf'
data_dir = join(base_dir, 'data')
# Create wrapped CTF dataset
wrap_f = create_wrapped_dataset(data_dir,
output_dataset_name="virtual.hdf5")
n_lstms = 512
n_repeats = 8
n_players = 4
n_pairs = n_players * (n_players - 1) // 2
n_samples = 4501
map_id = 0 # 0
matchup_id = 0 # 0-54
repeat_id = 0 # 0-7
player_id = 0 # 0-3
# Load pre-saved PCA's
n_pairs = n_players * (n_players - 1) // 2
n_matchups = 4
k = 100
lstms_pca = np.load(f'results/lstms_tanh-z_pca-k{k}.npy')
# Get matchups with all same agents (e.g. AA vs AA)
agent_ids = wrap_f['map/matchup/repeat/player/agent_id'][0, :, :, :, 0]
matchup_ids = np.all(agent_ids[:, 0, :] ==
agent_ids[:, 0, 0][:, np.newaxis], axis=1)
n_matchups = np.sum(matchup_ids) # 0, 34, 49, 54
# Extract pre-LSTMs for relevant matchups
prelstms = wrap_f[f'map/matchup/repeat/player/time/pre_lstm'][
map_id, matchup_ids, ...].astype(np.float32)
print("Loaded pre-LSTMs for within-population matchups")
# Apply log(x + 1) to pre-LSTMs
prelstms = np.log1p(prelstms)
# Loop through matchups and regress confounds out of PCs
lstms_res = np.full(lstms_pca.shape, np.nan)
for matchup in np.arange(n_matchups):
for repeat in np.arange(n_repeats):
for player in np.arange(n_players):
lstms = lstms_pca[matchup, repeat, player, ...]
confounds = prelstms[matchup, repeat, player, ...]
residuals = confound_regression(confounds, lstms)
lstms_res[matchup, repeat, player] = residuals
print("Finished confound regression for "
f"matchup {matchup} repeat {repeat}")
np.save(f'results/lstms_tanh-z_pca-k{k}_reg-pre.npy', lstms_res)
# Regress out HUD only
hud = prelstms[..., n_lstms:]
# Loop through matchups and regress confounds out of PCs
lstms_res = np.full(lstms_pca.shape, np.nan)
for matchup in np.arange(n_matchups):
for repeat in np.arange(n_repeats):
for player in np.arange(n_players):
lstms = lstms_pca[matchup, repeat, player, ...]
confounds = hud[matchup, repeat, player, ...]
residuals = confound_regression(confounds, lstms)
lstms_res[matchup, repeat, player] = residuals
print("Finished confound regression for "
f"matchup {matchup} repeat {repeat}")
np.save(f'results/lstms_tanh-z_pca-k{k}_reg-hud.npy', lstms_res)
# Extract behavioral output (i.e. actions) for relevant matchups
actions = wrap_f[f'map/matchup/repeat/player/time/action'][
map_id, matchup_ids, ...].astype(np.float32)
print("Loaded actions for within-population matchups")
# Loop through matchups and regress confounds out of PCs
lstms_res = np.full(lstms_pca.shape, np.nan)
for matchup in np.arange(n_matchups):
for repeat in np.arange(n_repeats):
for player in np.arange(n_players):
lstms = lstms_pca[matchup, repeat, player, ...]
confounds = actions[matchup, repeat, player, ...]
residuals = confound_regression(confounds, lstms)
lstms_res[matchup, repeat, player] = residuals
print("Finished confound regression for "
f"matchup {matchup} repeat {repeat}")
np.save(f'results/lstms_tanh-z_pca-k{k}_reg-act.npy', lstms_res)
# Combine pre-LSTMs and actions into single confound matrix
combined = np.concatenate([prelstms, actions], axis=4)
# Loop through matchups and regress confounds out of PCs
lstms_res = np.full(lstms_pca.shape, np.nan)
for matchup in np.arange(n_matchups):
for repeat in np.arange(n_repeats):
for player in np.arange(n_players):
lstms = lstms_pca[matchup, repeat, player, ...]
confounds = combined[matchup, repeat, player, ...]
residuals = confound_regression(confounds, lstms)
lstms_res[matchup, repeat, player] = residuals
print("Finished confound regression for "
f"matchup {matchup} repeat {repeat}")
np.save(f'results/lstms_tanh-z_pca-k{k}_reg-com.npy', lstms_res)
``` |
{
"source": "joecheng511/sfdc-backup",
"score": 3
} |
#### File: sfdc-backup/data-backup/IOHelper.py
```python
import os
import shutil
class IOHelper:
@staticmethod
def init():
IOHelper.makeClearDir('log')
IOHelper.makeClearDir('output')
@staticmethod
def makeClearDir(dirName):
strDirName = str(dirName)
if os.path.isdir(strDirName):
shutil.rmtree(strDirName)
os.makedirs(strDirName)
@staticmethod
def appendToLog(logName, message):
with open("log/{}".format(str(logName)), "a") as file:
file.write(str(message))
@staticmethod
def outputObjectToFile(objectName, text):
with open("output/{}.csv".format(objectName), "a") as text_file:
text_file.write(text)
``` |
{
"source": "joechiu/alarm",
"score": 3
} |
#### File: joechiu/alarm/action.py
```python
import inspect
class a:
def __init__(a, am):
a.am = am
a.h = am.h
a.all = am.alist
def set(a, i, k, v):
a.h[i]['act'][k] = v
def get(a, i, k):
try:
act = a.h[i]['act']
except:
act = a.am.act
try:
return act[k]
except:
return None
def ga(a, i, k):
try:
act = a.all[i]['act']
return act[k]
except:
return None
def p(a):
print("hello i am an act")
def isit(a, i):
print(a.all)
for x,e in enumerate(a.all):
t = a.ga(x, 't')
ai = a.ga(x, 'i')
print('i=',i,'ai:',ai,'t=',t)
if i==ai and t:
return True
return False
def i(a, i):
return a.get(i, inspect.stack()[0][3])
def cc(a, i):
return a.get(i, inspect.stack()[0][3])
def snz(a, i):
return a.get(i, inspect.stack()[0][3])
def sound(a, i):
return a.get(i, inspect.stack()[0][3])
def cb(a, i):
return a.get(i, inspect.stack()[0][3])
def nn(a, i):
return a.get(i, inspect.stack()[0][3])
def anim(a, i):
return a.get(i, inspect.stack()[0][3])
def tt(a, i):
return a.get(i, inspect.stack()[0][3])
def ct(a, i):
return a.get(i, inspect.stack()[0][3])
def t(a, i):
return a.get(i, inspect.stack()[0][3])
def w(a, i):
return a.get(i, inspect.stack()[0][3])
```
#### File: joechiu/alarm/runit.py
```python
import os, time, subprocess
from PyQt5.QtCore import QRunnable, pyqtSlot
DEV = True
if os.path.exists('python36.dll'):
DEV = False
class runit(QRunnable):
def __init__(self, rid):
super(runit, self).__init__()
self.id = str(rid)
@pyqtSlot()
def run(self):
print("Thread start - " + self.id)
if DEV:
cmd = [ "python", "message.py", self.id ]
else:
cmd = [ "message.exe", self.id ]
subprocess.call(cmd)
time.sleep(5)
print("Thread complete - " + self.id)
```
#### File: joechiu/alarm/worker.py
```python
import sys
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
class w(QThread):
# explicit signal sent in the startCounting function
ut = pyqtSignal(int)
# explicit slot that takes input from the scs
@pyqtSlot(int)
def startCounting(self, i):
while True:
self.ut.emit(i)
QThread.sleep(1)
``` |
{
"source": "joechu1/minipresto",
"score": 2
} |
#### File: minipresto/cmd/cmd_down.py
```python
import sys
import click
from minipresto.cli import pass_environment
from minipresto import utils
from minipresto import errors as err
from minipresto.settings import RESOURCE_LABEL
@click.command(
"down",
help=(
"""Bring down running Minipresto containers. This command follows the
behavior of `docker-compose down` where containers are both stopped and
removed."""
),
)
@click.option(
"-k",
"--keep",
is_flag=True,
default=False,
help=(
"""Does not remove containers; instead, containers will only be
stopped."""
),
)
@click.option(
"--sig-kill",
is_flag=True,
default=False,
help=("""Stop Minipresto containers without a grace period."""),
)
@utils.exception_handler
@pass_environment
def cli(ctx, sig_kill, keep):
"""Down command for Minipresto. Exits with a 0 status code if there are no
running minipresto containers."""
utils.check_daemon(ctx.docker_client)
utils.check_lib(ctx)
containers = ctx.docker_client.containers.list(
filters={"label": RESOURCE_LABEL}, all=True
)
if len(containers) == 0:
ctx.logger.log("No containers to bring down.")
sys.exit(0)
if sig_kill:
stop_timeout = 1
ctx.logger.log(
"Stopping Minipresto containers with sig-kill...",
level=ctx.logger.verbose,
)
else:
stop_timeout = 10
# Stop
for container in containers:
identifier = utils.generate_identifier(
{"ID": container.short_id, "Name": container.name}
)
if container.status == "running":
container.stop(timeout=stop_timeout)
ctx.logger.log(f"Stopped container: {identifier}", level=ctx.logger.verbose)
# Remove
if not keep:
for container in containers:
identifier = utils.generate_identifier(
{"ID": container.short_id, "Name": container.name}
)
container.remove()
ctx.logger.log(f"Removed container: {identifier}", level=ctx.logger.verbose)
ctx.logger.log("Brought down all Minipresto containers.")
```
#### File: minipresto/cmd/cmd_remove.py
```python
import sys
import click
from minipresto.cli import pass_environment
from minipresto import utils
from minipresto.settings import IMAGE
from minipresto.settings import VOLUME
from minipresto.settings import RESOURCE_LABEL
from docker.errors import APIError
@click.command(
"remove",
help=("""Remove Minipresto resources."""),
)
@click.option(
"-i",
"--images",
is_flag=True,
default=False,
help=("""Remove Minipresto images."""),
)
@click.option(
"-v",
"--volumes",
is_flag=True,
default=False,
help=("""Remove Minipresto container volumes."""),
)
@click.option(
"-l",
"--label",
"labels",
type=str,
default=[],
multiple=True,
help=(
"""Target specific labels for removal (format: key-value
pair(s))."""
),
)
@click.option(
"-f",
"--force",
is_flag=True,
default=False,
help=(
"""Force the removal of Minipresto resources. Normal Docker removal
restrictions apply."""
),
)
@utils.exception_handler
@pass_environment
def cli(ctx, images, volumes, labels, force):
"""Remove command for Minipresto."""
utils.check_daemon(ctx.docker_client)
if all((not images, not volumes, not labels)) or all((images, volumes, not labels)):
response = ctx.logger.prompt_msg(
"You are about to all remove minipresto images and volumes. Continue? [Y/N]"
)
if utils.validate_yes(response):
remove_items(IMAGE, force)
remove_items(VOLUME, force)
else:
ctx.logger.log(f"Opted to skip resource removal.")
sys.exit(0)
if images:
remove_items(IMAGE, force, labels)
if volumes:
remove_items(VOLUME, force, labels)
ctx.logger.log(f"Removal complete.")
@pass_environment
def remove_items(ctx, item_type, force, labels=[]):
"""Removes Docker items. If no labels are passed in, all Minipresto
resources are removed. If label(s) are passed in, the removal is limited to
the passed in labels."""
if not labels:
labels = [RESOURCE_LABEL]
images = []
volumes = []
for label in labels:
if item_type == IMAGE:
images.extend(ctx.docker_client.images.list(filters={"label": label}))
if item_type == VOLUME:
volumes.extend(ctx.docker_client.volumes.list(filters={"label": label}))
images = list(set(images))
for image in images:
try:
identifier = utils.generate_identifier(
{"ID": image.short_id, "Image:Tag": try_get_image_tag(image)}
)
if force:
ctx.docker_client.images.remove(
image.short_id, force=True, noprune=False
)
else:
ctx.docker_client.images.remove(image.short_id)
ctx.logger.log(
f"{item_type.title()} removed: {identifier}",
level=ctx.logger.verbose,
)
except APIError as e:
ctx.logger.log(
f"Cannot remove image: {identifier}\n"
f"Error from Docker: {e.explanation}",
level=ctx.logger.verbose,
)
volumes = list(set(volumes))
for volume in volumes:
try:
identifier = utils.generate_identifier({"ID": volume.id})
if force:
volume.remove(force=True)
else:
volume.remove()
ctx.logger.log(
f"{item_type.title()} removed: {identifier}",
level=ctx.logger.verbose,
)
except APIError as e:
ctx.logger.log(
f"Cannot remove volume: {identifier}\n"
f"Error from Docker: {e.explanation}",
level=ctx.logger.verbose,
)
def try_get_image_tag(image):
"""Tries to get an image tag. If there is no tag, returns an empty string."""
try:
return image.tags[0]
except:
return ""
```
#### File: minipresto/test/test_cmd_down.py
```python
import docker
import minipresto.test.helpers as helpers
from inspect import currentframe
from types import FrameType
from typing import cast
from minipresto.settings import RESOURCE_LABEL
def main():
helpers.log_status(__file__)
helpers.start_docker_daemon()
cleanup()
test_no_containers()
test_running_containers()
test_keep()
def test_no_containers():
"""Verifies that the down command functions appropriately when no containers
are running."""
helpers.log_status(cast(FrameType, currentframe()).f_code.co_name)
result = helpers.execute_command(["-v", "down"])
assert result.exit_code == 0
assert "No containers to bring down" in result.output
docker_client = docker.from_env()
containers = docker_client.containers.list(filters={"label": RESOURCE_LABEL})
assert len(containers) == 0, "There should be no running containers"
helpers.log_success(cast(FrameType, currentframe()).f_code.co_name)
cleanup()
def test_running_containers():
"""Verifies that the down command works when multiple containers are
running. This also verifies the --sig-kill option works."""
helpers.log_status(cast(FrameType, currentframe()).f_code.co_name)
helpers.execute_command(["-v", "provision", "--module", "test"])
result = helpers.execute_command(["-v", "down", "--sig-kill"])
assert result.exit_code == 0
assert all(
(
"Stopped container" in result.output,
"Removed container" in result.output,
"test" in result.output,
"presto" in result.output,
)
)
docker_client = docker.from_env()
containers = docker_client.containers.list(filters={"label": RESOURCE_LABEL})
assert len(containers) == 0, "There should be no running containers"
helpers.log_success(cast(FrameType, currentframe()).f_code.co_name)
cleanup()
def test_keep():
"""Verifies that the `--keep` flag works as expected."""
helpers.log_status(cast(FrameType, currentframe()).f_code.co_name)
helpers.execute_command(["-v", "provision", "--module", "test"])
result = helpers.execute_command(["-v", "down", "--keep"])
assert "Stopped container" in result.output
assert "Removed container" not in result.output
docker_client = docker.from_env()
containers = docker_client.containers.list(
filters={"label": RESOURCE_LABEL}, all=True
)
for container in containers:
assert container.name.lower() == "presto" or container.name.lower() == "test"
helpers.log_success(cast(FrameType, currentframe()).f_code.co_name)
cleanup()
def cleanup():
"""Stops/removes containers."""
helpers.execute_command(["-v", "down", "--sig-kill"])
if __name__ == "__main__":
main()
```
#### File: minipresto/test/test_misc.py
```python
import minipresto.test.helpers as helpers
from inspect import currentframe
from types import FrameType
from typing import cast
def main():
helpers.log_status(__file__)
test_daemon_off_all(
["-v", "down"],
["-v", "provision"],
["-v", "remove"],
[
"-v",
"snapshot",
"--name",
"test",
], # Applicable only when snapshotting active environment
["-v", "modules", "--running"],
)
test_env()
test_multiple_env()
test_invalid_env()
test_invalid_lib()
def test_daemon_off_all(*args):
"""Verifies that each Minipresto command properly exits properly if the
Docker daemon is off or unresponsive."""
helpers.log_status(cast(FrameType, currentframe()).f_code.co_name)
def run_daemon_assertions(result):
"""Runs standard assertions."""
assert result.exit_code == 2, f"Invalid exit code: {result.exit_code}"
assert (
"Error when pinging the Docker server. Is the Docker daemon running?"
in result.output
), f"Unexpected output: {result.output}"
helpers.stop_docker_daemon()
for arg in args:
result = helpers.execute_command(arg)
run_daemon_assertions(result)
helpers.log_success(cast(FrameType, currentframe()).f_code.co_name)
def test_env():
"""Verifies that an environment variable can be successfully passed in."""
helpers.log_status(cast(FrameType, currentframe()).f_code.co_name)
result = helpers.execute_command(
["-v", "--env", "COMPOSE_PROJECT_NAME=test", "version"]
)
assert result.exit_code == 0
assert "COMPOSE_PROJECT_NAME" and "test" in result.output
helpers.log_success(cast(FrameType, currentframe()).f_code.co_name)
def test_multiple_env():
"""Verifies that multiple environment variables can be successfully passed
in."""
helpers.log_status(cast(FrameType, currentframe()).f_code.co_name)
result = helpers.execute_command(
[
"-v",
"--env",
"COMPOSE_PROJECT_NAME=test",
"--env",
"STARBURST_VER=338-e.1",
"--env",
"PRESTO=is=awesome",
"version",
]
)
assert result.exit_code == 0
assert all(
(
'"COMPOSE_PROJECT_NAME": "test"' in result.output,
'"STARBURST_VER": "338-e.1"' in result.output,
'"PRESTO": "is=awesome"' in result.output,
)
)
helpers.log_success(cast(FrameType, currentframe()).f_code.co_name)
def test_invalid_env():
"""Verifies that an invalid environment variable will cause the CLI to exit
with a non-zero status code."""
helpers.log_status(cast(FrameType, currentframe()).f_code.co_name)
result = helpers.execute_command(
["-v", "--env", "COMPOSE_PROJECT_NAMEtest", "version"]
)
assert result.exit_code == 2
assert "Invalid key-value pair" in result.output
result = helpers.execute_command(["-v", "--env", "=", "version"])
assert result.exit_code == 2
assert "Invalid key-value pair" in result.output
helpers.log_success(cast(FrameType, currentframe()).f_code.co_name)
def test_invalid_lib():
"""Verifies that Minipresto exists with a user error if pointing to an
invalid library."""
helpers.log_status(cast(FrameType, currentframe()).f_code.co_name)
# Real directory, but ain't a real library
result = helpers.execute_command(["-v", "--env", "LIB_PATH=/tmp/", "modules"])
assert result.exit_code == 2
assert "You must provide a path to a compatible Minipresto library" in result.output
# Fake directory
result = helpers.execute_command(
["-v", "--env", "LIB_PATH=/gucci-is-overrated/", "modules"]
)
assert result.exit_code == 2
assert "You must provide a path to a compatible Minipresto library" in result.output
helpers.log_success(cast(FrameType, currentframe()).f_code.co_name)
if __name__ == "__main__":
main()
``` |
{
"source": "joe-cipolla/nyiso_sql",
"score": 3
} |
#### File: dashboard/tabs/side_panel.py
```python
import dash
import plotly
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
import pandas as pd
from dash.dependencies import Input, Output
from dashboard.app import app
from dashboard.tabs import tab_1, tab_2
from dashboard import test_data
df = test_data.default_df
all_options = {}
for iso in df.iso.unique():
all_options[iso] = df[df.iso == iso].zone.unique().tolist()
he_cols = [i for i in df.columns if i[:2] == 'he']
df_std = df[he_cols].std().mean().round(-1)
df_mean = df[he_cols].mean().mean().round(-1)
df_min = df[he_cols].min().min().round(-1)
df_max = df[he_cols].max().max().round(-1)
slider_inc = df_std/2/2
slider_vals = {
i: str(i) for i in range(int(df_mean - (slider_inc * 5)),
int(df_mean + (slider_inc * 5)),
int(slider_inc))
}
slider_min = int(df_mean - (df_std * 2))
slider_max = int(df_mean + (df_std * 2))
layout = html.Div([
html.H1('ISO Dash'),
dbc.Row([
dbc.Col(html.Div([
html.H2('Filters'),
html.Div([
html.P(),
html.H5('ISO'),
dcc.Dropdown(id='iso-drop',
options=[{'label': i, 'value': i} for i in df.iso.unique()],
value=['NYISO'],
multi=True)
]),
html.Div([
html.P(),
html.H5('Zone'),
dcc.Dropdown(id='zone-drop',
options=[{'label': i, 'value': i} for i in df.zone.unique()],
multi=True)
]),
html.Div([
html.P(),
html.H5('Price Slider ($/mwh)'),
dcc.RangeSlider(id='price-slider',
min=slider_min,
max=slider_max,
marks=slider_vals,
value=[slider_min, slider_max],
persistence=True)
]),
], style={'marginBottom': 50, 'marginTop': 25, 'marginLeft': 15, 'marginRight': 15}), width=3),
dbc.Col(html.Div([
dcc.Tabs(id="tabs", value='tab-1', children=[
dcc.Tab(label='Data Table', value='tab-1'),
dcc.Tab(label='Scatter Plot', value='tab-2'),
dcc.Tab(label='Heatmap Plot', value='tab-3'),
]),
html.Div(id='tabs-content')
]), width=9)
])
])
@app.callback(Output('zone-drop', 'options'),
[Input('iso-drop', 'value')])
def set_zone_options(isos):
if len(isos) > 0:
return [{'label': i, 'value': i} for i in [e for a in [all_options[iso] for iso in isos] for e in a]]
else:
return [{'label': i, 'value': i} for i in [e for a in list(all_options.values()) for e in a]]
@app.callback(Output('zone-drop', 'value'),
[Input('zone-drop', 'options')])
def set_zone_value(available_options):
return available_options[0]['value']
# @app.callback(Output('iso-drop', 'options'),
# [Input('zone-drop', 'value')])
# def set_iso_options(zones):
# if len(zones) > 0:
# if not isinstance(zones, list):
# zones = [zones]
# return [{'label': i, 'value': i} for i in sorted(df[df.zone.isin(zones)].iso.unique().tolist())]
# else:
# return [{'label': i, 'value': i} for i in sorted(df.iso.unique().tolist())]
```
#### File: nyiso_sql/tests/test_query_db.py
```python
import unittest
import nyiso_sql.query_db as q
import pandas as pd
import pandas.testing as pd_testing
from tests import data_snapshots
class TestQueryDb(unittest.TestCase):
"""Tests SQL query functions"""
def assertDataFrameEqual(self, a, b, msg):
try:
pd_testing.assert_frame_equal(a, b)
except AssertionError as e:
raise self.failureException(msg) from e
def setUp(self):
self.addTypeEqualityFunc(pd.DataFrame, self.assertDataFrameEqual)
# load static DataFrame objects and attributes files
self.static_default_df = data_snapshots.default_df
# load test DataFrame objects
self.test_default_df = q.get_da_lmp(['2020-05-01', '2020-05-07'], 'CAPITL')
def test_GetDaLmp(self):
test_data_types = ['default']
for test_data_type in test_data_types:
test_df = vars(self)['test_' + test_data_type + '_df']
test_df.date = [i.strftime('%Y-%m-%d') for i in test_df.date]
static_df = vars(self)['static_' + test_data_type + '_df']
with self.subTest(): # check columns match
self.assertEqual(test_df.columns.tolist(), static_df.columns.tolist())
with self.subTest():
self.assertEqual(test_df.shape, static_df.shape)
with self.subTest(): # test pandas DataFrame equality
self.assertEqual(test_df, static_df)
# test error raise
with self.subTest():
with self.assertRaises(ValueError):
q.get_da_lmp(['2020-05-01', '2020-05-07'], 'corgi')
with self.assertRaises(ValueError):
q.get_da_lmp(['2020-05-01', 'corgi'], 'CAPITL')
if __name__ == '__main__':
unittest.main()
``` |
{
"source": "joecomerisnotavailable/med2vec",
"score": 2
} |
#### File: joecomerisnotavailable/med2vec/med2vec.py
```python
import sys, random
import numpy as np
import pickle as pickle
from collections import OrderedDict
import argparse
import theano
import theano.tensor as T
from theano import config
def numpy_floatX(data):
return np.asarray(data, dtype=config.floatX)
def unzip(zipped):
new_params = OrderedDict()
for k, v in zipped.items():
new_params[k] = v.get_value()
return new_params
def init_params(options):
params = OrderedDict()
numXcodes = options['numXcodes']
numYcodes = options['numYcodes']
embDimSize= options['embDimSize']
demoSize = options['demoSize']
hiddenDimSize = options['hiddenDimSize']
params['W_emb'] = np.random.uniform(-0.01, 0.01, (numXcodes, embDimSize)).astype(config.floatX) #emb matrix needs an extra dimension for the time
params['b_emb'] = np.zeros(embDimSize).astype(config.floatX)
params['W_hidden'] = np.random.uniform(-0.01, 0.01, (embDimSize+demoSize, hiddenDimSize)).astype(config.floatX) #emb matrix needs an extra dimension for the time
params['b_hidden'] = np.zeros(hiddenDimSize).astype(config.floatX)
if numYcodes > 0:
params['W_output'] = np.random.uniform(-0.01, 0.01, (hiddenDimSize, numYcodes)).astype(config.floatX) #emb matrix needs an extra dimension for the time
params['b_output'] = np.zeros(numYcodes).astype(config.floatX)
else:
params['W_output'] = np.random.uniform(-0.01, 0.01, (hiddenDimSize, numXcodes)).astype(config.floatX) #emb matrix needs an extra dimension for the time
params['b_output'] = np.zeros(numXcodes).astype(config.floatX)
return params
def load_params(options):
params = np.load(options['modelFile'])
return params
def init_tparams(params):
tparams = OrderedDict()
for k, v in params.items():
tparams[k] = theano.shared(v, name=k)
return tparams
def build_model(tparams, options):
x = T.matrix('x', dtype=config.floatX)
d = T.matrix('d', dtype=config.floatX)
y = T.matrix('y', dtype=config.floatX)
mask = T.vector('mask', dtype=config.floatX)
logEps = options['logEps']
emb = T.maximum(T.dot(x, tparams['W_emb']) + tparams['b_emb'],0)
if options['demoSize'] > 0: emb = T.concatenate((emb, d), axis=1)
visit = T.maximum(T.dot(emb, tparams['W_hidden']) + tparams['b_hidden'],0)
results = T.nnet.softmax(T.dot(visit, tparams['W_output']) + tparams['b_output'])
mask1 = (mask[:-1] * mask[1:])[:,None]
mask2 = (mask[:-2] * mask[1:-1] * mask[2:])[:,None]
mask3 = (mask[:-3] * mask[1:-2] * mask[2:-1] * mask[3:])[:,None]
mask4 = (mask[:-4] * mask[1:-3] * mask[2:-2] * mask[3:-1] * mask[4:])[:,None]
mask5 = (mask[:-5] * mask[1:-4] * mask[2:-3] * mask[3:-2] * mask[4:-1] * mask[5:])[:,None]
t = None
if options['numYcodes'] > 0: t = y
else: t = x
forward_results = results[:-1] * mask1
forward_cross_entropy = -(t[1:] * T.log(forward_results + logEps) + (1. - t[1:]) * T.log(1. - forward_results + logEps))
forward_results2 = results[:-2] * mask2
forward_cross_entropy2 = -(t[2:] * T.log(forward_results2 + logEps) + (1. - t[2:]) * T.log(1. - forward_results2 + logEps))
forward_results3 = results[:-3] * mask3
forward_cross_entropy3 = -(t[3:] * T.log(forward_results3 + logEps) + (1. - t[3:]) * T.log(1. - forward_results3 + logEps))
forward_results4 = results[:-4] * mask4
forward_cross_entropy4 = -(t[4:] * T.log(forward_results4 + logEps) + (1. - t[4:]) * T.log(1. - forward_results4 + logEps))
forward_results5 = results[:-5] * mask5
forward_cross_entropy5 = -(t[5:] * T.log(forward_results5 + logEps) + (1. - t[5:]) * T.log(1. - forward_results5 + logEps))
backward_results = results[1:] * mask1
backward_cross_entropy = -(t[:-1] * T.log(backward_results + logEps) + (1. - t[:-1]) * T.log(1. - backward_results + logEps))
backward_results2 = results[2:] * mask2
backward_cross_entropy2 = -(t[:-2] * T.log(backward_results2 + logEps) + (1. - t[:-2]) * T.log(1. - backward_results2 + logEps))
backward_results3 = results[3:] * mask3
backward_cross_entropy3 = -(t[:-3] * T.log(backward_results3 + logEps) + (1. - t[:-3]) * T.log(1. - backward_results3 + logEps))
backward_results4 = results[4:] * mask4
backward_cross_entropy4 = -(t[:-4] * T.log(backward_results4 + logEps) + (1. - t[:-4]) * T.log(1. - backward_results4 + logEps))
backward_results5 = results[5:] * mask5
backward_cross_entropy5 = -(t[:-5] * T.log(backward_results5 + logEps) + (1. - t[:-5]) * T.log(1. - backward_results5 + logEps))
visit_cost1 = (forward_cross_entropy.sum(axis=1).sum(axis=0) + backward_cross_entropy.sum(axis=1).sum(axis=0)) / (mask1.sum() + logEps)
visit_cost2 = (forward_cross_entropy2.sum(axis=1).sum(axis=0) + backward_cross_entropy2.sum(axis=1).sum(axis=0)) / (mask2.sum() + logEps)
visit_cost3 = (forward_cross_entropy3.sum(axis=1).sum(axis=0) + backward_cross_entropy3.sum(axis=1).sum(axis=0)) / (mask3.sum() + logEps)
visit_cost4 = (forward_cross_entropy4.sum(axis=1).sum(axis=0) + backward_cross_entropy4.sum(axis=1).sum(axis=0)) / (mask4.sum() + logEps)
visit_cost5 = (forward_cross_entropy5.sum(axis=1).sum(axis=0) + backward_cross_entropy5.sum(axis=1).sum(axis=0)) / (mask5.sum() + logEps)
windowSize = options['windowSize']
visit_cost = visit_cost1
if windowSize == 2:
visit_cost = visit_cost1 + visit_cost2
elif windowSize == 3:
visit_cost = visit_cost1 + visit_cost2 + visit_cost3
elif windowSize == 4:
visit_cost = visit_cost1 + visit_cost2 + visit_cost3 + visit_cost4
elif windowSize == 5:
visit_cost = visit_cost1 + visit_cost2 + visit_cost3 + visit_cost4 + visit_cost5
iVector = T.vector('iVector', dtype='int32')
jVector = T.vector('jVector', dtype='int32')
preVec = T.maximum(tparams['W_emb'],0)
norms = (T.exp(T.dot(preVec, preVec.T))).sum(axis=1)
emb_cost = -T.log((T.exp((preVec[iVector] * preVec[jVector]).sum(axis=1)) / norms[iVector]) + logEps)
total_cost = visit_cost + T.mean(emb_cost) + options['L2_reg'] * (tparams['W_emb'] ** 2).sum()
if options['demoSize'] > 0 and options['numYcodes'] > 0: return x, d, y, mask, iVector, jVector, total_cost
elif options['demoSize'] == 0 and options['numYcodes'] > 0: return x, y, mask, iVector, jVector, total_cost
elif options['demoSize'] > 0 and options['numYcodes'] == 0: return x, d, mask, iVector, jVector, total_cost
else: return x, mask, iVector, jVector, total_cost
def adadelta(tparams, grads, x, mask, iVector, jVector, cost, options, d=None, y=None):
zipped_grads = [theano.shared(p.get_value() * numpy_floatX(0.), name='%s_grad' % k) for k, p in tparams.items()]
running_up2 = [theano.shared(p.get_value() * numpy_floatX(0.), name='%s_rup2' % k) for k, p in tparams.items()]
running_grads2 = [theano.shared(p.get_value() * numpy_floatX(0.), name='%s_rgrad2' % k) for k, p in tparams.items()]
zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)]
rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2)) for rg2, g in zip(running_grads2, grads)]
if options['demoSize'] > 0 and options['numYcodes'] > 0:
f_grad_shared = theano.function([x, d, y, mask, iVector, jVector], cost, updates=zgup + rg2up, name='adadelta_f_grad_shared')
elif options['demoSize'] == 0 and options['numYcodes'] > 0:
f_grad_shared = theano.function([x, y, mask, iVector, jVector], cost, updates=zgup + rg2up, name='adadelta_f_grad_shared')
elif options['demoSize'] > 0 and options['numYcodes'] == 0:
f_grad_shared = theano.function([x, d, mask, iVector, jVector], cost, updates=zgup + rg2up, name='adadelta_f_grad_shared')
else:
f_grad_shared = theano.function([x, mask, iVector, jVector], cost, updates=zgup + rg2up, name='adadelta_f_grad_shared')
updir = [-T.sqrt(ru2 + 1e-6) / T.sqrt(rg2 + 1e-6) * zg for zg, ru2, rg2 in zip(zipped_grads, running_up2, running_grads2)]
ru2up = [(ru2, 0.95 * ru2 + 0.05 * (ud ** 2)) for ru2, ud in zip(running_up2, updir)]
param_up = [(p, p + ud) for p, ud in zip(list(tparams.values()), updir)]
f_update = theano.function([], [], updates=ru2up + param_up, on_unused_input='ignore', name='adadelta_f_update')
return f_grad_shared, f_update
def load_data(xFile, dFile, yFile):
seqX = np.array(pickle.load(open(xFile, 'rb')))
seqD = []
if len(dFile) > 0: seqD = np.asarray(pickle.load(open(dFile, 'rb')), dtype=config.floatX)
seqY = []
if len(yFile) > 0: seqY = np.array(pickle.load(open(yFile, 'rb')))
return seqX, seqD, seqY
def pickTwo(codes, iVector, jVector):
for first in codes:
for second in codes:
if first == second: continue
iVector.append(first)
jVector.append(second)
def padMatrix(seqs, labels, options):
n_samples = len(seqs)
iVector = []
jVector = []
numXcodes = options['numXcodes']
numYcodes = options['numYcodes']
if numYcodes > 0:
x = np.zeros((n_samples, numXcodes)).astype(config.floatX)
y = np.zeros((n_samples, numYcodes)).astype(config.floatX)
mask = np.zeros((n_samples,)).astype(config.floatX)
for idx, (seq, label) in enumerate(zip(seqs, labels)):
if not seq[0] == -1:
x[idx][seq] = 1.
y[idx][label] = 1.
pickTwo(seq, iVector, jVector)
mask[idx] = 1.
return x, y, mask, iVector, jVector
else:
x = np.zeros((n_samples, numXcodes)).astype(config.floatX)
mask = np.zeros((n_samples,)).astype(config.floatX)
for idx, seq in enumerate(seqs):
if not seq[0] == -1:
x[idx][seq] = 1.
pickTwo(seq, iVector, jVector)
mask[idx] = 1.
return x, mask, iVector, jVector
def train_med2vec(seqFile='seqFile.txt',
demoFile='demoFile.txt',
labelFile='labelFile.txt',
outFile='outFile.txt',
modelFile='modelFile.txt',
L2_reg=0.001,
numXcodes=20000,
numYcodes=20000,
embDimSize=1000,
hiddenDimSize=2000,
batchSize=100,
demoSize=2,
logEps=1e-8,
windowSize=1,
verbose=False,
maxEpochs=1000):
options = locals().copy()
print('initializing parameters')
params = init_params(options)
#params = load_params(options)
tparams = init_tparams(params)
print('building models')
f_grad_shared = None
f_update = None
if demoSize > 0 and numYcodes > 0:
x, d, y, mask, iVector, jVector, cost = build_model(tparams, options)
grads = T.grad(cost, wrt=list(tparams.values()))
f_grad_shared, f_update = adadelta(tparams, grads, x, mask, iVector, jVector, cost, options, d=d, y=y)
elif demoSize == 0 and numYcodes > 0:
x, y, mask, iVector, jVector, cost = build_model(tparams, options)
grads = T.grad(cost, wrt=list(tparams.values()))
f_grad_shared, f_update = adadelta(tparams, grads, x, mask, iVector, jVector, cost, options, y=y)
elif demoSize > 0 and numYcodes == 0:
x, d, mask, iVector, jVector, cost = build_model(tparams, options)
grads = T.grad(cost, wrt=list(tparams.values()))
f_grad_shared, f_update = adadelta(tparams, grads, x, mask, iVector, jVector, cost, options, d=d)
else:
x, mask, iVector, jVector, cost = build_model(tparams, options)
grads = T.grad(cost, wrt=list(tparams.values()))
f_grad_shared, f_update = adadelta(tparams, grads, x, mask, iVector, jVector, cost, options)
print('loading data')
seqs, demos, labels = load_data(seqFile, demoFile, labelFile)
n_batches = int(np.ceil(float(len(seqs)) / float(batchSize)))
print('training start')
for epoch in range(maxEpochs):
iteration = 0
costVector = []
for index in random.sample(list(range(n_batches)), n_batches):
batchX = seqs[batchSize*index:batchSize*(index+1)]
batchY = []
batchD = []
if demoSize > 0 and numYcodes > 0:
batchY = labels[batchSize*index:batchSize*(index+1)]
x, y, mask, iVector, jVector = padMatrix(batchX, batchY, options)
batchD = demos[batchSize*index:batchSize*(index+1)]
cost = f_grad_shared(x, batchD, y, mask, iVector, jVector)
elif demoSize == 0 and numYcodes > 0:
batchY = labels[batchSize*index:batchSize*(index+1)]
x, y, mask, iVector, jVector = padMatrix(batchX, batchY, options)
cost = f_grad_shared(x, y, mask, iVector, jVector)
elif demoSize > 0 and numYcodes == 0:
x, mask, iVector, jVector = padMatrix(batchX, batchY, options)
batchD = demos[batchSize*index:batchSize*(index+1)]
cost = f_grad_shared(x, batchD, mask, iVector, jVector)
else:
x, mask, iVector, jVector = padMatrix(batchX, batchY, options)
cost = f_grad_shared(x, mask, iVector, jVector)
costVector.append(cost)
f_update()
if (iteration % 10 == 0) and verbose: print('epoch:%d, iteration:%d/%d, cost:%f' % (epoch, iteration, n_batches, cost))
iteration += 1
print('epoch:%d, mean_cost:%f' % (epoch, np.mean(costVector)))
tempParams = unzip(tparams)
np.savez_compressed(outFile + '.' + str(epoch), **tempParams)
def parse_arguments(parser):
parser.add_argument('seq_file', type=str, metavar='<visit_file>', help='The path to the Pickled file containing visit information of patients')
parser.add_argument('n_input_codes', type=int, metavar='<n_input_codes>', help='The number of unique input medical codes')
parser.add_argument('out_file', type=str, metavar='<out_file>', help='The path to the output models. The models will be saved after every epoch')
parser.add_argument('--label_file', type=str, default='', help='The path to the Pickled file containing grouped visit information of patients. If you are not using a grouped output, do not use this option')
parser.add_argument('--n_output_codes', type=int, default=0, help='The number of unique output medical codes (the number of unique grouped codes). If you are not using a grouped output, do not use this option')
parser.add_argument('--demo_file', type=str, default='', help='The path to the Pickled file containing demographic information of patients. If you are not using patient demographic information, do not use this option')
parser.add_argument('--demo_size', type=int, default=0, help='The size of the demographic information vector. If you are not using patient demographic information, do not use this option')
parser.add_argument('--cr_size', type=int, default=200, help='The size of the code representation (default value: 200)')
parser.add_argument('--vr_size', type=int, default=200, help='The size of the visit representation (default value: 200)')
parser.add_argument('--batch_size', type=int, default=1000, help='The size of a single mini-batch (default value: 1000)')
parser.add_argument('--n_epoch', type=int, default=10, help='The number of training epochs (default value: 10)')
parser.add_argument('--L2_reg', type=float, default=0.001, help='L2 regularization for the code representation matrix W_c (default value: 0.001)')
parser.add_argument('--window_size', type=int, default=1, choices=[1,2,3,4,5], help='The size of the visit context window (range: 1,2,3,4,5), (default value: 1)')
parser.add_argument('--log_eps', type=float, default=1e-8, help='A small value to prevent log(0) (default value: 1e-8)')
parser.add_argument('--verbose', action='store_true', help='Print output after every 10 mini-batches')
args = parser.parse_args()
return args
if __name__ == '__main__':
parser = argparse.ArgumentParser()
args = parse_arguments(parser)
train_med2vec(seqFile=args.seq_file, demoFile=args.demo_file, labelFile=args.label_file, outFile=args.out_file, numXcodes=args.n_input_codes, numYcodes=args.n_output_codes, embDimSize=args.cr_size, hiddenDimSize=args.vr_size, batchSize=args.batch_size, maxEpochs=args.n_epoch, L2_reg=args.L2_reg, demoSize=args.demo_size, windowSize=args.window_size, logEps=args.log_eps, verbose=args.verbose)
``` |
{
"source": "JoeCool02/Wireless_Simulator",
"score": 3
} |
#### File: Wireless_Simulator/source/awgn.py
```python
import numpy as N
import scipy as S
import pylab as PL
import numpy.random as R
from modulation import *
class awgnGen:
def __init__(self, period = .001, samplesperperiod = 10000, power = 1):
self.power = power
self.period = period
self.samples = samplesperperiod
def run(self, signal, plot = False):
self.length = len(signal)
noise = R.randn(self.length)
self.noisepower = N.sum(pow(noise, 2))*(self.samples/float(self.length))*(1/self.period)
self.sigpower = N.sum(pow(signal, 2))*(self.samples/float(self.length))*(1/self.period)
noise = noise * N.sqrt(self.power/self.noisepower)
self.noisepower = N.sum(pow(noise, 2))*(self.samples/float(self.length))*(1/self.period)
self.snrdb = 10*N.log10(self.sigpower/float(self.noisepower))
waveform = signal + noise
if plot:
PL.plot(noise)
PL.plot(signal + 4)
PL.show()
return waveform
if __name__=='__main__':
samples = 200
qm = qpskMod(samples = samples)
signal = qm.run('00011011')
for i in range(5):
PL.subplot(5,1,i)
awgn = awgnGen(power = pow(10,2*i), samplesperperiod = samples)
PL.plot(awgn.run(signal))
PL.title('SNR = %s dB' % int(awgn.snrdb))
PL.show()
```
#### File: Wireless_Simulator/source/channelsimworkspace.py
```python
def raisedCosine(alpha = .99, period = .001, samples = 16000, numperiods = 16):
t = N.arange(samples) * period/samples * numperiods #Generate the time array
t = t - period * numperiods / 2 #Shift the array to the left to center the pulse on time = 0
term1 = N.sinc(t/period)/period #The next four lines calculate the dependent variable
term2 = N.cos((t * alpha * S.pi)/period)
term3 = 1 - pow((4 * alpha * t) / (2 * period),2)
tempformula = term1 * term2 / term3
t = t + period * numperiods / 2 #Shift the pulse back over so it's causal
formula = N.zeros(len(t)) #Create a new array to hold a series of pulses
shiftvar = 2*samples/numperiods #Define shift variable to move pulses in time
a = len(t) #Variable for the upper index limit of the pulse array
for i in range(numperiods/2):
b = a - i*shiftvar - samples/numperiods #Variable for time 0 of shifted pulse
formula += N.hstack((tempformula[b:a],tempformula[0:b])) #Starts the pulse at time zero, wraps the remainder
formula /= samples/numperiods #Normalizes the pulse to an amplitude of 1
#PL.plot(t,formula)
#PL.show()
return (t,formula)
def bpskMod(period = .001, samples = 1000, binary = '1', amplitude = 1, frequency = 10000, numperiods = 1):
lookupdict = {'0':1, '1':0}
symbol = lookupdict[binary]
t = N.arange(samples) * period/samples #Generate the time array
formula = amplitude * N.cos(2 * S.pi * frequency * t + symbol * S.pi) #This line calculates the dependent variable
formula = stackarrays(formula, numperiods)
#PL.plot(formula)
#PL.show()
return(t, formula)
def qpskMod(period = .001, samples = 1000, binary = '00', amplitude = 1, frequency = 10000, numperiods = 1):
lookupdict = {'00':0, '01':1, '10':2, '11':3}
symbol = lookupdict[binary]
t = N.arange(samples) * period/samples #Generate the time array
formula = amplitude * N.cos(2 * S.pi * frequency * t + symbol * S.pi/2) #This line calculates the dependent variable
formula = stackarrays(formula, numperiods)
#PL.plot(formula)
#PL.show()
return(t, formula)
def stackarrays(array, numstack): #Replicates and appends an array numstack times
modlist = []
for i in range(numstack):
modlist.append(array)
newarray = N.hstack(tuple(modlist))
return newarray
#This main function records a bit of input and then plays it back
def main():
#cu = CursesUser() #Instance of CursesUser
#AE.register(cu.shutdown)
audio = AudioInterface() #Instance of AudioInterface
audioarray = N.zeros(50000)
audio.audioRead()
audio.audioWrite()
print "Recording..."
for i in range(len(audioarray)):
thissample = audio.unbin(audio.audioSampleGrab()) #put integers in the array
audioarray[i] = thissample
print "Playing..."
for i in range(len(audioarray)):
audio.audioSamplePut(audio.hexStream(audioarray[i])) #pass the output to audio
exit()
#This main function just passes the latest sample to the output -- there's a bit of a delay
def main():
#cu = CursesUser() #Instance of CursesUser
#AE.register(cu.shutdown)
audio = AudioInterface() #Instance of AudioInterface
audioarray = N.zeros(50000)
audio.audioRead()
audio.audioWrite()
while(1):
thissample = audio.unbin(audio.audioSampleGrab()) #put integers in the array
audio.audioSamplePut(audio.hexStream(thissample)) #pass the output to audio
exit()
class symboldict:
def __init__(self, pulsetype = 'raisedCos', modtype = 'bpsk',
samples = 2000, symperiod = .001,
frequency = 100000):
self.samples = samples #Set samples, period & frequency as attributes
self.symperiod = symperiod
self.frequency = frequency
self.modtype = modtype
self.pulsetype = pulsetype
self.symbolDict = {}
self.modDict = {'bpsk':'bpskMod', 'qpsk':'qpskMod', 'msk':'mskMod'}
self.pulseDict = {'raisedCos':'raisedCosine', 'rect':'rect')
entries = 256
try:
self.modDict[self.modulation]
except:
print "Unknown modulation. Exiting."
exit()
try:
self.pulseDict[self.pulsetype]
except:
print "Unknown pulse type. Exiting."
exit()
modvar = modulation.getattr(modulation, self.modDict[self.modtype]
modulator = modvar(self.samples, self.symperiod, self.frequency)
for i in range(entries):
binaryString = self.bin(i)
symbol = modulator.run(binaryString)
self.symbolDict[binaryString] = symbol
def bin(self, decimalValue):
digits = {'0':'0000','1':'0001','2':'0010','3':'0011',
'4':'0100','5':'0101','6':'0110','7':'0111',
'8':'1000','9':'1001','A':'1010','B':'1011',
'C':'1100','D':'1101','E':'1110','F':'1111'}
hexStr = "%X" % decimalValue # convert to hexidecimal string
binStr = ''
# convert hexidecimal digit to its binary equivalent
for i in hexStr: binStr += digits[i]
if len(binStr) == 4:
binStr = '0000' + binStr
return binStr
if len(psdarray) > len(randseq):
randseq = N.hstack((randseq, N.zeros(len(psdarray) - len(randseq))))
elif len(psdarray) < len(randseq):
randseq = randseq[1:len(psdarray)]
outfile = open('test.out', 'w')
audio = AudioInterface(4000) #Instance of AudioInterface
print "Working..."
for i in range(10000):
thissample = audio.hexsampleGrab(1) #put integers in the array
audio.hexsamplePut(thissample) #pass the output to audio
outfile.write(str(clock()))
outfile.close()
self.Qin = Queue.Queue()
self.Qout = Queue.Queue()
new_thread = threading.Thread(target = self.putAudioinQueue)
new_thread.start()
new_thread = threading.Thread(target = self.putAudiofromQueue)
new_thread.start()
new_thread = threading.Thread(target = self.passAudioThruChannel)
new_thread.start()
def putAudioinQueue(self):
while True:
thissample = self.audio.sampleGrab()
print thissample
self.Qin.put(thissample)
def putAudiofromQueue(self):
while True:
thissample = self.Qout.get()
self.audio.samplePut(thissample)
```
#### File: Wireless_Simulator/source/cursesuser.py
```python
import curses as C
class CursesUser:
def __init__(self):
self.stdscr = C.initscr() #Initialize the screen (clear it)
C.noecho() #Do not echo user keystrokes
C.cbreak() #React to keys immediately, without waiting for an enter or return
self.stdscr.keypad(1) #Allow curses to handle special keys (up, down, esc, etc.)
def shutdown(self):
#Reverses everything done in __init__
C.nocbreak()
self.stdscr.keypad(0)
C.echo()
print "Curses Shutdown"
def write(self, string, x = 0, y = 0):
#Writes a string to a standard place on the screen, refreshes
self.stdscr.addstr(y, x, string)
self.stdscr.refresh()
```
#### File: Wireless_Simulator/source/demodulator.py
```python
import numpy as N
import scipy as S
import pylab as PL
#from modulation import *
#from symboldict import *
#from awgn import *
import time
class demodulator:
def __init__(self, symboldict):
self.symboldict = symboldict
def run(self, signal):
decisiondict = {}
decisionstatmatrix = N.zeros(len(self.symboldict))
counter = 0
for i in self.symboldict:
newdecisionstat = N.sum(self.symboldict[i]*signal)
decisiondict[newdecisionstat] = i
decisionstatmatrix[counter] = newdecisionstat
counter += 1
symbol = decisiondict[N.amax(decisionstatmatrix)]
return symbol
if __name__=='__main__':
samples = 2000
slt = symbolLookupTable(samples = samples)
signal = slt.symbolDict['10011010']
dm = demodulator(slt.symbolDict)
for i in range(100):
awgn = awgnGen(power = 10, samplesperperiod = samples)
signal = awgn.run(signal)
print dm.run(signal)
```
#### File: Wireless_Simulator/source/pulses.py
```python
import numpy as N
import scipy as S
import pylab as PL
class raisedCosine:
def __init__(self, alpha = .99, period = .001, samples = 2000, numperiods = 8):
self.alpha = alpha
self.period = period
self.numperiods = numperiods * 2
self.samples = samples * numperiods
def raisedCos(self):
t = N.arange(self.samples) * self.period/self.samples * self.numperiods#Generate the time array
t = t - self.period * self.numperiods / 2 #Shift the array to the left to center the pulse on time = 0
term1 = N.sinc(t/self.period)/self.period #The next four lines calculate the dependent variable
term2 = N.cos((t * self.alpha * S.pi)/self.period)
term3 = 1 - pow((4 * self.alpha * t) / (2 * self.period),2)
tempformula = term1 * term2 / term3
t = t + self.period * self.numperiods / 2 #Shift the pulse back over so it's causal
formula = N.zeros(len(t)) #Create a new array to hold a series of pulses
shiftvar = 2*self.samples/self.numperiods #Define shift variable to move pulses in time
a = len(t) #Variable for the upper index limit of the pulse array
for i in range(self.numperiods/2):
b = a - i*shiftvar - self.samples/self.numperiods #Variable for time 0 of shifted pulse
formula += N.hstack((tempformula[b:a],tempformula[0:b])) #Starts the pulse at time zero, wraps the remainder
formula /= self.samples/self.numperiods #Normalizes the pulse to an amplitude of 1
return (t,formula)
def run(self, plot = False):
waveform = self.raisedCos()[1]
if plot:
PL.plot(waveform)
PL.show()
return waveform
class rect:
def __init__(self, alpha = .75, period = .001, samples = 2000, numperiods = 8):
self.alpha = alpha
self.period = period
self.numperiods = numperiods * 2
self.samples = samples * numperiods
def rectangular(self):
formula = N.ones(self.samples)
return formula
def run(self, plot = False):
waveform = self.rectangular()
if plot:
PL.plot(waveform)
PL.show()
return waveform
```
#### File: Wireless_Simulator/source/symboldict.py
```python
import modulation
import pulses
import pylab as PL
import scipy as S
class symbolLookupTable:
def __init__(self, pulsetype = 'raisedCos', modtype = 'bpsk',
samples = 2000, symperiod = .001, alpha = .75,
frequency = 100000):
self.samples = samples #Set samples, period & frequency as attributes
self.symperiod = symperiod
self.frequency = frequency
self.modtype = modtype
self.pulsetype = pulsetype
self.symbolDict = {}
self.modDict = {'bpsk':'bpskMod', 'qpsk':'qpskMod', 'msk':'mskMod'}
self.pulseDict = {'raisedCos':'raisedCosine', 'rect':'rect'}
self.alpha = alpha
entries = 256
try:
self.modDict[self.modtype]
except:
print "Unknown modulation. Exiting."
return None
try:
self.pulseDict[self.pulsetype]
except:
print "Unknown pulse type. Exiting."
return None
modvar = getattr(modulation, self.modDict[self.modtype])
pulsevar = getattr(pulses, self.pulseDict[self.pulsetype])
modulator = modvar(self.samples, self.symperiod, self.frequency)
pulsegen = pulsevar(self.alpha, self.symperiod, self.samples)
self.pulses = pulsegen.run()
for i in range(entries):
binaryString = self.bin(i)
symbol = modulator.run(binaryString)
symbol = symbol * self.pulses
self.symbolDict[binaryString] = symbol
def bin(self, decimalValue):
digits = {'0':'0000','1':'0001','2':'0010','3':'0011',
'4':'0100','5':'0101','6':'0110','7':'0111',
'8':'1000','9':'1001','A':'1010','B':'1011',
'C':'1100','D':'1101','E':'1110','F':'1111'}
hexStr = "%X" % decimalValue # convert to hexidecimal string
binStr = ''
# convert hexidecimal digit to its binary equivalent
for i in hexStr: binStr += digits[i]
if len(binStr) == 4:
binStr = '0000' + binStr
return binStr
def plot(self, binaryString):
PL.subplot(1,2,1)
PL.plot(self.symbolDict[binaryString])
fourier = S.fft(self.symbolDict[binaryString])
PL.subplot(1,2,2)
PL.semilogy(fourier)
PL.show()
``` |
{
"source": "JoeCotellese/TwitPy",
"score": 3
} |
#### File: TwitPy/twitpy/print_log_writer.py
```python
from datetime import datetime
from selenium.common.exceptions import NoSuchElementException
def log_follower_num(browser, username):
"""Prints and logs the current number of followers to
a seperate file"""
browser.get('https://www.twitter.com/' + username)
followed_by = browser.find_element_by_xpath('//a[@data-nav ="followers"]/span[@class="ProfileNav-value"]').text
with open('./logs/followerNum.txt', 'a') as numFile:
numFile.write('{:%Y-%m-%d %H:%M} {}\n'.format(datetime.now(), followed_by or 0))
```
#### File: TwitPy/twitpy/twitpy.py
```python
from datetime import datetime
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from .login_util import login_user
from .print_log_writer import log_follower_num
from .follow_util import follow_from_recommended
from .unfollow_util import unfollow_users
class TwitPy:
"""Class to be instantiated to use the script"""
def __init__(self, username=None, password=<PASSWORD>, nogui=False, chrome_path='./assets/chromedriver'):
if nogui:
self.display = Display(visible=0, size=(800, 600))
self.display.start()
chrome_options = Options()
chrome_options.add_argument('--dns-prefetch-disable')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--lang=en-US')
chrome_options.add_experimental_option('prefs', {'intl.accept_languages': 'en-US'})
# managed_default_content_settings.images = 2: Disable images load, this setting can improve pageload & save bandwidth
# default_content_setting_values.notifications = 2: Disable notifications
# credentials_enable_service & password_manager_enabled = false: Ignore save password prompt from chrome
chrome_prefs = {
'intl.accept_languages': 'en-US',
'profile.managed_default_content_settings.images': 2,
'profile.default_content_setting_values.notifications': 2,
'credentials_enable_service': False,
'profile': {
'password_manager_enabled': False
}
}
chrome_options.add_experimental_option('prefs', chrome_prefs)
self.browser = webdriver.Chrome(chrome_path, chrome_options=chrome_options)
self.browser.implicitly_wait(5)
self.logFile = open('./logs/logFile.txt', 'a')
self.logFile.write('Session started - %s\n' \
% (datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
if not username or not password:
print('Please provide Username and Password')
return
self.username = username
self.password = password
self.nogui = nogui
self.followed = 0
self.ignore_users = []
self.aborting = False
def login(self):
"""Used to login the user either with the username and password"""
if not login_user(self.browser, self.username, self.password):
print('Wrong login data!')
self.logFile.write('Wrong login data!\n')
self.aborting = True
else:
print('Logged in successfully!')
self.logFile.write('Logged in successfully!\n')
log_follower_num(self.browser, self.username)
return self
def follow_from_recom(self, amount=50):
"""Follows given amount of users from the 'Who to follow' list"""
if self.aborting:
return self
followed = amount
while followed > 0:
new_followed = follow_from_recommended(self.browser, followed)
if new_followed == 0:
print('Aborting because no recommendations left')
self.logFile.write('Aborting because no recommendations left\n')
break
followed -= new_followed
self.followed += followed
return self
def unfollow_users(self, amount=50):
"""Unfollows given amount of users"""
if self.aborting:
return self
to_unfollow = amount
while to_unfollow > 0:
new_unfollowed = unfollow_users(self.browser, to_unfollow)
if new_unfollowed == 0:
break
to_unfollow -= new_unfollowed
return self
def end(self):
"""Closes the current session"""
self.browser.delete_all_cookies()
self.browser.close()
if self.nogui:
self.display.stop()
print('')
print('Session ended')
print('-------------')
self.logFile.write(
'\nSession ended - {}\n'.format(
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
)
)
self.logFile.write('-' * 20 + '\n\n')
self.logFile.close()
with open('./logs/followed.txt', 'w') as followFile:
followFile.write(str(self.followed))
```
#### File: TwitPy/twitpy/unfollow_util.py
```python
from .actions import Actions
from .time_util import sleep
from selenium.webdriver.common.keys import Keys
def unfollow_users(browser, amount):
"""Unfollows given amount of users"""
unfollowed = 0
last_length = 0
#Click on the view all button on the main page to load all the recommended accounts
browser.get('https://twitter.com/following')
body_elem = browser.find_element_by_tag_name('body')
timeline = browser.find_elements_by_xpath(
'//div[@class = "ProfileCard-actions"]//span[contains(@class, "user-actions-follow-button js-follow-btn follow-button")]')
while len(timeline) < amount and len(timeline) > last_length:
last_length = len(timeline)
body_elem.send_keys(Keys.END)
sleep(1)
body_elem.send_keys(Keys.HOME)
sleep(1)
timeline = browser.find_elements_by_xpath(
'//div[@class = "ProfileCard-actions"]//span[contains(@class, "user-actions-follow-button js-follow-btn follow-button")]')
if len(timeline) > amount:
unfollowed = amount
else:
unfollowed = len(timeline)
action_chain = Actions(browser)
for index, button in enumerate(timeline[:unfollowed]):
action_chain.move_to_element(button)
action_chain.wait(1)
action_chain.move_to_element(button)
action_chain.click()
action_chain.wait(1)
action_chain.print_it(str(index + 1) + '/' + str(unfollowed))
action_chain.perform()
return unfollowed
``` |
{
"source": "joecrop/SDMO",
"score": 2
} |
#### File: SDMO/cgi-bin/main.py
```python
import random, sys, time, pygame, os
from pygame.locals import *
#import wifitools
import pickle
import sqlite3
import datetime
import medManager
import userManager
##TODO: change for PI
#os.environ["SDL_FBDEV"] = "/dev/fb1"
#os.environ["SDL_MOUSEDEV"] = "/dev/input/touchscreen"
#os.environ["SDL_MOUSEDRV"] = "TSLIB"
FPS = 30
WINDOWWIDTH = 320
WINDOWHEIGHT = 240
FLASHSPEED = 500 # in milliseconds
FLASHDELAY = 200 # in milliseconds
BUTTONSIZE = 80
BUTTONGAPSIZE = 10
# R G B
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
DARK = ( 18, 40, 13)
MID = ( 47, 82, 20)
LIGHT = ( 77, 129, 41)
DARKGRAY = ( 64, 64, 64)
bgColor = BLACK
HEADER = 30
BORDER = 10
# status bar
RECTSTATUS = pygame.Rect(0, 0, WINDOWWIDTH, HEADER)
IMAGE_WIFI0 = pygame.image.load("images/wifi0.BMP")
IMAGE_WIFI1 = pygame.image.load("images/wifi1.BMP")
IMAGE_WIFI2 = pygame.image.load("images/wifi2.BMP")
IMAGE_WIFI3 = pygame.image.load("images/wifi3.BMP")
IMAGE_WIFI4 = pygame.image.load("images/wifi4.BMP")
IMAGE_ALARM = pygame.image.load("images/alarm.BMP")
IMAGE_NOALARM = pygame.image.load("images/noalarm.BMP")
IMAGE_ALERT = pygame.image.load("images/alert.BMP")
IMAGE_WARNING = pygame.image.load("images/warning.BMP")
IMAGE_LOCK = pygame.image.load("images/lock.BMP")
IMAGE_TIMER = pygame.image.load("images/timer.BMP")
IMAGE_GEARS = pygame.image.load("images/gears.png")
IMAGE_BACK = pygame.image.load("images/back.png")
IMAGE_PILL = pygame.image.load("images/pill.png")
IMAGE_LOAD = pygame.image.load("images/load.png")
IMAGE_PLUS = pygame.image.load("images/plus.png")
IMAGE_FACE = pygame.image.load("images/face.png")
IMAGE_POWER = pygame.image.load("images/power.png")
IMAGE_BRIGHTNESS = pygame.image.load("images/brightness.png")
IMAGE_WIFI_SETTINGS = pygame.image.load("images/wifi_settings.png")
# main menu
RECT_BG = pygame.Rect(0, HEADER, 210, 320)
BUTTON_1 = pygame.Rect(10, HEADER+BORDER, 90, 90)
BUTTON_2 = pygame.Rect(110, HEADER+BORDER, 90, 90)
BUTTON_3 = pygame.Rect(210, HEADER+BORDER, 90, 90)
BUTTON_4 = pygame.Rect(10, HEADER+BORDER+100, 90, 90)
BUTTON_5 = pygame.Rect(110, HEADER+BORDER+100, 90, 90)
BUTTON_6 = pygame.Rect(210, HEADER+BORDER+100, 90, 90)
LIST_1 = pygame.Rect(10, HEADER+BORDER, 190, 40)
LIST_2 = pygame.Rect(10, HEADER+BORDER+50, 190, 40)
LIST_3 = pygame.Rect(10, HEADER+BORDER+100, 190, 40)
LIST_4 = pygame.Rect(10, HEADER+BORDER+150, 190, 40)
LIST_UP = pygame.Rect(210, HEADER+BORDER, 90, 40)
LIST_DN = pygame.Rect(210, HEADER+BORDER+50, 90, 40)
ACTION_DISPENSE = 1
ACTION_STATUS = 2
ACTION_LOAD = 3
ACTION_SETTINGS = 4
ACTION_BACK = 5
ACTION_WIFI = 6
ACTION_ADDUSER = 7
ACTION_USER1 = 8
ACTION_USER2 = 9
ACTION_USER3 = 10
ACTION_USER4 = 11
ACTION_SHUTDOWN = 12
ACTION_BRIGHTNESS = 13
ACTION_LIST_1 = 14
ACTION_LIST_2 = 15
ACTION_LIST_3 = 16
ACTION_LIST_4 = 17
ACTION_LIST_UP = 18
ACTION_LIST_DN = 19
ACTION_VENDING = 20
ACTION_HOME = 21
ACTION_MANAGE = 22
MENU_MAIN = 0
MENU_SETTINGS = 1
MENU_WIFI = 2
MENU_USERS = 3
MENU_ADDUSER = 4
MENU_DISPENSE = 5
MENU_LOAD = 6
MENU_LOADING = 7
MENU_SHUTDOWN = 8
MENU_BRIGHTNESS = 9
MENU_VENDING = 10
MENU_MANAGE = 11
##TODO: change for PI
wifipercent = 100 #int(wifitools.get_main_percent())
users = ['Joe', 'Amy', 'Dad', 'Mom']
pickle.dump(users, open("data/users.pkl","wb"))
users = pickle.load(open("data/users.pkl","rb"))
#global vars
list_position = 0
list_next = 0
list_id = 0
current_user = 0
pill_id = 0
pill_name = 0
def main():
global FPSCLOCK, DISPLAYSURF, BASICFONT, BEEP1, BEEP2, BEEP3, BEEP4
current_menu = MENU_MAIN
global list_position
global list_next
global list_id
global current_user
global pill_id
global pill_name
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
##TODO: change for PI
#pygame.mouse.set_visible(0)
IMAGE_GEARS = pygame.image.load("images/gears.png").convert_alpha()
IMAGE_BACK = pygame.image.load("images/back.png").convert_alpha()
IMAGE_PILL = pygame.image.load("images/pill.png").convert_alpha()
IMAGE_LOAD = pygame.image.load("images/load.png").convert_alpha()
IMAGE_PLUS = pygame.image.load("images/plus.png").convert_alpha()
IMAGE_FACE = pygame.image.load("images/face.png").convert_alpha()
IMAGE_POWER = pygame.image.load("images/power.png").convert_alpha()
IMAGE_BRIGHTNESS = pygame.image.load("images/brightness.png").convert_alpha()
IMAGE_WIFI_SETTINGS = pygame.image.load("images/wifi_settings.png").convert_alpha()
# when False, the pattern is playing. when True, waiting for the player to click a colored button:
waitingForInput = False
updateDisplay = True
while True: # main game loop
clickedButton = None # button that was clicked
if updateDisplay:
DISPLAYSURF.fill(bgColor)
drawStatusBar()
if current_menu == MENU_MAIN:
drawMainMenu()
elif current_menu == MENU_SETTINGS:
drawSettingsMenu()
elif current_menu == MENU_WIFI:
drawWIFIMenu()
elif current_menu == MENU_USERS:
drawUsersMenu()
elif current_menu == MENU_DISPENSE:
drawDispenseMenu()
elif current_menu == MENU_ADDUSER:
drawAddUserMenu()
elif current_menu == MENU_LOAD:
drawLoadMenu()
elif current_menu == MENU_LOADING:
drawLoadingMenu()
elif current_menu == MENU_SHUTDOWN:
drawShutdownMenu()
elif current_menu == MENU_BRIGHTNESS:
drawBrightnessMenu()
elif current_menu == MENU_VENDING:
drawVendingMenu()
elif current_menu == MENU_MANAGE:
drawManageMenu()
updateDisplay = False
checkForQuit()
for event in pygame.event.get(): # event handling loop
if event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
clickedButton = getButtonClicked(mousex, mousey, current_menu)
# wait for the player to enter buttons
if clickedButton:
if clickedButton == ACTION_SETTINGS:
current_menu = MENU_SETTINGS
elif clickedButton == ACTION_WIFI:
current_menu = MENU_WIFI
elif clickedButton == ACTION_HOME:
current_menu = MENU_MAIN
elif clickedButton == ACTION_BRIGHTNESS:
current_menu = MENU_BRIGHTNESS
elif clickedButton == ACTION_LOAD:
current_menu = MENU_LOAD
elif clickedButton == ACTION_DISPENSE:
current_menu = MENU_USERS
elif clickedButton == ACTION_SHUTDOWN:
current_menu = MENU_SHUTDOWN
elif clickedButton == ACTION_ADDUSER:
current_menu = MENU_ADDUSER
elif clickedButton == ACTION_MANAGE:
current_menu = MENU_MANAGE
elif clickedButton == ACTION_USER1:
current_menu = MENU_DISPENSE
current_user = users[0]
elif clickedButton == ACTION_USER2:
current_menu = MENU_DISPENSE
current_user = users[1]
elif clickedButton == ACTION_USER3:
current_menu = MENU_DISPENSE
current_user = users[2]
elif clickedButton == ACTION_USER4:
current_menu = MENU_DISPENSE
current_user = users[3]
elif clickedButton == ACTION_LIST_1:
if(list_position < list_next):
list_id = list_position
if(current_menu == MENU_DISPENSE):
current_menu = MENU_VENDING
elif(current_menu == MENU_LOAD):
current_menu = MENU_LOADING
elif clickedButton == ACTION_LIST_2:
if(list_position+1 < list_next):
list_id = list_position+1
if(current_menu == MENU_DISPENSE):
current_menu = MENU_VENDING
elif(current_menu == MENU_LOAD):
current_menu = MENU_LOADING
elif clickedButton == ACTION_LIST_3:
if(list_position+2 < list_next):
list_id = list_position+2
if(current_menu == MENU_DISPENSE):
current_menu = MENU_VENDING
elif(current_menu == MENU_LOAD):
current_menu = MENU_LOADING
elif clickedButton == ACTION_LIST_4:
if(list_position+3 < list_next):
list_id = list_position+3
if(current_menu == MENU_DISPENSE):
current_menu = MENU_VENDING
elif(current_menu == MENU_LOAD):
current_menu = MENU_LOADING
elif clickedButton == ACTION_LIST_DN:
if(list_next > 4):
list_position = list_position + 4
elif clickedButton == ACTION_LIST_UP:
if(list_position > 0):
list_position = list_position - 4
elif clickedButton == ACTION_BACK:
if current_menu == MENU_WIFI:
current_menu = MENU_SETTINGS
elif current_menu == MENU_SETTINGS:
current_menu = MENU_MAIN
elif current_menu == MENU_USERS:
current_menu = MENU_MAIN
elif current_menu == MENU_DISPENSE:
current_menu = MENU_USERS
elif current_menu == MENU_ADDUSER:
current_menu = MENU_USERS
elif current_menu == MENU_LOAD:
current_menu = MENU_MAIN
elif current_menu == MENU_SHUTDOWN:
current_menu = MENU_MAIN
elif current_menu == MENU_BRIGHTNESS:
current_menu = MENU_SETTINGS
elif current_menu == MENU_VENDING:
current_menu = MENU_DISPENSE
elif current_menu == MENU_LOADING:
current_menu = MENU_LOAD
elif current_menu == MENU_MANAGE:
current_menu = MENU_MAIN
updateDisplay = True
pygame.display.update()
FPSCLOCK.tick(FPS)
def terminate():
pygame.quit()
sys.exit()
def checkForQuit():
for event in pygame.event.get(QUIT): # get all the QUIT events
terminate() # terminate if any QUIT events are present
for event in pygame.event.get(KEYUP): # get all the KEYUP events
if event.key == K_ESCAPE:
terminate() # terminate if the KEYUP event was for the Esc key
pygame.event.post(event) # put the other KEYUP event objects back
def getButtonClicked(x, y, current_menu):
global list_id
global list_position
global list_next
global pill_id
if current_menu == MENU_MAIN:
if BUTTON_1.collidepoint( (x, y) ):#dispense
return ACTION_DISPENSE
elif BUTTON_2.collidepoint( (x, y) ):#status
return ACTION_LOAD
elif BUTTON_3.collidepoint( (x, y) ):
return ACTION_STATUS
elif BUTTON_4.collidepoint( (x, y) ):
return ACTION_MANAGE
elif BUTTON_5.collidepoint( (x, y) ):#shutdown
return ACTION_SHUTDOWN
elif BUTTON_6.collidepoint( (x, y) ):#settings
return ACTION_SETTINGS
elif current_menu == MENU_SETTINGS:
if BUTTON_6.collidepoint( (x, y) ):#back
return ACTION_BACK
elif BUTTON_5.collidepoint( (x, y) ):#wifi
return ACTION_WIFI
elif BUTTON_4.collidepoint( (x, y) ):#wifi
return ACTION_BRIGHTNESS
elif current_menu == MENU_WIFI:
if BUTTON_6.collidepoint( (x, y) ):#back
return ACTION_BACK
elif current_menu == MENU_VENDING:
if BUTTON_6.collidepoint( (x, y) ):#back
pill_id = 0
pill_name = ""
return ACTION_BACK
if BUTTON_5.collidepoint( (x, y) ):#back
x = medManager.getMedX(pill_id)
y = medManager.getMedY(pill_id)
print(pill_id, x,y)
#TODO: do vending here
medManager.removeInventory(x,y)
list_id = 0
list_next = 0
list_position = 0
pill_id = 0
pill_name = ""
return ACTION_HOME
elif current_menu == MENU_LOADING:
if BUTTON_6.collidepoint( (x, y) ):#back
pill_id = 0
pill_name = ""
return ACTION_BACK
if BUTTON_5.collidepoint( (x, y) ):#back
print(pill_id, x,y)
#TODO: do vending here
x = medManager.getFreeSpaceX()
y = medManager.getFreeSpaceY()
d = datetime.date(2016, 11, 23)
medManager.addInventory(x, y, pill_id, d)
print("inserted into: ", x, y)
#return ACTION_HOME
elif current_menu == MENU_BRIGHTNESS:
if BUTTON_6.collidepoint( (x, y) ):#back
return ACTION_BACK
elif current_menu == MENU_DISPENSE:
if BUTTON_6.collidepoint( (x, y) ):#back
list_id = 0
list_next = 0
list_position = 0
return ACTION_BACK
if LIST_UP.collidepoint( (x, y) ):#back
return ACTION_LIST_UP
if LIST_DN.collidepoint( (x, y) ):#back
return ACTION_LIST_DN
if LIST_1.collidepoint( (x, y) ):#back
return ACTION_LIST_1
if LIST_2.collidepoint( (x, y) ):#back
return ACTION_LIST_2
if LIST_3.collidepoint( (x, y) ):#back
return ACTION_LIST_3
if LIST_4.collidepoint( (x, y) ):#back
return ACTION_LIST_4
elif current_menu == MENU_ADDUSER:
if BUTTON_6.collidepoint( (x, y) ):#back
return ACTION_BACK
elif current_menu == MENU_MANAGE:
if BUTTON_6.collidepoint( (x, y) ):#back
list_id = 0
list_next = 0
list_position = 0
return ACTION_BACK
if LIST_UP.collidepoint( (x, y) ):#back
return ACTION_LIST_UP
if LIST_DN.collidepoint( (x, y) ):#back
return ACTION_LIST_DN
if LIST_1.collidepoint( (x, y) ):#back
return ACTION_LIST_1
if LIST_2.collidepoint( (x, y) ):#back
return ACTION_LIST_2
if LIST_3.collidepoint( (x, y) ):#back
return ACTION_LIST_3
if LIST_4.collidepoint( (x, y) ):#back
return ACTION_LIST_4
elif current_menu == MENU_LOAD:
if BUTTON_6.collidepoint( (x, y) ):#back
list_id = 0
list_next = 0
list_position = 0
return ACTION_BACK
if LIST_UP.collidepoint( (x, y) ):#back
return ACTION_LIST_UP
if LIST_DN.collidepoint( (x, y) ):#back
return ACTION_LIST_DN
if LIST_1.collidepoint( (x, y) ):#back
return ACTION_LIST_1
if LIST_2.collidepoint( (x, y) ):#back
return ACTION_LIST_2
if LIST_3.collidepoint( (x, y) ):#back
return ACTION_LIST_3
if LIST_4.collidepoint( (x, y) ):#back
return ACTION_LIST_4
elif current_menu == MENU_SHUTDOWN:
if BUTTON_5.collidepoint( (x, y) ):#back
os.system("sudo shutdown -h now") #shut down the system
if BUTTON_6.collidepoint( (x, y) ):#back
return ACTION_BACK
elif current_menu == MENU_USERS:
if BUTTON_6.collidepoint( (x, y) ):#back
return ACTION_BACK
if BUTTON_3.collidepoint( (x, y) ):#back
return ACTION_ADDUSER
if BUTTON_1.collidepoint( (x, y) ):#back
return ACTION_USER1
if BUTTON_2.collidepoint( (x, y) ):#back
return ACTION_USER2
if BUTTON_4.collidepoint( (x, y) ):#back
return ACTION_USER3
if BUTTON_5.collidepoint( (x, y) ):#back
return ACTION_USER4
return None
def drawStatusBar():
pygame.draw.rect(DISPLAYSURF, DARKGRAY, RECTSTATUS)
if wifipercent == 0:
DISPLAYSURF.blit(IMAGE_WIFI0, (0,0))
elif wifipercent <= 20:
DISPLAYSURF.blit(IMAGE_WIFI1, (0,0))
elif wifipercent <= 40:
DISPLAYSURF.blit(IMAGE_WIFI2, (0,0))
elif wifipercent <= 60:
DISPLAYSURF.blit(IMAGE_WIFI3, (0,0))
elif wifipercent <= 80:
DISPLAYSURF.blit(IMAGE_WIFI4, (0,0))
else:
DISPLAYSURF.blit(IMAGE_WIFI0, (0,0))
DISPLAYSURF.blit(IMAGE_ALARM, (50,0))
DISPLAYSURF.blit(IMAGE_NOALARM, (80,0))
DISPLAYSURF.blit(IMAGE_ALERT, (110,0))
DISPLAYSURF.blit(IMAGE_WARNING, (140,0))
DISPLAYSURF.blit(IMAGE_LOCK, (170,0))
DISPLAYSURF.blit(IMAGE_TIMER, (200,0))
def drawUsersMenu():
i=0
for user in users:
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render(user, 1, BLACK)
if i == 0:
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_1)
DISPLAYSURF.blit(IMAGE_FACE, (25,HEADER+BORDER+10))
DISPLAYSURF.blit(label, (15, HEADER+BORDER+70))
elif i == 1:
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_2)
DISPLAYSURF.blit(IMAGE_FACE, (125,HEADER+BORDER+10))
DISPLAYSURF.blit(label, (115, HEADER+BORDER+70))
elif i == 2:
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_4)
DISPLAYSURF.blit(IMAGE_FACE, (25,HEADER+BORDER+110))
DISPLAYSURF.blit(label, (15, HEADER+BORDER+170))
elif i == 3:
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_5)
DISPLAYSURF.blit(IMAGE_FACE, (125,HEADER+BORDER+110))
DISPLAYSURF.blit(label, (115, HEADER+BORDER+170))
i=i+1
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_3)
DISPLAYSURF.blit(IMAGE_PLUS, (225,HEADER+BORDER+10))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("ADD User", 1, BLACK)
DISPLAYSURF.blit(label, (220, HEADER+BORDER+70))
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Back", 1, BLACK)
DISPLAYSURF.blit(label, (237, 210))
def drawSettingsMenu():
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_4)
DISPLAYSURF.blit(IMAGE_BRIGHTNESS, (25,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Brightness", 1, BLACK)
DISPLAYSURF.blit(label, (11, 210))
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_5)
DISPLAYSURF.blit(IMAGE_WIFI_SETTINGS, (125,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("WIFI", 1, BLACK)
DISPLAYSURF.blit(label, (137, 210))
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Back", 1, BLACK)
DISPLAYSURF.blit(label, (237, 210))
def drawWIFIMenu():
myfont = pygame.font.SysFont("monospace", 15)
##TODO: change for PI
ip = 0#wifitools.get_connection_info('ip')
mask = 0#wifitools.get_connection_info('mask')
brd = 0#wifitools.get_connection_info('broadcast')
mac = 0#wifitools.get_connection_info('mac')
label = myfont.render(' IP Address: '+ip, 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+20))
label = myfont.render(' Broadcast: '+brd, 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+35))
label = myfont.render(' Net Mask: '+mask, 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+50))
label = myfont.render('MAC Address: '+mac, 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+65))
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Back", 1, BLACK)
DISPLAYSURF.blit(label, (237, 210))
def drawBrightnessMenu():
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render('Adjust Screen Brightness', 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+20))
SLIDER_OUT = pygame.Rect(5, HEADER+BORDER+40, 200, 30)
pygame.draw.rect(DISPLAYSURF, MID, SLIDER_OUT)
brightness = 160
#print brightness
SLIDER_VAL = pygame.Rect(10, HEADER+BORDER+45, brightness, 20)
pygame.draw.rect(DISPLAYSURF, LIGHT, SLIDER_VAL)
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Back", 1, BLACK)
DISPLAYSURF.blit(label, (237, 210))
def drawDispenseMenu():
global list_position
global list_next
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_1)
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_2)
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_3)
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_4)
myfont = pygame.font.SysFont("monospace", 15)
i=0
for med in medManager.getInventory(0):
if(i >= list_position):
label = myfont.render(med[1], 1, BLACK)
DISPLAYSURF.blit(label, (15, HEADER+20+50*(i-list_position)))
print(med[1])
i=i+1
list_next = i - list_position
if(list_position > 0):
pygame.draw.rect(DISPLAYSURF, MID, LIST_UP)
else:
pygame.draw.rect(DISPLAYSURF, DARK, LIST_UP)
label = myfont.render("Last", 1, BLACK)
DISPLAYSURF.blit(label, (215, HEADER+20))
if(list_next > 4):
pygame.draw.rect(DISPLAYSURF, MID, LIST_DN)
else:
pygame.draw.rect(DISPLAYSURF, DARK, LIST_DN)
label = myfont.render("Next", 1, BLACK)
DISPLAYSURF.blit(label, (215, HEADER+70))
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Back", 1, BLACK)
DISPLAYSURF.blit(label, (237, 210))
def drawAddUserMenu():
myfont = pygame.font.SysFont("monospace", 15)
i = 0
for letter in ['q','w','e','r','t','y','u','i','o','p']:
button = pygame.Rect(10+30*i, HEADER+75, 25, 30)
pygame.draw.rect(DISPLAYSURF, MID, button)
label = myfont.render(letter, 1, WHITE)
DISPLAYSURF.blit(label, (20+30*i, HEADER+80))
i = i + 1
i = 0
for letter in ['a','s','d','f','g','h','j','k','l']:
button = pygame.Rect(25+30*i, HEADER+110, 25, 30)
pygame.draw.rect(DISPLAYSURF, MID, button)
label = myfont.render(letter, 1, WHITE)
DISPLAYSURF.blit(label, (35+30*i, HEADER+115))
i = i + 1
i = 0
for letter in ['^','z','x','c','v','b','n','m',',','.']:
button = pygame.Rect(10+30*i, HEADER+145, 25, 30)
pygame.draw.rect(DISPLAYSURF, MID, button)
label = myfont.render(letter, 1, WHITE)
DISPLAYSURF.blit(label, (20+30*i, HEADER+150))
i = i + 1
i = 0
for letter in ['space', 'del', 'done']:
button = pygame.Rect(25+90*i, HEADER+180, 85, 30)
pygame.draw.rect(DISPLAYSURF, MID, button)
label = myfont.render(letter, 1, WHITE)
DISPLAYSURF.blit(label, (35+90*i, HEADER+185))
i = i + 1
#pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
#DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
#myfont = pygame.font.SysFont("monospace", 15)
#label = myfont.render("Back", 1, BLACK)
#DISPLAYSURF.blit(label, (237, 210))
def drawShutdownMenu():
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render('Push the \'Turn Off\'', 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+20))
label = myfont.render('button one more time', 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+35))
label = myfont.render('to shut down machine', 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+50))
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_5)
DISPLAYSURF.blit(IMAGE_POWER, (125,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Turn Off", 1, BLACK)
DISPLAYSURF.blit(label, (117, 210))
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Back", 1, BLACK)
DISPLAYSURF.blit(label, (237, 210))
def drawVendingMenu():
global list_id
global pill_id
global pill_name
i=0
for med in medManager.getInventory(0):
if(i == list_id):
pill_name = med[1]
pill_id = med[0]
i=i+1
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render('Push the \'Dispense\'', 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+20))
label = myfont.render('button one more time', 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+35))
label = myfont.render('to dispense one pill of:', 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+50))
label = myfont.render(pill_name, 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+75))
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_5)
DISPLAYSURF.blit(IMAGE_PILL, (125,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Dispense", 1, BLACK)
DISPLAYSURF.blit(label, (117, 210))
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Back", 1, BLACK)
DISPLAYSURF.blit(label, (237, 210))
def drawLoadMenu():
global list_position
global list_next
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_1)
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_2)
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_3)
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_4)
myfont = pygame.font.SysFont("monospace", 15)
i=0
for med in medManager.getInventory(1):
if(i >= list_position):
label = myfont.render(med[1], 1, BLACK)
DISPLAYSURF.blit(label, (15, HEADER+20+50*(i-list_position)))
print(med[1])
i=i+1
list_next = i - list_position
if(list_position > 0):
pygame.draw.rect(DISPLAYSURF, MID, LIST_UP)
else:
pygame.draw.rect(DISPLAYSURF, DARK, LIST_UP)
label = myfont.render("Last", 1, BLACK)
DISPLAYSURF.blit(label, (215, HEADER+20))
if(list_next > 4):
pygame.draw.rect(DISPLAYSURF, MID, LIST_DN)
else:
pygame.draw.rect(DISPLAYSURF, DARK, LIST_DN)
label = myfont.render("Next", 1, BLACK)
DISPLAYSURF.blit(label, (215, HEADER+70))
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Back", 1, BLACK)
DISPLAYSURF.blit(label, (237, 210))
def drawLoadingMenu():
global list_id
global pill_id
global pill_name
i=0
for med in medManager.getInventory(1):
if(i == list_id):
pill_name = med[1]
pill_id = med[0]
i=i+1
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render('Push the \'Load\'', 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+20))
label = myfont.render('once for each pill you', 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+35))
label = myfont.render('want to load of:', 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+50))
label = myfont.render(pill_name, 1, WHITE)
DISPLAYSURF.blit(label, (10, HEADER+75))
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_5)
DISPLAYSURF.blit(IMAGE_PILL, (125,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Load", 1, BLACK)
DISPLAYSURF.blit(label, (117, 210))
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Back", 1, BLACK)
DISPLAYSURF.blit(label, (237, 210))
def drawManageMenu():
global list_position
global list_next
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_1)
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_2)
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_3)
pygame.draw.rect(DISPLAYSURF, LIGHT, LIST_4)
myfont = pygame.font.SysFont("monospace", 15)
i=0
for med in medManager.getInventory(1):
if(i >= list_position):
label = myfont.render(med[1], 1, BLACK)
DISPLAYSURF.blit(label, (15, HEADER+20+50*(i-list_position)))
print(med[1])
i=i+1
list_next = i - list_position
if(list_position > 0):
pygame.draw.rect(DISPLAYSURF, MID, LIST_UP)
else:
pygame.draw.rect(DISPLAYSURF, DARK, LIST_UP)
label = myfont.render("Last", 1, BLACK)
DISPLAYSURF.blit(label, (215, HEADER+20))
if(list_next > 4):
pygame.draw.rect(DISPLAYSURF, MID, LIST_DN)
else:
pygame.draw.rect(DISPLAYSURF, DARK, LIST_DN)
label = myfont.render("Next", 1, BLACK)
DISPLAYSURF.blit(label, (215, HEADER+70))
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_6)
DISPLAYSURF.blit(IMAGE_BACK, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Back", 1, BLACK)
DISPLAYSURF.blit(label, (237, 210))
def drawMainMenu():
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_1) #dispense
DISPLAYSURF.blit(IMAGE_PILL, (25,HEADER+BORDER+10))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Dispense", 1, BLACK)
DISPLAYSURF.blit(label, (19, 110))
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_2) #load
DISPLAYSURF.blit(IMAGE_LOAD, (125,HEADER+BORDER+10))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Load", 1, BLACK)
DISPLAYSURF.blit(label, (137, 110))
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_3) #status
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_4)
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Manage", 1, BLACK)
DISPLAYSURF.blit(label, (22, 210))
pygame.draw.rect(DISPLAYSURF, MID, BUTTON_5)#power
DISPLAYSURF.blit(IMAGE_POWER, (125,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Turn Off", 1, BLACK)
DISPLAYSURF.blit(label, (117, 210))
pygame.draw.rect(DISPLAYSURF, LIGHT, BUTTON_6)#settings
DISPLAYSURF.blit(IMAGE_GEARS, (225,HEADER+BORDER+110))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Settings", 1, BLACK)
DISPLAYSURF.blit(label, (217, 210))
if __name__ == '__main__':
main()
```
#### File: SDMO/cgi-bin/servos.py
```python
import sys
import argparse
from Adafruit_PWM_Servo_Driver import PWM
import time
import RPi.GPIO as GPIO
#import pigpio
# ===========================================================================
# Example Code
# ===========================================================================
# Initialise the PWM device using the default address
# bmp = PWM(0x40, debug=True)
pwm = PWM(0x40, debug=False)
#GPIO = pigpio.pi()
# low end: 281 (1ms)
#high end: 562 (2ms)
servoMin = 281 # Min pulse length out of 4096
servoMax = 562 # Max pulse length out of 4096
PWM_OPEN = 370 #500
PWM_CLOSE = 300
PWM_LEFT = 330
PWM_RIGHT = 360
PWM_SEL_1 = 298
PWM_SEL_2 = 340
PWM_SEL_3 = 390
PWM_SEL_4 = 455
def readEncoder():
num = 0
num = num + (GPIO.input(40))
num = num + (GPIO.input(31)*2)
num = num + (GPIO.input(32)*4)
num = num + (GPIO.input(33)*8)
num = num + (GPIO.input(35)*16)
num = num + (GPIO.input(36)*32)
num = num + (GPIO.input(37)*64)
num = num + (GPIO.input(38)*128)
#sys.stderr.write("Encoder Position: %d" % num)
return num
def setServoPulse(channel, pulse):
pulseLength = 1000000 # 1,000,000 us per second
pulseLength /= 60 # 60 Hz
#print "%d us per period" % pulseLength
pulseLength /= 4096 # 12 bits of resolution
#print "%d us per bit" % pulseLength
pulse *= 1000
pulse /= pulseLength
pwm.setPWM(channel, 0, pulse)
def setup():
pwm.setPWMFreq(60) # Set frequency to 60 Hz
GPIO.setmode(GPIO.BOARD)
GPIO.setup(40 ,GPIO.IN)
GPIO.setup(31 ,GPIO.IN)
GPIO.setup(32 ,GPIO.IN)
GPIO.setup(33 ,GPIO.IN)
GPIO.setup(35 ,GPIO.IN)
GPIO.setup(36 ,GPIO.IN)
GPIO.setup(37 ,GPIO.IN)
GPIO.setup(38 ,GPIO.IN)
def select(position):
if(position == 0):
pwm.setPWM(5, 0, PWM_SEL_1)
elif(position == 1):
pwm.setPWM(5, 0, PWM_SEL_2)
elif(position == 2):
pwm.setPWM(5, 0, PWM_SEL_3)
elif(position == 3):
pwm.setPWM(5, 0, PWM_SEL_4)
def turn(direction):
if(direction == 0): #stop
pwm.setPWM(0, 0, 0)
elif(direction == 1): #right
pwm.setPWM(0, 0, PWM_RIGHT)
elif(direction == -1): #left
pwm.setPWM(0, 0, PWM_LEFT)
def rotateTo(position):
sys.stderr.write("rotating to %d \n" % position)
if(position < 15):
decoder=[1,219,2,223,8,127,16,254,64,253,12,247,48,175,192,187]
pos = decoder[position]
enc = readEncoder()
while enc != pos:
turn(1)
enc = readEncoder()
turn(0)
def open(channel):
sys.stderr.write('open channel: %d\n' % channel)
if(channel == 0):
pwm.setPWM(1, 0, PWM_OPEN-30)
elif(channel == 1):
pwm.setPWM(2, 0, PWM_OPEN-65)
elif(channel == 2):
pwm.setPWM(3, 0, PWM_OPEN+10)
elif(channel == 3):
pwm.setPWM(4, 0, PWM_OPEN-90)
def close(channel):
sys.stderr.write('close channel: %d\n' % channel)
if(channel == 0):
pwm.setPWM(1, 0, PWM_CLOSE-30)
elif(channel == 1):
pwm.setPWM(2, 0, PWM_CLOSE-65)
elif(channel == 2):
pwm.setPWM(3, 0, PWM_CLOSE+10)
elif(channel == 3):
pwm.setPWM(4, 0, PWM_CLOSE-90)
def encoderLight(on):
pwm.setPWM(8,0,4095*on);
def load(x,y):
sys.stderr.write('loading ')
sys.stderr.write('x: %d ' % x)
sys.stderr.write('y: %d\n' % y)
setup()
rotateTo(y)
select(x)
turn(0)
def dispense(x,y):
sys.stderr.write('dispensing ')
sys.stderr.write('x: %d ' % x)
sys.stderr.write('y: %d\n' % y)
setup()
rotateTo((y+8)%16)
open(x)
time.sleep(1)
close(x)
turn(0)
def goHome():
setup()
close(0)
time.sleep(1)
close(1)
time.sleep(1)
close(2)
time.sleep(1)
close(3)
time.sleep(1)
rotateTo((8)%16) # output 0
time.sleep(1)
pwm.setPWM(1, 0, 0)
time.sleep(1)
pwm.setPWM(2, 0, 0)
time.sleep(1)
pwm.setPWM(3, 0, 0)
time.sleep(1)
pwm.setPWM(4, 0, 0)
time.sleep(1)
turn(0)
#############
# main code
def run_self_test():
#init i2c
setup()
# test top selector positions
servo = 0
while(servo < 0):
select(servo)
time.sleep(2)
servo = servo + 1
select(0)
# test bottom doors
servo = 0
while(servo < 4):
open(servo)
print "open"
time.sleep(3)
close(servo)
print "closed"
time.sleep(3)
pwm.setPWM(servo+1, 0, 0)
servo = servo + 1
# test barrel position
servo=0
while(servo < 16):
rotateTo(servo)
time.sleep(3)
servo = servo + 1
#databas tests
#load(6,2) #rotation,door
#time.sleep(5)
#load(9,2) #rotation,door
#time.sleep(5)
#dispense(9,2)
#dispense(6,2)
#finish test
GPIO.cleanup()
exit()
#run_self_test()
parser = argparse.ArgumentParser()
parser.add_argument("-x")
parser.add_argument("-y")
parser.add_argument("-mode")
args = parser.parse_args()
#print args.x
#print args.y
if(args.mode == "vend"):
sys.stderr.write('vending... \n')
dispense(int(args.x), int(args.y))
elif(args.mode == "load"):
sys.stderr.write('loading... \n')
load(int(args.x), int(args.y))
elif(args.mode == "home"):
goHome()
GPIO.cleanup()
```
#### File: SDMO/cgi-bin/userManager.py
```python
import sqlite3 as lite
import sys
import datetime
SEX_M = 0
SEX_F = 1
db = 'data/meds.db'
def addUser(name, sex, weight, dob):
con = None
try:
con = lite.connect(db)
con.execute("INSERT INTO users(name, sex, weight, dob) values (?, ?, ?, ?)", (name ,sex, weight, dob))
con.commit()
except lite.Error:
print("Error %s:" % e.args[0])
sys.exit(1)
finally:
if con:
con.close()
def updateUser(name, sex, weight, dob):
con = None
try:
con = lite.connect(db)
con.execute("UPDATE users SET name = ? AND sex = ? AND weight = ? AND dob = ? WHERE name = ?", (name ,sex, weight, dob, name))
con.commit()
except lite.Error:
print("Error %s:" % e.args[0])
sys.exit(1)
finally:
if con:
con.close()
def getUsers():
con = None
rows = []
try:
con = lite.connect(db)
cur = con.cursor()
cur.execute("SELECT name, sex, weight, dob FROM users")
rows = cur.fetchall()
con.commit()
except lite.Error:
print("Error %s:" % e.args[0])
finally:
if con:
con.close()
return rows
def createUserTable():
con = None
try:
con = lite.connect(db)
# id: unique id
# sex: 0=male, 1=female
# weight: integer in pounds
# dob: unix date
con.execute("CREATE TABLE users(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, sex INT, weight INT, dob DATE)")
con.commit()
except lite.Error:
print("Error %s:" % e.args[0])
sys.exit(1)
finally:
if con:
con.close()
#userM = userManager()
#userM.createUserTable()
#d = datetime.date(1982, 11, 23)
#userM.addUser("Amy", userM.SEX_F, 98, d)
#d = datetime.date(1985, 8, 13)
#userM.addUser("Joe", userM.SEX_M, 120, d)
``` |
{
"source": "JoeCullen/freemail",
"score": 3
} |
#### File: freemail/freemail/__init__.py
```python
import os
import tldextract
import subprocess
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
free_file = os.path.join(__location__, './data/free.txt')
disp_file = os.path.join(__location__, './data/disposable.txt')
def is_free(email_address):
try:
email_address = str(email_address)
except:
raise TypeError('email must be a string')
with open(free_file, 'r') as free, open(disp_file, 'r') as disposable:
domain_list = free.read().splitlines() + disposable.read().splitlines()
domain = tldextract.extract(email_address).registered_domain
return domain in domain_list
def is_disposable(email_address):
try:
email_address = str(email_address)
except:
raise TypeError('email must be a string')
with open(disp_file, 'r') as disposable:
domain_list = disposable.read().splitlines()
domain = tldextract.extract(email_address).registered_domain
return domain in domain_list
def update():
try:
subprocess.call("./update", shell=True)
return True
except subprocess.CalledProcessError:
return False
``` |
{
"source": "joecummings/gitmine",
"score": 3
} |
#### File: gitmine/commands/go.py
```python
import logging
from typing import Optional
import click
logger = logging.getLogger()
def go_command(repo: str, number: Optional[int]) -> None:
"""Implementation of the *go* command."""
logger.info(f"Launching browser session at repo: {repo}, issue: {number}")
url = f"https://github.com/{repo}/issues/{number if number else ''}"
click.launch(url)
```
#### File: gitmine/tests/test_get.py
```python
import json
from typing import Dict
import click
import pytest
from click.testing import CliRunner
from test_constants import TEST_ISSUES_PATH, TEST_PRS_PATH
from gitmine.commands.get import echo_info
from gitmine.gitmine import gitmine # gitmine?
runner = CliRunner()
@pytest.fixture(scope="module")
def get_configuration():
data = {}
with open(TEST_ISSUES_PATH, "r") as issues_handle:
issue_data = json.load(issues_handle)
data["issue"] = issue_data["issues"]
data["issue_output"] = issue_data["print_output"]
with open(TEST_PRS_PATH, "r") as prs_handle:
issue_data = json.load(prs_handle)
yield data
def base_runner(options):
command = ["get", *options]
return runner.invoke(gitmine, command)
def test_get_none():
result = base_runner([""])
assert result.exit_code == 2
def test_get_bad_argument():
result = base_runner(["banana-boat"])
assert result.exit_code == 2
def test_get_bad_argument2():
result = base_runner(["banana-boat"])
assert result.exit_code == 2
def test_get_issues(capsys):
pass
# with open(TEST_ISSUES_PATH, "r") as issues_handle:
# json_dict = json.load(issues_handle)
# issues = json_dict["issues"]
# print_output = json_dict["print_output"]["11"]
# print_issues(issues, color=False, asc=True)
# captured = capsys.readouterr()
# captured_out = captured.out.replace("\n", "").split("#") # Don't care about newlines
# for issue in captured_out:
# assert issue in print_output
def test_get_issues_spec_repo():
# specify repository to pull from and make sure only those get returned
pass
def test_get_issues_option_asc_nocolor():
pass
def test_get_issues_opetion_desc_color():
pass
def test_get_issues_option_desc_nocolorr():
pass
def test_get_all():
pass
def test_get_bad_credentials():
pass
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.