text stringlengths 38 1.54M |
|---|
from . import ErrorState
class ScanError(Exception):
def __init__(self, line: int, message: str):
self.line = line
self.message = message
def report(self):
print(f'[line {self.line}] Error: {self.message}')
ErrorState.hadError = True
|
#################################################################################
# FOQUS Copyright (c) 2012 - 2023, by the software owners: Oak Ridge Institute
# for Science and Education (ORISE), TRIAD National Security, LLC., Lawrence
# Livermore National Security, LLC., The Regents of the University of
# California, through Lawrence Berkeley National Laboratory, Battelle Memorial
# Institute, Pacific Northwest Division through Pacific Northwest National
# Laboratory, Carnegie Mellon University, West Virginia University, Boston
# University, the Trustees of Princeton University, The University of Texas at
# Austin, URS Energy & Construction, Inc., et al. All rights reserved.
#
# Please see the file LICENSE.md for full copyright and license information,
# respectively. This file is also available online at the URL
# "https://github.com/CCSI-Toolset/FOQUS".
#################################################################################
import subprocess
# ---------------------------------------
# SOLVENTFIT EMULATOR predict function
# ---------------------------------------
def pred(modelfile, xdatfile, yhatfile, nsamples="50", transform="1"):
p = subprocess.Popen(
[
"Rscript",
"solvfit_emulpred.R",
modelfile,
xdatfile,
yhatfile,
nsamples,
transform,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = p.communicate()
print(stdout)
print(stderr)
return yhatfile
# ---------------------------------------
# Example usage
# ---------------------------------------
rdsfile = "solvfit_emulator.rds"
infile = "example/infile.emulpred"
outfile = "outfile.emulpred"
resfile = pred(rdsfile, infile, outfile)
print(resfile)
|
import leafly.search_for_words as sfw
import leafly.nlp_funcs as nl
import leafly.explore_individ_reviews as eir
import pandas as pd
import numpy as np
from scipy import spatial
from fancyimpute import BiScaler, KNN, NuclearNormMinimization, SoftImpute
from sklearn.preprocessing import StandardScaler
import os
import pickle as pk
# tf-idf similarity
review_vects_file = 'leafly/review_vects_full.pk'
review_vects2_file = 'leafly/review_vects2_full.pk'
dist_file1 = 'leafly/review_tfidf_dists1.pk'
dist_file2 = 'leafly/review_tfidf_dists2.pk'
vect_words1_file = 'leafly/vect_words1.pk'
vect_words2_file = 'leafly/vect_words2.pk'
strain_name_file = 'leafly/tfidf_strain_names.pk'
if os.path.exists(dist_file1):
tfidf_dists1 = pk.load(dist_file1)
tfidf_dists2 = pk.load(dist_file2)
# review_vects = pd.read_pickle(review_vects_file)
# review_vects2 = pd.read_pickle(review_vects2_file)
else:
df, prod_review_df = sfw.load_data(full=True)
tfvect, vect_words, review_vects = nl.lemmatize_tfidf(prod_review_df, max_features=1000, ngram_range=(1, 2))
tfvect2, vect_words2, review_vects2 = nl.lemmatize_tfidf(prod_review_df, max_features=1000, ngram_range=(2, 2))
review_vects = pd.DataFrame(review_vects)
review_vects2 = pd.DataFrame(review_vects2)
names = prod_review_df['product'].values
pk.dump(names, open(strain_name_file, 'w'), 2)
# pre-compute distances for efficiency
dist_list = []
for i in range(review_vects.shape[0]):
print(i)
dists = []
for j in range(review_vects.shape[0]):
dists.append(spatial.distance.cosine(review_vects[j], review_vects[i]))
dist_list.append(dists)
dist_list2 = []
for i in range(review_vects2.shape[0]):
print(i)
dists = []
for j in range(review_vects2.shape[0]):
dists.append(spatial.distance.cosine(review_vects2[j], review_vects2[i]))
dist_list2.append(dists)
pk.dump(dist_list, open(dist_file1, 'w'), 2)
pk.dump(dist_list2, open(dist_file2, 'w'), 2)
pk.dump(vect_words, open(vect_words1_file, 'w'), 2)
pk.dump(vect_words2, open(vect_words2_file, 'w'), 2)
pk.dump(review_vects, open(review_vects_file, 'w'), 2)
pk.dump(review_vects2, open(review_vects2_file, 'w'), 2)
def get_tfidf_sims(strain, names, dist_list, dist_list2, mix_factor = 0.8):
'''
uses pre-computed lists of cosine distances of products to calculate
most similar strains
args:
strain -- (string) name of strain to search for close relatives
names -- (list) list of strain names with same indexing as dist_lists
dist_list, dist_list2: (lists) lists of cosine distances
of tf-idf vectors from full reviews
mix_factor -- (float) value for % of final result due to dist_list vs
dist_list2
'''
names = list(names)
idx = names.index(strain)
dists1 = np.array(dist_list[idx])
dists2 = np.array(dist_list2[idx])
dist_avg = dists1 * mix_factor + dists2 * (mix_factor - 1)
return dist_avg
# testing tfidf sims func
testStr = names[100]
dist_avg = get_tfidf_sims(testStr, names, dist_list, dist_list2)
sorted_idxs = np.argsort(dist_avg)
names[sorted_idxs[:10]]
# effects similarity
ohe_file = 'leafly/prod_ohe.pk'
if os.exists(ohe_file):
prod_ohe = pd.read_pickle(ohe_file)
else:
ohe_df, prod_ohe = eir.load_all_full_reviews()
prod_ohe.to_pickle(ohe_file)
prod_ohe.drop('isok', axis=1, inplace=True)
prod_ohe.drop('rating', axis=1, inplace=True)
unique_effects = pk.load(open('leafly/unique_effects.pk'))
effects_df = prod_ohe[list(unique_effects)]
# flavors similarity
unique_flavors = pk.load(open('leafly/unique_flavors.pk'))
flavors_df = prod_ohe[list(unique_flavors)]
# chemistry similarity
def get_chem_df():
'''
retrieves, cleans dataframe of chemistry data for strains in leafly
'''
chem_df_file = 'analytical360/scealed_leaf_chem.pk'
if os.path.exists(chem_df_file):
scaled_leaf_chem = pd.read_pickle(chem_df_file)
else:
leaf_df = pd.read_pickle('analytical360/leafly_matched_df_11-13-2016.pk')
leaf_df.drop('mask', axis=1, inplace=True)
leaf_df.drop('isedible', axis=1, inplace=True)
leaf_df.drop('filename', axis=1, inplace=True)
leaf_df.drop('clean_name', axis=1, inplace=True)
# unfortunately need to drop a few terps because too much nan
# dropping anything with less than 75% non-nan in leaf_prod_chem
leaf_df.drop('Terpinolene', axis=1, inplace=True)
leaf_df.drop('cbg', axis=1, inplace=True)
leaf_df.drop('cbn', axis=1, inplace=True)
leaf_df.drop('Limonene', axis=1, inplace=True)
leaf_df.drop('Linalool', axis=1, inplace=True)
leaf_df.drop('caryophyllene_oxide', axis=1, inplace=True)
# impute missing values with means`
# skip_cols = set(['name'])
# for c in leaf_df.columns:
# if c not in skip_cols:
# leaf_df[c].fillna(value=leaf_df[c].mean(), inplace=True)
# impute missing values with knn
leaf_df_vals = leaf_df.drop('name', axis=1).values
leaf_df_filled = KNN(k=6).complete(leaf_df_vals)
cols = list(leaf_df.columns.values)
cols.remove('name')
new_leaf_df = pd.DataFrame(columns=cols, data=leaf_df_filled)
new_leaf_df['name'] = leaf_df['name'].values
leaf_prod_chem = new_leaf_df.groupby('name').mean()
# need to normalize data a bit...thc/cbd should still have the highest influence,
# but only by a factor of 3 (arbitrary choice)
scaled_leaf_chem = leaf_prod_chem.copy()
scalers = []
for c in scaled_leaf_chem.columns:
sc = StandardScaler()
scalers.append(sc)
scaled_leaf_chem[c] = sc.fit_transform(scaled_leaf_chem[c])
scaled_leaf_chem['thc_total'] = scaled_leaf_chem['thc_total'] * 3
scaled_leaf_chem['cbd_total'] = scaled_leaf_chem['cbd_total'] * 3
scaled_leaf_chem.to_pickle(chem_df_file)
return scaled_leaf_chem
def test_chem_sim(scaled_leaf_chem):
testStr = scaled_leaf_chem.iloc[666].name
testVect = scaled_leaf_chem.ix[testStr].values
dists = []
for i, r in scaled_leaf_chem.iterrows():
dists.append(spatial.distance.cosine(testVect, r.values))
# the lowest numbers are the closest distance (most similar) so we keep numpy's
# default sorting (low->high)
# of course it's most similar to itself, so need to exclude first result
chem_dists = np.argsort(dists)
# this is for ALL strains from the chem DB
all_df = pd.read_pickle('analytical360/data_df_11-13-2016.pk')
all_df.drop('mask', axis=1, inplace=True)
all_df.drop('isedible', axis=1, inplace=True)
all_df.drop('filename', axis=1, inplace=True)
all_prod_chem = all_df.groupby('clean_name').mean()
testStr = all_df['clean_name'].iloc[666]
testVect = all_df[all_df['clean_name'] == testStr]
def calc_sim(scaled_leaf_chem):
testStr = scaled_leaf_chem.iloc[666].name
testVect = scaled_leaf_chem.ix[testStr].values
dists = []
for i, r in scaled_leaf_chem.iterrows():
dists.append(spatial.distance.cosine(testVect, r.values))
# the lowest numbers are the closest distance (most similar) so we keep numpy's
# default sorting (low->high)
# of course it's most similar to itself, so need to exclude first result
chem_dists = np.argsort(dists)
return chem_dists
|
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
import h5py
import colorsys
import argparse
import glob
import sys
from hic import flow
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import Circle
aspect = 1/1.618
resolution = 72.27
columnwidth = 206.79/resolution
textwidth = 428.72/resolution
textiny, texsmall, texnormal = 8.0, 9.25, 10.0
offblack = '#262626'
plt.rcdefaults()
plt.rcParams.update({
'font.family': 'serif',
'font.serif': ['DejaVu Serif'],
'mathtext.fontset': 'custom',
'mathtext.default': 'it',
'mathtext.rm': 'serif',
'mathtext.it': 'serif:italic:medium',
'mathtext.cal': 'serif',
'font.size': texsmall,
'legend.fontsize': texsmall,
'axes.labelsize': texsmall,
'axes.titlesize': texsmall,
'xtick.labelsize': textiny,
'ytick.labelsize': textiny,
'font.weight': 400,
'axes.labelweight': 400,
'axes.titleweight': 400,
'lines.linewidth': .6,
'lines.markersize': 2,
'lines.markeredgewidth': .1,
'patch.linewidth': .6,
'axes.linewidth': .4,
'xtick.major.width': .4,
'ytick.major.width': .4,
'xtick.minor.width': .4,
'ytick.minor.width': .4,
'xtick.major.size': 1,
'ytick.major.size': 1,
'xtick.minor.size': 0.6,
'ytick.minor.size': 0.6,
'xtick.major.pad': 1.8,
'ytick.major.pad': 1.8,
'text.color': offblack,
'axes.edgecolor': offblack,
'axes.labelcolor': offblack,
'xtick.color': offblack,
'ytick.color': offblack,
'legend.numpoints': 1,
'legend.scatterpoints': 1,
'legend.frameon': False,
'image.interpolation': 'none',
'pdf.fonttype': 3,
})
plot_functions = {}
def plot(f):
def wrapper(*args, **kwargs):
print(f.__name__)
f(*args, **kwargs)
plt.savefig('{}.pdf'.format(f.__name__))
plt.close()
plot_functions[f.__name__] = wrapper
return wrapper
def finish(despine=True, remove_ticks=False, pad=0.1, h_pad=None, w_pad=None,
rect=[0, 0, 1, 1]):
fig = plt.gcf()
for ax in fig.axes:
if despine:
for spine in 'top', 'right':
ax.spines[spine].set_visible(False)
if remove_ticks:
for ax_name in 'xaxis', 'yaxis':
getattr(ax, ax_name).set_ticks_position('none')
else:
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
def set_loc(ax, xy=None, nbins=5, steps=[1, 2, 3, 4, 10],
prune=None, minor=0):
if xy == 'x':
axes = ax.xaxis,
elif xy == 'y':
axes = ax.yaxis,
else:
axes = ax.xaxis, ax.yaxis
for axis in axes:
axis.set_major_locator(
tick.MaxNLocator(nbins=nbins, steps=steps, prune=prune)
)
if minor:
axis.set_minor_locator(tick.AutoMinorLocator(minor))
def fmt_tick(n):
s = str(float(n))
if abs(n) > 10 and s.endswith('.0'):
return s[:-2]
return s
def desaturate(color, fraction=0.5):
h, l, s = colorsys.rgb_to_hls(*color[:3])
return colorsys.hls_to_rgb(h, l, fraction*s)
TRENTO_LABEL = r'T\raisebox{-.5ex}{R}ENTo'
def set_trento_label(legend, i):
"""
Mark the `i`th label of a legend as containing the T_RENTo logo.
"""
t = legend.get_texts()[i]
t.set_usetex(True)
t.set_y(-.18*t.get_size())
return legend
finish()
def thickness_substructure(sys='Pb'):
fig, axes = plt.subplots(
nrows=2, ncols=2,
sharex=True, sharey=True,
figsize=(0.4*textwidth, 0.4*textwidth)
)
cdict = plt.cm.Blues._segmentdata.copy()
cdict['red'][0] = (0, 1, 1)
cdict['blue'][0] = (0, 1, 1)
cdict['green'][0] = (0, 1, 1)
my_cmap = LinearSegmentedColormap('Blues2', cdict)
npartons = [3, 20]
parton_width = [0.2, 0.3]
xymax = 8 if sys == 'Pb' else 1.5
dim = [-xymax, xymax, -xymax, xymax]
for row, v in zip(axes, parton_width):
for ax, m in zip(row, npartons):
path = 'data/thickness-grid/{}/'.format(sys)
fn = 'events_{}_{}.hdf'.format(v, m)
with h5py.File(path + fn, 'r') as f:
dens = f['event_0']
ax.imshow(dens, extent=dim, cmap=my_cmap)
if ax.is_first_row():
ax.annotate(
'{} partons'.format(m), xy=(0.5, 1.0),
ha='center', va='bottom', xycoords='axes fraction',
fontsize=textiny)
if ax.is_last_col():
ax.annotate(
'width {} fm'.format(v), xy=(1.05, 0.5),
ha='left', va='center', xycoords='axes fraction',
rotation=-90, fontsize=textiny)
fig.text(0.53, 0.01, '$x$ [fm]', ha='center', fontsize=textiny)
fig.text(0.01, 0.53, '$y$ [fm]', va='center', fontsize=textiny, rotation=90)
rect = [0.06, 0.06, 0.92, 0.94]
finish(h_pad=0, w_pad=0, rect=rect)
@plot
def Pb_thickness():
return thickness_substructure('Pb')
@plot
def p_thickness():
return thickness_substructure('p')
def proton_shapes(partons=False):
fig, axes = plt.subplots(nrows=1, ncols=3,
figsize=(textwidth, 0.38*textwidth))
cdict = plt.cm.Blues._segmentdata.copy()
cdict['red'][0] = (0, 1, 1)
cdict['blue'][0] = (0, 1, 1)
cdict['green'][0] = (0, 1, 1)
my_cmap = LinearSegmentedColormap('Blues2', cdict)
fnames = 'p1.hdf', 'p0.hdf', 'p-1.hdf'
pvals = '$1$', '$0$', '$-1$'
for fn, ax, p in zip(fnames, axes, pvals):
if partons:
fn = 'data/proton_shapes/substructure/{}'.format(fn)
else:
fn = 'data/proton_shapes/gaussian/{}'.format(fn)
with h5py.File(fn, 'r') as f:
dens = np.array(f['event_0']).T
ax.imshow(dens, cmap=my_cmap)
ax.set_xlabel('p={}'.format(p), fontsize=16)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
origin = 0.5*np.array(dens.shape)
b = 1/0.02
radius = 1/0.02
n1 = Circle(origin + [0, b/2], radius, fc='none', color=offblack)
n2 = Circle(origin - [0, b/2], radius, fc='none', color=offblack)
ax.add_patch(n1)
ax.add_patch(n2)
finish(w_pad=-2, pad=1)
@plot
def proton_shapes_gaussian():
return proton_shapes(partons=False)
@plot
def proton_shapes_substructure():
return proton_shapes(partons=True)
@plot
def posterior_protons():
fig, axes = plt.subplots(nrows=2, ncols=4,
sharex=True, sharey=True,
figsize=(textwidth, 0.5*textwidth))
cdict = plt.cm.Blues._segmentdata.copy()
cdict['red'][0] = (0, 1, 1)
cdict['blue'][0] = (0, 1, 1)
cdict['green'][0] = (0, 1, 1)
my_cmap = LinearSegmentedColormap('Blues2', cdict)
for n, ax in enumerate(axes.flat):
with h5py.File('data/trento_protons/protons.hdf', 'r') as f:
dens = f['event_{}'.format(n)]
dmax = np.max(dens)
ax.imshow(dens, my_cmap)
ax.contour(dens, levels=np.linspace(dmax/3, dmax, 4),
colors=offblack, alpha=0.2, linewidths=0.5)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
finish()
@plot
def Pb_thick():
fig, axes = plt.subplots(nrows=1, ncols=2,
sharex=True, sharey=True,
figsize=(textwidth, 0.5*textwidth))
cdict = plt.cm.Blues._segmentdata.copy()
cdict['red'][0] = (0, 1, 1)
cdict['blue'][0] = (0, 1, 1)
cdict['green'][0] = (0, 1, 1)
my_cmap = LinearSegmentedColormap('Blues2', cdict)
dens = np.zeros((160, 160))
with h5py.File('data/justify_substructure/pb.hdf') as f:
for ev in f.values():
dens += np.array(ev)
axes[0].imshow(dens, cmap=my_cmap)
axes[0].set_title('Optical nucleus', fontsize=10)
axes[0].set_xticks([])
axes[0].set_yticks([])
axes[1].imshow(f['event_0'], cmap=my_cmap)
axes[1].set_title('Nucleus w/ nucleons', fontsize=10)
axes[1].set_xticks([])
axes[1].set_yticks([])
finish(h_pad=0, w_pad=0, pad=0)
@plot
def p_thick():
fig, axes = plt.subplots(nrows=1, ncols=2,
sharex=True, sharey=True,
figsize=(textwidth, 0.5*textwidth))
cdict = plt.cm.Blues._segmentdata.copy()
cdict['red'][0] = (0, 1, 1)
cdict['blue'][0] = (0, 1, 1)
cdict['green'][0] = (0, 1, 1)
my_cmap = LinearSegmentedColormap('Blues2', cdict)
dens = np.zeros((140, 140))
with h5py.File('data/justify_substructure/p.hdf') as f:
for ev in f.values():
dens += np.array(ev)
axes[0].imshow(dens, cmap=my_cmap)
axes[0].set_title('Optical proton', fontsize=10)
axes[0].set_xticks([])
axes[0].set_yticks([])
axes[1].imshow(f['event_4'], cmap=my_cmap)
axes[1].set_title('Proton w/ partons', fontsize=10)
axes[1].set_xticks([])
axes[1].set_yticks([])
finish(h_pad=0, w_pad=0, pad=0)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('plots', nargs='*')
args = parser.parse_args()
if args.plots:
for i in args.plots:
if i.endswith('.pdf'):
i = i[:-4]
if i in plot_functions:
plot_functions[i]()
else:
print('unknown plot:', i)
else:
for f in plot_functions.values():
f()
if __name__ == "__main__":
main()
|
import cv2
clicked = False
def onMouse(event, x, y, flags, param):
global clicked
if event == cv2.EVENT_LBUTTONUP:
clicked = True
cameraCapture = cv2.VideoCapture(0)
cv2.namedWindow('Live')
cv2.setMouseCallback('Live', onMouse)
print('Showing camera feed. Click window or press any key to stop.')
success, frame = cameraCapture.read()
while success and cv2.waitKey(1) == -1 and not clicked:
cv2.imshow('Live', frame)
success, frame = cameraCapture.read()
cv2.destroyWindow('Live')
cameraCapture.release() |
from helpers.post_helper import post_helper
from helpers.user_helper import user_helper
from helpers.user_connection_helper import user_connection_helper
from dal.user_provider import user_provider
from mysql_dal.mysql_user_provider import mysql_user_provider
class profile_helper(object):
def __init__(self, user_provider):
self.user_provider = user_provider
def get_user(self, user_provider, user_id):
my_local_user_helper = user_helper(user_provider)
result = my_local_user_helper.is_user_exist(user_id)
return result
user_provider_new = user_provider()
mysql_user_provider_new = mysql_user_provider()
new_profile_helper = profile_helper(mysql_user_provider_new)
print(new_profile_helper.get_user(mysql_user_provider_new,1))
|
from django.urls import path,include
import dl
urlpatterns = [
path('', include('dl.urls')),
]
|
import errors
from api.validator import TokenId, Choose
from model.account.role import Role
class TokenRole(TokenId):
def __init__(self, role):
self.role = role
super().__init__()
def __call__(self, value):
token = super().__call__(value)
if not Role.validate(token.role, self.role):
raise errors.UserInvalidRole()
return token
class TokenAdmin(TokenRole):
def __init__(self):
super().__init__(Role.ADMIN)
class TokenAccount(TokenRole):
def __init__(self):
super().__init__(Role.ACCOUNT)
class TokenManager(TokenRole):
def __init__(self):
super().__init__(Role.MANAGER)
class TokenSupport(TokenRole):
def __init__(self):
super().__init__(Role.SUPPORT)
Roles = Choose(Role.ROLE_LIST)
|
from adapter.repository.models.usermodel import UserModel
from domain.user import User
class UserRepo:
def __init__(self):
self.users = self.create_users()
def create_users(self):
user_list = []
for n in range(3):
u = UserModel(n, "name" + str(n), n)
user_list.append(u)
return user_list
def find_by_id(self, id):
for user in self.users:
if user.id == id:
return User.from_dict(user.to_dict())
def find_by_name(self, name):
for user in self.users:
if user.name == name:
return User.from_dict(user.to_dict())
|
import csv
import sys, os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from plot_invisibles import colors
import time
import glob
import re
import json
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument("--channel",type=str,default=None)
parser.add_argument("--models",nargs="+",default=None)
parser.add_argument("--modelnames",nargs="+",default=None)
parser.add_argument("--outpath",type=str,default=None)
args = parser.parse_args()
if args.channel is None or args.models is None or args.outpath is None or args.modelnames is None:
print "Please provide arguments. See --help"
exit(1)
if len(args.models) != len(args.modelnames):
print "number of paths to models and number of their names must be equal"
exit(1)
channel_name = {"tt": r'$\tau_{h} \tau_{h}$', "mt": r'$\mu \tau_{h}$', "em" : r'$e \mu$', "et" : r'$e \tau_{h}$'}
channel = args.channel
modelpaths = args.models
modelnames = args.modelnames
outpath = args.outpath
channel_outpath = os.path.join(args.outpath,args.channel)
if not os.path.exists(channel_outpath):
os.makedirs(channel_outpath)
signal_patterns = {
"SMH" : "^(VBFH|GluGluH|WplusH|WminusH|ZH)",
"SUSYbbH" : "BBHToTauTau",
"SUSYggH" : "SUSYGluGluToH",
}
colors_nn = {
"2016" : "red",
"2016oldPrescription" : "red",
"2017BCD" : "orange",
"Raphaels" : "orange",
"2017EF" : "green",
"2017realistic" : "green",
}
for s in signal_patterns:
if "SUSY" in s:
fig = plt.figure(figsize=(6,4))
ax = fig.add_subplot(111)
ranges = [70,3500]
y_min = 0.0001
yranges = [y_min,1.0]
titles = r'fraction of events $\|m_N - m_H\|/m_H \geq 2$'
ax.set_xlabel(r'Generator mass $m_H$ (GeV)')
ax.set_ylabel(titles)
ax.set_title("Method Stability (" + channel_name[channel] + ")")
ax.set_xlim(ranges)
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xticks([100,200,400,1000,2000,3000])
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.grid(color='gray', linestyle='-', linewidth=1, which='major')
ax.grid(color='gray', linestyle='-',alpha=0.3, linewidth=1, which='minor')
ax.set_ylim(yranges)
svplotted = False
for model,name in zip(modelpaths,modelnames):
results = {}
results_path = os.path.join(model,channel,"data","%s.json"%s.replace("SUSY",""))
j = glob.glob(results_path)
if len(j) == 1:
f = open(j[0],"r")
j = os.path.basename(j[0])
s = j.replace(".json","")
results[s] = json.load(f)
masses = [info[2] for info in results[s.replace("SUSY","")]["info"]]
if not svplotted:
ax.plot(masses, np.maximum(y_min,results[s.replace("SUSY","")]["stability_sv"]), 'k', color=colors["color_svfit"], marker='.', markersize=10, label = 'SVFit')
svplotted = True
ax.plot(masses, np.maximum(y_min,results[s.replace("SUSY","")]["stability_nn"]), 'k', color=colors_nn[name], marker='.', markersize=10, label = 'Nostradamass %s'%name)
plt.legend(loc=2, ncol=1)
plt.tight_layout()
plt.savefig(os.path.join(channel_outpath, "stability_%s.pdf"%s.replace("SUSY","")))
plt.savefig(os.path.join(channel_outpath, "stability_%s.png"%s.replace("SUSY","")))
plt.close()
else:
fig = plt.figure(figsize=(6,4))
ax = fig.add_subplot(111)
ranges = [0.,5.]
y_min = 0.0001
yranges = [y_min,1.0]
titles = r'fraction of events $\|m_N - m_H\|/m_H \geq 2$'
ax.set_xlabel(r'Process')
ax.set_ylabel(titles)
ax.set_title("Method Stability (" + channel_name[channel] + ")")
ax.set_xlim(ranges)
ax.set_yscale('log')
tick_numbers = np.array(range(5))+0.5
ax.set_xticks(tick_numbers)
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.grid(color='gray', linestyle='-', linewidth=1, which='major')
ax.grid(color='gray', linestyle='-',alpha=0.3, linewidth=1, which='minor')
ax.set_ylim(yranges)
svplotted = False
tick_labels = []
for model,name in zip(modelpaths,modelnames):
results = {}
results_path = os.path.join(model,channel,"data","%s.json"%s.replace("SUSY",""))
j = glob.glob(results_path)
if len(j) == 1:
f = open(j[0],"r")
j = os.path.basename(j[0])
s = j.replace(".json","")
results[s] = json.load(f)
processes = [info[1] for info in results[s.replace("SUSY","")]["info"]]
if tick_labels == []:
tick_labels = processes
if not svplotted:
ax.plot(tick_numbers, np.maximum(y_min,results[s.replace("SUSY","")]["stability_sv"]),'k', color=colors["color_svfit"], marker='.',linewidth=0.0, markersize=10, label = 'SVFit')
svplotted = True
ax.plot(tick_numbers, np.maximum(y_min,results[s.replace("SUSY","")]["stability_nn"]),'k', color=colors_nn[name], marker='.', linewidth=0.0, markersize=10, label = 'Nostradamass %s'%name)
ax.set_xticklabels(tick_labels)
#ax.tick_params(axis="x")
plt.legend(loc=2, ncol=1)
plt.tight_layout()
plt.savefig(os.path.join(channel_outpath, "stability_%s.pdf"%s.replace("SUSY","")))
plt.savefig(os.path.join(channel_outpath, "stability_%s.png"%s.replace("SUSY","")))
plt.close()
|
print('''Crie um Software de gerenciamento bancário. Esse software deverá ser capaz de criar clientes e contas.
Cada cliente possiu nome, cpf, idade.
Cada conta possui um cliente, saldo, limite, sacar, depositar e consultar saldo.''')
from Exercicios.Ex_Aula09_cliente import Cliente
from Exercicios.Ex_Aula09_conta import Conta
cliente1 = Cliente('Sandro', '123.456.789-10', 23)
print('\n{}'.format(cliente1))
conta1 = Conta(cliente1, 10.50, 1000)
print(conta1.consultar_saldo())
conta1.depositar(1000.00)
conta1.sacar(2500.00) |
def rotate_matrix(matrix):
n = len(matrix)
if n == 0:
return []
print matrix
for i in range(0, (n/2)):
first = i
last = n - 1 - i
for j in range(first, last):
offset = j - first
# save top
top = matrix[first][j]
# right -> top
matrix[first][j] = matrix[j][last]
# bottom -> right
matrix[j][last] = matrix[last][last - offset]
# left -> bottom
matrix[last][last - offset] = matrix[last - offset][first]
# top -> left
matrix[last - offset][first] = top
return matrix
print rotate_matrix([[1,2],[3,4]])
print rotate_matrix([[1,2,3],[4,5,6],[7,8,9]])
print rotate_matrix([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
|
import sys as S
def f(case_number, n):
seen = set()
s = str(n)
for i in range(10**(len(s)+1)):
for d in str(n*(i + 1)):
seen.add(d)
if len(seen) == 10:
break
if len(seen) == 10:
print 'Case #' + str(case_number) + ': ' + str(n * (i + 1))
else:
print 'Case #' + str(case_number) + ': INSOMNIA'
i = 0
for line in S.stdin:
i += 1
if i == 1:
continue
f(i-1, int(line))
|
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 05 19:29:12 2016
@author: Kevin
"""
from directionsAPI import DirAPI
from ElevationAPI import ElevationAPI
from decode import decode
from geopy.distance import vincenty
from math import floor, atan2
from subprocess import call
def getDSVFile(lat1, lng1, lat2, lng2, avdHigh):
d = DirAPI()
#d.load_old_json()
#d.get_new_json(avoid_highways=False)
d.get_new_json(
origin=(lat1,lng1),
destination=(lat2, lng2),
avoid_highways=avdHigh,
alternatives=False)
sample_distance = 100
f = open('file', 'w')
#f2 = open('highway_100_height', 'w')
#f2.write('SegmentID,Segment2ID,EPointID,latitude,longitude,elevtaion,resolution\n')
#for step in d.steps(0):
for sid in range(len(d.steps(0))):
step = d.steps(0)[sid]
velocity = float(step['distance']['value']) / float(step['duration']['value'])
path_ = decode(step['polyline']['points'])
path_ = [(p[1], p[0]) for p in path_]
spath_ = ['%f,%f' % p for p in path_]
for i in range(0, len(path_), 50):
i2 = min(len(path_), i+50)
path = path_[i:i2]
distance = [vincenty(path[j], path[j+1]).m for j in range(len(path) - 1)]
mileage = sum(distance)
if mileage < sample_distance: break
samples = int(floor(mileage / sample_distance) + 1)
e = ElevationAPI()
e.get_new_json(path = '|'.join(spath_[i:i2]), samples = samples)
assert len(e.points()) == samples
e_distance = [vincenty(e.latlng(ei), e.latlng(ei+1)).m for ei in range(samples-1)]
e_height = [e.elev(ei) - e.elev(ei+1) for ei in range(samples-1)]
e_slope = [atan2(e_height[ei], e_distance[ei]) for ei in range(samples-1)]
for ei in range(samples - 1):
f.write('%d\t%f\t%f\n' % (e_distance[ei], e_slope[ei], velocity))
# f.flush()
# for ei in range(samples):
# f2.write('%d,%d,%d,%f,%f,%f,%f\n' % (sid, i, ei, e.lat(ei), e.lng(ei), e.elev(ei), e.res(ei)))
# print '%d\t%f\t%f\n' % (e_distance[ei], e_slope[ei], velocity)
f.close()
#f2.close()
def getJDWE():
with open('C:/Users/CGGM-kevinkuan0/Desktop/eaas-demo/file.out') as f:
line = f.readline()
return map(float, line.split(' '))
def getAll(lat1, lng1, lat2, lng2, avdHigh):
print 'test'
getDSVFile(lat1, lng1, lat2, lng2, avdHigh)
call('EV.cmd', shell=True)
print 'call fin'
(energy_j, distance, energy_kwh, efficiency) = getJDWE()
print 'energy_j %f distance %f energy_kwh %f efficiency %f' % (energy_j, distance, energy_kwh, efficiency)
return energy_kwh
if __name__ == "__main__":
getAll(24.841443,121.015447,24.705530,121.739171,False) |
# -*- coding: utf-8 -*-
n = int(raw_input())
if n % 4 == 0:
print('{} {}'.format(n / 2 - 2, n / 2 + 2))
elif n % 2 == 0:
print('{} {}'.format(n / 2 - 3, n / 2 + 3))
else:
middle = n / 2
first = middle - middle % 3
if first % 2 == 0:
first += 3
second = n - first
print('{} {}'.format(first, second))
|
from django.urls import path
from rest_framework import routers
from .views import (
QuestionViewSet,
AnswerViewSet,
TagListView,
CategoryListView,
OpenQuestionListView,
SolvedQuestionListView
)
router = routers.DefaultRouter(trailing_slash=False)
router.register('questions', QuestionViewSet, basename='questions')
router.register('answers', AnswerViewSet, basename='answers')
urlpatterns = router.urls
urlpatterns += [
path('solved', SolvedQuestionListView.as_view()),
path('open', OpenQuestionListView.as_view()),
path('tags/<str:slug>', TagListView.as_view()),
path('categories', CategoryListView.as_view())
]
|
def survey1():
answer={}
question=["What is your first name? ","What is your last name? ", "How old are you? ", "What is your birthday? Format in MM/DD/YY ","How much time do you spend on your phone? Type the following options: A little, average, or often."]
data= ["name", "last name", "age", "birthday", "phone amount"]
for i in range (len(question)):
answer[data[i]]=input(question[i])
return answer
def survey2():
answer2={}
question2=["What is your favorite color?", "What state do you live in?", "Do you have any pets?", "Are you a female or male?"]
data2=["color", "state", "pets","gender"]
for u in range (len(question2)):
answer2[data2[u]]=input(question2[u])
return answer2
import json
def analyze_data(listtwo):
num_of_answers=len(listtwo)
print("Number of responses:"+str(num_of_answers))
def main():
list1=[]
list2=[]
reply3="yes"
while reply3== "yes":
answer={}
answer2={}
print("Hello and thank you for selecting this survey.")
reply="no"
while reply=="no":
answer=survey1()
print("Is this information correct? Type yes or no.")
print(answer)
reply=input()
print("Do you want to continue this survey? Type 1 to stop, and 2 to continue.")
reply2=input()
if reply2 =="1":
print("Thank you for your time.")
else:
answer2=survey2()
list2.append(answer2)
list1.append(answer)
print("Do you want to keep on collecting responses?")
reply3=input()
print(list1)
print(list2)
listtwo=[]
listone=[]
with open ("data.json", 'r') as data:
listone=json.load(data)
data.close()
with open ("data.json",'w') as data:
listone.extend(list1)
json.dump(listone, data)
data.close()
with open ("data.json", 'r') as mdata:
listtwo=json.load(mdata)
with open ("data.json",'w') as mdata:
listtwo.extend(list2)
json.dump(listtwo, mdata)
analyze_data(listtwo)
main()
|
import ytglobal
import ytSet
import ytGet
print "---Use ytSet() to set global---"
ytSet.SetBrowser()
print "#1 Isolate Method, set browser to: " + ytglobal.runEnv.BROWSER
ytSet.SetPlatform()
print "#2 Class Method, set browser to: " + ytglobal.runEnv.PLATFORM
print "Directly get Browser: " + ytglobal.runEnv.BROWSER
print "---Use ytGet() to get global---"
ytGet.get()
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Functional tests for the Admin module."""
__author__ = 'Todd larsen (tlarsen@google.com)'
import datetime
import logging
import random
import appengine_config
from google.appengine.ext import db
from common import utc
from common import utils
from controllers import sites
from models import models
from models import transforms
from models.data_sources import paginated_table
from modules.admin import enrollments
from tests.functional import actions
class EnrollmentsTests(actions.TestBase):
"""Functional tests for enrollments counters."""
def test_total_inc_get_set(self):
ns_name = "ns_single"
key_name = "%s:total" % ns_name
key = db.Key.from_path(
enrollments.TotalEnrollmentDAO.ENTITY.kind(), key_name,
namespace=appengine_config.DEFAULT_NAMESPACE_NAME)
# Use namespace that is *not* appengine_config.DEFAULT_NAMESPACE_NAME.
with utils.Namespace("test_total_inc_get_set"):
self.assertEquals(
enrollments.TotalEnrollmentDAO.get(ns_name), 0)
load_dto = enrollments.TotalEnrollmentDAO.load_or_default(ns_name)
new_dto = enrollments.TotalEnrollmentDAO.new_dto(ns_name)
# DAO.get(), DAO.load_or_default(), and DAO.new_dto() do *not*
# save a zero-value counter in the Datastore for missing counters.
self.assertEquals(
enrollments.TotalEnrollmentDAO.ENTITY.get(key), None)
# DTO.get() does not save a zero-value 'count' in the DTO.
self.assertEquals(load_dto.get(), 0)
self.assertTrue(load_dto.is_empty)
self.assertTrue(load_dto.is_missing)
self.assertFalse(load_dto.is_pending)
self.assertFalse(load_dto.is_stalled)
self.assertEquals(new_dto.get(), 0)
self.assertTrue(new_dto.is_empty)
self.assertTrue(new_dto.is_missing)
self.assertFalse(new_dto.is_pending)
self.assertFalse(new_dto.is_stalled)
# Increment the missing total enrollment count for ns_single
# (which should also initially create the DTO and store it,
# JSON-encoded, in the Datastore).
expected_count = 1 # Expecting non-existant counter (0) + 1.
inc_dto = enrollments.TotalEnrollmentDAO.inc(ns_name)
self.assertEquals(inc_dto.get(), expected_count)
self.assertEquals(
enrollments.TotalEnrollmentDAO.get(ns_name), inc_dto.get())
# Confirm that a JSON-encoded DTO containing the incremented total
# enrollment count was stored in the AppEngine default namespace
# (not the test_total_inc_get_set "course" namespace).
entity = enrollments.TotalEnrollmentDAO.ENTITY.get(key)
db_dto = enrollments.TotalEnrollmentDAO.new_dto("", entity=entity)
self.assertEquals(db_dto.get(), inc_dto.get())
# Set "ns_single:total" to a value of 5.
expected_count = 5 # Forces to fixed value, ignoring old value.
set_dto = enrollments.TotalEnrollmentDAO.set(ns_name, 5)
self.assertEquals(set_dto.get(), expected_count)
self.assertEquals(
enrollments.TotalEnrollmentDAO.get(ns_name), set_dto.get())
# Increment the existing total enrollment count for ns_single
# by an arbitrary offset (not the default offset of 1). Expecting
# what was just set() plus this offset.
expected_count = set_dto.get() + 10
ofs_dto = enrollments.TotalEnrollmentDAO.inc(ns_name, offset=10)
self.assertEquals(ofs_dto.get(), expected_count)
self.assertEquals(
enrollments.TotalEnrollmentDAO.get(ns_name), ofs_dto.get())
def test_total_delete(self):
ns_name = "ns_delete"
key_name = "%s:total" % ns_name
key = db.Key.from_path(
enrollments.TotalEnrollmentDAO.ENTITY.kind(), key_name,
namespace=appengine_config.DEFAULT_NAMESPACE_NAME)
# Use namespace that is *not* appengine_config.DEFAULT_NAMESPACE_NAME.
with utils.Namespace("test_total_delete"):
# Set "ns_delete:total" to a value of 5.
expected_count = 5 # Forces to fixed value, ignoring old value.
set_dto = enrollments.TotalEnrollmentDAO.set(ns_name, 5)
self.assertFalse(set_dto.is_empty)
self.assertFalse(set_dto.is_missing)
self.assertFalse(set_dto.is_pending)
self.assertFalse(set_dto.is_stalled)
self.assertEquals(set_dto.get(), expected_count)
self.assertEquals(
enrollments.TotalEnrollmentDAO.get(ns_name), set_dto.get())
# Confirm that a JSON-encoded DTO containing the set total
# enrollment count was stored in the AppEngine default namespace
# (not the test_total_delete "course" namespace).
entity = enrollments.TotalEnrollmentDAO.ENTITY.get(key)
db_dto = enrollments.TotalEnrollmentDAO.new_dto("", entity=entity)
self.assertEquals(db_dto.get(), set_dto.get())
# Delete the existing total enrollment count for ns_delete.
enrollments.TotalEnrollmentDAO.delete(ns_name)
# Confirm that DAO.delete() removed the entity from the Datastore.
self.assertEquals(
enrollments.TotalEnrollmentDAO.ENTITY.get(key), None)
load_dto = enrollments.TotalEnrollmentDAO.load_or_default(ns_name)
self.assertEquals(load_dto.get(), 0)
self.assertTrue(load_dto.is_empty)
self.assertTrue(load_dto.is_missing)
self.assertFalse(load_dto.is_pending)
self.assertFalse(load_dto.is_stalled)
self.assertEquals(
enrollments.TotalEnrollmentDAO.get(ns_name), 0)
def test_binned_inc_get_set(self):
now_dt = datetime.datetime.utcnow()
now = utc.datetime_to_timestamp(now_dt)
ns_name = "ns_binned"
key_name = "%s:adds" % ns_name
key = db.Key.from_path(
enrollments.EnrollmentsAddedDAO.ENTITY.kind(), key_name,
namespace=appengine_config.DEFAULT_NAMESPACE_NAME)
# Use namespace that is *not* appengine_config.DEFAULT_NAMESPACE_NAME.
with utils.Namespace("test_binned_inc_get_set"):
self.assertEquals(
enrollments.EnrollmentsAddedDAO.get(ns_name, now_dt), 0)
load_dto = enrollments.EnrollmentsAddedDAO.load_or_default(ns_name)
new_dto = enrollments.EnrollmentsAddedDAO.new_dto(ns_name)
# DAO.get(), DAO.load_or_default(), and DAO.new_dto() do *not* save
# a zero-value binned counter in the Datastore for missing counters.
self.assertEquals(
enrollments.EnrollmentsAddedDAO.ENTITY.get(key), None)
# DTO.get() does not create zero-value bins for missing bins.
self.assertEquals(new_dto.get(now), 0)
self.assertTrue(new_dto.is_empty)
self.assertTrue(new_dto.is_missing)
self.assertFalse(new_dto.is_pending)
self.assertFalse(new_dto.is_stalled)
self.assertEquals(len(new_dto.binned), 0)
self.assertEquals(load_dto.get(now), 0)
self.assertTrue(load_dto.is_empty)
self.assertTrue(load_dto.is_missing)
self.assertFalse(load_dto.is_pending)
self.assertFalse(load_dto.is_stalled)
self.assertEquals(len(load_dto.binned), 0)
# Increment a missing ns_single:adds enrollment count for the
# "now" bin (which should also initially create the DTO and store
# it, JSON-encoded, in the Datastore).
expected_count = 1 # Expecting non-existant counter (0) + 1.
inc_dto = enrollments.EnrollmentsAddedDAO.inc(ns_name, now_dt)
self.assertEquals(len(inc_dto.binned), 1)
self.assertEquals(inc_dto.get(now), expected_count)
self.assertEquals(
enrollments.EnrollmentsAddedDAO.get(ns_name, now_dt),
inc_dto.get(now))
# DTO.get() and DAO.get() do not create zero-value bins for missing
# bins in existing counters. (0 seconds since epoch is most
# certainly not in the same daily bin as the "now" time.)
zero_dt = datetime.datetime.utcfromtimestamp(0)
self.assertEquals(
enrollments.EnrollmentsAddedDAO.get(ns_name, zero_dt), 0)
self.assertEquals(inc_dto.get(0), 0)
self.assertEquals(len(inc_dto.binned), 1)
# Confirm that a JSON-encoded DTO containing the incremented
# enrollment counter bins was stored in the AppEngine default
# namespace (not the test_binned_inc_get_set "course" namespace).
entity = enrollments.EnrollmentsAddedDAO.ENTITY.get(key)
db_dto = enrollments.EnrollmentsAddedDAO.new_dto("", entity=entity)
self.assertEquals(db_dto.get(now), inc_dto.get(now))
self.assertEquals(len(db_dto.binned), len(inc_dto.binned))
# Force "ns_single:adds" to a value of 5.
expected_count = 5 # Forces to fixed value, ignoring old value.
set_dto = enrollments.EnrollmentsAddedDAO.set(ns_name, now_dt, 5)
self.assertEquals(len(set_dto.binned), 1)
self.assertEquals(set_dto.get(now), expected_count)
self.assertEquals(
enrollments.EnrollmentsAddedDAO.get(ns_name, now_dt),
set_dto.get(now))
# Increment the existing enrollment counter bin for ns_single
# by an arbitrary offset (not the default offset of 1).
# Expecting what was just set() plus this offset.
expected_count = set_dto.get(now) + 10
ofs_dto = enrollments.EnrollmentsAddedDAO.inc(
ns_name, now_dt, offset=10)
self.assertEquals(ofs_dto.get(now), expected_count)
self.assertEquals(
enrollments.EnrollmentsAddedDAO.get(ns_name, now_dt),
ofs_dto.get(now))
# Increment the "start-of-day" time computed from "now" and show
# that it is the same bin as the "now" bin (and that no new bins
# were created).
now_start = utc.day_start(now)
now_start_dt = now_dt.replace(hour=0, minute=0, second=0)
# Expecting just-incremented value + 1.
expected_count = ofs_dto.get(now) + 1
start_dto = enrollments.EnrollmentsAddedDAO.inc(
ns_name, now_start_dt)
self.assertEquals(len(start_dto.binned), 1)
self.assertEquals(start_dto.get(now), expected_count)
self.assertEquals(
enrollments.EnrollmentsAddedDAO.get(ns_name, now_dt),
start_dto.get(now))
# Increment the "end-of-day" time computed from "now" and show
# that it is in the same bin as the "now" bin"
now_end = utc.day_end(now)
now_end_dt = now_dt.replace(hour=23, minute=59, second=59)
# Expecting just-incremented value + 1.
expected_count = start_dto.get(now) + 1
end_dto = enrollments.EnrollmentsAddedDAO.inc(
ns_name, now_end_dt)
self.assertEquals(len(end_dto.binned), 1)
self.assertEquals(end_dto.get(now), expected_count)
self.assertEquals(
enrollments.EnrollmentsAddedDAO.get(ns_name, now_dt),
end_dto.get(now))
def test_load_many(self):
NUM_MANY = 100
ns_names = ["ns_many_%03d" % i for i in xrange(NUM_MANY)]
course_totals = dict([(ns_name, random.randrange(1, 1000))
for ns_name in ns_names])
# Use namespace that is *not* appengine_config.DEFAULT_NAMESPACE_NAME.
with utils.Namespace("test_total_load_many"):
for ns_name, count in course_totals.iteritems():
enrollments.TotalEnrollmentDAO.set(ns_name, count)
# load_many() should not fail in the presence of bad course
# namespace names. Instead, the returned results list should have
# None values in the corresponding locations.
bad_ns_names = ["missing_course", "also_missing"]
all_names = ns_names + bad_ns_names
many_dtos = enrollments.TotalEnrollmentDAO.load_many(all_names)
self.assertEquals(len(many_dtos), len(all_names))
mapped = enrollments.TotalEnrollmentDAO.load_many_mapped(all_names)
self.assertEquals(len(mapped), len(all_names))
for ns_name in all_names:
popped = many_dtos.pop(0)
if ns_name in bad_ns_names:
ns_total = 0
self.assertTrue(mapped[ns_name].is_empty)
self.assertTrue(mapped[ns_name].is_missing)
self.assertFalse(mapped[ns_name].is_pending)
self.assertFalse(mapped[ns_name].is_stalled)
self.assertTrue(popped.is_empty)
self.assertTrue(popped.is_missing)
self.assertFalse(popped.is_pending)
self.assertFalse(popped.is_stalled)
else:
ns_total = course_totals[ns_name]
key_name = enrollments.TotalEnrollmentDAO.key_name(ns_name)
self.assertEquals(popped.id, key_name)
self.assertEquals(
enrollments.TotalEnrollmentDAO.namespace_name(popped.id),
ns_name)
self.assertEquals(popped.get(), ns_total)
self.assertTrue(ns_name in mapped)
self.assertEquals(mapped[ns_name].id, key_name)
self.assertEquals(mapped[ns_name].get(), ns_total)
def test_load_all(self):
# 500 is larger than the default common.utils.iter_all() batch_size.
all_totals = dict([("ns_all_%03d" % i, random.randrange(1, 1000))
for i in xrange(500)])
# Use namespace that is *not* appengine_config.DEFAULT_NAMESPACE_NAME.
with utils.Namespace("test_total_load_all"):
for ns, count in all_totals.iteritems():
enrollments.TotalEnrollmentDAO.set(ns, count)
for total in enrollments.TotalEnrollmentDAO.load_all():
ns = enrollments.TotalEnrollmentDAO.namespace_name(total.id)
self.assertEquals(
enrollments.TotalEnrollmentDAO.key_name(ns), total.id)
self.assertEquals(total.get(), all_totals[ns])
del all_totals[ns]
# All totals should have been checked, and checked exactly once.
self.assertEquals(len(all_totals), 0)
class LogsExaminer(actions.TestBase):
CHARS_IN_ISO_8601_DATETIME = '[0-9T:.Z-]+'
CHARS_IN_TIME_DELTA = '[0-9:]+'
CHARS_IN_TOTAL = '[0-9]+'
## Log messages emitted by StartComputeCounts.cron_action().
CANCELING_PATTERN_FMT = (
'.*CANCELING periodic "{}" enrollments total refresh found'
' unexpectedly still running.')
def expect_canceling_in_logs(self, logs, dto):
self.assertRegexpMatches(logs,
self.CANCELING_PATTERN_FMT.format(dto.id))
def expect_no_canceling_in_logs(self, logs, dto):
self.assertNotRegexpMatches(logs,
self.CANCELING_PATTERN_FMT.format(dto.id))
INTERRUPTING_PATTERN_FMT = (
'.*INTERRUPTING missing "{{}}" enrollments total initialization'
' started on {}.'.format(CHARS_IN_ISO_8601_DATETIME))
def expect_interrupting_in_logs(self, logs, dto):
self.assertRegexpMatches(logs,
self.INTERRUPTING_PATTERN_FMT.format(dto.id))
def expect_no_interrupting_in_logs(self, logs, dto):
self.assertNotRegexpMatches(logs,
self.INTERRUPTING_PATTERN_FMT.format(dto.id))
REFRESHING_PATTERN_FMT = (
'.*REFRESHING existing "{{}}" enrollments total, {{}}'
' as of {}.'.format(CHARS_IN_ISO_8601_DATETIME))
def expect_refreshing_in_logs(self, logs, dto):
self.assertRegexpMatches(logs,
self.REFRESHING_PATTERN_FMT.format(dto.id, dto.get()))
def expect_no_refreshing_in_logs(self, logs, dto):
self.assertNotRegexpMatches(logs,
self.REFRESHING_PATTERN_FMT.format(dto.id, self.CHARS_IN_TOTAL))
COMPLETING_PATTERN_FMT = (
'.*COMPLETING "{{}}" enrollments total initialization'
' started on {} stalled for {}.'.format(
CHARS_IN_ISO_8601_DATETIME, CHARS_IN_TIME_DELTA))
def expect_completing_in_logs(self, logs, dto):
self.assertRegexpMatches(logs,
self.COMPLETING_PATTERN_FMT.format(dto.id))
def expect_no_completing_in_logs(self, logs, dto):
self.assertNotRegexpMatches(logs,
self.COMPLETING_PATTERN_FMT.format(dto.id))
## Log messages emitted by init_missing_total().
SKIPPING_PATTERN_FMT = (
'.*SKIPPING existing "{{}}" enrollments total recomputation,'
' {{}} as of {}.'.format(CHARS_IN_ISO_8601_DATETIME))
def expect_skipping_in_logs(self, logs, dto):
self.assertRegexpMatches(logs,
self.SKIPPING_PATTERN_FMT.format(dto.id, dto.get()))
def expect_no_skipping_in_logs(self, logs, dto):
self.assertNotRegexpMatches(logs,
self.SKIPPING_PATTERN_FMT.format(dto.id, self.CHARS_IN_TOTAL))
PENDING_PATTERN_FMT = (
'.*PENDING "{{}}" enrollments total initialization in progress for'
' {}, since {}.'.format(
CHARS_IN_TIME_DELTA, CHARS_IN_ISO_8601_DATETIME))
def expect_pending_in_logs(self, logs, dto):
self.assertRegexpMatches(logs,
self.PENDING_PATTERN_FMT.format(dto.id))
def expect_no_pending_in_logs(self, logs, dto):
self.assertNotRegexpMatches(logs,
self.PENDING_PATTERN_FMT.format(dto.id))
STALLED_PATTERN_FMT = (
'.*STALLED "{{}}" enrollments total initialization for'
' {}, since {}.'.format(
CHARS_IN_TIME_DELTA, CHARS_IN_ISO_8601_DATETIME))
def expect_stalled_in_logs(self, logs, dto):
self.assertRegexpMatches(logs,
self.STALLED_PATTERN_FMT.format(dto.id))
def expect_no_stalled_in_logs(self, logs, dto):
self.assertNotRegexpMatches(logs,
self.STALLED_PATTERN_FMT.format(dto.id))
SCHEDULING_PATTERN_FMT = (
'.*SCHEDULING "{{}}" enrollments total update at {}.'.format(
CHARS_IN_ISO_8601_DATETIME))
def expect_scheduling_in_logs(self, logs, dto):
self.assertRegexpMatches(logs,
self.SCHEDULING_PATTERN_FMT.format(dto.id))
def expect_no_scheduling_in_logs(self, logs, dto):
self.assertNotRegexpMatches(logs,
self.SCHEDULING_PATTERN_FMT.format(dto.id))
def check_no_exceptional_states_in_logs(self, logs, dto, ignore=None):
if ignore is None:
ignore = frozenset()
if 'CANCELING' not in ignore:
self.expect_no_canceling_in_logs(logs, dto)
if 'INTERRUPTING' not in ignore:
self.expect_no_interrupting_in_logs(logs, dto)
if 'COMPLETING' not in ignore:
self.expect_no_completing_in_logs(logs, dto)
if 'SKIPPING' not in ignore:
self.expect_no_skipping_in_logs(logs, dto)
if 'PENDING' not in ignore:
self.expect_no_pending_in_logs(logs, dto)
if 'STALLED' not in ignore:
self.expect_no_stalled_in_logs(logs, dto)
def get_new_logs(self, previous_logs):
"""Get log lines since previous all_logs, plus new all_logs lines."""
num_previous_log_lines = len(previous_logs)
all_logs = self.get_log()
return all_logs[num_previous_log_lines:], all_logs
class EventHandlersTests(LogsExaminer):
ADMIN_EMAIL = 'admin@example.com'
STUDENT_EMAIL = 'student@example.com'
STUDENT_NAME = 'Test Student'
LOG_LEVEL = logging.DEBUG
def tearDown(self):
sites.reset_courses()
def test_counters(self):
# pylint: disable=too-many-statements
COURSE = 'test_counters_event_handlers'
NAMESPACE = 'ns_' + COURSE
all_logs = [] # No log lines yet obtained via get_log().
# This test relies on the fact that simple_add_course() does *not*
# execute the CoursesItemRESTHandler.NEW_COURSE_ADDED_HOOKS, to
# simulate "legacy" courses existing prior to enrollments counters.
self.app_ctxt = actions.simple_add_course(
COURSE, self.ADMIN_EMAIL, 'Enrollments Events')
with utils.Namespace(NAMESPACE):
start = utc.day_start(utc.now_as_timestamp())
start_dt = datetime.datetime.utcfromtimestamp(start)
user = actions.login(self.STUDENT_EMAIL)
# _new_course_counts() was not called by simple_add_course().
# As a result, all counters will *not exist at all*, instead of
# simply starting out with zero values (as is the case when
# courses are created via the actual web UI.
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 0)
total_dto = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
self.assertTrue(total_dto.is_empty)
self.assertTrue(total_dto.is_missing)
self.assertFalse(total_dto.is_pending)
self.assertFalse(total_dto.is_stalled)
self.assertEquals(enrollments.EnrollmentsAddedDAO.get(
NAMESPACE, start_dt), 0)
added_dto = enrollments.EnrollmentsAddedDAO.load_or_default(
NAMESPACE)
self.assertTrue(added_dto.is_empty)
self.assertTrue(added_dto.is_missing)
self.assertFalse(added_dto.is_pending)
self.assertFalse(added_dto.is_stalled)
self.assertEquals(enrollments.EnrollmentsDroppedDAO.get(
NAMESPACE, start_dt), 0)
dropped_dto = enrollments.EnrollmentsDroppedDAO.load_or_default(
NAMESPACE)
self.assertTrue(dropped_dto.is_empty)
self.assertTrue(dropped_dto.is_missing)
self.assertFalse(dropped_dto.is_pending)
self.assertFalse(dropped_dto.is_stalled)
actions.login(self.STUDENT_EMAIL)
actions.register(self, self.STUDENT_NAME, course=COURSE)
self.execute_all_deferred_tasks(
models.StudentLifecycleObserver.QUEUE_NAME)
# The enrollments._count_add() callback is triggered by the above
# StudentLifecycleObserver.EVENT_ADD action. That callback will
# call init_missing_total() because the counter was "missing"
# (did not exist *at all*).
pending_add_dto = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
# Still no count value, since the MapReduce has not run (and will
# not, because execute_all_deferred_tasks() is being called by
# this test *only* for the StudentLifecycleObserver.QUEUE_NAME).
self.assertTrue(pending_add_dto.is_empty)
self.assertTrue(pending_add_dto.is_pending)
# Now "pending" instead of "missing" because last_modified has
# been set by init_missing_total() via mark_pending().
self.assertFalse(pending_add_dto.is_missing)
self.assertFalse(pending_add_dto.is_stalled)
# init_missing_total() will have logged that it is "SCHEDULING"
# a ComputeCounts MapReduce (that will never be run by this test).
logs, all_logs = self.get_new_logs(all_logs)
self.check_no_exceptional_states_in_logs(logs, pending_add_dto)
self.expect_scheduling_in_logs(logs, pending_add_dto)
# Confirm executing deferred tasks did not cross day boundary.
registered = utc.now_as_timestamp()
self.assertEquals(utc.day_start(registered), start)
# When the counters are completely uninitialized (e.g. "legacy"
# courses in an installation that is upgrading to enrollments
# counters), student lifecycle events will *not* increment or
# decrement missing 'total' counters. However, the information is
# not lost, since ComputeCounts MapReduceJobs will recover actual
# enrollment totals when they are scheduled (e.g. via the register
# and unregister student lifecycle events, or via the
# site_admin_enrollments cron jobs).
total_dto = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
self.assertTrue(total_dto.is_empty) # No inc for a missing total.
self.assertFalse(total_dto.is_missing)
self.assertTrue(total_dto.is_pending)
self.assertFalse(total_dto.is_stalled)
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 0)
added_dto = enrollments.EnrollmentsAddedDAO.load_or_default(
NAMESPACE)
# Always count today's 'adds', since ComputeCounts will not.
self.assertFalse(added_dto.is_empty)
self.assertFalse(added_dto.is_missing)
self.assertFalse(added_dto.is_pending)
self.assertFalse(added_dto.is_stalled)
self.assertEquals(1, added_dto.get(start))
self.assertEquals(enrollments.EnrollmentsAddedDAO.get(
NAMESPACE, start_dt), 1)
dropped_dto = enrollments.EnrollmentsDroppedDAO.load_or_default(
NAMESPACE)
self.assertTrue(dropped_dto.is_empty) # No 'drops' to count yet.
self.assertTrue(dropped_dto.is_missing)
self.assertFalse(dropped_dto.is_pending)
self.assertFalse(dropped_dto.is_stalled)
self.assertEquals(enrollments.EnrollmentsDroppedDAO.get(
NAMESPACE, start_dt), 0)
actions.unregister(self, course=COURSE)
self.execute_all_deferred_tasks(
models.StudentLifecycleObserver.QUEUE_NAME)
# The enrollments._count_drop() callback is triggered by the above
# StudentLifecycleObserver.EVENT_UNENROLL_COMMANDED action. That
# callback will *not* call init_missing_total() because this time,
# while the counter is "empty" (contains no count), it *does* have
# a last modified time, so is "pending" and no longer "missing".
# Confirm executing deferred tasks did not cross day boundary.
unregistered = utc.now_as_timestamp()
self.assertEquals(utc.day_start(unregistered), start)
total_dto = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
self.assertTrue(total_dto.is_empty) # Still does not exist.
self.assertFalse(total_dto.is_missing)
self.assertTrue(total_dto.is_pending) # Still pending.
self.assertFalse(total_dto.is_stalled)
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 0)
added_dto = enrollments.EnrollmentsAddedDAO.load_or_default(
NAMESPACE)
self.assertFalse(added_dto.is_empty) # Unchanged by a drop event.
self.assertFalse(added_dto.is_missing)
self.assertFalse(added_dto.is_pending)
self.assertFalse(added_dto.is_stalled)
self.assertEquals(1, added_dto.get(start))
self.assertEquals(enrollments.EnrollmentsAddedDAO.get(
NAMESPACE, start_dt), 1)
dropped_dto = enrollments.EnrollmentsDroppedDAO.load_or_default(
NAMESPACE)
# Always count today's 'drops', since ComputeCounts will not.
self.assertFalse(dropped_dto.is_empty)
self.assertFalse(dropped_dto.is_missing)
self.assertFalse(dropped_dto.is_pending)
self.assertFalse(dropped_dto.is_stalled)
self.assertEquals(1, dropped_dto.get(start))
self.assertEquals(enrollments.EnrollmentsDroppedDAO.get(
NAMESPACE, start_dt), 1)
# Run the MapReduceJob to recover the missing 'total' and 'adds'.
enrollments.init_missing_total(total_dto, self.app_ctxt)
self.execute_all_deferred_tasks()
total_dto = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
self.assertFalse(total_dto.is_empty) # Finally exists.
self.assertFalse(total_dto.is_missing)
self.assertFalse(total_dto.is_pending)
self.assertFalse(total_dto.is_stalled)
self.assertEquals(0, total_dto.get()) # Add and then drop is 0.
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 0)
models.StudentProfileDAO.update(
user.user_id(), self.STUDENT_EMAIL, is_enrolled=True)
self.execute_all_deferred_tasks(
models.StudentLifecycleObserver.QUEUE_NAME)
# Confirm executing deferred tasks did not cross day boundary.
updated = utc.now_as_timestamp()
self.assertEquals(utc.day_start(updated), start)
total_dto = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
self.assertFalse(total_dto.is_empty)
self.assertFalse(total_dto.is_missing)
self.assertFalse(total_dto.is_pending)
self.assertFalse(total_dto.is_stalled)
self.assertEquals(1, total_dto.get())
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 1)
added_dto = enrollments.EnrollmentsAddedDAO.load_or_default(
NAMESPACE)
self.assertFalse(added_dto.is_empty)
self.assertFalse(added_dto.is_missing)
self.assertFalse(added_dto.is_pending)
self.assertFalse(added_dto.is_stalled)
self.assertEquals(2, added_dto.get(start))
self.assertEquals(enrollments.EnrollmentsAddedDAO.get(
NAMESPACE, start_dt), 2)
dropped_dto = enrollments.EnrollmentsDroppedDAO.load_or_default(
NAMESPACE)
self.assertFalse(dropped_dto.is_empty)
self.assertFalse(dropped_dto.is_missing)
self.assertFalse(dropped_dto.is_pending)
self.assertFalse(dropped_dto.is_stalled)
self.assertEquals(1, dropped_dto.get(start))
self.assertEquals(enrollments.EnrollmentsDroppedDAO.get(
NAMESPACE, start_dt), 1)
class MapReduceTests(LogsExaminer):
ADMIN1_EMAIL = 'admin1@example.com'
STUDENT2_EMAIL = 'student2@example.com'
STUDENT3_EMAIL = 'student3@example.com'
STUDENT4_EMAIL = 'student4@example.com'
LOG_LEVEL = logging.DEBUG
@staticmethod
def _count_add(unused_id, unused_utc_date_time):
pass
@staticmethod
def _count_drop(unused_id, unused_utc_date_time):
pass
@staticmethod
def _new_course_counts(unused_app_context, unused_errors):
pass
def setUp(self):
super(MapReduceTests, self).setUp()
# Replace enrollments counters callbacks with ones that do *not*
# increment or decrement the 'total' enrollment counters.
models.StudentLifecycleObserver.EVENT_CALLBACKS[
models.StudentLifecycleObserver.EVENT_ADD][
enrollments.MODULE_NAME] = MapReduceTests._count_add
models.StudentLifecycleObserver.EVENT_CALLBACKS[
models.StudentLifecycleObserver.EVENT_REENROLL][
enrollments.MODULE_NAME] = MapReduceTests._count_add
models.StudentLifecycleObserver.EVENT_CALLBACKS[
models.StudentLifecycleObserver.EVENT_UNENROLL][
enrollments.MODULE_NAME] = MapReduceTests._count_drop
models.StudentLifecycleObserver.EVENT_CALLBACKS[
models.StudentLifecycleObserver.EVENT_UNENROLL_COMMANDED][
enrollments.MODULE_NAME] = MapReduceTests._count_drop
def tearDown(self):
sites.reset_courses()
# Restore enrollments counters callbacks to originals.
models.StudentLifecycleObserver.EVENT_CALLBACKS[
models.StudentLifecycleObserver.EVENT_ADD][
enrollments.MODULE_NAME] = enrollments._count_add
models.StudentLifecycleObserver.EVENT_CALLBACKS[
models.StudentLifecycleObserver.EVENT_REENROLL][
enrollments.MODULE_NAME] = enrollments._count_add
models.StudentLifecycleObserver.EVENT_CALLBACKS[
models.StudentLifecycleObserver.EVENT_UNENROLL][
enrollments.MODULE_NAME] = enrollments._count_drop
models.StudentLifecycleObserver.EVENT_CALLBACKS[
models.StudentLifecycleObserver.EVENT_UNENROLL_COMMANDED][
enrollments.MODULE_NAME] = enrollments._count_drop
def test_total_enrollment_map_reduce_job(self):
# pylint: disable=too-many-statements
COURSE = 'test_total_enrollment_map_reduce_job'
NAMESPACE = 'ns_' + COURSE
all_logs = [] # No log lines yet obtained via get_log().
# This test relies on the fact that simple_add_course() does *not*
# execute the CoursesItemRESTHandler.NEW_COURSE_ADDED_HOOKS, to
# simulate "legacy" courses existing prior to enrollments counters.
app_context = actions.simple_add_course(
COURSE, self.ADMIN1_EMAIL, 'Total Enrollment MapReduce Job')
with utils.Namespace(NAMESPACE):
start = utc.day_start(utc.now_as_timestamp())
start_dt = datetime.datetime.utcfromtimestamp(start)
# Both 'total' and 'adds' counters should start out at zero.
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 0)
empty_total = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
self.assertTrue(empty_total.is_empty)
self.assertTrue(empty_total.is_missing)
self.assertFalse(empty_total.is_pending)
self.assertFalse(empty_total.is_stalled)
self.assertEquals(enrollments.EnrollmentsAddedDAO.get(
NAMESPACE, start_dt), 0)
empty_adds = enrollments.EnrollmentsAddedDAO.load_or_default(
NAMESPACE)
self.assertTrue(empty_adds.is_empty)
self.assertTrue(empty_adds.is_missing)
self.assertFalse(empty_adds.is_pending)
self.assertFalse(empty_adds.is_stalled)
admin1 = actions.login(self.ADMIN1_EMAIL)
actions.register(self, self.ADMIN1_EMAIL, course=COURSE)
# Manipulate the enrolled_on time of the first student (the
# course creator admin) to be last month.
student1 = models.Student.get_by_user(admin1)
last_month_dt = start_dt - datetime.timedelta(days=30)
student1.enrolled_on = last_month_dt
student1.put()
user2 = actions.login(self.STUDENT2_EMAIL)
actions.register(self, self.STUDENT2_EMAIL, course=COURSE)
# Manipulate the enrolled_on time of the second student to be
# last week.
student2 = models.Student.get_by_user(user2)
last_week_dt = start_dt - datetime.timedelta(days=7)
student2.enrolled_on = last_week_dt
student2.put()
user3 = actions.login(self.STUDENT3_EMAIL)
actions.register(self, self.STUDENT3_EMAIL, course=COURSE)
# Manipulate the enrolled_on time of the third student to be
# yesterday.
student3 = models.Student.get_by_user(user3)
yesterday_dt = start_dt - datetime.timedelta(days=1)
student3.enrolled_on = yesterday_dt
student3.put()
# Unregister and re-enroll today, which does not affect the original
# (manipulated above) enrolled_on value.
actions.unregister(self, course=COURSE)
models.StudentProfileDAO.update(
user3.user_id(), self.STUDENT3_EMAIL, is_enrolled=True)
# Leave the fourth student enrollment as happening today.
student4 = actions.login(self.STUDENT4_EMAIL)
actions.register(self, self.STUDENT4_EMAIL, course=COURSE)
self.execute_all_deferred_tasks(
models.StudentLifecycleObserver.QUEUE_NAME)
# Both 'total' and 'adds' counters should still be zero, because
# student lifecycle event handlers for modules.admin.enrollments have
# been disabled by MapReduceTests.setUp().
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 0)
after_queue_total = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
self.assertTrue(after_queue_total.is_empty)
self.assertTrue(after_queue_total.is_missing)
self.assertFalse(after_queue_total.is_pending)
self.assertFalse(after_queue_total.is_stalled)
self.assertEquals(enrollments.EnrollmentsAddedDAO.get(
NAMESPACE, start_dt), 0)
after_queue_adds = enrollments.EnrollmentsAddedDAO.load_or_default(
NAMESPACE)
self.assertTrue(after_queue_adds.is_empty)
self.assertTrue(after_queue_adds.is_missing)
self.assertFalse(after_queue_adds.is_pending)
self.assertFalse(after_queue_adds.is_stalled)
enrollments.init_missing_total(after_queue_total, app_context)
logs, all_logs = self.get_new_logs(all_logs)
self.check_no_exceptional_states_in_logs(logs, after_queue_total)
self.expect_scheduling_in_logs(logs, after_queue_total)
self.execute_all_deferred_tasks()
logs, all_logs = self.get_new_logs(all_logs)
self.check_no_exceptional_states_in_logs(logs, after_queue_total)
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 4) # ADMIN1, STUDENT2, STUDENT3, STUDENT4
after_mr_dto = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
self.assertFalse(after_mr_dto.is_empty)
self.assertFalse(after_mr_dto.is_missing)
self.assertFalse(after_mr_dto.is_pending)
self.assertFalse(after_mr_dto.is_stalled)
# The 'adds' DTO will not be empty, because some of the enrollments
# occurred on days other than "today".
after_mr_adds = enrollments.EnrollmentsAddedDAO.load_or_default(
NAMESPACE)
self.assertFalse(after_mr_adds.is_empty)
self.assertFalse(after_mr_adds.is_missing)
self.assertFalse(after_mr_adds.is_pending)
self.assertFalse(after_mr_adds.is_stalled)
self.assertEquals(enrollments.EnrollmentsAddedDAO.get(
NAMESPACE, last_month_dt), 1) # ADMIN1
self.assertEquals(enrollments.EnrollmentsAddedDAO.get(
NAMESPACE, last_week_dt), 1) # STUDENT2
# The third student registered yesterday, but then unregistered and
# re-enrolled today. Those subsequent activities do not affect the
# original enrolled_on value.
self.assertEquals(enrollments.EnrollmentsAddedDAO.get(
NAMESPACE, yesterday_dt), 1) # STUDENT3
# Even after the ComputeCounts MapReduce runs, the "today" 'adds'
# 'adds' counter for the course will still be empty, because any
# registration events inside the `with` block that above happened
# today are not updated, to avoid race conditions with real time
# updates that would be occurring in production (where the student
# lifecycle handlers have not been disabled by test code as in
# this test).
self.assertEquals(enrollments.EnrollmentsAddedDAO.get(
NAMESPACE, start_dt), 0) # STUDENT4
# Log in as an admin and cause the /cron/site_admin_enrollments/total
# MapReduce to be enqueued, but do this *twice*. This should produce
# both a "REFRESHING" log message for the existing enrollments total
# counter *and* a "CANCELING" log message when one of the calls to
# StartComputeCounts.cron_action() cancels the job just started by the
# previous call.
actions.login(self.ADMIN1_EMAIL, is_admin=True)
response = self.get(enrollments.StartComputeCounts.URL)
self.assertEquals(200, response.status_int)
response = self.get(enrollments.StartComputeCounts.URL)
self.assertEquals(200, response.status_int)
self.execute_all_deferred_tasks()
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 4) # Refreshed value still includes all enrollees.
after_refresh_total = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
self.assertFalse(after_refresh_total.is_empty)
self.assertFalse(after_refresh_total.is_missing)
self.assertFalse(after_refresh_total.is_pending)
self.assertFalse(after_refresh_total.is_stalled)
# No other "exceptional" states are expected other than 'CANCELING'.
logs, all_logs = self.get_new_logs(all_logs)
self.check_no_exceptional_states_in_logs(logs, after_refresh_total,
ignore=frozenset(['CANCELING']))
self.expect_canceling_in_logs(logs, after_refresh_total)
self.expect_refreshing_in_logs(logs, after_refresh_total)
# Inject some "exceptional" states and confirm that the corresponding
# condition is detected and logged.
# Put the DTO for the NAMESPACE course into the "pending" state, having
# a last_modified time but no count.
marked_dto = enrollments.TotalEnrollmentDAO.mark_pending(
namespace_name=NAMESPACE)
# A DTO in the "pending" state contains no count value.
self.assertTrue(marked_dto.is_empty)
# DTO *does* have a last modified time, even though it is empty.
self.assertTrue(marked_dto.is_pending)
# DTO has not be in the "pending" state for longer than the maximum
# pending time (MAX_PENDING_SEC), so is not yet "stalled".
self.assertFalse(marked_dto.is_stalled)
# DTO is not "missing" because, even though it is "empty", it is in
# the "pending" state (waiting for a MapReduce started by
# init_missing_total() MapReduce to complete.
self.assertFalse(marked_dto.is_missing)
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 0) # mark_pending() sets last_modified but not count.
# Now cause the /cron/site_admin_enrollments/total cron job to run,
# but schedule *two* of them, so that one will be "COMPLETING" because
# the DTO is marked "pending", and the other will be "INTERRUPTING"
# because the DTO is "pending" *and* another ComputeCounts MapReduce
# job appears to already be running.
response = self.get(enrollments.StartComputeCounts.URL)
self.assertEquals(200, response.status_int)
response = self.get(enrollments.StartComputeCounts.URL)
self.assertEquals(200, response.status_int)
self.execute_all_deferred_tasks()
# Correct total should have been computed and stored despite one
# StartComputeCounts.cron_action() canceling the other.
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 4) # Computed value still includes all enrollees.
exceptional_dto = enrollments.TotalEnrollmentDAO.load_or_default(
NAMESPACE)
self.assertFalse(exceptional_dto.is_empty)
self.assertFalse(exceptional_dto.is_missing)
self.assertFalse(exceptional_dto.is_pending)
self.assertFalse(exceptional_dto.is_stalled)
# No other "exceptional" states are expected other than the two below.
logs, all_logs = self.get_new_logs(all_logs)
self.check_no_exceptional_states_in_logs(logs, marked_dto,
ignore=frozenset(['COMPLETING', 'INTERRUPTING']))
self.expect_completing_in_logs(logs, marked_dto)
self.expect_interrupting_in_logs(logs, marked_dto)
# No existing count value (since DTO is "empty"), so no "REFRESHING"
# of an existing enrollments total.
self.expect_no_refreshing_in_logs(logs, marked_dto)
self.expect_no_scheduling_in_logs(logs, marked_dto)
def test_start_init_missing_counts(self):
COURSE = 'test_start_init_missing_counts'
NAMESPACE = 'ns_' + COURSE
all_logs = [] # No log lines yet obtained via get_log().
# This test relies on the fact that simple_add_course() does *not*
# execute the CoursesItemRESTHandler.NEW_COURSE_ADDED_HOOKS, to
# simulate "legacy" courses existing prior to enrollments counters.
app_context = actions.simple_add_course(
COURSE, self.ADMIN1_EMAIL, 'Init Missing Counts')
admin1 = actions.login(self.ADMIN1_EMAIL, is_admin=True)
# Courses list page should show em dashes for enrollment total counts.
response = self.get('/admin?action=courses')
dom = self.parse_html_string_to_soup(response.body)
enrollment_div = dom.select('#enrolled_')[0]
self.assertEquals(enrollments.NONE_ENROLLED,
enrollment_div.text.strip())
# The resulting DTO should be empty (have no count) and should *not*
# be "pending" (last_modified value should be zero).
before = enrollments.TotalEnrollmentDAO.load_or_default(NAMESPACE)
self.assertTrue(before.is_empty)
self.assertTrue(before.is_missing)
self.assertNotIn('count', before.dict)
self.assertFalse(before.is_pending)
self.assertFalse(before.is_stalled)
self.assertFalse(before.last_modified)
# Confirm that the StartInitMissingCounts cron job will find the
# courses that are missing an enrollment total entity in the Datastore
# and trigger the ComputeCounts MapReduce for them, but only once.
response = self.get(enrollments.StartInitMissingCounts.URL)
self.assertEquals(200, response.status_int)
self.execute_all_deferred_tasks()
logs, all_logs = self.get_new_logs(all_logs)
self.check_no_exceptional_states_in_logs(logs, before)
self.expect_scheduling_in_logs(logs, before)
# init_missing_total() does not use StartComputeCounts, but instead
# invokes ComputeCounts.submit() directly.
self.expect_no_refreshing_in_logs(logs, before)
# Load the courses page again, now getting 0 for number of students.
response = self.get('/admin?action=courses')
dom = self.parse_html_string_to_soup(response.body)
enrollment_div = dom.select('#enrolled_')[0]
self.assertEquals('0', enrollment_div.text.strip())
# The resulting DTO should be non-empty (have a count of zero) and
# thus should also not be "pending".
after = enrollments.TotalEnrollmentDAO.load_or_default(NAMESPACE)
self.assertFalse(after.is_empty)
self.assertIn('count', after.dict)
self.assertEquals(0, after.get())
self.assertFalse(after.is_pending)
self.assertTrue(after.last_modified)
# Run the cron job a second time, which should find nothing needing
# to be done.
response = self.get(enrollments.StartInitMissingCounts.URL)
self.assertEquals(200, response.status_int)
self.execute_all_deferred_tasks()
logs, all_logs = self.get_new_logs(all_logs)
self.check_no_exceptional_states_in_logs(logs, after,
ignore=frozenset(['SKIPPING']))
self.expect_skipping_in_logs(logs, after)
self.expect_no_scheduling_in_logs(logs, after)
self.expect_no_refreshing_in_logs(logs, after)
# Inject some "exceptional" states and confirm that the corresponding
# condition is detected and logged.
# Put the DTO for the NAMESPACE course into the "pending" state, having
# a last_modified time but no count.
marked_dto = enrollments.TotalEnrollmentDAO.mark_pending(
namespace_name=NAMESPACE)
self.assertTrue(marked_dto.is_empty)
self.assertTrue(marked_dto.is_pending)
self.assertFalse(marked_dto.is_stalled)
self.assertFalse(marked_dto.is_missing)
self.assertEquals(enrollments.TotalEnrollmentDAO.get(
NAMESPACE), 0) # mark_pending() sets last_modified but not count.
# Run the cron job again, which should find a "pending" but not
# "stalled" count, 'SKIPPING' it to allow a previously deferred
# MapReduce to initialize it.
response = self.get(enrollments.StartInitMissingCounts.URL)
self.assertEquals(200, response.status_int)
self.execute_all_deferred_tasks()
# No other "exceptional" states are expected other than 'SKIPPING'.
logs, all_logs = self.get_new_logs(all_logs)
self.check_no_exceptional_states_in_logs(logs, marked_dto,
ignore=frozenset(['SKIPPING']))
self.expect_skipping_in_logs(logs, marked_dto)
# StartInitMissingCounts.cron_action() deferred enrollments totals
# that are not "stalled" to be initialized by previously scheduled
# MapReduce jobs.
self.expect_no_scheduling_in_logs(logs, marked_dto)
self.expect_no_refreshing_in_logs(logs, marked_dto)
# Now call init_missing_total() directly, which logs a 'PENDING'
# messages instead. (StartInitMissingCounts.cron_action() did not even
# invoke init_missing_total() in the above get().)
enrollments.init_missing_total(marked_dto, app_context)
# No other "exceptional" states are expected other than 'PENDING'.
logs, all_logs = self.get_new_logs(all_logs)
self.check_no_exceptional_states_in_logs(logs, marked_dto,
ignore=frozenset(['PENDING']))
self.expect_pending_in_logs(logs, marked_dto)
# init_missing_total() leaves "pending" but not "stalled" deferred
# enrollments totals to be initialized by previously scheduled
# MapReduce jobs.
self.expect_no_scheduling_in_logs(logs, marked_dto)
self.expect_no_refreshing_in_logs(logs, marked_dto)
# Force the "pending" DTO into the "stalled" state by setting its
# last modified value into the past by more than MAX_PENDING_SEC.
past = 2 * enrollments.EnrollmentsDTO.MAX_PENDING_SEC
marked_dto._force_last_modified(marked_dto.last_modified - past)
enrollments.TotalEnrollmentDAO._save(marked_dto)
past_dto = enrollments.TotalEnrollmentDAO.load_or_default(NAMESPACE)
self.assertTrue(past_dto.is_empty)
self.assertTrue(past_dto.is_pending)
self.assertTrue(past_dto.is_stalled)
self.assertFalse(past_dto.is_missing)
# Run the cron job again, which should find a "stalled" count.
# StartInitMissingCounts.cron_action() calls init_missing_total() for
# a "stalled" count. init_missing_total() should then log that the
# count is 'STALLED'.
response = self.get(enrollments.StartInitMissingCounts.URL)
self.assertEquals(200, response.status_int)
self.execute_all_deferred_tasks()
# No other "exceptional" states are expected other than 'STALLED'.
logs, all_logs = self.get_new_logs(all_logs)
self.check_no_exceptional_states_in_logs(logs, marked_dto,
ignore=frozenset(['STALLED']))
self.expect_stalled_in_logs(logs, marked_dto)
# init_missing_total() should be 'SCHEDULING' a new MapReduce, via a
# direct invocation of ComputeCounts.submit(), to replace the
# stalled total.
self.expect_scheduling_in_logs(logs, marked_dto)
self.expect_no_refreshing_in_logs(logs, marked_dto)
class GraphTests(actions.TestBase):
COURSE = 'test_course'
NAMESPACE = 'ns_%s' % COURSE
ADMIN_EMAIL = 'admin@example.com'
def setUp(self):
super(GraphTests, self).setUp()
self.app_context = actions.simple_add_course(
self.COURSE, self.ADMIN_EMAIL, 'Test Course')
self.base = '/%s' % self.COURSE
actions.login(self.ADMIN_EMAIL)
def tearDown(self):
sites.reset_courses()
super(GraphTests, self).tearDown()
def _get_items(self):
data_source_token = paginated_table._DbTableContext._build_secret(
{'data_source_token': 'xyzzy'})
response = self.post('rest/data/enrollments/items',
{'page_number': 0,
'chunk_size': 0,
'data_source_token': data_source_token})
self.assertEquals(response.status_int, 200)
result = transforms.loads(response.body)
return result.get('data')
def _get_dashboard_page(self):
response = self.get('dashboard?action=analytics_enrollments')
self.assertEquals(response.status_int, 200)
return response
def test_no_enrollments(self):
self.assertEquals([], self._get_items())
body = self._get_dashboard_page().body
self.assertIn('No student enrollment data.', body)
def test_one_add(self):
now = utc.now_as_timestamp()
now_dt = utc.timestamp_to_datetime(now)
enrollments.EnrollmentsAddedDAO.inc(self.NAMESPACE, now_dt)
expected = [{
'timestamp_millis': utc.day_start(now) * 1000,
'add': 1,
'drop': 0,
}]
self.assertEquals(expected, self._get_items())
body = self._get_dashboard_page().body
self.assertNotIn('No student enrollment data.', body)
def test_only_drops(self):
now_dt = utc.timestamp_to_datetime(utc.now_as_timestamp())
enrollments.EnrollmentsDroppedDAO.inc(self.NAMESPACE, now_dt)
body = self._get_dashboard_page().body
self.assertIn('No student enrollment data.', body)
def test_one_add_and_one_drop(self):
now = utc.now_as_timestamp()
now_dt = utc.timestamp_to_datetime(now)
enrollments.EnrollmentsAddedDAO.inc(self.NAMESPACE, now_dt)
enrollments.EnrollmentsDroppedDAO.inc(self.NAMESPACE, now_dt)
expected = [{
'timestamp_millis': utc.day_start(now) * 1000,
'add': 1,
'drop': 1,
}]
self.assertEquals(expected, self._get_items())
body = self._get_dashboard_page().body
self.assertNotIn('No student enrollment data.', body)
def test_many(self):
now = utc.now_as_timestamp()
num_items = 1000
# Add a lot of enrollments, drops.
for x in xrange(num_items):
when = utc.timestamp_to_datetime(
now - random.randrange(365 * 24 * 60 * 60))
if x % 10:
enrollments.EnrollmentsAddedDAO.inc(self.NAMESPACE, when)
else:
enrollments.EnrollmentsDroppedDAO.inc(self.NAMESPACE, when)
items = self._get_items()
# Expect some overlap, but still many distinct items. Here, we're
# looking to ensure that we get some duplicate items binned together.
self.assertGreater(len(items), num_items / 10)
self.assertLess(len(items), num_items)
self.assertEquals(num_items, sum([i['add'] + i['drop'] for i in items]))
|
from django.shortcuts import redirect
from django.http import HttpResponseRedirect
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from django.views.generic import ListView
from django.urls import reverse_lazy
from django.contrib import messages
import datetime as dt
from .budget_business import BudgetCollection, NextMonthBudgetCreator
from .utilities import get_next_month
from .models import Budget
from .forms import BudgetForm
class BudgetListView(ListView):
model = Budget
template_name = "budget/budget_base_list.html"
ordering = ['-start_date', 'category__name']
budget_type = 0
def get_context_data(self, **kwargs):
ctx = super(BudgetListView, self).get_context_data(**kwargs)
ctx['fields'] = ['category', 'monthly_amount', 'start_date', 'freq_month' ]
if 'year' in self.kwargs:
start_date = "{}-{}".format(self.kwargs['year'],self.kwargs['month'])
ctx['allow_copy'] = False
if dt.datetime.strptime(start_date+"-1", "%Y-%m-%d").date() > dt.date.today():
ctx['allow_create'] = True
else:
start_date = dt.datetime.now().date().strftime('%Y-%m')
ctx['allow_copy'] = True
ctx['start_date'] = start_date
ctx['budget_type'] = self.budget_type
return ctx
def get_queryset(self):
qs = BudgetCollection.get_current_budget(self.budget_type)
if 'year' in self.kwargs and 'month' in self.kwargs:
y = self.kwargs['year']
m = self.kwargs['month']
start_date = dt.date(int(y), int(m), 1)
qs = Budget.objects.filter(category__type=self.budget_type)\
.filter(start_date=start_date)
return qs
def copyBudgetForm(request, type):
# if request.method == 'POST':
nextMonth = get_next_month().month
currYear =get_next_month().year
future_start_date = get_next_month()
added = NextMonthBudgetCreator.copy_current_budget(future_start_date,type)
messages.info(request, "{} number of budget items were copied".format(added))
if type==0:
return redirect('bunnySpend5:budget_list', year=currYear, month=nextMonth)
#or HttpRedirectResponse(reverse('bunnySpend5:budget_list', args=( currYear, nextMonth)))
else:
return redirect('bunnySpend5:budget_income_list', year=currYear, month=nextMonth)
class BudgetCreateView(CreateView):
budget_type =1
form_class = BudgetForm
template_name = 'budget/budget_create.html'
def get_form_kwargs(self):
kwargs = super(BudgetCreateView, self).get_form_kwargs()
kwargs.update({'budget_type': self.budget_type, 'min_start_date':get_next_month()})
return kwargs
def get_success_url(self):
if self.budget_type== 0:
return reverse_lazy('bunnySpend5:budget_list',
kwargs={'year': get_next_month().year, \
'month': get_next_month().month})
else:
return reverse_lazy('bunnySpend5:budget_income_list',
kwargs={'year': get_next_month().year, \
'month': get_next_month().month})
def get_context_data(self, **kwargs):
ctx = super(BudgetCreateView, self).get_context_data(**kwargs)
ctx['budget_type'] = self.budget_type
return ctx
#TODO initial field not showing, got overridden possibily
def get_form(self, form_class=None):
form = super().get_form(form_class)
form.initial['start_date'] = dt.datetime.strftime(\
get_next_month(prev=False), '%Y-%m-%d')
return form
class BudgetUpdateView(UpdateView):
# budget_type =0
model = Budget
form_class = BudgetForm
template_name = "budget/budget_edit.html"
# pass request args or other data as kwargs to BudgetForm creation
def get_form_kwargs(self):
kwargs = super(BudgetUpdateView, self).get_form_kwargs()
kwargs.update({'budget_type': self.kwargs['budget_type'], 'min_start_date':get_next_month()})
return kwargs
def get_context_data(self, **kwargs):
ctx = super(BudgetUpdateView, self).get_context_data(**kwargs)
ctx['budget_type'] = self.kwargs['budget_type']
return ctx
def get_success_url(self):
if self.kwargs['budget_type'] == 0:
return reverse_lazy('bunnySpend5:budget_list',
kwargs={'year': get_next_month().year, \
'month': get_next_month().month})
else:
return reverse_lazy('bunnySpend5:budget_income_list',
kwargs={'year': get_next_month().year, \
'month': get_next_month().month})
class BudgetDeleteView(DeleteView):
# success_url = reverse_lazy('bunnySpend5:budget_list',
# kwargs={'year': get_next_month().year, \
# 'month': get_next_month().month})
budget_type = 0
template_name = "budget/budget_delete.html"
model = Budget
def post(self, request, *args, **kwargs):
if "cancel" in request.POST:
self.object = self.get_object()
url = self.get_success_url()
return HttpResponseRedirect(url)
else:
return super(BudgetDeleteView, self).post(request, *args, **kwargs)
def get_success_url(self):
if self.budget_type == 0:
return reverse_lazy('bunnySpend5:budget_list',
kwargs={'year': get_next_month().year, \
'month': get_next_month().month})
else:
return reverse_lazy('bunnySpend5:budget_income_list',
kwargs={'year': get_next_month().year, \
'month': get_next_month().month})
|
import sys
from Foundation import NSObject, NSLog
from netrepr import NetRepr, RemoteObjectPool, RemoteObjectReference
__all__ = ["ConsoleReactor"]
class ConsoleReactor(NSObject):
def init(self):
self = super().init()
self.pool = None
self.netReprCenter = None
self.connection = None
self.commands = {}
return self
def connectionEstablished_(self, connection):
# NSLog(u'connectionEstablished_')
self.connection = connection
self.pool = RemoteObjectPool(self.writeCode_)
self.netReprCenter = NetRepr(self.pool)
def connectionClosed_(self, connection):
# NSLog(u'connectionClosed_')
self.connection = None
self.pool = None
self.netReprCenter = None
def writeCode_(self, code):
# NSLog(u'writeCode_')
self.connection.writeBytes_(repr(code) + "\n")
def netEval_(self, s):
# NSLog(u'netEval_')
return eval(s, self.pool.namespace, self.pool.namespace)
def lineReceived_fromConnection_(self, lineReceived, connection):
# NSLog(u'lineReceived_fromConnection_')
code = lineReceived.rstrip()
if not code:
return
self.pool.push()
command = map(self.netEval_, eval(code))
try:
self.handleCommand_(command)
finally:
self.pool.pop()
def handleCommand_(self, command):
# NSLog(u'handleCommand_')
basic = command[0]
sel = "handle%sCommand:" % (basic.capitalize())
cmd = command[1:]
if not self.respondsToSelector_(sel):
NSLog("%r does not respond to %s", self, command)
else:
self.performSelector_withObject_(sel, cmd)
getattr(self, sel.replace(":", "_"))(cmd)
def handleRespondCommand_(self, command):
self.doCallback_sequence_args_(
self.commands.pop(command[0]), command[0], map(self.netEval_, command[1:])
)
def sendResult_sequence_(self, rval, seq):
nr = self.netReprCenter
code = f"__result__[{seq!r}] = {nr.netrepr(rval)}"
self.writeCode_(code)
def sendException_sequence_(self, e, seq):
nr = self.netReprCenter
code = "raise " + nr.netrepr_exception(e)
print("forwarding:", code)
self.writeCode_(code)
def doCallback_sequence_args_(self, callback, seq, args):
# nr = self.netReprCenter
try:
rval = callback(*args)
except Exception as e:
self.sendException_sequence_(e, seq)
else:
self.sendResult_sequence_(rval, seq)
def deferCallback_sequence_value_(self, callback, seq, value):
self.commands[seq] = callback
self.writeCode_(f"pipe.respond({seq!r}, netrepr({value}))")
def handleExpectCommand_(self, command):
# NSLog(u'handleExpectCommand_')
seq = command[0]
name = command[1]
args = command[2:]
netrepr = self.netReprCenter.netrepr
if name == "RemoteConsole.raw_input":
self.doCallback_sequence_args_(input, seq, args)
elif name == "RemoteConsole.write":
self.doCallback_sequence_args_(sys.stdout.write, seq, args)
elif name == "RemoteConsole.displayhook":
obj = args[0]
def displayhook_respond(reprobject):
print(reprobject)
def displayhook_local(obj):
if obj is not None:
displayhook_respond(repr(obj))
if isinstance(obj, RemoteObjectReference):
self.deferCallback_sequence_value_(
displayhook_respond, seq, f"repr({netrepr(obj)})"
)
else:
self.doCallback_sequence_args_(displayhook_local, seq, args)
elif name.startswith("RemoteFileLike."):
fh = getattr(sys, args[0])
meth = getattr(fh, name[len("RemoteFileLike.") :]) # noqa: E203
self.doCallback_sequence_args_(meth, seq, args[1:])
elif name == "RemoteConsole.initialize":
self.doCallback_sequence_args_(lambda *args: None, seq, args)
else:
self.doCallback_sequence_args_(
NSLog, seq, ["%r does not respond to expect %r", self, command]
)
def close(self):
if self.connection is not None:
self.writeCode_("raise SystemExit")
self.pool = None
self.netReprCenter = None
self.connection = None
self.commands = None
|
from django.shortcuts import render, redirect, Http404
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth import login as _login
from django.contrib.auth import logout as _logout
from django.conf import settings
from appointment.forms.authentication import LoginForm, RegisterForm
from appointment.forms.profile import DoctorForm
REGISTRATION_TYPE_DOCTOR = 'doctor'
REGISTRATION_TYPE_PATIENT = 'patient'
def login(request):
"""
Login a User and return a page
:param request:
:return:
"""
if request.method == "POST":
form = LoginForm(request.POST)
username = request.POST.get("email")
password = request.POST.get("password")
if form.is_valid():
user = authenticate(username=username, password=password)
if user is not None:
_login(request, user)
return redirect("home_page")
else:
messages.error(request, "Invalid Email or Password")
return redirect("login")
template = "authentication/login.html"
form = LoginForm()
context = {
"form": form
}
return render(request, template, context)
def logout(request):
"""
Log user out and return the homepage
:param request:
:return:
"""
_logout(request)
return redirect("home_page")
def register(request):
"""
Register a user and return the profile page
:param request:
:return:
"""
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.email = form.cleaned_data.get("username")
user.set_password(form.cleaned_data.get("password"))
user.save()
registration_type = request.POST.get("registration_type")
if registration_type == REGISTRATION_TYPE_DOCTOR:
profile_form = DoctorForm({"user": user, "country": "GH"})
# import pdb; pdb.set_trace()
if profile_form.is_valid():
profile_form.save()
else:
import pdb; pdb.set_trace()
return redirect("home_page")
template = "authentication/register.html"
form = RegisterForm()
context = {
"form": form
}
return render(request, template, context)
|
from django.shortcuts import render
from trades.models import Trades
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.db.models import Max
from user.models import Profile
@login_required
def get_data(request):
trades = Trades.objects.filter(user_id=request.user.id).order_by('exit_date')
return JsonResponse(list(trades.values()), safe=False)
def get_max_pnl(request):
max_trade = Trades.objects.filter(user_id=request.user.id).aggregate(Max('pnl'))
return JsonResponse(max_trade, safe=False)
def index(request):
trades = Trades.objects.filter(user_id=request.user.id).order_by('id')[:4]
context = {
'trades': trades
}
return render(request, 'charts/charts.html', context)
def get_future_pnl(request):
user = Profile.objects.select_related('user_id').all()
return JsonResponse(list(user.values()), safe=False)
def get_winning_percentage(request):
wins = Trades.objects.filter(success="success").count()
loses = Trades.objects.filter(success="fail").count()
context = {
'wins': wins,
'losses': loses,
'percent': wins / (wins + loses)
}
return JsonResponse(context, safe=False) |
celebAction = input('Enter a verb...')
Celebrity = input('Please enter the name of a celebrity...')
Gender = input('is that a he, she or they?')
Animal = input('Please enter a type of animal...')
Verb = input('What is the animal doing...')
numberofAnimals = input('How many of them are there?')
print ("%s " "%s " "are" " %s" " %s " "while %s %ss" % (numberofAnimals, Animal, Verb, Celebrity, Gender, celebAction)) |
# formhandler/tpl.py
# Lillian Lemmer <lillian.lynn.lemmer@gmail.com>
#
# This module is part of FormHandler and is released under the
# MIT license: http://opensource.org/licenses/MIT
"""tpl: super simple templater.
"""
import os
TEMPLATE_ROOT = 'tpl'
def template(content, head_filename=None, foot_filename=None,
replacements=None):
"""A simple way to generate forms.
Args:
head_filename (str):
foot_filename (str):
replacements (dict): {find: replace}; requiers at least "content"
and likely that header uses "title".
"""
head_filename = head_filename or 'head-default.html'
foot_filename = foot_filename or 'foot-default.html'
head = open(os.path.join(TEMPLATE_ROOT, head_filename)).read()
foot = open(os.path.join(TEMPLATE_ROOT, foot_filename)).read()
pieces = {
'title': '',
'within head': '',
}
if replacements:
pieces.update(replacements)
pieces['head'] = head.format(**pieces)
pieces['foot'] = foot.format(**pieces)
pieces['content'] = content
return '''
{head}
<section id="content" class="content">
<h1>{title}</h1>
{content}
</section>
{foot}
'''.format(**pieces)
|
# Generated by Django 2.2.1 on 2019-05-08 03:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mm', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='song',
name='hotComment',
field=models.IntegerField(blank=True, null=True),
),
]
|
# -*- coding: utf-8 -*-
# Scrapy settings for Doubanspider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'Doubanspider'
SPIDER_MODULES = ['Doubanspider.spiders']
NEWSPIDER_MODULE = 'Doubanspider.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = 1
ITEM_PIPELINES = {
'Doubanspider.pipelines.DoubanspiderPipeline': 300,
}
MONGODB_HOST = '127.0.0.1'
MONGODB_PORT = 27017
MONGODB_DBNAME = 'DouBan'
MONGODB_DOCNAME = 'DouBanMoies'
|
#!/usr/bin/python
import sys
def compute(prey, otherHunter, dist):
temp0 = max( otherHunter[0] , otherHunter[0] )
temp1 = otherHunter[0] - otherHunter[0]
temp1 = min( prey[1] , dist )
if temp0 > prey[0] :
temp0 = otherHunter[1] - temp0
else:
if otherHunter[1] != 0:
temp0 = dist % otherHunter[1]
else:
temp0 = otherHunter[1]
temp1 = -1 * temp0
if otherHunter[0] != 0:
temp0 = prey[1] % otherHunter[0]
else:
temp0 = otherHunter[0]
temp1 = otherHunter[0] - prey[1]
if prey[0] != 0:
temp2 = otherHunter[0] / prey[0]
else:
temp2 = prey[0]
temp2 = prey[0] * temp0
temp0 = prey[1] + prey[0]
temp3 = min( temp0 , prey[0] )
temp4 = max( prey[1] , prey[1] )
if prey[1] != 0:
temp3 = dist % prey[1]
else:
temp3 = prey[1]
temp4 = temp3 * temp2
if temp2 > temp1 :
temp3 = otherHunter[1] * otherHunter[0]
else:
temp3 = max( temp3 , prey[0] )
if otherHunter[1] > temp1 :
if prey[0] > temp2 :
if prey[0] != 0:
temp5 = dist % prey[0]
else:
temp5 = prey[0]
else:
temp5 = prey[0] * temp3
else:
temp5 = -1 * otherHunter[0]
temp5 = min( prey[0] , otherHunter[1] )
return [ temp4 , temp0 ]
|
from flask import render_template, flash, redirect, session, url_for, request, abort
from flask.ext.login import login_user, logout_user, current_user, login_required
from smh import app, db, lm, blogic
from smh.forms import LoginForm, NameForm
from smh.models.models import User, Post
from datetime import datetime
from smh.auth import *
@app.route('/posts', methods=['GET', 'POST'])
@login_required
def posts():
all_user_posts = Post.query.all()
session_user_identity = User.query.filter_by(nickname="gogosanka").first()
session_user_posts = Post.query.filter_by(author=session_user_identity, rebin='false').all()
session_user_posts_count = Post.query.filter_by(author=session_user_identity, rebin='true').count()
session_user_recycled_posts = Post.query.filter_by(author=session_user_identity).all()
session_user_hidden_posts = Post.query.filter_by(author=session_user_identity, hidden='true').all()
user = 'temp' #create session logins and place user object here
return render_template('posts-test.html',
title="My Pages",
user=user,
post=session_user_posts,
count=session_user_posts_count)
@app.route('/bin', methods=['GET', 'POST'])
def bin():
session_user_identity = User.query.filter_by(nickname="gogosanka").first()
session_user_posts_count = Post.query.filter_by(author=session_user_identity, rebin='true').count()
session_user_recycled_posts = Post.query.filter_by(author=session_user_identity).all()
user = 'temp' #create session logins and place user object here
return render_template('bin.html',
title="Recycling Bin",
user=user,
post=session_user_recycled_posts,
count=session_user_posts_count)
@app.route('/update', methods=['POST'])
def update_post():
body = request.form['body']
author = request.form['author']
postid = request.form['postid']
title = request.form['title']
blogic.update(body,author,postid,title)
return redirect(url_for('posts'))
@app.route('/edit/<int:postid>/', methods=['GET'])
def edit(postid):
post_record = Post.query.get(postid)
if post_record:
return render_template('edit.html',
title="Edit DA Post",
post=post_record)
else:
return render_template('404.html')
@app.route('/show/<int:postid>/', methods=['GET'])
def show(postid):
post_record = Post.query.get(postid)
if post_record:
return render_template('show.html',
title="View Post",
post=post_record)
else:
return render_template('404.html')
@app.route('/delete/<postid>/', methods=['GET'])
def delete(postid):
post = Post.query.filter_by(id=postid).first()
if post:
blogic.delete(post)
return redirect(url_for('bin'))
else:
return render_template('404.html')
@app.route('/recycle/<postid>/', methods=['GET'])
def recycle(postid):
post = Post.query.filter_by(id=postid).first()
if post:
blogic.recycle(post)
return redirect(url_for('posts'))
else:
return render_template('404.html')
@app.route('/create', methods=['POST'])
def create():
post = request.form['body']
author = request.form['author']
title = request.form['title']
if post:
if author:
blogic.new(post,author,title)
return redirect(url_for('posts'))
else:
return render_template('404.html')
@app.route('/template')
def template():
return render_template('index2.html')
@app.route('/new')
def new():
session_user_identity = User.query.filter_by(nickname="gogosanka").first()
return render_template('create.html',
title="My Pages",
user = session_user_identity)
@app.route('/index')
def index():
author = 'temp'
return render_template('index.html',
title="Style Makeup Hair Magazine",
author=author)
@app.route('/')
@auth.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
return render_template(url_for('posts'))
return url_for('404')
return render_template('auth/login.html',
form=form)
@app.route('/js')
def js():
return "/static/style/js"
@app.route('/css')
def css():
return "/static/style/css/"
if __name__ == '__main__':
app.run() |
import re
from collections import defaultdict
import argparse
import os
from numpy.random import shuffle
def read_examples(f):
example_lines = []
for line in f.readlines():
if line.strip() == '':
if example_lines:
yield Example.from_lines(example_lines)
example_lines = []
else:
continue
else:
example_lines.append(line)
if example_lines:
yield Example.from_lines(example_lines)
def parse_metadata(line):
match = re.match(r"\#\s*(\S+)\s*\=\s*\'(.*)\'", line)
if not match:
print(line)
return match.group(1), match.group(2)
class Example():
def __init__(self, example_id, corpus, modification, show_comment,
utts, break_points):
assert all(p <= len(utts) for p in break_points)
self.id = example_id
self.corpus = corpus
self.modification = modification
self.show_comment = show_comment
self.utts = utts
self.break_points = break_points
@classmethod
def from_lines(cls, lines):
utts = []
metadata = {}
break_points = []
for line in lines:
if line.startswith('#'):
key, value = parse_metadata(line)
metadata[key] = value
elif line.startswith('*'):
break_points.append(len(utts))
utts.append(Utt.from_line(line[1:]))
else:
utts.append(Utt.from_line(line))
example_id = metadata.get('id')
corpus = metadata.get('corpus')
modification = metadata.get('modification')
show_comment = metadata.get('show_comment')
return cls(example_id, corpus, modification, show_comment, utts, break_points)
class Utt():
def __init__(self, speaker, text):
self.speaker = speaker
self.text = text
@classmethod
def from_line(cls, line):
line = line.strip()
try:
speaker, text = line.split('\t')
except ValueError as e:
embed()
raise ValueError(f"Malformated utterance line: {line}\n{e}")
return cls(speaker, text)
def __str__(self):
return f"{self.speaker}\t{self.text}"
parser = argparse.ArgumentParser(description='Simple CLI for collecting dialogue NLI annotations.')
parser.add_argument('input_file', type=str,
help='Formatted corpus file to be annotated.')
parser.add_argument('--output-file', type=str, default='output.txt',
help='Destination for the annotation output.')
parser.add_argument('--incremental', dest='incremental', action='store_true')
parser.add_argument('--no-incremental', dest='incremental', action='store_false')
parser.add_argument('--sample', type=int, default=1000)
parser.set_defaults(feature=False)
args = parser.parse_args()
if __name__ == '__main__':
args = parser.parse_args()
print_metadata = True #TODO: Make cli option?
annotations = {}
annotation_prompts = [('Entailment', 'two statements that the last speaker would take to be true at this point in the dialogue'),
('Contradiction', 'two statements that the last speaker would take to not be true at this point in the dialogue'),
('Neutral','two statements for which there is no evidence that the last speaker would take to be true or false at this point in the dialogue')]
if os.path.exists(args.output_file):
overwrite = input(f"The output file {args.output_file} already exsits. Are you sure you want to overwrite it? (Y/n))\n> ")
if not overwrite.lower() == 'y':
exit()
# save dialogues for nicer output
dialogues_with_annot = []
with open(args.input_file, 'r') as f:
data = [x for x in read_examples(f)]
shuffle(data)
data = data[:args.sample] # just select all samples if not sampling... default = 1000
for example in data:
dialogues_with_annot.append([f'# example id: {example.id}'])
annotations[example.id] = defaultdict(list)
if print_metadata:
print('# example id:', example.id)
print('# corpus:', example.corpus)
print('# modification:', example.modification)
print('# show_comment:', example.show_comment)
for i, utt in enumerate(example.utts):
print(utt)
dialogues_with_annot[-1].append('\t'.join([utt.speaker, utt.text]))
if i in example.break_points: # ???
#shuffle(annotation_prompts)
for label, prompt in annotation_prompts:
print(f'> Please provide {prompt}')
for i in range(2): # collect two annotations for each prompt
annotation = input(f"> {i+1}: ")
dialogues_with_annot[-1].append(f'> {label} {annotation}')
annotations[example.id][i].append((label, annotation))
elif args.incremental:
input()
print()
with open(args.output_file, 'w') as f: #TODO: make output file name cli argument?
for dialogue in dialogues_with_annot:
for line in dialogue:
f.write(line+'\n')
f.write('\n')
#f.write(str(annotations)) #TODO: format nicely |
import numpy as np
def trimboth(a, proportiontocut, axis=0):
"""
Slices off a proportion of items from both ends of an array.
Slices off the passed proportion of items from both ends of the passed
array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
rightmost 10% of scores). The trimmed values are the lowest and
highest ones.
Slices off less if proportion results in a non-integer slice index (i.e.,
conservatively slices off`proportiontocut`).
Parameters
----------
a : array_like
Data to trim.
proportiontocut : float
Proportion (in range 0-1) of total data set to trim of each end.
axis : int or None, optional
Axis along which to trim data. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
out : ndarray
Trimmed version of array `a`. The order of the trimmed content
is undefined.
See Also
--------
trim_mean
Examples
--------
>>> from scipy import stats
>>> a = np.arange(20)
>>> b = stats.trimboth(a, 0.1)
>>> b.shape
(16,)
"""
a = np.asarray(a)
if a.size == 0:
return a
if axis is None:
a = a.ravel()
axis = 0
nobs = a.shape[axis]
lowercut = int(proportiontocut * nobs)
uppercut = nobs - lowercut
if (lowercut >= uppercut):
raise ValueError("Proportion too big.")
atmp = np.partition(a, (lowercut, uppercut - 1), axis)
sl = [slice(None)] * atmp.ndim
sl[axis] = slice(lowercut, uppercut)
return atmp[sl]
|
from ProblemConfigurations.Hallway import generate_hallway_problem, generate_hallway_reeb_graph
import matplotlib.pyplot as plt
from Drawing import draw_problem_configuration
from DRRRT import augment_reeb_graph
environment, robot, start, goal = generate_hallway_problem()
reeb_graph = generate_hallway_reeb_graph()
draw_problem_configuration(environment, robot, start, goal, draw_robot=False)
reeb_graph.draw("green")
plt.show()
reeb_graph, start_node, goal_node = augment_reeb_graph(environment, start, goal,
link_step_size=0.001 * environment.width,
reeb_graph=reeb_graph,
connection_distance_threshold=0.25 * environment.width)
# reeb_graph = prune_reeb_graph(reeb_graph, goal_node)
draw_problem_configuration(environment, robot, start, goal, draw_robot=False)
reeb_graph.draw('green')
plt.show()
|
"""TDGam Component, sub-class of TDGamContainer."""
import re
import json
import logging
from pprint import pformat
from .plugins import TouchDesigner
from .container import TDGamContainer
class TDGamComponent(TDGamContainer):
"""Class to interface with the selection of ops by the user.
These ops need to be converted to JSON and destroyed, then
re-created again on the fly. This class is only responsible for
dealing with functionality on the selection of ops and their data.
This class is intended as the main interface with the user and
their application.
"""
def __init__(self, selection, name):
"""Create a component from the selected ops.
:param selection: List of selected td.OP instances.
:type selection: list of td.OP
:param data: Properties for creation.
:type data: dict
:param name: Name of the Component.
:type name: str
"""
super(TDGamComponent, self).__init__(name)
if not selection:
logging.error("Nothing selected!")
self.type = "touchdesigner" # planning ahead for Nuke UI...
# convert raw selection into useable TDGamComponentUI dict.
self.selection = self.convert_selection(selection)
self.parent_op = selection[0].parent()
self.__setup()
def __repr__(self):
return "<TDGamConponent: {name}, {repo_dir}>".format(
name=self.name,
repo_dir=self.folder())
def rip_node_params(self):
"""Convert the current selection into tdgam ParDict.
:return: the ripped params in dict form.
:rtype: dict
"""
params = []
for op_dict in self.selection:
op_dict_as_string = str(op_dict).replace("\"", re.escape("\""))
op_dict_as_string = op_dict_as_string.replace("'", "\"")
logging.debug(pformat(op_dict))
try:
params.append(json.loads(op_dict_as_string))
except json.decoder.JSONDecodeError as e:
logging.exception("FAILED ON {}".format(op_dict["path"]))
logging.debug(op_dict)
return params
def __setup(self):
"""Create necessary directory tree and repo."""
self.create_json_stash(self.folder(), self.rip_node_params())
# init git repo for this component's folder
self.init_repo(self.folder())
def convert_selection(self, selection):
"""Pull what we need from the original operator instances.
:return: list of parameter-dicts pulled from the selection
:rtype: list
"""
converted_selection = []
if self.type == "touchdesigner":
touch_designer = TouchDesigner()
converted_selection = touch_designer.convert_to_tdgam_data(
selection, recurse=True)
return converted_selection
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 11 08:29:29 2021
Autores:
SANTIAGO GAONA CARVAJAL
LUIS DIAZ DIAZ
"""
from timeit import default_timer
def fib(n): #Funcion Fibonacci Iterativo
terminos = [0,1]
i = 2
while i <= n:
terminos.append(terminos[i-1]+terminos[i-2]) #Fibonacci
i = i + 1
return terminos[n]
def fibonacci_recursivo(n): #Fibonacci Recursivo
if n == 0 or n == 1:
return n
else:
return fibonacci_recursivo(n - 1) + fibonacci_recursivo(n - 2) #Fibonacci
def suma_lista_100(a,b,c): #sumaLista100
for i in range(len(a)):
Suma_lista.append((a[i]+b[i]+c[i])/3) #Promedio de las 3 listas
return Suma_lista
Suma_lista = []
def suma_lista_100k(a,b,c):#sumaLista100K
for i in range(len(a)):
Suma_listak.append((a[i]+b[i]+c[i])/3) #Promedio de las 3 listas
return Suma_listak
Suma_listak = []
def proceso_cien():#ProcesoCien
#100 primeros
m = 0 #Medición 1,2,3
medicion1 = []
medicion2 = []
medicion3 = []
while m < 3:
m=m+1
x = 0 #Número de la sucesión
while x < 100:
inicio = default_timer() * 1000
fib(x)
fin = default_timer() * 1000
tiempo = fin - inicio
x=x+1
if m == 1:
medicion1.append(tiempo)
if m == 2:
medicion2.append(tiempo)
if m == 3:
medicion3.append(tiempo)
suma_lista_100(medicion1, medicion2, medicion3)
f = open("ProcesoCien.txt", "a")#Nombre del archivo de 1 a 100 datos de la sucesión.
for i in Suma_lista:
f.write((str(i))+"\n")
f.close()
def proceso_100k():#Proceso100k
k = 0 # k = cantidad de mediciones
contador = 0
medicion_1 = []
medicion_2 = []
medicion_3 = []
while k < 3:
k=k+1
contador = 0
while contador < 100000:#100k
contador = contador + 200 #200 en 200 hasta sucesion 100.000 Fib
if contador < 100000:#100k
inicio = default_timer() * 1000
fib(contador-1)
fin = default_timer() * 1000
tiempo = fin - inicio
if k == 1:
medicion_1.append(tiempo)
if k == 2:
medicion_2.append(tiempo)
if k == 3:
medicion_3.append(tiempo)
else:
inicio = default_timer() * 1000
fib(contador-1)
fin = default_timer() * 1000
tiempo = fin - inicio
if k == 1:
medicion_1.append(tiempo)
if k == 2:
medicion_2.append(tiempo)
if k == 3:
medicion_3.append(tiempo)
suma_lista_100k(medicion_1, medicion_2, medicion_3)
f = open("Nombre_archivo.txt", "a")#Iterativo_Ultimo2 ANAHSE
for i in Suma_listak:
f.write((str(i))+"\n")
f.close()
proceso_cien()
proceso_100k()
|
#!/usr/bin/env python3
import math
import random
import sys
# enumerate(A[1:],1) the second 1 means the index start from 1
# because of the slice, the first item in A is excluded, you need the start=1
# so the index is the same as the index of A.
def buy_and_sell_stock_twice(prices):
max_total_profit, min_price_so_far = 0.0, float('inf')
first_buy_sell_profits = [0] * len(prices)
# Forward phase. For each day, we record maximum profit if we sell on that
# day. (Could be 0, which means buy and sell once is the best solution.)
for i, price in enumerate(prices):
min_price_so_far = min(min_price_so_far, price)
max_total_profit = max(max_total_profit, price - min_price_so_far)
first_buy_sell_profits[i] = max_total_profit
# Backward phase. For each day, find the maximum profit if we make the
# second buy on that day. (Also could be 0)
max_price_so_far = float('-inf')
for i, price in reversed(list(enumerate(prices[1:], 1))):
max_price_so_far = max(max_price_so_far, price)
max_total_profit = max(max_total_profit, max_price_so_far - price +
first_buy_sell_profits[i - 1])
return max_total_profit
# O(n) timing, and O(1) space
# Equivalent to the following (the sequence just assure non-blocking assignment)
# max_profits[1] = max(<itself>, price - min_prices[1])
# min_prices[1] = min(<itself>, price - max_profits[0])
# max_profits[0] = max(<itself>, price - min_prices[0])
# min_prices[0] = min(<itself>, price)
# The min_prices is the cost, max_profits is the profit,
# The 1st buy's cost is just the price,
# the 2nd buy's cost is price - 1st buy's profit.
# the 1st buy's profit is current price -1st buy's cost
# the 2nd buy's profit is current price -2nd buy's cost
# The final result (the return value) is max_profits[1]
def buy_and_sell_stock_twice_constant_space(prices):
min_prices, max_profits = [float('inf')] * 2, [0] * 2
for price in prices:
for i in reversed(list(range(2))):
max_profits[i] = max(max_profits[i], price - min_prices[i])
min_prices[i] = min(min_prices[i],
price - (0 if i == 0 else max_profits[i - 1]))
return max_profits[-1]
def main():
for _ in range(1000):
n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 100)
a = [random.uniform(0, 10000) for _ in range(n)]
assert math.isclose(
buy_and_sell_stock_twice_constant_space(a),
buy_and_sell_stock_twice(a))
if __name__ == '__main__':
main()
|
import os
import zipfile
import random
import json
import paddle
import sys
import numpy as np
from PIL import Image
from PIL import ImageEnhance
import paddle.fluid as fluid
from multiprocessing import cpu_count
import matplotlib.pyplot as plt
from model import VGGNet
from data_processor import *
def load_image(img_path):
'''
预测图片预处理
'''
img = Image.open(img_path)
if img.mode != 'RGB':
img = img.convert('RGB')
img = img.resize((224, 224), Image.BILINEAR)
img = np.array(img).astype('float32')
img = img.transpose((2, 0, 1)) # HWC to CHW
img = img / 255 # 像素值归一化
return img
label_dic = train_parameters['label_dict']
'''
模型预测
'''
with fluid.dygraph.guard():
model, _ = fluid.dygraph.load_dygraph("vgg")
vgg = VGGNet()
vgg.load_dict(model)
vgg.eval()
# 展示预测图片
infer_path = '/home/aistudio/data/data23615/infer_mask01.jpg'
img = Image.open(infer_path)
plt.imshow(img) # 根据数组绘制图像
plt.show() # 显示图像
# 对预测图片进行预处理
infer_imgs = []
infer_imgs.append(load_image(infer_path))
infer_imgs = np.array(infer_imgs)
for i in range(len(infer_imgs)):
data = infer_imgs[i]
dy_x_data = np.array(data).astype('float32')
dy_x_data = dy_x_data[np.newaxis, :, :, :]
img = fluid.dygraph.to_variable(dy_x_data)
out = vgg(img)
lab = np.argmax(out.numpy()) # argmax():返回最大数的索引
print("第{}个样本,被预测为:{}".format(i + 1, label_dic[str(lab)]))
print("结束") |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 18 09:11:33 2017
@author: beoka
"""
import numpy as np
import App
import Vector
import Body
from PIL import Image
import struct
Q = Vector.Quaternion.fromArray
from pybullet import getQuaternionFromEuler as eToQ
class Level(object):
""" Houses all the code necessary for building sprites, determining the
speed and location of bodies, etc. Basically builds the game world.
"""
def __init__(self, imagesDirectory, level, ctx):
self.level = level
self.imagesDirectory = imagesDirectory
self.ctx = ctx
self.listOfEntities = []
self.l, self.r, self.t, self.b, self.f, self.a, = [None]*6
self.gravity = True
self.box = False
# This runs level#() without having to do a bunch of if statements
getattr(self,'level'+str(level))()
def getAttributes(self):
return self.listOfEntities, self.l, self.r, self.t, self.b, self.f, self.a, self.box, self.gravity
def level1(self):
"""
"""
self.level=1
##### Parameters for Autobuilder #####
M =2.*10**34
smallM =[2.*10**27, 7.*10**22]
a =[4.0*10**11, 3.0*10**10.3]
e =[0,0]
imageString = [self.imagesDirectory + "ganymedeSmall.png",
self.imagesDirectory + "gasPlanetSmall.png"]
##### Parameters for Manual builder #####
mass=[M, 1*10**23 , 1*10**24 , 1*10**25 , 1*10**26 ]
xPos=[0, 1*10**11, -1*10**11, 2.*10**11, 3.*10**11]
yPos=[0, 0, 0, 0, 0 ]
zPos=[0, 0, 0, 0, 0 ]
vel=self.orbVel(M,np.array(mass[1:]),np.array(xPos[1:]))
xVel=[0, 0, 0, 0, 0 ]
yVel=[0, vel[0], -vel[1], vel[2], vel[3] ]
zVel=[0, 0, 0, 0, 0 ]
imageString2 =[self.imagesDirectory + "blackhole.png",
self.imagesDirectory + "planetSmall.png",
self.imagesDirectory + "planet2Small.png",
self.imagesDirectory + "planet3Small.png",
self.imagesDirectory + "planet4Small.png"]
##### Build Rocket #####
mRocket = [6.*10**30]
xRocket,yRocket,zRocket = [5.0*10**11], [0], [0]
vxRocket,vyRocket,vzRocket = [0],[self.orbVel(M,mRocket[0],
xRocket[0])],[0]
rocketImage = [self.imagesDirectory + "shipSmall.png"]
self.rocketImageOrig=pg.image.load(rocketImage[0])
self.genSpriteAndBodManual(xRocket,yRocket,zRocket,
vxRocket,vyRocket,vzRocket,
mRocket,rocketImage)
self.rocketOnImage=pg.image.load(self.imagesDirectory + "shipSmallThrusting.png")
self.rocketOnImageOrig=pg.image.load(self.imagesDirectory + "shipSmallThrusting.png")
##### Initialize ship characteristics #####
self.listOfSprites[0].angle = 0
self.listOfSprites[0].thrust = 20000.
##### Build bodies #####
self.genSpriteAndBodManual(xPos, yPos, zPos, xVel, yVel, zVel, mass,
imageString2)
# self.genSpriteAndBod(smallM,e,M,a,imageString,
# moon=True,keepCentral=False)
##### Make central body a black hole and ship the 'main body' #####
self.listOfSprites[1].blackHole = True
def level2(self):
""" Solar System!
"""
self.level=2
##### Parameters for Manual builder #####
mass=[1.989*10**30, 3.285*10**23, 4.867*10**24, 5.972*10**24, 6.39*10**23, 1.898*10**27, 5.683*10**26, 8.681*10**25, 1.024*10**26]
xPos=[0, 57.9*10**9, 108.2*10**9, 149.6*10**9, 227.9*10**9, 778.3*10**9, 1427.0*10**9, 2871.0*10**9, 4497.1*10**9]
yPos=[0, 0, 0, 0, 0, 0, 0, 0, 0, ]
zPos=[0, 0, 0, 0, 0, 0, 0, 0, 0, ]
vel=self.orbVel(1.989*10**30,np.array(mass[1:]),np.array(xPos[1:]))
# print vel
xVel=[0, 0, 0, 0, 0, 0, 0, 0, 0, ]
yVel=[0, vel[0], vel[1], vel[2], vel[3], vel[4], vel[5], vel[6], vel[7] ]
zVel=[0, 0, 0, 0, 0, 0, 0, 0, 0, ]
imageString =[self.imagesDirectory + 'sun.png',self.imagesDirectory + 'mercurySmall.png',self.imagesDirectory + 'venusSmall.png',
self.imagesDirectory + 'earthSmall.png',self.imagesDirectory + 'marsSmall.png',self.imagesDirectory + 'jupiterSmall.png',
'saturn.png',self.imagesDirectory + 'uranusSmall.png',self.imagesDirectory + 'neptuneSmall.png']
##### Build Rocket #####
mRocket = [2030.*10**3]
xRocket,yRocket,zRocket = [5.0*10**10], [0], [0]
vxRocket,vyRocket,vzRocket = [0],[self.orbVel(1.989*10**30,mRocket[0],
xRocket[0])],[0]
rocketImage = [self.imagesDirectory + "shipSmall.png"]
self.rocketImageOrig=pg.image.load(rocketImage[0])
self.genSpriteAndBodManual(xRocket,yRocket,zRocket,
vxRocket,vyRocket,vzRocket,
mRocket,rocketImage)
self.rocketOnImage=pg.image.load(self.imagesDirectory + "shipSmallThrusting.png")
self.rocketOnImageOrig=pg.image.load(self.imagesDirectory + "shipSmallThrusting.png")
##### Initialize ship characteristics #####
self.listOfSprites[0].angle= 0
self.listOfSprites[0].thrust = 20000.
##### Build bodies #####
self.genSpriteAndBodManual(xPos, yPos, zPos, xVel, yVel, zVel, mass,
imageString)
##### Make central body a black hole and ship the 'main body' #####
self.listOfSprites[1].blackHole = True
def level3(self):
""" Random assortment of planets
"""
self.level=3
mass=[1*10**23,1.*10**22,1.*10**20,1.*10**20, 1.*10**22]
xPos=[0,-5.*10**8,-2.*10**8,2.*10**8,5.*10**8]
yPos=[0,0,0,2.*10**8,0]
zPos=[0,0,0,0,0]
xVel=[0,0,10.,0,0]
yVel=[0,15.,10.,10.,-15.]
zVel=[0,0,0,0,0]
imageString = [self.imagesDirectory + 'jupiterSmall.png',self.imagesDirectory + 'uranusSmall.png',self.imagesDirectory + 'marsSmall.png',
self.imagesDirectory + 'venusSmall.png',self.imagesDirectory + 'neptuneSmall.png']
self.genSpriteAndBodManual(xPos,yPos,zPos,xVel,yVel,zVel,mass,imageString)
self.listOfSprites[0].mainBody=True
self.f=-3.*10**8
self.c=3.*10**8
self.r=6.*10**8
self.l=-6.*10**8
self.box = True
def level4(self):
""" Earth in the middle, neptune and uranus come in on both sides
"""
self.level=4
mass=[8.681*10**25, 1.024*10**26,5.972*10**24]
xPos=[-5.*10**8,5.*10**8,0]
yPos=[0,0,0]
zPos=[0,0,0]
xVel=[1500.,-1500.,0]
yVel=[0,0,0]
zVel=[0,0,0]
imageString = [self.imagesDirectory + 'uranusSmall.png',self.imagesDirectory + 'neptuneSmall.png',
self.imagesDirectory + 'earthSmall.png']
self.genSpriteAndBodManual(xPos,yPos,zPos,xVel,yVel,zVel,mass,imageString)
self.listOfSprites[0].mainBody=True
self.f=-3.*10**8
self.c=3.*10**8
self.r=6.*10**8
self.l=-6.*10**8
self.box = True
def level5(self):
""" 3 balls equal in size and mass meet in the same frame in the center
"""
self.level=5
mass=[1.,1.,1.]
xPos=[-1.,1.,0]
yPos=[0,0,1.]
zPos=[0,0,0]
xVel=[0,0,0]
yVel=[0,0,0]
zVel=[0,0,0]
imageString = [self.imagesDirectory + 'neptuneSmall.png',self.imagesDirectory + 'neptuneSmall.png',self.imagesDirectory + 'neptuneSmall.png']
self.genSpriteAndBodManual(xPos,yPos,zPos,xVel,yVel,zVel,mass,imageString)
self.listOfSprites[0].mainBody=True
self.f=-3.7
self.c=3.7
self.r=7.
self.l=-7.
def level6(self):
""" 2 boxes
"""
self.level=6
self.box = False
self.gravity=True
size = [[.1,.1,.1],[.1,.1,.1]]
mass = [.2,.2]
Ibody = [self.momentInertiaCube(size[i],mass[i]) for i in range(len(mass))]
x=[np.array((0,0.3,0)),
np.array((0,-0.30,0))]
# q=[Vector.Quaternion(1,np.array([0,0,0])).normalize(),
# Vector.Quaternion(1,np.array([0,0,0])).normalize()]
q=[Vector.Quaternion.fromPyBulletEuler(eToQ((np.pi/4, 0, np.pi/4))), Vector.Quaternion.fromPyBulletEuler(eToQ((0, 0, 0)))]
P=[np.array((.0, -1, 0)),
np.array((.0,1,0))]
L=[np.array((0.0,0, 0.01)),
np.array((0.05,.01,0))]
images = [self.imagesDirectory + 'purmesh.jpg']
for i in range(len(images)):
img = Image.open(images[i]).convert('RGBA')
tex = self.ctx.texture(img.size, 4, img.tobytes())
tex.use(i)
imageIndex = [0,0]
entityTypes = ['box']*2
self.genSpriteAndBodManualQ(mass,Ibody,x,q,P,L,imageIndex,size,entityTypes)
def level7(self):
""" A 4 body system of spheres
"""
self.level=7
self.box = True
self.gravity=True
self.setWalls([-1,1,1,-1,1,-1])
# print('floor position is ' + str(self.f))
size = [[.03]*3,[.03]*3,[.1]*3,[.05]*3]
mass = [.2,.2,.1,.1]
Ibody = [2/5*mass[i]*(size[i][0]**2+size[i][1]**2)*
np.array(([1,0,0],[0,1,0],[0,0,1])) for i in range(len(mass))]
x=[np.array((.1, 0, 0)), np.array((-.1,0,0)), np.array((0,-.3,0)),np.array((.4,0,0))]
q=[Vector.Quaternion.fromMatrix(np.array(([0,0,0],[0,0,0],[0,0,0])))]*len(mass)
P=[np.array((0, .1, 0)), np.array((0,-.2,0)),np.array((.045,0,0)),np.array((0,0,0))]
L=[np.array((.0, .0, .01)),np.array((0,0,.1)),np.array((0,0,-.1)),np.array((0,0,0))]
images = [self.imagesDirectory + 'purmesh.jpg', self.imagesDirectory + 'wood.jpg']
for i in range(len(images)):
img = Image.open(images[i])
tex = self.ctx.texture(img.size, 3, img.tobytes())
tex.build_mipmaps()
tex.use(i)
imageIndex = [0,0,1,1]
entityTypes = ['ball']*4
self.genSpriteAndBodManualQ(mass,Ibody,x,q,P,L,imageIndex,size,entityTypes)
def level8(self):
""" A 3 body system
"""
self.level=8
mass = [.1,.1,.5]
Ibody = [m/12*np.array(([1,0,0],[0,1,0],[0,0,1])) for m in mass]
x=[np.array((.1, 0, 0)), np.array((-.1,0,0)), np.array((0,-.5,0))]
q=[Vector.Quaternion.fromMatrix(np.array(([0,0,0],[0,0,0],[0,0,0])))]*3
P=[np.array((-.06, .0, 0)), np.array((0,-.01,0)),np.array((.019,0,0))]
L=[np.array((.0, .0, .0)),np.array((0,0,-.4)),np.array((0,0,0))]
images = [self.imagesDirectory + 'purmesh.jpg', self.imagesDirectory + 'crate.png']
size = [[.03,.03,.03],[.04,.04,.04],[.1,.1,.1]]
self.gravity=True
for i in range(len(images)):
img = Image.open(images[i]).convert('RGBA')
tex = self.ctx.texture(img.size, 4, img.tobytes())
tex.use(i)
imageIndex = [1,1,0]
entityTypes = ['box', 'box', 'ball']
self.genSpriteAndBodManualQ(mass,Ibody,x,q,P,L,imageIndex,size,entityTypes)
def level9(self):
""" two planets along the y axis
"""
self.level=9
mass = [.1]*3
Ibody = [mass[0]/12*np.array(([1,0,0],[0,1,0],[0,0,1]))]*3
x=[np.array((0, -.2, 0)), np.array((0,.2,0)), np.array((0.2,0,0))]
q=[Vector.Quaternion.fromMatrix(np.array(([0,0,0],[0,0,0],[0,0,0])))]*3
P=[np.array((.0, .0, 0)), np.array((-.0,0,0)),np.array((0,0,0))]
L=[np.array((.0, .0, 0)),np.array((0,0,5)),np.array((.0, .0, 0))]
images = [self.imagesDirectory + 'purmesh.jpg', self.imagesDirectory+'wood.jpg']
size = [[.1,.1,.1]]*3
self.gravity=True
for i in range(len(images)):
# print( i)
img = Image.open(images[i]).convert('RGBA')
tex = self.ctx.texture(img.size, 4, img.tobytes())
tex.use(i)
imageIndex = [0,1,1]
entityTypes = ['box']*3
self.genSpriteAndBodManualQ(mass,Ibody,x,q,P,L,imageIndex,size,entityTypes)
def level10(self):
""" A bunch of small balls
"""
self.level = 10
self.box=True
self.l, self.r, self.t, self.b, self.f, self.a = [-1, 1, 1, -1, 1, -1]
n = 50
mass = [1]*n
r = 1/n
Ibody = [self.momentInertiaSphere(mass[0],r)]*n
x=[np.array([2*np.random.random()-1,
2*np.random.random()-1,
0
]) for i in range(n)]
q=[Vector.Quaternion.fromMatrix(np.array(([0,0,0],[0,0,0],[0,0,0])))]*n
P=[np.array([np.random.random()*(-1)**i/10,
np.random.random()*(-1)**i/10,
0
]) for i in range(n)]
L=[np.array([0,0,0])]*n
images = [self.imagesDirectory + 'purmesh.jpg']
size = [np.array([r]*3)]*n
self.gravity=True
for i in range(len(images)):
img = Image.open(images[i]).convert('RGBA')
tex = self.ctx.texture(img.size, 4, img.tobytes())
tex.use(i)
imageIndex = [0]*n
entityTypes = ['ball']*n
self.genSpriteAndBodManualQ(mass,Ibody,x,q,P,L,imageIndex,size,entityTypes)
def level11(self):
""" A bunch of small cubes
"""
self.level = 10
self.box=True
self.l, self.r, self.t, self.b, self.f, self.a = [-1, 1, 1, -1, 1, -1]
n = 50
mass = [1]*n
r = 1/n
Ibody = [self.momentInertiaSphere(mass[0],r)]*n
x=[np.array([2*np.random.random()-1,
2*np.random.random()-1,
0
]) for i in range(n)]
q=[Vector.Quaternion.fromMatrix(np.array(([0,0,0],[0,0,0],[0,0,0])))]*n
P=[np.array([np.random.random()*(-1)**i/10,
np.random.random()*(-1)**i/10,
0
]) for i in range(n)]
L=[np.array([0,0,0])]*n
images = [self.imagesDirectory + 'crate.png']
size = [np.array([r]*3)]*n
self.gravity=True
for i in range(len(images)):
img = Image.open(images[i]).convert('RGBA')
tex = self.ctx.texture(img.size, 4, img.tobytes())
tex.use(i)
imageIndex = [0]*n
entityTypes = ['box']*n
self.genSpriteAndBodManualQ(mass,Ibody,x,q,P,L,imageIndex,size,entityTypes)
@staticmethod
def orbVel(m1, m2, r):
""" Automatically calculates orbital velocities needed to make a
circular orbit around the central body. This velocity can easily be
adjusted to get more elliptical orbits.
Parameters
-----
m1 : float
Mass of one body (usually the central mass).
m2 : float
Mass of the other body (usually the mass of the orbiting body).
r : float
The distance between the orbiting body and the center of mass.
"""
r=abs(r)
G=6.6408*10**-11
return (G*(m1+m2)/r)**0.5
def genSpriteAndBodManualQ(self, mass,Ibody,x,q,P,L, imageIndex,size,entityTypes):
""" Generates new bodies and sprites with a manual set of parameters.
Parameters
-----
xPos : list of float
A list of all the x position values of the bodies being created.
yPos : list of float
A list of all the y position values of the bodies being created.
zPos : list of float
A list of all the z position values of the bodies being created.
xPos : list of float
A list of all the x velocity values of the bodies being created.
yPos : list of float
A list of all the y velocity values of the bodies being created.
zPos : list of float
A list of all the z velocity values of the bodies being created.
mass : list of float
A list of all the masses for each body being created
imageString : list of strings
A list of all the strings of the image file names for each body.
"""
bodies = self.manualOrbitBuilderQ(mass,Ibody,x,q,P,L)
for i in range(len(mass)):
rectInfo=size[i]
radius=rectInfo[0]
bodies[i].radius=radius
self.listOfEntities.append(App.SimEntity(bodies[i],imageIndex[i],entityTypes[i],rectInfo))
@staticmethod
def closed2BodyAutoBuilder(omega,i,mBig,mSmall,ap,e):
"""
"""
G = 1 #6.67408*10**(-11)
vp=np.sqrt(G*mBig**3*(1+e)/(ap*(mSmall+mBig)**2*(1-e)))
vs=-(mSmall/mBig)*vp
rp=ap-ap*e
rs=-(mSmall/mBig)*rp
body1x=rp
body1y=0
body1z=0
body1pos=Vector.Vector(x=body1x,y=body1y,z=body1z)
body1pos.rotZ(omega)
body1pos.rotX(i)
body2x=rs
body2y=0
body2z=0
body2pos=Vector.Vector(x=body2x,y=body2y,z=body2z)
body2pos.rotZ(omega)
body2pos.rotX(i)
body1vx=0
body1vy=vp
body1vz=0
body1vel=Vector.Vector(x=body1vx,y=body1vy,z=body1vz)
body1vel.rotZ(omega)
body1vel.rotX(i)
body2vx=0
body2vy=vs
body2vz=0
body2vel=Vector.Vector(x=body2vx,y=body2vy,z=body2vz)
body2vel.rotZ(omega)
body2vel.rotX(i)
body1=Body.GravBody(body1vel,body1pos,mSmall)
body2=Body.GravBody(body2vel,body2pos,mBig)
bodies=[body1,body2]
return bodies
@staticmethod
def manualOrbitBuilderQ(mass, Ibody, x, q, P, L):
"""
"""
bodies=[]
for i in range(len(mass)):
body = Body.RigidBody(mass[i],Ibody[i],Q(x[i]),q[i],Q(P[i]),Q(L[i]))
bodies.append(body)
return bodies
@staticmethod
def momentInertiaCube(size,mass):
mInertia = mass*size[0]**2/6*np.identity(3)
return mInertia
@staticmethod
def momentInertiaRectPrism(size, mass):
l = size[0]
w = size[1]
h = size[2]
m = mass
mInertia = np.array([m/3*(l**2 + h**2), m/4*w*h, m/4*h*w,
m/4*w*l, m/3*(w**2 + h**2), m/4*h*l,
m/4*h*w, m/4*h*l, m/3*(l**2 + w**2)]).reshape([3,3])
print(mInertia)
return mInertia
@staticmethod
def momentInertiaSphere(size, mass):
return 2/5*mass*size**2*np.identity(3)
def setWalls(self,listOfWalls):
self.l = listOfWalls[0]
self.r = listOfWalls[1]
self.t = listOfWalls[2]
self.b = listOfWalls[3]
self.f = listOfWalls[4]
self.a = listOfWalls[5]
|
import client
import os
import logging
import numpy as np
import pickle
import random
import sys
import shutil
import torch
import utils.dists as dists # pylint: disable=no-name-in-module
from utils.fl_model import load_weights, extract_weights # pylint: disable=no-name-in-module
from datetime import datetime
import pytz
def current_time():
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
return datetime_NY.strftime("%m_%d_%H:%M:%S")
class Server(object):
"""Basic federated learning server."""
def __init__(self, config, env=None, agent=None):
self.config = config
self.saved_reports = {}
self.agent = agent
self.env = env
self.init_run_path()
# Set logging
logging.basicConfig(
filename=os.path.join(self.current_run_path, 'logger.log'),
format='[%(threadName)s][%(asctime)s]: %(message)s',
level=self.config.log_level,
datefmt='%H:%M:%S')
def init_run_path(self):
if self.config.lottery_args.subcommand == "lottery":
self.current_run_path = os.path.join("/mnt/open_lth_data",\
current_time()+"-"+self.config.lottery_args.subcommand\
+"_"+self.config.fl.prune_level_setter)
else:
self.current_run_path = os.path.join("/mnt/open_lth_data",\
current_time()+"-"+self.config.lottery_args.subcommand)
if not os.path.exists(self.current_run_path):
os.mkdir(self.current_run_path)
# Set up server
def boot(self):
pass
def load_model(self):
pass
def make_clients(self, num_clients):
pass
# Run federated learning
def run(self):
rounds = self.config.fl.rounds
target_accuracy = self.config.fl.target_accuracy
reports_path = self.config.paths.reports
if target_accuracy:
logging.info('Training: {} rounds or {}% accuracy\n'.format(
rounds, 100 * target_accuracy))
else:
logging.info('Training: {} rounds\n'.format(rounds))
# Perform rounds of federated learning
for round_id in range(1, rounds + 1):
logging.info('**** Round {}/{} ****'.format(round_id, rounds))
self.set_params(round_id)
# Run the federated learning round
accuracy = self.round()
# Break loop when target accuracy is met
if target_accuracy and (accuracy >= target_accuracy):
logging.info('Target accuracy reached.')
break
if reports_path:
with open(reports_path, 'wb') as f:
pickle.dump(self.saved_reports, f)
logging.info('Saved reports: {}'.format(reports_path))
def set_params(self, round_id):
self.config.lottery_args.round_num = round_id
self.config.lottery_args.client_num = self.config.clients.total
self.global_model_path_per_round = os.path.join(
self.current_run_path, str(round_id))
self.config.lottery_args.prefix_path = self.current_run_path
# Static global model path
self.config.lottery_args.global_model_path = os.path.join(
self.config.paths.model)
# Backup config file
shutil.copyfile(self.config.config_path, \
os.path.join(self.current_run_path, "config.json"))
def round(self):
return 0
# Federated learning phases
def selection(self):
# Select devices to participate in round
clients_per_round = self.config.clients.per_round
# Select clients randomly
sample_clients = [client for client in random.sample(
self.clients, clients_per_round)]
return sample_clients
def configuration(self, sample_clients):
pass
def reporting(self, sample_clients):
# Recieve reports from sample clients
reports = [client.get_report() for client in sample_clients]
logging.info('Reports recieved: {}'.format(len(reports)))
assert len(reports) == len(sample_clients)
return reports
# Report aggregation
def extract_client_updates(self, weights):
# Calculate updates from weights
updates = []
for weight in weights:
update = []
for i, (name, weight) in enumerate(weight):
bl_name, baseline = self.baseline_weights[i]
# Ensure correct weight is being updated
assert name == bl_name
# Calculate update
delta = weight - baseline
update.append((name, delta))
updates.append(update)
return updates
def federated_averaging(self, reports, weights):
# Extract updates from reports
updates = self.extract_client_updates(weights)
# Extract total number of samples
total_samples = sum([report.num_samples for report in reports])
# Perform weighted averaging
avg_update = [torch.zeros(x.size()) # pylint: disable=no-member
for _, x in updates[0]]
for i, update in enumerate(updates):
num_samples = reports[i].num_samples
for j, (_, delta) in enumerate(update):
# Use weighted average by number of samples
avg_update[j] += delta * (num_samples / total_samples)
# Load updated weights into model
updated_weights = []
for i, (name, weight) in enumerate(self.baseline_weights):
updated_weights.append((name, weight + avg_update[i]))
return updated_weights
# Server operations
@staticmethod
def flatten_weights(weights):
# Flatten weights into vectors
weight_vecs = []
for _, weight in weights:
weight_vecs.extend(weight.flatten().tolist())
return np.array(weight_vecs)
def save_model(self, model, path, filename=None):
if not os.path.exists(path):
os.makedirs(path)
if filename:
path += '/'+filename
else:
path += '/global.pth'
torch.save(model.state_dict(), path)
logging.info('Saved global model: {}'.format(path))
def save_reports(self, round, reports):
if reports:
self.saved_reports['round{}'.format(round)] = [(
report.client_id, self.flatten_weights(report.weights))
for report in reports]
# Extract global weights
self.saved_reports['w{}'.format(round)] = self.flatten_weights(
extract_weights(self.model))
|
import numpy as np
import math
import random
##initialization
ts_rew = 0
ad_feat = []
d = 10 #dimension
delta = input("Delta : ") #preferably 0.05
delta = float(delta)
B = [np.identity(d)] #B deals with contexts, 10 is dimension of context
mu_hat = [np.zeros(d)] #parameter which we want to estimate
f = [np.zeros(d)]
for i in range(d-1):
B = np.append([np.identity(10)], B, axis=0)
mu_hat = np.append([np.zeros(10)], mu_hat, axis=0)
f = np.append([np.zeros(10)], f, axis = 0)
mu_star = [] #it is the mean parameter from which
#print(mu_hat)
for i in range(d):
temp = random.sample(range(1, 100),10)
temp[i] = temp[i] * 10
s =sum(temp)
temp = [x/s for x in temp]
ad_feat.append(temp)
t = random.sample(range(1,100),10)
s1 =sum(t)
t = [x/s1 for x in t]
mu_star.append(t)
mu_star = np.array(mu_star)
t = 10000 # number of iterations
eps = 1/(math.log(t)) #from remark 2 of the paper TS for CMAB
R = 0.1
v = R * math.sqrt((24/eps)*d*(math.log(1/delta)))
##############
#generate features feature[i] is context for arm i
for i in range(t):
temp1 = random.sample(range(1, 100),10)
ind = random.randint(0,9)#to generate context randomly from 0 to 9
temp1[ind] = temp1[ind] * 10 #here context is more similar to the first
s =sum(temp1)
temp1 = [x/s for x in temp1]
temp1 = np.array(temp1)
#temp1 is a random user
for j in range(10):
if j ==0 :
feature = [ ad_feat[j] * temp1]
#print (type(features))
else:
feature = np.append(feature, [ad_feat[j]*temp1], axis=0)
feature = np.array(feature)
#print("feature",feature)
ran_sample = np.array([])
count = 0
for j in range(d):
#print(mu_hat[j])
#print(v*v*(np.linalg.inv(B[j])))
sam = np.random.multivariate_normal(mu_hat[j], v*v*(np.linalg.inv(B[j])))#generating sample
if j ==0:
ran_sample = [sam]
else:
ran_sample = np.append(ran_sample, [sam], axis =0 )
count += 1
#print (ran_sample)
#print("hello")
#mu_hat = ran_sample
temp_val = np.array([])
for k in range(d):
t10 = np.matmul(np.transpose(feature[k]), ran_sample[k])
if k ==0:
temp_val = [t10]
else:
temp_val = np.append(temp_val, [t10] , axis =0)
opt_arm_ind = np.argmax(temp_val)
rew = np.matmul(np.transpose(feature[opt_arm_ind]), mu_star[opt_arm_ind])
ts_rew += rew
#####
#update step
resh = np.reshape(feature[opt_arm_ind], (1, 10))
resh1 = np.reshape(feature[opt_arm_ind], (10,1))
B[opt_arm_ind] = B[opt_arm_ind] + np.matmul(resh1, resh)
f[opt_arm_ind]= f[opt_arm_ind] = feature[opt_arm_ind]*rew
mu_hat[opt_arm_ind] = np.matmul(np.linalg.inv(B[opt_arm_ind]), f[opt_arm_ind])
print(ts_rew) |
#!/usr/bin/env python
# coding: utf-8
# # Assignment 1
# ## Python Basic Programs
# ### 1. Print Hello world! :
# In[ ]:
print("Hello world!")
# ### 2. Declare the following variables: Int, Float, Boolean, String & print its value.
#
# In[ ]:
a = 10
print(a, "is of type", type(a))
b = 5.0
print(b, "is a type of", type(b))
c = []
print(c, "is", bool(c))
d = [0]
print(d, "is", bool(d))
e = 0.0
print(e, "is", bool(e))
my_string = "Hello"
print(my_string, type(my_string))
my_strings = """Hello, welcome to my world"""
print(my_strings, type(my_string))
# ### 3. Program to calculate the Area Of Triangle:
# In[ ]:
a = float (input ('Enter first side: '))
b = float (input ('Enter second side: '))
c = float (input ('Enter third side: '))
# semi-perimeter
s = (a + b + c) / 2
# area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print ('The area of the triangle is %0.2f' %area)
# ### 4. Program to calculate area of a square.
# In[ ]:
s = int(input('Enter side: '))
area = s * s
print("{} is area of sqaure".format(area))
# ### 5. Program to swap two variables:
# In[ ]:
x = input ('Enter value of x: ')
y = input ('Enter value of y: ')
temp = x
x = y
y = temp
print ('the value of x after swapping: {}'.format(x))
print ('the value of y after swapping: {}'.format(y))
# ### 6. Program is to check if a number is positive, negative or zero.
# In[ ]:
num = float(input("Enter number"))
if num < 0:
print("Negative")
elif num == 0:
print("Zero")
else:
print("Positive")
# ### 7. Program is to check if a number is Even or Odd.
# In[ ]:
n = int(input('Enter a number'))
if n % 2 == 0:
print('{} is an even number.'. format(n))
else:
print('{} is an odd number.'.format(n))
# ### 8. Program to print Odd number within a given range.
# In[ ]:
lower= int (input ("Enter the lower limit for the range :"))
upper= int (input ("Enter the upper limit for the range :"))
for i in range (lower, upper+1):
if (i%2 != 0):
print (i)
# ### 9. Python program to find the factorial of a number.
# In[ ]:
n = int(input ("Enter number :"))
fact = 1
while (n>0):
fact =fact*n
n=n-1
print("Factorial of the number is: ")
print(fact)
# ### 10. Program to reverse a given number.
# In[ ]:
n=int (input ("Enter number: "))
rev =0
while (n>0):
dig =n%10
rev =rev*10+dig
n =n//10
print ("Reverse of the number:", rev)
# ### 11. Program to find out the sum of N Natural numbers.
# In[ ]:
num = int (input ("Enter a number: "))
if num < 0:
print ("Enter a positive number")
else:
sum = 0
# ## Strings
# ### 1. Program to reverse a string.
# In[ ]:
a=str(input ("Enter a string: "))
print("Reverse of the string is: ")
print(a[::-1])
# ### 2. Program to check if string is palindrome or not:
# In[ ]:
my_str = 'aIbohPhoBiA'
my_str = my_str.casefold()
rev_str = reversed(my_str)
if list (my_str) == list(rev_str):
print("It is palindrome")
else:
print("It is not palindrome")
# ### 3. Python Program to Replace all Occurrences of ‘a’ with $ in a String from user:
# In[ ]:
string = input("Enter string :")
string= string.replace('a','$')
string= string.replace('A','$')
print("Modified string:")
print(string)
# ### 4. Python Program to Count the Number of Vowels in a String Input Two Strings and Display the Larger String without Using Built-in Functions:
# In[ ]:
string = input("Enter string:")
vowels = 0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
vowels = vowels + 1
print("Vowel number {}".format(vowels))
print(i)
string1 = input("Enter first string :")
string2 = input("Enter second string :")
count1=0
count2=0
for i in string1:
count1=count1+1
for j in string2:
count2=count2+1
if (count1<count2):
print ("Larger string is :")
print (string2)
elif(count1==count2):
print("Both strings are equal.")
else:
print("Larger string is:")
print(string1)
# ### 5. Count the number of digits & letter in a string:
# In[ ]:
string = input("Enter string :")
word = input("Enter word :")
a= []
count= 0
a=string.split(" ")
for i in range (0, len(a)):
if (word == a[i]):
count = count+1
print ("Count of the word is:")
print(count)
# ### 6. Count Number of Lowercase Characters in a String:
# In[ ]:
string = input ("Enter string:")
count = 0
for i in string:
if (i.islower()):
count = count + 1
print("The number of lowercase characters is :")
print(count)
else:
print("please use lower case")
# ### 7. Program to check if a Substring is Present in a Given String:
# In[ ]:
string = input("Enter string: ")
sub_str = input("Enter word : ")
if (string.find(sub_str)==-1):
print ("Substring not found in string!")
else:
print("Substring in string!")
# ## Conditional statements
# ### 1. W. A P. which takes one number from 0 to 9 from the user and prints it in the word. And if the word is not from 0 to 9 then it should print that number is outside of the range and program should exit.
# In[ ]:
n = int(input("Enter number: "))
if n == 0:
print("Zero")
elif n == 1:
print("One")
elif n == 2:
print("Two")
elif n == 3:
print("Three")
elif n == 4:
print("Four")
elif n == 5:
print("Five")
elif n == 6:
print("Six")
elif n == 7:
print("Seven")
elif n == 8:
print("Eight")
elif n == 9:
print("Nine")
else:
print("Invalid output")
# ### 2. W. A P. to implement calculator but the operation to be done and two numbers will be taken as input from user:- Operation console should show below:-
# Please select any one operation from below:-
# 1. To add enter 1
# 2. to subtract enter 2
# 3. To multiply enter 3
# 4. To divide enter 4
# 5. To divide and find quotient enter 5
# 6. To divide and find remainder enter 6
# 7. To find num1 to the power of num2 enter 7
# 8. To Come out of the program enter 8
# In[ ]:
n1 = float(input("Enter a number "))
n2 = float(input("Enter a number "))
op = input("Enter the operator ")
1 == '+'
2 == '-'
3 == '*'
4 == '/'
5 == '//'
6 == '%'
7 == '**'
8 == exit()
if op == '1':
print(n1 + n2)
elif op == '2':
print(n1 - n2)
elif op == '3':
print(n1 * n2)
elif op == '4':
if n2 == 0:
print("Invalid input")
else:
print(n1 / n2)
elif op == '5':
print(n1 // n2)
elif op == '6':
print(n1 % n2)
elif op == '7':
print(n1 ** n2)
elif op == '8':
quit()
else:
print('Invalid output')
# ### 3. W A P to check whether a year entered by user is an leap year or not?
# Check with below input:-
# 1. leap year:- 2012, 1968, 2004, 1200, 1600,2400
# 2. Non-leap year:- 1971, 2006, 1700,1800,1900
# In[ ]:
year = int(input('Enter an year: '))
if year % 4 == 0:
print('Divisible by 4')
if year % 100 == 0:
print('Divisible by 100')
if year % 400 == 0:
print('Divisible by 400')
print('Year is a leap year')
else:
print('not Divisible by 400')
print('Year is not a leap year')
else:
print('Not Divisible by 100')
print('Year is a leap year')
else:
print('Not Divisible by 4')
print('Year is not a leap year')
# ### 4. W A P which takes one number from the user and checks whether it is an even or odd number? If it even then prints number is even number else prints that number is odd number.
#
# In[ ]:
n = input('Enter a number: ')
if n.isdigit():
n = int(n)
if n%2 == 0:
print('{} is an even number.'.format(n))
else:
print('{} is an odd number.'.format(n))
else:
print('Invalid input!!!')
# ### 5. W A P which takes two numbers from the user and prints below output:-
# -num1 is greater than num2 if num1 is greater than num2
#
# -num1 is smaller than num2 if num1 is smaller than num2
#
# -num1 is equal to num2 if num1 and num2 are equal
#
# Note: -
# 1. Do this problem using if - else
# In[ ]:
num1 = float(input("Enter 1st Number: "))
num2 = float(input("Enter 2nd Number: "))
if num1 > num2:
print("1st Number is greater then 2nd Number")
elif num1 == num2:
print("Both numbers are equal")
elif num1 < num2:
print("1st Number is smaller then 2nd Number")
else:
print("Invalid input")
# 2. Do this using ternary operator
# In[ ]:
num1, num2 =float(input("Enter 1st Number: ")), float(input("Enter 2nd Number: "))
print ("Both 1st Number and 2nd Number are equal" if num1 == num2 else "1st Number is greater than 2nd Number"
if num1 > num2 else "1st number is smaller then 2nd Number")
# ### 6. W A P which takes three numbers from the user and prints below output:-
# -num1 is greater than num2 and num3 if num1 is greater than num2 and num3
#
# -num2 is greater than num1 and num3 if num2 is greater than num1 and num3
#
# -num3 is greater than num1 and num2 if num3 is greater than num1 and num2
#
# Note:-
# 1. Do this problem using if - elif - else
# In[ ]:
num1 = float(input("Enter 1st Number: "))
num2 = float(input("Enter 2nd Number: "))
num3 = float(input("Enter 3rd Number: "))
if (num1 > num2 and num1 > num3):
print("1st Number is greater then 2nd & 3rd Number")
elif (num2 > num1 and num2 > num3):
print("2nd Number is greater then 1st & 3rd Number")
elif (num3 > num1 and num3 > num2):
print("3rd Number is greater then 1st & 2nd Number")
else:
print("Invalid input")
# 2. Do this using ternary operator
# In[ ]:
num1, num2, num3 =float(input("Enter 1st Number: ")), float(input("Enter 2nd Number: ")), float(input("Enter 3rd Number: "))
mx = (num1 if (num1 > num2 and num1 > num3) else
(num2 if (num2 > num1 and num2 > num3) else num3))
print("Largest number among is " + str(mx))
# ## Loops - for loop, while loop
# ### 7. Write a Python program to find the length of the my_str using loop
#
# Input:- 'Write a Python program to find the length of the my_str'
#
# Output:- 55
# In[4]:
my_str = "Write a Python program to find the length of the my_str"
counter = 0
while counter < len(my_str):
counter += 1
print('Length of string - {} = {}'.format(my_str, counter))
# ### 8. Write a Python program to find the total number of times letter 'p' is appeared in the below string using loop:-
#
# Input:- 'peter piper picked a peck of pickled peppers.\n'
#
# Output:- 9
# In[8]:
mystr = 'peter piper picked a peck of pickled peppers.'
c = 0
for i in mystr:
if i == 'p':
c += 1
print(c)
# ### 9. Q. Write a Python Program, to print all the indexes of all occurrences of letter 'p' appeared in the string using loop:-
#
# Input: - 'peter piper picked a peck of pickled peppers.'
#
# Output:-
# 0
# 6
# 8
# 12
# 21
# 29
# 37
# 39
# 40
# In[10]:
mystr = 'peter piper picked a peck of pickled peppers.'
for i in range(len(mystr)):
if mystr[i] == 'p':
print(i)
# ### 10. Write a python program to find below output using loop:-
#
# Input: - 'peter piper picked a peck of pickled peppers.'
#
# Output:- ['peter', 'piper', 'picked', 'a', 'peck', 'of', 'pickled', 'peppers']
# In[12]:
mystr = 'peter piper picked a peck of pickled peppers.'
i = 0
from_indx = 0
str_list = []
while i < len(mystr):
if mystr[i] == ' ':
curr_indx = i
str_list.append(mystr[from_indx:curr_indx])
from_indx = i+1
elif i == len(mystr) - 1:
str_list.append(mystr[from_indx:])
i += 1
print('Result:- {}'.format(str_list))
# ### 11. Write a python program to find below output using loop:-
#
# Input: - 'peter piper picked a peck of pickled peppers.'
#
# Output:- 'peppers pickled of peck a picked piper peter'
# In[ ]:
mystr = 'peter piper picked a peck of pickled peppers.'
mystr = mystr[:len(mystr) - 1]
i = len(mystr) - 1
last_indx = len(mystr)
newstr = []
while i >= 0:
if mystr[i] == ' ':
newstr.append(mystr[i+1 : last_indx ])
last_indx = i
elif i == 0:
newstr.append(mystr[i : last_indx ])
i = i - 1
print('Method 1: Output:- {}'.format(" ".join(newstr)))
# ### 12. Write a python program to find below output using loop:-
#
# Input: - 'peter piper picked a peck of pickled peppers.'
#
# Output:- '.sreppep delkcip fo kcep a dekcip repip retep'
#
# In[ ]:
mystr = 'peter piper picked a peck of pickled peppers.'
i = len(mystr) - 1
newstr = ''
while i >= 0:
newstr = newstr + mystr[i]
i = i -1
print('Method 1: Output:- {}'.format(newstr))
# ### 13. Write a python program to find below output using loop:-
#
# Input: - 'peter piper picked a peck of pickled peppers.'
#
# Output:- 'retep repip dekcip a kcep fo delkcip sreppep'
# In[ ]:
mystr = 'peter piper picked a peck of pickled peppers.'
i = 0
from_indx = 0
newstr = ''
while i < len(mystr):
if mystr[i] == ' ':
curr_indx = i
newstr = newstr + mystr[from_indx:curr_indx][::-1] + ' '
from_indx = i+1
elif i == len(mystr) - 1:
newstr = newstr + mystr[from_indx:i+1][::-1]
i += 1
print('Method 1: Output:- {}'.format(newstr))
# ### 14. Write a python program to find below output using loop:-
#
# Input: - 'peter piper picked a peck of pickled peppers.'
#
# Output:- 'Peter Piper Picked A Peck Of Pickled Peppers'
#
# In[ ]:
mystr = 'peter piper picked a peck of pickled peppers.'
i = 0
from_indx = 0
from_indx = 0
newstr = ''
while i < len(mystr):
if mystr[i] == ' ':
curr_indx = i
newstr = newstr + mystr[from_indx].upper() + mystr[from_indx + 1:curr_indx] + ' '
from_indx = i+1
elif i == len(mystr) - 1:
newstr = newstr + mystr[from_indx].upper() +mystr[from_indx + 1:i+1]
i += 1
print('Output:- {}'.format(newstr))
# ### 15. Write a python program to find below output using loop:-
#
# Input: - 'Peter Piper Picked A Peck Of Pickled Peppers.'
#
# Output:- 'Peter piper picked a peck of pickled peppers'
# In[ ]:
mystr = 'Peter Piper Picked A Peck Of Pickled Peppers.'
i = 0
newstr = ''
from_indx = 0
while i < len(mystr):
if mystr[i] == ' ':
newstr = newstr + mystr[from_indx].upper() + mystr[from_indx + 1: ]
break
i += 1
print('Method 1: Output:- {}'.format(newstr))
# ### 16. Write a python program to implement index method using loop. If sub_str is found in my_str then it will print the index of first occurrence of first character of matching string in my_str:-
#
# Input: - my_str = 'Peter Piper Picked A Peck Of Pickled Peppers.',
#
# sub_str = 'Pickl'
#
# Output:- 29
#
# In[ ]:
mystr = 'Peter Piper Picked A Peck Of Pickled Peppers.'
sub_str = 'Pickl'
print('Input:- {}'.format(mystr))
i = 0
from_indx = 0
newstr = ''
while i < len(mystr):
if sub_str == mystr[i:i+len(sub_str)]:
break
i += 1
print('Output:- {}'.format(i))
# ### 17. Write a python program to implement replace method using loop. If sub_str is found in my_str then it will replace the first occurrence of sub_str with new_str else it will will print sub_str not found:-
#
# Input: - my_str = 'Peter Piper Picked A Peck Of Pickled Peppers.',
#
# sub_str = 'Peck', new_str = 'Pack'
#
# Output: - 'Peter Piper Picked A Pack Of Pickled Peppers.'
#
# In[ ]:
mystr = 'Peter Piper Picked A Peck Of Pickled Peppers.'
sub_str = 'Peck'
new_str = 'Pack'
print('Input:- {}'.format(mystr))
curr_indx = 0
from_indx = 0
newstr = ''
IS_FOUND = False
while curr_indx < len(mystr):
if mystr[curr_indx] == ' ':
if sub_str == mystr[from_indx:curr_indx]:
newstr = newstr + new_str + mystr[curr_indx:]
IS_FOUND = True
break
else:
newstr = newstr + mystr[from_indx:curr_indx+1]
from_indx = curr_indx + 1
elif curr_indx == len(mystr) - 1:
if sub_str == mystr[from_indx:curr_indx]:
newstr = newstr + new_str + mystr[curr_indx:]
IS_FOUND = True
break
curr_indx += 1
if IS_FOUND == False:
print('Output:- {} not found.'.format(sub_str))
else:
print('Output:- {}'.format(newstr))
# ### 18. Write a python program to find below output (implements rjust and ljust) using loop:-
#
# Input: - 'Peter Piper Picked A Peck Of Pickled Peppers.'
#
# sub_str ='Peck',
#
# Output:- '*********************Peck********************'
# In[ ]:
mystr = 'Peter Piper Picked A Peck Of Pickled Peppers.'
sub_str = 'Peck'
i = 0
from_indx = 0
newstr = ''
while i < len(mystr):
if mystr[i] == ' ':
curr_indx = i
if sub_str == mystr[from_indx:curr_indx]:
break
else:
from_indx = i+1
elif i == len(mystr) - 1:
curr_indx = i
from_indx = i+1
i += 1
newstr = '*'*len(mystr[0:from_indx]) + mystr[from_indx:curr_indx] + '*'*len(mystr[curr_indx])
print('Output:- {}'.format(newstr))
# ### 19. Write a python program to find below output using loop:-
#
# Input:- 'This is Python class', sep = ' is',
#
# Output:- ['This', 'Python class']
#
# In[ ]:
mystr = 'This is Python class'
sep = 'is'
outlist = []
for each in mystr.split(' '):
if each != sep:
outlist.append(each)
print('Output:- {}'.format(outlist))
# ### 20. WAP to read input from user. Allow the user to enter more numbers as long as the user enters valid integers. Terminate the program with proper message when they entered value is anything except integer.
#
# In[ ]:
while(True):
n = input('Enter an integer: ')
FLAG = False
if(n.isdigit()):
FLAG = True
else:
FLAG = False
if(FLAG== True):
pass
else:
print('Invalid input')
# ### 21. WAP to read input from a user. Allow the user to enter more numbers as long as the user enters valid numbers. Terminate the program with proper message when the user enters a value anything except valid number.
# In[ ]:
while(True):
n = input('Enter a number: ')
flag = False
if(n.isnumeric() | n.replace('.','',1).isnumeric()):
flag = True
else:
flag = False
if(flag):
pass
else:
print('Invalid Input')
break
# ### 22. WAP to read input from a user. Allow the user to enter more numbers as long as the user enters valid numbers. Terminate the program with proper message when the user enters a value anything except valid number. Allow wrong entry 'N' times.
#
# In[ ]:
counter = 1
N = 2
while(True):
n = input('Enter a number: ')
flag = False
if(n.isnumeric() | n.replace('.','',1).isnumeric()):
flag = True
else:
flag = False
if(flag ):
pass
else:
counter += 1
if(counter <= N):
pass
else:
print('You have entered invalid input {} times. Hence, Exiting the loop.'.format(counter))
break
|
import os
import shutil
import re
def remove_dir(rm_dir):
dir_under = os.listdir(rm_dir)
for each in dir_under:
filepath = os.path.join(rm_dir, each)
if os.path.isfile(filepath):
try:
os.remove(filepath)
except:
print("remove %s error." % filepath)
elif os.path.isdir(filepath):
try:
remove_dir(filepath)
except:
print("remove %s error." % filepath)
os.rmdir(rm_dir)
return
if __name__ == '__main__':
nl_level = [10, 30, 64]
nl_kind_dic = {}
with open('Area_4km2_Random_100_NL_Statistic_Table.csv', 'r', encoding='gbk') as f:
attrs = f.readline().strip().split(',')
# print(attrs)
sort_setting = 'MEAN'
sort_attr_index = attrs.index(sort_setting)
# print(sort_attr_index)
for line in f:
# print(line)
# break
data = line.strip().split(',')
if len(data) < 2:
print('empty line')
break
# print(data[0])
file_name = data[2] + ',' + data[1]
# print(file_name)
if file_name in nl_kind_dic:
print(file_name, data[0])
nl_value = float(data[sort_attr_index])
nl_kind = 0
while(nl_value > nl_level[nl_kind]):
nl_kind += 1
## because classification kind index strat from 1, so here should add 1
nl_kind += 1
nl_kind_dic[file_name] = nl_kind
reclassification_dir = './data'
if not os.path.exists(reclassification_dir):
os.mkdir(reclassification_dir)
else:
remove_dir(reclassification_dir)
os.mkdir(reclassification_dir)
for i in range(len(nl_level)):
dir_name = 'NL_%d' % (i+1)
os.mkdir(reclassification_dir + '/' + dir_name)
pattern = re.compile(r'^\d+.\d+,\d+.\d+')
rootdir = './NewData0706'
seconddir = os.listdir(rootdir)
for each in seconddir:
secondpath = os.path.join(rootdir, each)
if os.path.isdir(secondpath):
countys = os.listdir(secondpath)
for eachcounty in countys:
countypath = os.path.join(secondpath, eachcounty)
for eachfile in os.listdir(countypath):
try:
filepath = os.path.join(countypath, eachfile)
file_mark = re.search(pattern, eachfile).group()
# print(file_mark)
nl_kind = nl_kind_dic[file_mark]
destinypath = './data/NL_%d' % nl_kind
shutil.copy(filepath, destinypath)
except:
print('error in %s' % filepath)
|
import sys
import json
from deriva.core import ErmrestCatalog, AttrDict, get_credential, DEFAULT_CREDENTIAL_FILE, tag, urlquote, DerivaServer, get_credential, BaseCLI
from deriva.core.ermrest_model import builtin_types, Schema, Table, Column, Key, ForeignKey, DomainType, ArrayType
import utils
import traceback
tables = [
'chem_comp_mon_nstd_flag',
'chem_comp_atom_substruct_code',
'chem_comp_atom_pdbx_stereo_config',
'chem_comp_atom_pdbx_aromatic_flag',
'chem_comp_atom_pdbx_leaving_atom_flag',
'entity_src_method',
'entity_type',
'entity_poly_nstd_chirality',
'entity_poly_nstd_linkage',
'entity_poly_nstd_monomer',
'entity_poly_seq_hetero',
'struct_asym_pdbx_type'
]
def update_vocabularies(catalog):
try:
for table in tables:
url = '/attribute/Vocab:{}/RID,Name'.format(table)
resp = catalog.get(url)
resp.raise_for_status()
rows = resp.json()
values = []
for row in rows:
values.append({'RID': row['RID'], 'Name': row['Name'].upper()})
columns = ['RID', 'Name']
url = '/attributegroup/Vocab:{}/RID;Name'.format(table)
resp = catalog.put(
url,
json=values
)
resp.raise_for_status()
print('Updated {}'.format(table))
except:
et, ev, tb = sys.exc_info()
print('got exception "%s"' % str(ev))
print('%s' % ''.join(traceback.format_exception(et, ev, tb)))
# ============================================================
def main(server_name, catalog_id, credentials):
server = DerivaServer('https', server_name, credentials)
catalog = server.connect_ermrest(catalog_id)
catalog.dcctx['cid'] = 'oneoff/model'
model = catalog.getCatalogModel()
schema = model.schemas['Vocab']
for table_name in tables:
table = schema.tables[table_name]
referenced_by = table.referenced_by
if len(referenced_by) != 1:
print('Table {} has more than 1 FK'.format(table_name))
else:
referenced_by = referenced_by[0]
schema_name = referenced_by.constraint_schema.name
tname = referenced_by.table.name
fk_name = referenced_by.constraint_name
utils.alter_on_update_fkey_if_exist(model, schema_name, tname, fk_name, 'CASCADE')
"""
Update vocabularies
"""
update_vocabularies(catalog)
print('Updated the vocabulary tables.')
# ===================================================
if __name__ == '__main__':
args = BaseCLI('ad-hoc table creation tool', None, 1).parse_cli()
credentials = get_credential(args.host, args.credential_file)
main(args.host, 1, credentials)
|
import shutil
import subprocess
from pathlib import Path
import pytest
from cookiecutter.main import cookiecutter
from common import EXTRA, PARAMS, OUTPUT_DIR
@pytest.fixture(autouse=True)
def post_build():
if Path(OUTPUT_DIR).is_dir():
shutil.rmtree(OUTPUT_DIR)
yield
try:
container_build = subprocess.run(f"docker build --quiet {OUTPUT_DIR}/.")
assert container_build.returncode == 0
finally:
shutil.rmtree(OUTPUT_DIR)
def test_defaults():
cookiecutter(".", extra_context=EXTRA, **PARAMS)
@pytest.mark.parametrize("database", ["SQL", "NoSQL (Column/OLAP)", "NoSQL (Document)", "Object-Based"])
@pytest.mark.parametrize("frontend", ["vue", "react", "angular"])
@pytest.mark.parametrize("manager", ["pip", "pipenv"])
@pytest.mark.parametrize("webserver", ["waitress", "uwsgi"])
def test_flask(manager, webserver, frontend, database):
overwrite_backend = dict(
app_backend="flask",
app_dependency_manager=manager,
app_webserver=webserver,
app_frontend=frontend,
app_database=database,
)
overwrite = dict(EXTRA, **overwrite_backend)
cookiecutter(".", extra_context=overwrite, **PARAMS)
|
#coding:utf-8
__author__ = 'findme'
import warnings
warnings.filterwarnings("ignore")
import jieba #分词包
import numpy #numpy计算包
import codecs #codecs提供的open方法来指定打开的文件的语言编码,它会在读取的时候自动转换为内部unicode
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['figure.figsize'] = (10.0, 5.0)
from wordcloud import WordCloud#词云包
df = pd.read_csv("./data/entertainment_news.csv", encoding='utf-8')
df = df.dropna()
content=df.content.values.tolist()
#jieba.load_userdict(u"data/user_dic.txt")
segment=[]
for line in content:
try:
segs=jieba.lcut(line)
for seg in segs:
if len(seg)>1 and seg!='\r\n':
segment.append(seg)
except:
print(line)
continue
#去停用词
words_df=pd.DataFrame({'segment':segment})
#words_df.head()
stopwords=pd.read_csv("data/stopwords.txt",index_col=False,quoting=3,sep="\t",names=['stopword'], encoding='utf-8')#quoting=3全不引用
#stopwords.head()
words_df=words_df[~words_df.segment.isin(stopwords.stopword)]
#统计词频
words_stat=words_df.groupby(by=['segment'])['segment'].agg({"计数":numpy.size})
words_stat=words_stat.reset_index().sort_values(by=["计数"],ascending=False)
words_stat.head()
#词云
wordcloud=WordCloud(font_path="data/simhei.ttf",background_color="white",max_font_size=80)
word_frequence = {x[0]:x[1] for x in words_stat.head(1000).values}
wordcloud=wordcloud.fit_words(word_frequence)
plt.imshow(wordcloud)
#体育新闻
df = pd.read_csv("./data/sports_news.csv", encoding='utf-8')
df = df.dropna()
content=df.content.values.tolist()
#jieba.load_userdict(u"data/user_dic.txt")
segment=[]
for line in content:
try:
segs=jieba.lcut(line)
for seg in segs:
if len(seg)>1 and seg!='\r\n':
segment.append(seg)
except:
print(line)
continue
matplotlib.rcParams['figure.figsize'] = (10.0, 8.0)
words_df=pd.DataFrame({'segment':segment})
#words_df.head()
stopwords=pd.read_csv("data/stopwords.txt",index_col=False,quoting=3,sep="\t",names=['stopword'], encoding='utf-8')#quoting=3全不引用
#stopwords.head()
words_df=words_df[~words_df.segment.isin(stopwords.stopword)]
words_stat=words_df.groupby(by=['segment'])['segment'].agg({"计数":numpy.size})
words_stat=words_stat.reset_index().sort_values(by=["计数"],ascending=False)
words_stat.head()
wordcloud=WordCloud(font_path="data/simhei.ttf",background_color="black",max_font_size=80)
word_frequence = {x[0]:x[1] for x in words_stat.head(1000).values}
wordcloud=wordcloud.fit_words(word_frequence)
plt.imshow(wordcloud)
|
"""
This module contains the main LatexBot class.
"""
import aiohttp
import asyncio
import atexit
import datetime
import json
import logging
import marshmallow
import os
import pyryver
import random
import re
import signal
import time
import typing # pylint: disable=unused-import
from dataclasses import dataclass
from traceback import format_exc
from . import analytics, commands, schemas, server, trivia, util
from .aho_corasick import Automaton
from .cid import CaseInsensitiveDict
from .command import Command, CommandSet, CommandError
from .tba import TheBlueAlliance
logger = logging.getLogger("latexbot")
@dataclass(unsafe_hash=True, eq=False)
class UserInfo:
"""
A class for storing additional runtime user info.
"""
avatar: typing.Optional[str] = None
presence: typing.Optional[str] = None
last_activity: float = 0
muted: typing.Optional[typing.Dict[int, asyncio.Task]] = None
# Global LatexBot instance
bot = None # type: LatexBot
class LatexBot:
"""
An instance of LaTeX Bot.
"""
def __init__(self, version: str, debug: bool = False):
self.debug = debug
if debug:
self.version = version + f" (DEBUG: pyryver v{pyryver.__version__})"
else:
self.version = version
self.enabled = True
self.ryver = None # type: pyryver.Ryver
self.session = None # type: pyryver.RyverWS
self.username = None # type: str
self.user = None # type: pyryver.User
self.user_info = {} # type: typing.Dict[int, UserInfo]
self.config_file = None # type: str
self.config = None # type: schemas.Config
self.gh_issues_board = None # type: pyryver.TaskBoard
self.tba = None # type: TheBlueAlliance
self.maintainer = None # type: pyryver.User
self.roles_file = None # type: str
self.roles = CaseInsensitiveDict()
self.trivia_file = None # type: str
self.trivia_games = {} # type: typing.Dict[int, trivia.LatexBotTriviaGame]
self.analytics_file = None # type: str
self.analytics = None # type: analytics.Analytics
self.watch_file = None # type: str
self.keyword_watches = None # type: typing.Dict[int, schemas.KeywordWatch]
self.keyword_watches_automaton = None # type: Automaton
self.daily_msg_task = None # type: typing.Awaitable
self.commands = None # type: CommandSet
self.help = None # typing.Dict[str, typing.List[typing.Tuple[str, str]]]
self.command_help = {} # type: typing.Dict[str, str]
self.msg_creator = pyryver.Creator("LaTeX Bot " + self.version)
self.webhook_server = None # type: server.Webhooks
self.start_time = None # type: datetime.datetime
self.timeout_tasks = {} # type: typing.Dict[int, asyncio.Task]
self.recently_sent_tips = [] # type: typing.List[int]
global bot # pylint: disable=global-statement
bot = self
def init_commands(self) -> None:
"""
Initialize the command set.
"""
self.commands = CommandSet()
for name in dir(commands):
obj = getattr(commands, name)
if isinstance(obj, Command):
self.commands.add_command(obj)
# Set access levels for sub-commands
self.commands.add_command(Command("trivia importCustomQuestions", None, Command.ACCESS_LEVEL_ORG_ADMIN))
self.commands.add_command(Command("trivia exportCustomQuestions", None, Command.ACCESS_LEVEL_ORG_ADMIN))
self.commands.add_command(Command("trivia end", None, Command.ACCESS_LEVEL_FORUM_ADMIN))
self.commands.add_command(Command("setEnabled", None, Command.ACCESS_LEVEL_BOT_ADMIN))
self.commands.add_command(Command("macro create", None, Command.ACCESS_LEVEL_ORG_ADMIN))
self.commands.add_command(Command("macro delete", None, Command.ACCESS_LEVEL_ORG_ADMIN))
async def init(self, org: str, user: str, password: str, cache_dir: str, cache_prefix: str) -> None:
"""
Initialize LaTeX Bot.
Note: This does not load the configuration files.
The files should be loaded with load_files() before run() is called.
"""
self.username = user
cache = pyryver.FileCacheStorage(cache_dir, cache_prefix)
self.ryver = pyryver.Ryver(org=org, user=user, password=password, cache=cache)
await self.ryver.load_missing_chats()
self.user = self.ryver.get_user(username=self.username)
self.maintainer = self.ryver.get_user(id=int(os.environ.get("LATEXBOT_MAINTAINER_ID", 0)))
# Get user avatar URLs
# This information is not included in the regular user info
info = await self.ryver.get_info()
for user in info["users"]:
if user["id"] not in self.user_info:
self.user_info[user["id"]] = UserInfo()
self.user_info[user["id"]].avatar = user["avatarUrl"]
if os.environ.get("LATEXBOT_TBA_KEY"):
self.tba = TheBlueAlliance(os.environ.get("LATEXBOT_TBA_KEY"))
self.init_commands()
async def load_config(self, data: typing.Dict[str, typing.Any]) -> typing.Optional[str]:
"""
Load the config from a dict.
Returns an error message if there are errors, or None if no errors.
"""
msg = ""
try:
self.config = schemas.config.load(data)
except marshmallow.ValidationError as e:
msg += "Encountered errors while loading the config JSON:\n"
msg += util.format_validation_error(e)
msg += "\n\nConfig will be loaded with those values set to their defaults.\n\n"
try:
# Ignore errors by loading only the valid data
self.config = schemas.config.load(e.valid_data)
except marshmallow.ValidationError:
msg += "\n\nEncountered more errors trying to load the valid fields. Falling back to empty config."
self.config = schemas.config.load({})
# Extra step: Verify that the GitHub Issues chat has a task board with categories
if self.config.gh_issues_chat is not None:
self.gh_issues_board = await self.config.gh_issues_chat.get_task_board()
# If it does not exist, then create it
if self.gh_issues_board is None:
self.gh_issues_board = await self.config.gh_issues_chat.create_task_board(pyryver.TaskBoard.BOARD_TYPE_BOARD)
else:
# If it exists then verify that it has categories
if self.gh_issues_board.get_board_type() != pyryver.TaskBoard.BOARD_TYPE_BOARD:
self.gh_issues_board = None
msg += "Invalid GitHub task board: Task board have categories."
return msg or None
async def load_watches(self, data: typing.Dict[str, typing.Any]) -> typing.Optional[str]:
"""
Load the keyword watches from a dict.
Returns an error message if there are errors, or None if no errors.
"""
self.keyword_watches = {}
msg = ""
for user, watches in data.items():
try:
self.keyword_watches[int(user)] = schemas.keyword_watch.load(watches)
except marshmallow.ValidationError as e:
msg += f"Encountered errors while loading keyword watches for user {user}:\n{util.format_validation_error(e)}"
self.rebuild_automaton()
return msg or None
async def load_files(self, config_file: str, roles_file: str, trivia_file: str, analytics_file: str, watch_file: str) -> None:
"""
Load all configuration files, including the config, roles and custom trivia.
"""
self.config_file = config_file
self.roles_file = roles_file
self.trivia_file = trivia_file
self.analytics_file = analytics_file
self.watch_file = watch_file
# Load config
try:
with open(config_file, "r") as f:
err = await self.load_config(json.load(f))
if err:
logger.error(err)
if self.maintainer is not None:
await self.maintainer.send_message(err, self.msg_creator)
except (json.JSONDecodeError, FileNotFoundError) as e:
msg = f"Config does not exist or is not valid json: {e}. Falling back to empty config."
logger.error(msg)
if self.maintainer is not None:
await self.maintainer.send_message(msg, self.msg_creator)
await self.load_config({})
# Load watches
try:
with open(watch_file, "r") as f:
err = await self.load_watches(json.load(f))
if err:
logger.error(err)
if self.maintainer is not None:
await self.maintainer.send_message(err, self.msg_creator)
except (json.JSONDecodeError, FileNotFoundError) as e:
msg = f"Watches do not exist or is not valid json: {e}. Falling back to empty."
logger.error(msg)
if self.maintainer is not None:
await self.maintainer.send_message(msg, self.msg_creator)
await self.load_watches({})
# Load roles
try:
with open(roles_file, "r") as f:
self.roles = CaseInsensitiveDict(json.load(f))
except (json.JSONDecodeError, FileNotFoundError) as e:
logger.error(f"Error while loading roles: {e}. Defaulting to {{}}.")
if self.maintainer is not None:
await self.maintainer.send_message(f"Error while loading roles: {e}. Defaulting to {{}}.", self.msg_creator)
self.roles = CaseInsensitiveDict()
# Load analytics
if os.environ.get("LATEXBOT_ANALYTICS") == "1":
try:
with open(analytics_file, "r") as f:
self.analytics = schemas.analytics.load(json.load(f))
except marshmallow.ValidationError as e:
msg = f"Encountered errors while loading analytics:\n{util.format_validation_error(e)}"
msg += "\n\nAnalytics data will be loaded with those values set to their defaults.\n\n"
try:
self.analytics = schemas.analytics.load(e.valid_data)
except marshmallow.ValidationError:
msg += "\n\nEncountered more errors trying to load the valid fields. Falling back to empty data."
self.analytics = schemas.analytics.load({})
logger.error(msg)
if self.maintainer is not None:
await self.maintainer.send_message(msg, self.msg_creator)
except (json.JSONDecodeError, FileNotFoundError) as e:
msg = f"Analytics data does not exist or is not valid json: {e}. Falling back to empty."
logger.error(msg)
if self.maintainer is not None:
await self.maintainer.send_message(msg, self.msg_creator)
self.analytics = analytics.Analytics({}, {}, [])
# Register atexit and signal handlers for saving the analytics data
# so no data loss occurs when latexbot is terminated unexpectedly
atexit.register(self.save_analytics)
def signal_handler(num, frame): # pylint: disable=unused-argument
self.save_analytics()
exit()
signal.signal(signal.SIGABRT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Load trivia
try:
with open(trivia_file, "r") as f:
trivia.set_custom_trivia_questions(json.load(f))
except (json.JSONDecodeError, FileNotFoundError) as e:
logger.error(f"Error while loading custom trivia questions: {e}.")
if self.maintainer is not None:
await self.maintainer.send_message(f"Error while loading custom trivia questions: {e}.", self.msg_creator)
def save_config(self) -> None:
"""
Save the current config to the config JSON.
"""
with open(self.config_file, "w") as f:
f.write(schemas.config.dumps(self.config))
def save_roles(self) -> None:
"""
Save the current roles to the roles JSON.
"""
with open(self.roles_file, "w") as f:
json.dump(self.roles.to_dict(), f)
def save_analytics(self) -> None:
"""
Save the analytics data to JSON.
"""
with open(self.analytics_file, "w") as f:
f.write(self.analytics.dumps())
def save_watches(self) -> None:
"""
Save the current keyword watches to the watches JSON.
"""
data = {str(user): schemas.keyword_watch.dump(watches) for user, watches in self.keyword_watches.items()}
with open(self.watch_file, "w") as f:
json.dump(data, f)
def update_help(self) -> None:
"""
Re-generate the help text.
"""
self.help, self.command_help = self.commands.generate_help_text(self.ryver)
async def _daily_msg(self, init_delay: float = 0):
"""
A task that sends the daily message after a delay.
"""
cancelled = False
try:
await asyncio.sleep(init_delay)
logger.info("Executing daily message routine...")
await commands.command_daily_message(self, None, None, None, None)
logger.info("Daily message was sent.")
except asyncio.CancelledError:
cancelled = True
except Exception: # pylint: disable=broad-except
exc = format_exc()
logger.error(f"Daily message routine error: {exc}")
if self.maintainer is not None:
await self.maintainer.send_message(f"Exception while sending daily message:\n```\n{exc}\n```", self.msg_creator)
finally:
if not cancelled:
self.schedule_daily_message()
def schedule_daily_message(self):
"""
Start the daily message task with the correct delay.
"""
if self.daily_msg_task:
self.daily_msg_task.cancel()
if self.config.daily_message_time is None:
logger.info("Daily message not scheduled because time isn't defined.")
return
now = self.current_time()
# Get that time, today
t = datetime.datetime.combine(now, self.config.daily_message_time, tzinfo=self.config.tzinfo)
# If already passed, get that time the next day
if t < now:
t += datetime.timedelta(days=1)
init_delay = (t - now).total_seconds()
self.daily_msg_task = asyncio.create_task(self._daily_msg(init_delay))
logger.info(f"Daily message re-scheduled, starting after {init_delay} seconds.")
async def update_cache(self) -> None:
"""
Update cached chat data.
"""
old_users = set(user.get_id() for user in self.ryver.users)
await self.ryver.load_chats()
# Get user avatar URLs
# This information is not included in the regular user info
info = await self.ryver.get_info()
for user in info["users"]:
if user["id"] not in self.user_info:
self.user_info[user["id"]] = UserInfo()
self.user_info[user["id"]].avatar = user["avatarUrl"]
# Send welcome message
if self.config.welcome_message:
new_users = [user for user in self.ryver.users if user.get_id() not in old_users]
for new_user in new_users:
msg = self.config.welcome_message.format(name=new_user.get_name(), username=new_user.get_username())
await new_user.send_message(msg, self.msg_creator)
def rebuild_automaton(self) -> None:
"""
Rebuild the DFA used for keyword searching in messages using Aho-Corasick.
"""
dfa = Automaton()
keywords = {}
# Gather up all the keywords
for user, watches in self.keyword_watches.items():
if not watches.on:
continue
for keyword in watches.keywords:
if keyword.keyword not in keywords:
keywords[keyword.keyword] = []
# Each keyword has a list of users and whether it should match case and whole words
keywords[keyword.keyword].append((user, keyword.match_case, keyword.whole_word))
for k, v in keywords.items():
dfa.add_str(k.lower(), (k, v))
dfa.build_automaton()
self.keyword_watches_automaton = dfa
async def get_replace_message_creator(self, msg: pyryver.Message) -> pyryver.Creator:
"""
Get the Creator object that can be used for replacing a message.
"""
# Get the creator
msg_creator = msg.get_creator()
# If no creator then get author
if not msg_creator:
# First attempt to search for the ID in the list
# if that fails then get it directly using a request
msg_author = self.ryver.get_user(id=msg.get_author_id()) or (await msg.get_author())
info = self.user_info.get(msg_author.get_id())
avatar = "" if info is None or info.avatar is None else info.avatar
msg_creator = pyryver.Creator(msg_author.get_name(), avatar)
return msg_creator
def preprocess_command(self, command: str, is_dm: bool) -> typing.Optional[typing.Tuple[str, str]]:
"""
Preprocess a command.
Separate the command into the command name and args and resolve aliases
if it is a command. Otherwise return None.
If it encouters a recursive alias, it raises ValueError.
"""
for prefix in self.config.command_prefixes:
# Check for a valid command prefix
if command.startswith(prefix) and len(command) > len(prefix):
# Remove the prefix
command = command[len(prefix):]
break
else:
if command.startswith("@" + self.msg_creator.name + " "):
command = command[len(self.msg_creator.name) + 2:]
# DMs don't require command prefixes
elif not is_dm:
return None
# Repeat until all aliases are expanded
used_aliases = set()
while True:
# Separate command from args
# Find the first whitespace
command = command.strip()
space = None
# Keep track of this for alias expansion
space_char = ""
for i, c in enumerate(command):
if c.isspace():
space = i
space_char = c
break
if space:
cmd = command[:space]
args = command[space + 1:]
else:
cmd = command
args = ""
# Expand aliases
command = None
for alias in self.config.aliases:
if alias.from_ == cmd:
# Check for recursion
if alias.from_ in used_aliases:
raise ValueError(f"Recursive alias: '{alias.from_}'!")
used_aliases.add(alias.from_)
# Expand the alias
command = alias.to + space_char + args
break
# No aliases were expanded - return
if not command:
return (cmd.strip(), args.strip())
# Otherwise go again until no more expansion happens
def current_time(self) -> datetime.datetime:
"""
Get the current time in the organization's timezone.
"""
return datetime.datetime.now(datetime.timezone.utc).astimezone(self.config.tzinfo)
async def run(self) -> None:
"""
Run LaTeX Bot.
"""
self.start_time = self.current_time()
logger.info(f"LaTeX Bot {self.version} has been started. Initializing...")
self.update_help()
self.schedule_daily_message()
# Start webhook server
if os.environ.get("LATEXBOT_SERVER_PORT") or os.environ.get("LATEXBOT_SERVER") == "1":
if os.environ.get("LATEXBOT_SERVER_PORT"):
try:
port = int(os.environ["LATEXBOT_SERVER_PORT"])
except ValueError as e:
logger.error(f"Invalid port specified: {e}. Defaulting to 80.")
port = 80
else:
port = 80
logger.info(f"Starting server on port {port}")
self.webhook_server = server.Server(self)
await self.webhook_server.start(port or 80)
# Start live session
logger.info("Starting live session")
async with self.ryver.get_live_session(auto_reconnect=True) as session: # type: pyryver.RyverWS
logger.info("Initializing live session")
self.session = session
@session.on_connection_loss
async def _on_conn_loss():
logger.error(" Connection lost!")
@session.on_reconnect
async def _on_reconnect():
logger.info("Reconnected!")
@session.on_chat
async def _on_chat(msg: pyryver.WSChatMessageData, is_edit: bool = False):
# Ignore non-chat messages
if msg.subtype != pyryver.ChatMessage.SUBTYPE_CHAT_MESSAGE:
return
# Check the sender and destination
to = self.ryver.get_chat(jid=msg.to_jid)
from_user = self.ryver.get_user(jid=msg.from_jid)
if to is None or from_user is None:
logger.warning("Received message from/to user/chat not in cache. Updating cache...")
await self.update_cache()
if to is None:
to = self.ryver.get_chat(jid=msg.to_jid)
if from_user is None:
from_user = self.ryver.get_user(jid=msg.from_jid)
if to is None or from_user is None:
logger.error("Still not found after cache update. Command skipped.")
return
# Ignore messages sent by us
if from_user.get_username() == self.username:
return
# Record activity
if from_user.get_id() not in self.user_info:
self.user_info[from_user.get_id()] = UserInfo()
self.user_info[from_user.get_id()].last_activity = time.time()
# Check if this is a DM
if isinstance(to, pyryver.User):
# For DMs special processing is required
# Since we don't want to reply to ourselves, reply to the sender directly instead
to = from_user
is_dm = True
else:
is_dm = False
# See if user is muted
if from_user.get_id() in self.user_info:
muted = self.user_info[from_user.get_id()].muted
if muted is not None and to.get_id() in muted:
try:
msg_obj = await pyryver.retry_until_available(to.get_message, msg.message_id, retry_delay=0.1, timeout=5.0)
await msg_obj.delete()
except TimeoutError:
pass
return
# See if chat is read-only and check roles if it is
if to in self.config.read_only_chats and not from_user.is_admin() \
and not any(from_user.get_id() in bot.roles.get(role, ())
for role in self.config.read_only_chats[to]):
try:
text = msg.text
msg_obj = await pyryver.retry_until_available(to.get_message, msg.message_id, retry_delay=0.1, timeout=5.0)
await msg_obj.delete()
await from_user.send_message(f"Sorry, your message to {to.get_name()} was deleted because {to.get_name()} is a read-only chat. Here is the removed message:", bot.msg_creator)
await from_user.send_message(text, bot.msg_creator)
except TimeoutError:
pass
return
if not is_dm and self.analytics is not None and not is_edit:
self.analytics.message(msg.text, from_user)
try:
preprocessed = self.preprocess_command(msg.text, is_dm)
except ValueError as e:
# Skip if not self.
if self.enabled:
await to.send_message(f"Cannot process command: {e}", self.msg_creator)
return
if preprocessed:
command, args = preprocessed
# Processing for re-enabling after disable
if (command == "setEnabled" and args == "true") or command == "wakeUp":
if not await self.commands.commands["setEnabled"].is_authorized(self, to, from_user):
message = random.choice(self.config.access_denied_messages) if self.config.access_denied_messages else "Access denied."
await to.send_message(message, self.msg_creator)
return
if self.analytics:
self.analytics.command(command, args, from_user, to)
# Send the presence change anyways in case it gets messed up
await session.send_presence_change(pyryver.RyverWS.PRESENCE_AVAILABLE)
if not self.enabled:
self.enabled = True
logger.info(f"Re-enabled by user {from_user.get_name()}!")
await to.send_message("I have been re-enabled!", self.msg_creator)
else:
await to.send_message("I'm already enabled.", self.msg_creator)
return
elif command == "setEnabled" and args == "false" and self.enabled:
if not await self.commands.commands["setEnabled"].is_authorized(self, to, from_user):
message = random.choice(self.config.access_denied_messages) if self.config.access_denied_messages else "Access denied."
await to.send_message(message, self.msg_creator)
return
if self.analytics:
self.analytics.command(command, args, from_user, to)
self.enabled = False
logger.info(f"Disabled by user {from_user.get_name()}.")
await to.send_message("I have been disabled.", self.msg_creator)
await session.send_presence_change(pyryver.RyverWS.PRESENCE_AWAY)
return
if not self.enabled:
return
if is_dm:
logger.info(f"DM {'edited' if is_edit else 'received'} from {from_user.get_name()}: {msg.text}")
else:
logger.info(f"Command {'edited' if is_edit else 'received'} from {from_user.get_name()} to {to.get_name()}: {msg.text}")
async with session.typing(to):
if command in self.commands.commands:
if is_dm and self.analytics is not None:
self.analytics.message(msg.text, from_user)
try:
if not await self.commands.process(command, args, self, to, from_user, msg.message_id):
message = random.choice(self.config.access_denied_messages) if self.config.access_denied_messages else "Access denied."
await to.send_message(message, self.msg_creator)
logger.info("Access Denied")
else:
if self.analytics:
self.analytics.command(command, args, from_user, to)
logger.info("Command processed.")
except CommandError as e:
logger.info(f"Command error: {e}")
await to.send_message(f"Error: {e}", bot.msg_creator)
except Exception as e: # pylint: disable=broad-except
exc = format_exc()
logger.error(f"Exception raised:\n{exc}")
await to.send_message(f"An exception occurred while processing the command:\n```{exc}\n```\n\nPlease try again.", self.msg_creator)
if self.maintainer is not None:
await self.maintainer.send_message(f"An exception occurred while processing command `{msg.text}` in {to.get_name()}:\n```\n{exc}\n```", self.msg_creator)
else:
logger.info("Invalid command.")
await to.send_message("Sorry, I didn't understand what you were asking me to do.", self.msg_creator)
# Not a command
else:
# Replace roles + macros
def role_replace_func(match: re.Match):
# First capture group is character in front of @ and the @ itself
prefix = match.group(1)
name = match.group(2)
if name in self.roles:
name = " @".join(self.ryver.get_user(id=user).get_username() for user in self.roles[name])
return prefix + name
def macro_replace_func(match: re.Match):
prefix = match.group(1)
macro = match.group(2)
if macro in self.config.macros:
return prefix + self.config.macros[macro]
return prefix + "." + macro
new_text = util.MENTION_REGEX.sub(role_replace_func, msg.text)
new_text = util.MACRO_REGEX.sub(macro_replace_func, new_text)
# Replace the message if changed
if new_text != msg.text:
msg.text = new_text
async with session.typing(to):
try:
# Get the message object
msg_obj = (await pyryver.retry_until_available(to.get_message, msg.message_id, timeout=5.0))
# Pretend to be the creator
msg_creator = await self.get_replace_message_creator(msg_obj)
await to.send_message(msg.text, msg_creator)
except TimeoutError:
pass
# Can't delete the other person's messages in DMs, so skip
if not is_dm:
await msg_obj.delete()
# Search for keyword matches
notify_users = dict() # type: typing.Dict[int, typing.Set[str]]
for i, (keyword, users) in self.keyword_watches_automaton.find_all(msg.text.lower()):
for user, match_case, whole_word in users:
# Verify case matching
if match_case:
err = False
for j, c in enumerate(keyword):
# Aho-Corasick returns rightmost char index
if msg.text[i - len(keyword) + 1 + j] != c:
err = True
break
if err:
continue
# Verify whole words
if whole_word:
# Check right boundary
if i != len(msg.text) - 1 and msg.text[i].isalnum() == msg.text[i + 1].isalnum():
continue
# Check left boundary
l = i - len(keyword)
if l >= 0 and msg.text[l].isalnum() == msg.text[l + 1].isalnum():
continue
# Record match
if user not in notify_users:
notify_users[user] = set()
notify_users[user].add(keyword)
# Notify the users
if notify_users:
quoted_msg = f"> *{from_user.get_name()}* said in *{to.get_name()}*:"
for line in msg.text.splitlines():
quoted_msg += "\n> " + line
t = time.time()
for uid, keywords in notify_users.items():
# Check if it's from the same user
if from_user.get_id() == uid:
continue
if uid in self.user_info:
# Check user presence
if self.user_info[uid].presence == pyryver.RyverWS.PRESENCE_AVAILABLE:
continue
# Check user last activity
if t - self.user_info[uid].last_activity < self.keyword_watches[uid].activity_timeout:
continue
# Check suppression
if (self.keyword_watches[uid].suppressed or 0) > t:
continue
# Verify that the user is a member of this chat
if isinstance(to, pyryver.GroupChat) and await to.get_member(uid) is None:
continue
user = self.ryver.get_user(id=uid)
resp = "The following message matched your watches for the keyword(s) " + ", ".join(f"\"**{w}**\"""" for w in keywords) + ":"
await user.send_message(resp + "\n" + quoted_msg, self.msg_creator)
@session.on_chat_updated
async def _on_chat_updated(msg: pyryver.WSChatUpdatedData):
# Sometimes updates are sent for things other than message edits
if msg.text is None:
return
await _on_chat(msg, is_edit=True)
@session.on_event(pyryver.RyverWS.EVENT_REACTION_ADDED)
async def _on_reaction_added(msg: pyryver.WSEventData):
# Extra processing for interfacing trivia with reactions
await commands.reaction_trivia(self, self.ryver, session, msg.event_data)
@session.on_presence_changed
async def _on_presence_changed(msg: pyryver.WSPresenceChangedData):
# Keep track of user presences
user = self.ryver.get_user(jid=msg.from_jid)
if user.get_id() not in self.user_info:
self.user_info[user.get_id()] = UserInfo()
self.user_info[user.get_id()].presence = msg.presence
if not self.debug and self.config.home_chat is not None:
await asyncio.sleep(5)
logger.info("Sending startup message...")
try:
await session.send_presence_change(pyryver.RyverWS.PRESENCE_AVAILABLE)
logger.info("Presence change sent.")
await self.config.home_chat.send_message(f"LaTeX Bot {self.version} is online!", self.msg_creator)
except (pyryver.WSConnectionError, aiohttp.ClientError, asyncio.TimeoutError) as e:
logger.error(f"Exception during startup routine: {format_exc()}")
logger.info("LaTeX Bot is running!")
await session.run_forever()
async def shutdown(self):
"""
Stop running LaTeX Bot.
"""
await self.webhook_server.stop()
await self.session.terminate()
|
#reference: https://gist.github.com/govert/1b373696c9a27ff4c72a
#Some helpers for converting GPS readings from the WGS84 geodetic system to a local North-East-Up cartesian axis.
#The implementation here is according to the paper:
#"Conversion of Geodetic coordinates to the Local Tangent Plane" Version 2.01.
#"The basic reference for this paper is J.Farrell & M.Barth 'The Global Positioning System & Inertial Navigation'"
#Also helpful is Wikipedia: http://en.wikipedia.org/wiki/Geodetic_datum
import math
#WGS-84 geodetic constants
a = 6378137 #WGS-84 Earth semimajor axis (m)
b = 6356752.3142 #WGS-84 Earth semiminor axis (m)
f = (a-b)/a #Ellipsoid Flatness
e_sq = f * (2 - f) #Square of Eccentricity
#Converts WGS-84 Geodetic point (lat, lon, h) to the
#Earth-Centered Earth-Fixed (ECEF) coordinates (x, y, z).
def GeodeticToEcef(lat, lon, h):
#Convert to math.radians in notation consistent with the paper:
#lambda i sa reserved word
lamb = math.radians(lat)
phi = math.radians(lon)
s = math.sin(lamb)
N = a / math.sqrt(1 - e_sq * s * s)
sin_lambda = math.sin(lamb)
cos_lambda = math.cos(lamb)
cos_phi = math.cos(phi)
sin_phi = math.sin(phi)
x = (h + N) * cos_lambda * cos_phi
y = (h + N) * cos_lambda * sin_phi
z = (h + (1 - e_sq) * N) * sin_lambda
return (x, y, z)
#Converts the Earth-Centered Earth-Fixed (ECEF) coordinates (x, y, z) to
#East-North-Up coordinates in a Local Tangent Plane that is centered at the
#(WGS-84) Geodetic point (lat0, lon0, h0).
def EcefToEnu(x, y, z, lat0, lon0, h0):
#Convert to math.radians in notation consistent with the paper:
lamb = math.radians(lat0)
phi = math.radians(lon0)
s = math.sin(lamb)
N = a / math.sqrt(1 - e_sq * s * s)
sin_lambda = math.sin(lamb)
cos_lambda = math.cos(lamb)
cos_phi = math.cos(phi)
sin_phi = math.sin(phi)
x0 = (h0 + N) * cos_lambda * cos_phi
y0 = (h0 + N) * cos_lambda * sin_phi
z0 = (h0 + (1 - e_sq) * N) * sin_lambda
xd = x - x0
yd = y - y0
zd = z - z0
#This is the matrix multiplication
xEast = -sin_phi * xd + cos_phi * yd
yNorth = -cos_phi * sin_lambda * xd - sin_lambda * sin_phi * yd + cos_lambda * zd
zUp = cos_lambda * cos_phi * xd + cos_lambda * sin_phi * yd + sin_lambda * zd
return (xEast, yNorth, zUp)
#Converts the geodetic WGS-84 coordinated (lat, lon, h) to
#East-North-Up coordinates in a Local Tangent Plane that is centered at the
#(WGS-84) Geodetic point (lat0, lon0, h0).
def GeodeticToEnu(lat, lon, h, lat0, lon0, h0):
x,y,z = GeodeticToEcef(lat, lon, h)
xEast, yNorth, zUp = EcefToEnu(x, y, z, lat0, lon0, h0)
return (xEast, yNorth, zUp) |
import webbrowser
import time
print time.ctime()
count = 0
while count < 3:
webbrowser.open('https://goo.gl/9u9E97')
time.sleep(10)
count += 1
|
usernames = input().split(", ")
allowed_chars = set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-")
valid_usernames = []
for username in usernames:
validation = set(username)
if 3 <= len(username) <= 16 and validation.issubset(allowed_chars):
valid_usernames.append(username)
for name in valid_usernames:
print(name) |
import os
import glob
import sys
def readFile(currentFile, limitstr):
count = 0
limit = int(limitstr)
countLines = 0
prevLine = ""
funcName = ""
fp = open(currentFile, 'r')
lines = fp.readlines()
print("in file ", currentFile, "\n")
for line in lines:
if ("{" in line):
if("=" not in line):
if (count == 0):
funcName = prevLine
count+= 1
elif ("}" in line):
if (";" not in line):
count-= 1
if (count == 0):
if (countLines >= limit):
print("\t",funcName,"\t", countLines + 1, "lines\n\n")
countLines = 0
if (count > 0):
countLines += 1
prevLine = line
fp.close()
def readFolder(limit):
for filename in glob.glob("*.c"):
readFile(filename, limit)
if(len(sys.argv) > 1):
readFolder(sys.argv[1])
else:
readFolder(1)
|
class Solution:
def constructDistancedSequence(self, n: int) -> List[int]:
rslt = [0]*(2*n-1)
mark = [0]*(n+1)
def bk(i, cnt):
if cnt == 0:
return True
if i >= 2*n-1:
return False
if rslt[i]:
return bk(i+1, cnt)
for num in range(n, 0, -1):
left, right = i, i+num if num > 1 else i
if not mark[num] and right < (2*n -1) and rslt[right] == 0:
mark[num] = 1
rslt[left] = rslt[right] = num
if bk(i+1, cnt-1): return True
mark[num] = 0
rslt[left] = rslt[right] = 0
return False
bk(0, n)
return rslt
|
# 766. Toeplitz Matrix
# https://leetcode.com/problems/toeplitz-matrix/description/
class Solution:
def isToeplitzMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i-1][j-1]!=matrix[i][j]: return False
return True
def isToeplitzMatrixRough(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
last_row = None
for row in matrix:
if last_row and last_row != row[1:]: return False
last_row = row[:-1]
return True |
#!/usr/bin/env python2.5
"""
#######################################################################
#
# Copyright (c) Stoke, Inc.
# All Rights Reserved.
#
# This code is confidential and proprietary to Stoke, Inc. and may only
# be used under a license from Stoke.
#
#######################################################################
DESCRIPTION: Route delete and recovery behavior due to OSPF Hello unreachable.
TEST PLAN: DoCoMo regression
TEST CASES: DoCoMo_4_3_1
HOW TO RUN: python2.5 DoCoMo_4_3_1.py
AUTHOR: jameer@stoke.com
REIEWER: kra@stoke.com
"""
import sys, os
mydir = os.path.dirname(__file__)
qa_lib_dir = os.path.join(mydir, "../../lib/py")
if qa_lib_dir not in sys.path:
sys.path.insert(1,qa_lib_dir)
# Frame-work libraries
from SSX import *
from CISCO import *
from Linux import *
from StokeTest import test_case, test_suite, test_runner
from log import buildLogger
from logging import getLogger
from vlan import *
from misc import *
from ospf_ikev2 import *
from helpers import is_healthy
import re
#Import Config and topo file
from config_docomo import *
from topo import *
class test_DoCoMo_4_3_1(test_case):
myLog = getLogger()
def setUp(self):
#Establish a telnet session to the SSX box.
self.ssx1 = SSX(ssx1["ip_addr"])
self.cisco = CISCO(cisco["ip_addr"])
self.ssx1.telnet()
self.cisco.console(cisco["ip_addr"])
# Clear the SSX config
self.ssx1.clear_config()
# wait for card to come up
self.ssx1.wait4cards()
self.ssx1.clear_health_stats()
def tearDown(self):
# Close the telnet session of SSX
self.ssx1.close()
def test_DoCoMo_4_3_1(self):
self.myLog.output("==================Starting The Test====================")
# Push SSX config
self.ssx1.config_from_string(route_var['DoCoMo_4_3_1'])
self.myLog.info("Configured the OSPF, \nConfiguring in the Cisco")
self.cisco.clear_interface_config(intf=p_ssx1_cisco[1])
self.myLog.info("Adding required vlans to database")
self.cisco.cmd("vlan database")
self.cisco.cmd("vlan %s"%route_var['ospf_vlan1'])
self.cisco.cmd("exit")
self.cisco.cmd("conf t")
self.cisco.cmd("no interface vlan %s"%route_var['ospf_vlan1'])
self.cisco.cmd("interface vlan %s"%route_var['ospf_vlan1'])
self.cisco.cmd("no ip address")
self.cisco.cmd("no shutdown")
self.cisco.cmd("ip address %s"%route_var['cisco_ospf_intf1_ip/mask'])
self.cisco.cmd("exit")
self.cisco.cmd("interface giga %s"%p_ssx1_cisco[1])
self.cisco.cmd("switchport")
self.cisco.cmd("switchport access vlan %s"%route_var['ospf_vlan1'])
self.cisco.cmd("switchport trunk encapsulation dot1q")
self.cisco.cmd("switchport trunk allowed vlan %s"%route_var['ospf_vlan1'])
self.cisco.cmd("switchport mode trunk")
self.cisco.cmd("no ip address")
self.cisco.cmd("exit")
self.cisco.cmd("no router ospf 123")
self.cisco.cmd("router ospf 123")
self.cisco.cmd("router-id 56.1.2.2")
self.cisco.cmd("log-adjacency-changes")
self.cisco.cmd("redistribute connected subnets")
self.cisco.cmd("redistribute static subnets")
self.cisco.cmd("network %s area 0"%route_var['ospf_route1'])
self.cisco.cmd("exit")
# Adding null routes to verify the routes delete/recovery
self.myLog.info("Adding null routes at Cisco to verify the routes delete/recovery")
self.cisco.cmd("ip route %s null0"%route_var['static_route1'])
self.cisco.cmd("ip route %s null0"%route_var['static_route2'])
self.cisco.cmd("ip route %s null0"%route_var['static_route3'])
self.cisco.cmd("ip route %s null0"%route_var['static_route4'])
self.cisco.cmd("ip route %s null0"%route_var['static_route5'])
self.cisco.cmd("ip route %s null0"%route_var['static_route6'])
self.cisco.cmd("ip route %s null0"%route_var['static_route7'])
self.cisco.cmd("ip route %s null0"%route_var['static_route8'])
self.cisco.cmd("ip route %s null0"%route_var['static_route9'])
self.cisco.cmd("ip route %s null0"%route_var['static_route10'])
self.cisco.cmd("end")
time.sleep(10)
#Moving to context
self.ssx1.cmd("context %s"%route_var['context_name1'])
self.myLog.info("Given delay to OSPF come up")
time.sleep(100)
#Verify the all ospf's are up with the neighbor
self.myLog.info("Verifying the ospf states at router - %s"%route_var['context_name1'])
self.myLog.info("\n\n Verifying the route behavior with respect the routes\n\n")
ospf_op1 = self.ssx1.cmd('show ip ospf neighbor | grep "%s"'%route_var['ospf_intf1_ip'])
if not "Full" in ospf_op1:
self.fail("OSPF Router is not established with the adjacent interface %s"%route_var['cisco_ospf_intf1_ip'])
# Verify the routes before OSPF Hello Unreachable
self.myLog.info("Verify the routes before OSPF Hello Unreachable")
for i in xrange(1,11):
op1, op2 = chk_ip_route_proto(self.ssx1,route=route_var["static_route%s"%i],proto="ospf")
self.failIf(len(op2) > 0, "check ip route failed for these parameters for route %s:%s"%(route_var["static_route%s"%i],op2))
# Movomg to other context
self.myLog.info(" Moving to other context")
self.ssx1.cmd("context local")
self.myLog.info("\n\nVerifying that routes are specific to context\n\n")
for i in xrange(1,11):
op1, op2 = chk_ip_route_proto(self.ssx1,route=route_var["static_route%s"%i])
self.failIf(op2[0] != "Wrong input","Route is not deleted from the routing table after OSPF Hello Unreachable for the route %s"%route_var["static_route%s"%i])
# Verfi the context parameters
self.myLog.info("Verify the context parameters")
contOp = self.ssx1.cmd("show context")
self.failIf(contOp.splitlines()[-1].split()[0] == route_var['context_name1'] , "Context name is %s instead of local"% route_var['context_name1'])
contOp = self.ssx1.cmd("show context %s"%route_var['context_name1'])
self.failIf(contOp.splitlines()[-1].split()[0] != route_var['context_name1'] , "Context name is local instead of %s"% route_var['context_name1'])
contOp = self.ssx1.cmd("show context local")
self.failIf(contOp.splitlines()[-1].split()[0] == route_var['context_name1'] , "Context name is %s instead of local"% route_var['context_name1'])
contOp = self.ssx1.cmd("show context all")
self.failIf(route_var['context_name1'] not in contOp , "Context name %s is not found in 'show cont all'"% route_var['context_name1'])
self.failIf("local" not in contOp , "Context name 'local' is not found in 'show cont all'")
contOp = self.ssx1.cmd("show context summary")
self.failIf(int(contOp.split()[-1]) != 2 , "Number of context shows more/less than configured")
self.ssx1.cmd("config")
self.ssx1.cmd("context test")
self.ssx1.cmd("end")
contOp = self.ssx1.cmd("show context summary")
self.failIf(int(contOp.split()[-1]) != 3 , "Number of context shows more/less than configured")
#Moving to context
self.myLog.info(" Moving to context")
self.ssx1.cmd("context %s"%route_var['context_name1'])
self.myLog.info("Verify the context parameters @ context %s"% route_var['context_name1'])
contOp = self.ssx1.cmd("show context")
self.failIf(contOp.splitlines()[-1].split()[0] != route_var['context_name1'] , "Context name is %s instead of local"% route_var['context_name1'])
contOp = self.ssx1.cmd("show context %s"%route_var['context_name1'])
self.failIf(contOp.splitlines()[-1].split()[0] != route_var['context_name1'] , "Context name is local instead of %s"% route_var['context_name1'])
contOp = self.ssx1.cmd("show context local")
self.failIf(contOp.splitlines()[-1].split()[0] == route_var['context_name1'] , "Context name is %s instead of local"% route_var['context_name1'])
contOp = self.ssx1.cmd("show context all")
self.failIf(route_var['context_name1'] not in contOp , "Context name %s is not found in 'show cont all'"% route_var['context_name1'])
self.failIf("local" not in contOp , "Context name 'local' is not found in 'show cont all'")
contOp = self.ssx1.cmd("show context summary")
self.failIf(int(contOp.split()[-1]) != 3 , "Number of context shows more/less than configured")
self.ssx1.cmd("config")
self.ssx1.cmd("context test")
self.ssx1.cmd("end")
contOp = self.ssx1.cmd("show context summary")
self.failIf(int(contOp.split()[-1]) != 3 , "Number of context shows more/less than configured")
self.myLog.info("\n\nVerifying that routes are recovered properly after OSPF Hello reachable\n\n")
for i in xrange(1,11):
op1, op2 = chk_ip_route_proto(self.ssx1,route=route_var["static_route%s"%i],proto="ospf")
self.failIf(len(op2) > 0, "route %s is not recovered"%route_var["static_route%s"%i])
# Checking SSX Health
hs1 = self.ssx1.get_health_stats()
self.failUnless(is_healthy( hs1), "Platform is not healthy at SSX1")
if __name__ == '__main__':
if os.environ.has_key('TEST_LOG_DIR'):
os.mkdir(os.environ['TEST_LOG_DIR'])
os.chdir(os.environ['TEST_LOG_DIR'])
log = buildLogger("DoCoMo_4_3_1.log", debug=True,console=True)
suite = test_suite()
suite.addTest(test_DoCoMo_4_3_1)
test_runner().run(suite)
|
from django.forms import ModelForm
from .models import Projects, Profile, Review
from django.contrib.auth.forms import UserCreationForm
from django.contrib .auth.models import User
from django import forms
from pyuploadcare.dj.forms import ImageField
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
class NewProjectForm(forms.ModelForm):
class Meta:
model = Projects
exclude = ['Owner', 'pub_date', 'owner_profile']
widgets = {
'project_description': forms.Textarea(attrs={'rows':6, 'cols':6,}),
}
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
exclude = ['user']
widgets = {
'bio': forms.Textarea(attrs={'rows':2, 'cols':10,}),
}
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
fields = ['design', 'usability', 'content']
|
from django.contrib import admin
#from leaflet.admin import LeafletGeoAdmin
# Register your models here.
#admin.site.register(GeoSite, LeafletGeoAdmin)
|
from InProfileComboBox import *
class BedComboBox(InProfileComboBox):
def __init__(self, parent, managementDialogClass, finderClass):
DataSelectionComboBox.__init__(self,
parent,
BedManagementDialog,
BedFinder)
|
# Generated by Django 3.2.3 on 2021-05-25 15:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='Location',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='Image',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=60)),
('pic', models.ImageField(upload_to='uploads/')),
('picture', models.ImageField(blank=True, default='./media', upload_to='')),
('description', models.TextField()),
('image_category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='capture.category')),
('image_location', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='capture.location')),
],
options={
'ordering': ['name'],
},
),
]
|
#!/usr/bin/python # This is server.py file
import socket
import sys
if 1 :
for arg in sys.argv:
print(arg)
# create an INET, STREAMing socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (socket.gethostname(), 12345)
print ('[TCP Server] starting up on %s port %s' % server_address)
# Bind the socket to the port
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print ('[TCP Server] waiting for a connection')
connection, client_address = sock.accept()
try:
print ('[TCP Server] connection from', client_address)
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1400)
if data:
print('[TCP Server] received "%s"' % data.decode())
print ('[TCP Server] sending data back to the client')
connection.sendall(data)
else:
print ('[TCP Server] no more data from', client_address)
break
finally:
# Clean up the connection
connection.close()
|
"""
paper,scissors,rock,lizard,spock
paper X -1 1 -1 1
scissors 1 X -1 1 -1
rock -1 1 X 1 -1
lizard 1 -1 -1 X 1
spock -1 1 1 -1 X
"""
import random
res = [ [ {"r": 0, "t": "draws"}, {"r": -1, "t": "is cut"}, {"r": 1, "t": "covers"}, {"r": -1, "t": "is eaten"}, {"r": 1, "t": "disproves"} ],
[ {"r": 1, "t": "cuts"}, {"r": 0, "t": "draws"}, {"r": -1, "t": "are crushed"}, {"r": 1, "t": "decapitates"}, {"r": -1, "t": "are smashed"} ],
[ {"r": -1, "t": "is covered"}, {"r": 1, "t": "crushes"}, {"r": 0, "t": "draws"}, {"r": 1, "t": "crashes"}, {"r": -1, "t": "is vaporized"} ],
[ {"r": 1, "t": "eats"}, {"r": -1, "t": "is decapitated"}, {"r": -1, "t": "is crushed"}, {"r": 0, "t": "draws"}, {"r": 1, "t": "poisons"} ],
[ {"r": -1, "t": "is disproved"}, {"r": 1, "t": "smashes"}, {"r": 1, "t": "vaportizes"}, {"r": -1, "t": "is poisoned"}, {"r": 0, "t": "draws"} ] ]
moves = {"paper": 0, "scissors":1, "rock": 2, "lizard": 3, "Spock": 4}
def playMe(playerChoice):
k, v = random.choice(list(moves.items()))
print("Your choice: " + playerChoice + ", opponent choice: " + k)
r = res[moves[playerChoice]][moves[k]]
if r["r"] == -1:
print("You lose, {} {} by {}".format(playerChoice, r["t"], k))
elif r["r"] == 1:
print("You won, {} {} {}".format(playerChoice, r["t"], k))
else:
print("draw")
def play():
ch = input("Choose\n 0 for paper,\n 1 for scissors,\n 2 for rock,\n 3 for lizard and\n 4 for Spock: ")
sanitize(ch)
playMe(list(moves.keys())[int(ch)])
def sanitize(ch):
if not str.isnumeric(ch):
raise Exception('Argument not a number', ch)
if int(ch) < 0 or int (ch) > 4:
raise Exception('Argument outside of accepted range 0 - 4', ch)
if __name__ == "__main__":
play() |
from django.db import models
from listArch.models import Company
class Collection(models.Model):
name = models.CharField(max_length=250, null=True, blank=True, verbose_name='Koleksiyon Adı')
company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.CASCADE)
creationDate = models.DateTimeField(auto_now_add=True, verbose_name='Kayıt Tarihi', null=True, blank=True)
modificationDate = models.DateTimeField(auto_now=True, verbose_name='Güncelleme Tarihi')
|
import numpy as np
import java
def utils_gen_windows(data_length, window_size, step_width):
"Generate indices for window-slizes with given length & step width."
start = 0
while start < data_length:
yield start, start + window_size
start += step_width
def reshape(raw_data, window_size, step_width):
'''
input:
[n_input,9]
n_input = n_sec * frequence
9, data from 3 sensors
output:
[n_output, window_size, 9]
n_output =
'''
python_raw_data = java.cast(java.jarray(java.jarray(java.jfloat)), raw_data)
raw_data = np.array(python_raw_data)
new_feat_count = ((raw_data.shape[0] - window_size) // step_width) + 1
reshaped_feat = np.empty((new_feat_count, window_size, 9))
for idx, window in enumerate(
utils_gen_windows(raw_data.shape[0], window_size, step_width)
):
new_row = raw_data[window[0] : window[1]]
if idx < new_feat_count:
reshaped_feat[idx, :] = new_row
return reshaped_feat |
# Partial simulation of gravity
# I have predifined a path (an ellipse) but the velocity (and even acceeleration) at each instant of time
# is decided by the distance between the star and respective planet (only gravitational force)
# This is PART 2 in my attempt to make a full simulation
# WORKING !!
import turtle
import math
space = turtle.Screen()
space.bgcolor('black')
space.title('Planetary Simulation - v2')
space.tracer(0)
planets = []
x = [200 , 300]
y = [0 , 300]
colors = ['skyblue', 'brown']
Mass = [1 , 18]
ellipse = [(200,100) , (300 , 150)]
for i in range(2):
planets.append(turtle.Turtle())
for i in range(2):
planets[i].color(colors[i])
planets[i].shape('circle')
planets[i].penup()
planets[i].speed(0)
planets[i].theta = 0
planets[i].setx(x[i])
planets[i].sety(y[i])
planets[i].mass = Mass[i]
star = turtle.Turtle()
star.color('orange')
star.turtlesize(3)
star.shape('circle')
star.penup()
star.setx(math.sqrt(200**2 - 100**2) - 80)
while True:
space.update()
# planet.pendown()
for i in range(2) :
dis = math.sqrt((star.xcor() - planets[i].xcor())**2 + (star.ycor() - planets[i].ycor())**2)
planets[i].setx(ellipse[i][0]*math.cos(math.radians(planets[i].theta)))
planets[i].sety(ellipse[i][1]*math.sin(math.radians(planets[i].theta)))
if(planets[i].ycor() == y[i] and planets[i].xcor() == x[i]) :
planets[i].theta = 0
planets[i].theta += 10/dis
space.mainloop()
|
# Title : List comprehension examples
# Author : Kiran raj R.
# Date : 27:10:2020
# Transpose of a matrix
list1 = [[1, 2], [3, 4], [5, 6], [7, 8]]
out = [[row[i] for row in list1] for i in range(2)]
print(out)
# Square of elements
square = [i*i for i in range(1, 11)]
print(square)
# Print vowels
name = "kiran raj r"
vowels_in_name = [i for i in name if i in 'aeiou']
print(vowels_in_name)
# Print only positive values(including zero)
val = [1, -2, 3, 4, -5, -6, 7, 0]
positive_val = [i if i >= 0 else 0 for i in val]
print(positive_val)
# Print even numbers
even_num = [num for num in range(1, 21) if num % 2 == 0]
print(even_num)
# Create a dictionary
odd_dict = {num: num**3 for num in range(1, 21) if num % 2 != 0}
print(odd_dict)
# Create a dictionary
list1 = ['Trivandrum', 'Chennai', 'Mumbai', 'Jaipur']
list2 = ['kerala', 'tamil nadu', 'maharastra', 'rajasthan']
out = {x: y for x, y in zip(list1, list2)}
print(out)
|
def encode(json, schema):
payload = schema.Main()
payload.type = json['type']
payload.coordinates = json['coordinates']
return payload
def decode(payload):
return payload.__dict__
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tarutil.py
#
# Copyright 2012 Alma Observatory <hyperion@Neptune>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
# /\/\
# ( 00 ) Neptuno 2014
# / ¯ \
# (((/ \)))
import os
import sys
import fnmatch
import tarfile
import itertools
import re
def main():
if len(sys.argv) < 2:
sys.exit('Usage: tarutil.py <Project Code>')
else:
code = sys.argv[1]
working_dir = '.'
dir_list = os.listdir(working_dir)
project_list = []
for d in dir_list:
if not fnmatch.fnmatch(d, code + '*.tar'):
print 'Skiping file [%s]' % d
continue
project_list.append(d)
if project_list is 0:
sys.exit('ERROR: No tars with code [%s] files in directory' % code)
lines = []
file_names_tar = []
for p in project_list:
tar = tarfile.open(os.path.join(working_dir, p))
file_names = [name.split('/') for name in tar.getnames()] #<--- 00
readme_file = [f for f in file_names if 'README' in f]
if readme_file:
readme_path = '/'.join(readme_file[0])
tar.extract(readme_path) #<--- 00
f = open(readme_path, 'r')
for l in f:
if l[0] == '|':
lines.append(re.sub('\s+','',l))
f.close()
file_names_tar = file_names_tar + file_names
if len(lines) == 0:
print 1
sys.exit()
#Save a list of files in tars----------------------------------------+
lines_out = [('/').join(line) + '\n' for line in file_names_tar]
file_name = '%s_files_tar.out' % code
f = open(file_name, 'w')
f.writelines(lines_out)
f.write('Total ' + str(len(file_names_tar)))
f.close()
#Parser the README tree ---------------------------------------------+
file_names_readme = []
dnode = 0
n = []
for i in lines:
#l = i.strip(' \n').split('|')
l = i.split('|')
path_element = l[len(l) - 1][2:]
if '/' in path_element:
path_element = path_element.replace('/','')
if dnode < len(l):
n.append(path_element)
if dnode == len(l):
file_names_readme.append(n)
n = n[:-1]
n.append(path_element)
if dnode > len(l):
file_names_readme.append(n)
diff = len(l) - dnode
n = n[:diff - 1]
n.append(path_element)
if lines.index(i) == (len(lines) - 1): #Last line!
file_names_readme.append(n)
dnode = len(l)
#Save a list of files/directories in README file----------------------------------+
file_name = '%s_files_readme.out' % code
lines_out = ['/'.join(line) + '\n' for line in file_names_readme]
f = open(file_name, 'w')
f.writelines(lines_out)
f.close()
flatlist_readme = itertools.chain(*file_names_readme)
flatlist_tar = itertools.chain(*file_names_tar)
not_found = list(set(flatlist_readme) - set(flatlist_tar))
print not_found
os.remove(readme_path)
os.removedirs(os.path.dirname(readme_path))
if len(not_found) > 0:
print 1
else:
print 0
if __name__ == '__main__':
main()
|
import os
import glob
import shutil
import argparse
import configparser
from collections import Counter
import numpy as np
from imblearn.over_sampling import SMOTE
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def join_split(folder, test_size=0.2, lookback=5):
train_list = []
test_list = []
for f in glob.glob(os.path.join(folder, 'processed_*.csv')):
df = pd.read_csv(f, sep=',', decimal='.', dtype={'immediate_failure': np.int})
df.drop(['id', 'cycle_id', 'sequence_id', 'timestamp_start', 'timestamp_end', 'rul'], inplace=True, axis=1)
train, test = train_test_split(df, shuffle=False, test_size=test_size)
train = train[:-lookback + 1]
train_list.append(train)
test_list.append(test)
return pd.concat(train_list, ignore_index=True), pd.concat(test_list, ignore_index=True)
def normalize(train, test):
ss = StandardScaler()
x_train_data = train[train.columns[:-1]]
y_train_data = train[train.columns[-1]]
x_test_data = test[test.columns[:-1]]
y_test_data = test[test.columns[-1]]
return ss.fit_transform(x_train_data), y_train_data.values, ss.transform(x_test_data), y_test_data.values
def smote(x, y, p=.2, seed=None):
all_classes = Counter(y)
minority_classes = all_classes.most_common()[1:]
desired_minority_classes_size = int(y.shape[0] * p)
sampling_strategy = dict((c[0], max(desired_minority_classes_size, c[1])) for c in minority_classes)
sm = SMOTE(sampling_strategy=sampling_strategy, random_state=seed)
x_res, y_res = sm.fit_sample(x, y)
return x_res, y_res
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Prepare data')
parser.add_argument('config', type=str, help='Configuration file')
args = parser.parse_args()
config = configparser.ConfigParser()
config.read(args.config)
config_test_size = config.getfloat('CONFIGURATION', 'test_size')
config_lookback = config.getint('CONFIGURATION', 'lookback')
config_p = config.getfloat('CONFIGURATION', 'p')
path_in = config.get('CONFIGURATION', 'path_in')
path_out = config.get('CONFIGURATION', 'path_out')
directories = []
for directory in glob.glob(os.path.join(path_in, '*', ''), recursive=False):
directories.append(os.path.basename(os.path.normpath(directory)))
for d in directories:
input_base_path = os.path.join(path_in, d)
output_base_path = os.path.join(path_out, d)
# Create dirs
if os.path.isdir(output_base_path):
shutil.rmtree(output_base_path)
os.makedirs(output_base_path)
print('With %s:' % d)
print('Joining all files and doing train-test split ... ', end='')
train_df, test_df = join_split(input_base_path, test_size=config_test_size, lookback=config_lookback)
print('Done!')
print('Normalizing data ... ', end='')
x_train, y_train, x_test, y_test = normalize(train_df, test_df)
print('Done!')
print('SMOTING ...', end='')
x_train, y_train = smote(x_train, y_train, p=config_p)
print('Done!')
train_file = os.path.join(output_base_path, 'train.csv')
test_file = os.path.join(output_base_path, 'test.csv')
print('Saving files ...', end='')
pd.DataFrame(data=np.append(x_train, y_train.reshape(-1, 1), axis=1)).to_csv(train_file, index=False,
decimal='.', sep=',')
pd.DataFrame(data=np.append(x_test, y_test.reshape(-1, 1), axis=1)).to_csv(test_file, index=False,
decimal='.', sep=',')
print('Done!')
|
import pygame
from time import sleep
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# This sets the WIDTH and HEIGHT of each grid location
WIDTH = 74
HEIGHT = 74
# This sets the margin between each cell
MARGIN = 5
#test
# Create a 2 dimensional array. A two dimensional
# array is simply a list of lists.
grid = []
for row in range(10):
# Add an empty array that will hold each cell
# in this row
grid.append([])
for column in range(10):
grid[row].append(0) # Append a cell
# Set row 1, cell 5 to one. (Remember rows and
# column numbers start at zero.)
#grid[1][5] = 1
# Initialize pygame
pygame.init()
# Set the HEIGHT and WIDTH of the screen
WINDOW_SIZE = [800, 800]
screen = pygame.display.set_mode(WINDOW_SIZE)
# Set title of screen
pygame.display.set_caption("Array Backed Grid")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
blockColumnLeft = 4
blockColumnMid = 5
blockColumnRight = 6
currentRow = 9
fallingRow = 0
fallCol = 0
fallCol2 = 0
last_update = 0
previousUpdate = 0
leftToRight = True
rightToLeft = False
size = 3
SPEED = 180
def clearGrid():
for row in range(10):
for col in range(10):
grid[row][col] = 0
def checkEmptyRow(row):
count = 0
for i in range(9):
if grid[row][i] == 1:
count += 1
return count
fallingBlock = False
twoFallingBlocks = False
# -------- Main Program Loop -----------
while not done:
# Set the screen background
screen.fill(BLACK)
# Draw the grid
for row in range(10):
for column in range(10):
color = WHITE
if grid[row][column] == 1:
color = GREEN
pygame.draw.rect(screen,
color,
[(MARGIN + WIDTH) * column + MARGIN,
(MARGIN + HEIGHT) * row + MARGIN,
WIDTH,
HEIGHT])
if currentRow == -1:
clearGrid()
currentRow = 9
SPEED = 180
size = 3
blockColumnLeft = 4
blockColumnMid = 5
blockColumnRight = 6
if currentRow < 7 and size == 3:
size = 2
elif currentRow < 3 and size == 2:
size = 1
if size == 3:
grid[currentRow][blockColumnLeft] = 1
grid[currentRow][blockColumnMid] = 1
grid[currentRow][blockColumnRight] = 1
elif size == 2:
grid[currentRow][blockColumnLeft] = 0
grid[currentRow][blockColumnMid] = 1
grid[currentRow][blockColumnRight] = 1
elif size == 1:
grid[currentRow][blockColumnLeft] = 0
grid[currentRow][blockColumnMid] = 0
grid[currentRow][blockColumnRight] = 1
else:
done = True
if fallingBlock:
currentTime = pygame.time.get_ticks()
if currentTime - previousUpdate > 140 and fallingRow < 10:
if grid[fallingRow][fallCol] != 1:
grid[fallingRow-1][fallCol] = 0
previousUpdate = currentTime
grid[fallingRow][fallCol] = 1
fallingRow += 1
else:
grid[fallingRow-1][fallCol] = 0
elif fallingRow >= 9:
currentTime = pygame.time.get_ticks()
grid[fallingRow-1][fallCol] = 1
if currentTime - previousUpdate > 140:
print("PASS")
fallingBlock = False
grid[fallingRow-1][fallCol] = 0
if twoFallingBlocks:
currentTime = pygame.time.get_ticks()
if currentTime - previousUpdate > 140 and fallingRow < 10:
grid[fallingRow-1][fallCol] = 0
grid[fallingRow-1][fallCol2] = 0
previousUpdate = currentTime
grid[fallingRow][fallCol] = 1
grid[fallingRow][fallCol2] = 1
fallingRow += 1
else:
grid[fallingRow-1][fallCol] = 0
grid[fallingRow-1][fallCol2] = 0
if fallingRow >= 9:
currentTime = pygame.time.get_ticks()
grid[fallingRow-1][fallCol] = 1
grid[fallingRow-1][fallCol2] = 1
if currentTime - previousUpdate > 140:
print("PASS")
twoFallingBlocks = False
grid[fallingRow-1][fallCol] = 0
grid[fallingRow-1][fallCol2] = 0
if leftToRight:
now = pygame.time.get_ticks()
if now - last_update > SPEED:
last_update = now
if size == 3:
grid[currentRow][blockColumnLeft] = 0
blockColumnLeft += 1
blockColumnMid += 1
blockColumnRight += 1
if blockColumnRight == 9:
leftToRight = False
rightToLeft = True
elif size == 2:
grid[currentRow][blockColumnMid] = 0
grid[currentRow][blockColumnLeft] = 0
blockColumnMid += 1
blockColumnRight += 1
if blockColumnRight == 9:
leftToRight = False
rightToLeft = True
else:
grid[currentRow][blockColumnMid] = 0
grid[currentRow][blockColumnLeft] = 0
grid[currentRow][blockColumnRight] = 0
blockColumnRight += 1
if blockColumnRight == 9:
leftToRight = False
rightToLeft = True
else:
now = pygame.time.get_ticks()
if now - last_update > SPEED:
last_update = now
if size == 3:
grid[currentRow][blockColumnRight] = 0
blockColumnLeft -= 1
blockColumnMid -= 1
blockColumnRight -= 1
if blockColumnLeft == 0:
leftToRight = True
rightToLeft = False
elif size == 2:
grid[currentRow][blockColumnMid] = 0
grid[currentRow][blockColumnRight] = 0
blockColumnMid -= 1
blockColumnRight -= 1
if blockColumnMid == 0:
rightToLeft = False
leftToRight = True
else:
grid[currentRow][blockColumnMid] = 0
grid[currentRow][blockColumnLeft] = 0
grid[currentRow][blockColumnRight] = 0
blockColumnRight -= 1
if blockColumnRight == 0:
rightToLeft = False
leftToRight = True
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
currentRow -= 1
if SPEED >= 80:
SPEED -= 20
if currentRow < 8 and checkEmptyRow(currentRow+2) > 0:
if size == 1:
if grid[currentRow+1][blockColumnRight] == grid[currentRow+2][blockColumnRight]:
print("perfect")
else:
print("YOU LOST")
done = True
elif size == 2:
if (grid[currentRow+1][blockColumnMid] == grid[currentRow+2][blockColumnMid]) and (grid[currentRow+1][blockColumnRight] == grid[currentRow+2][blockColumnRight]):
print("perfect!")
else:
if grid[currentRow+1][blockColumnMid] != grid[currentRow+2][blockColumnMid]:
size -= 1
fallCol = blockColumnMid
fallingRow = currentRow + 1
fallingBlock = True
grid[currentRow+1][blockColumnMid] = 0
print("DOWNSIZE 2-->1")
if grid[currentRow+1][blockColumnRight] != grid[currentRow+2][blockColumnRight]:
size -= 1
fallCol = blockColumnRight
fallingRow = currentRow + 1
fallingBlock = True
print("DOWNSIZE 2-->1")
grid[currentRow+1][blockColumnRight] = 0
else:
if (grid[currentRow+1][blockColumnLeft] == grid[currentRow+2][blockColumnLeft] and grid[currentRow+1][blockColumnMid] == grid[currentRow+2][blockColumnMid]) and grid[currentRow+1][blockColumnRight] == grid[currentRow+2][blockColumnRight]:
print("perfect <3")
else:
if grid[currentRow+1][blockColumnLeft] != grid[currentRow+2][blockColumnLeft]:
size -= 1
fallCol = blockColumnLeft
fallingRow = currentRow + 1
print("DOWNSIZE 3-->2")
grid[currentRow+1][blockColumnLeft] = 0
if grid[currentRow+1][blockColumnRight] != grid[currentRow+2][blockColumnRight]:
size -= 1
fallCol = blockColumnRight
fallingRow = currentRow + 1
print("Downsize 3 --> 2")
grid[currentRow+1][blockColumnRight] = 0
if grid[currentRow+1][blockColumnMid] != grid[currentRow+2][blockColumnMid]:
size -= 1
fallCol2 = blockColumnMid
fallingRow = currentRow + 1
print("DOWNSIZE 3--> 1")
grid[currentRow+1][blockColumnMid] = 0
if size == 1:
twoFallingBlocks = True
elif size == 2:
fallingBlock = True
else:
if currentRow < 8:
if size == 2:
grid[currentRow+2][blockColumnRight] = 1
grid[currentRow+2][blockColumnMid] = 1
elif size == 3:
grid[currentRow+2][blockColumnRight] = 1
grid[currentRow+2][blockColumnMid] = 1
grid[currentRow+2][blockColumnLeft] = 1
else:
grid[currentRow+2][blockColumnRight] = 1
# Limit to 60 frames per second
clock.tick(300)
# Go ahead and update the screen with what we've drawn.
pygame.display.update()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit() |
from django.db import models
from .message_handlers import Handler
from .texts import get_text
class Tournoment(models.Model):
name = models.CharField(max_length=32)
cost = models.PositiveIntegerField(default=0)
background = models.PositiveIntegerField(default=0)
# rewards here
level_min = models.PositiveIntegerField(default=0)
level_max = models.PositiveIntegerField(default=0)
max_loses = models.PositiveIntegerField(default=3)
max_wins = models.PositiveIntegerField(default=12)
reward_coins = models.PositiveIntegerField(default=0)
reward_copouns = models.PositiveIntegerField(default=0)
def give_rewards(self, user):
if user.user.is_bot:
return True
reward_coins = int(self.reward_coins*(user.wins/self.max_wins))
reward_copouns = int(self.reward_copouns*(user.wins/self.max_wins))
user.user.coins += reward_coins
user.user.copouns += reward_copouns
context = {}
context['wins'] = user.wins
context['finished'] = user.wins >= self.max_wins
context['reward_coins'] = reward_coins
context['reward_copouns'] = reward_copouns
user.user.send_message('tournoment_result', context)
user.user.save()
user.delete()
return False
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
from .models import User
if self.users.filter(user__is_bot=True).count() == 0:
bots = User.objects.filter(is_bot=True)
for bot in bots:
TournomentUser.objects.create(tournoment=self, user=bot)
class TournomentUser(models.Model):
from .models import User
tournoment = models.ForeignKey(
Tournoment, related_name="users", on_delete=models.CASCADE
)
user = models.ForeignKey(User, related_name="tournoments", on_delete=models.CASCADE)
wins = models.PositiveIntegerField(default=0)
loses = models.PositiveIntegerField(default=0)
def save(self, *args, **kwargs):
commit = True
if self.wins >= self.tournoment.max_wins or self.loses >= self.tournoment.max_loses:
commit = self.tournoment.give_rewards(self)
if commit:
super().save(*args, **kwargs)
class TournomentParticipateHandler(Handler):
def handle(self):
params = self.get_params()
tournoment = Tournoment.objects.get(pk=params["pk"])
context = {}
context["succeed"] = False
level, _ = self.request.user.get_level()
if tournoment.users.filter(user=self.request.user).count() > 0:
context["error"] = get_text("tournoment_already_participated")
elif level < tournoment.level_min or level > tournoment.level_max:
context["error"] = get_text("tournoment_level_range")
elif self.request.user.coins < tournoment.cost:
context["error"] = get_text("not_enough_coins")
else:
TournomentUser.objects.create(tournoment=tournoment, user=self.request.user)
self.request.user.coins -= tournoment.cost
self.request.user.save()
context["succeed"] = True
return self.response("tournoment_participate", context)
TOURNOMENT_MESSAGE_HANDLERS = {"tournoment_participate": TournomentParticipateHandler}
|
#**************************************************************************#
# This file is part of pymsc which is released under MIT License. See file #
# LICENSE or go to https://github.com/jam1garner/pymsc/blob/master/LICENSE #
# for full license details. #
#**************************************************************************#
import struct
from sys import argv
from msc import *
from param import *
from time import sleep
from random import randint,random
from os.path import isfile
from argparse import ArgumentParser
from math import sqrt, cos, sin, atan2
class FunctionInfo:
def __init__(self, thisLocalVarPos, returnAddress, stackPos):
self.localVarPos = thisLocalVarPos
self.returnAddress = returnAddress
self.stackPos = stackPos
def restore(self):
global evalPos, localVarPos
localVarPos = self.localVarPos
evalPos = returnAddress
#Simulate an MSC syscall given the information from
def syscall(syscallNum, args, pushBit):
global sharedVars,evalPos,stack,y_unit
#Random int in range
if syscallNum == 0x9:
push(randint(args[0], args[1]-1), pushBit)
#Variable access
elif syscallNum == 0x16:
operation = args[0]
if operation == 0x6:
if not args[1] in sharedVars:
print("ERROR: Variable 0x%08X doesn't not exist (Accessed at %X)" % (args[1],evalPos))
quit()
else:
push(sharedVars[args[1]], pushBit)
elif operation == 0x7:
sharedVars[args[2]] = args[1]
elif operation == 0x10:
if not args[1] in sharedVars:
print("ERROR: Variable 0x%08X doesn't not exist (Accessed at %X)" % (args[1],evalPos))
quit()
else:
push(0 if sharedVars[args[1]] == 0 else 1, pushBit)
elif operation == 0x2710:
sharedVars[args[1]] = 0
elif operation == 0x2711:
sharedVars[args[1]] = 1
elif syscallNum == 0xA:
operation = args[0]
if operation == 0: #sqrt
push(sqrt(intToFloat(args[1])),pushBit)
elif operation == 1: #angle
push(atan2(intToFloat(args[1]), intToFloat(args[2])),pushBit)
elif operation == 2:
push(intToFloat(args[1])**args[2],pushBit)
elif operation == 3:
push(sqrt((intToFloat(args[1])**2)+(intToFloat(args[2])**2)+(intToFloat(args[3])**2)),pushBit)
elif operation == 4:
push(cos(intToFloat(args[1])),pushBit)
elif operation == 5:
push(sin(intToFloat(args[1])),pushBit)
elif operation == 6:
push(random(), pushBit)
elif operation == 7:
push(abs(atan2(intToFloat(args[1]), intToFloat(args[2])) - atan2(intToFloat(args[3]), intToFloat(args[4]))),pushBit)
elif operation == 8:
push(y_unit, pushBit)
elif operation == 0xA:
mag = sqrt((intToFloat(args[1])**2)+(intToFloat(args[2])**2))
x = intToFloat(args[1]) / mag
y_unit = intToFloat(args[2]) / mag
push(x,pushBit)
#Variable access
elif syscallNum == 0x17:
operation = args[0]
if operation == 0x0:
if not args[1] in sharedVars:
print("ERROR: Variable 0x%08X doesn't not exist (Accessed at %X)" % (args[1],evalPos))
quit()
else:
push(sharedVars[args[1]], pushBit)
#Debug stack dump
elif syscallNum == 0xF0:
stackString = "DEBUG: ["
for i in range(len(stack)):
if stack[i] != None:
stackString += ('*' if i == stackPos else '') + hex(stack[i]) + (', ' if i != len(stack) - 1 else '')
if stackString != "[":
stackString = stackString[:-2]
print("Stack [Position = %i] - %s" % (stackPos, str([intToFloat(j) if j else 0 for j in stack])))
#Debug var print
elif syscallNum == 0xF1:
if len(args) == 0:
l = tuple(["0x%08X : 0x%08X, " % (i,j) for i,j in sharedVars.items()])
print('DEBUG: {' + (('%s' * len(l)) % l).rstrip(', ') + '}')
else:
if args[0] in sharedVars:
print("DEBUG: 0x%08X = 0x%08X" % (args[0], sharedVars[args[0]]))
else:
print("ERROR: Unsupported syscall 0x%X at location %X" % (syscallNum,evalPos))
quit()
#push a value onto the stack given that the push bit is enabled
def push(val, actuallyPush=True):
global mscFile,mscFileBytes,stack,functionStack,stackPos,localVarPos,evalPos,exceptionRegister,globalVars,executing,strings,linkRegister
if not actuallyPush:
return
if stackPos == 0x80:
print("At instruction %08X:")
print("WARNING: STACK OVERFLOW, STACK INDEX OVERWRITTEN ")
newVal = None
if type(val) == int:
newVal = (val & 0xFFFFFFFF)
elif type(val) == float:
newVal = floatToInt(val)
else:
print("ERROR: Invalid type to push type=%s at position %X (Object = %s)" % (str(type(val)), evalPos, str(val)))
raise TypeError("Invalid push type")
if stackPos < 0x80 and stackPos >= 0:
stack[stackPos] = newVal
elif stackPos == 0x80:
stackPos = newVal
elif stackPos < 0:
globalVars[0x8A + stackPos] = newVal
else:
print("WARNING: WRITE OOB (Not in emulated memory)")
stackPos += 1
def pop():
global mscFile,mscFileBytes,stack,functionStack,stackPos,localVarPos,evalPos,exceptionRegister,globalVars,executing,strings,linkRegister
if stackPos == 0:
print("At instruction %08X:" % evalPos)
print("WARNING: STACK UNDERFLOW")
stackPos -= 1
value = None
if stackPos < 0 and stackPos >= -0x8A:
value = globalVars[0x8A + stackPos]
elif stackPos >= 0 and stackPos < 0x80:
value = stack[stackPos]
elif value == 0x80:
value = stackPos
else:
print("WARNING: OOB POP UNHANDLED BY EMU, RETURNING 0")
print(" this will cause inaccuracy in emulation")
return 0
if value == None:
print("WARNING: POPPED UNINITIALIZED VALUE, ASSUMING 0")
return 0
else:
return value
def getVar(varType, varNum):
global mscFile,mscFileBytes,stack,functionStack,stackPos,localVarPos,evalPos,exceptionRegister,globalVars,executing,strings,linkRegister
if varType == 0: #(Local)
if localVarPos + varNum == 0x80:
return stackPos
elif localVarPos + varNum < 0x80:
return stack[localVarPos+varNum]
else:
print("WARNING: OOB READ OF LOCAL VAR %i AT LOCATION %X" % (varNum, evalPos))
print(" IS UNMAPPED IN EMULATOR MEMORY, TO AVOID")
print(" ERRORS ASSUMING VALUE OF 0, THIS WILL")
print(" LIKELY BE INACCURATE TO ON CONSOLE BEHAIVIOR")
return 0
elif varType == 1: #(global variable)
if varNum < 0x8A:
return globalVars[varNum]
elif varNum >= 0x8A and varNum < 0x10A:
return stack[varNum - 0x8A]
elif varNum == 0x10A:
return stackPos
elif varNum > 0x10A:
print("WARNING: OOB READ OF GLOBAL VAR %i AT LOCATION %X" % (varNum, evalPos))
print(" IS UNMAPPED IN EMULATOR MEMORY, TO AVOID")
print(" ERRORS ASSUMING VALUE OF 0, THIS WILL")
print(" LIKELY BE INACCURATE TO ON CONSOLE BEHAIVIOR")
return 0
else:
print("ERROR: UNKNOWN VARIABLE TYPE %i AT LOCATION %X" % (varType, evalPos))
raise ValueError
def setVar(varType, varNum, value, pushBit):
global mscFile,mscFileBytes,stack,functionStack,stackPos,localVarPos,evalPos,exceptionRegister,globalVars,executing,strings,linkRegister
if varType == 0: #(Local)
if localVarPos + varNum == 0x80:
stackPos = value
elif localVarPos + varNum < 0x80:
stack[localVarPos+varNum] = value
else:
print("WARNING: OOB WRITE OF LOCAL VAR %i AT LOCATION %X" % (varNum, evalPos))
print(" IS UNMAPPED IN EMULATOR MEMORY, THIS WRITE")
print(" WILL NOT HAVE HAPPENED MORE OR LESS")
elif varType == 1: #(global variable)
if varNum < 0x8A:
globalVars[varNum] = value
elif varNum >= 0x8A and varNum < 0x10A:
stack[varNum - 0x8A] = value
elif varNum == 0x10A:
stackPos = value
elif varNum > 0x10A:
print("WARNING: OOB READ OF GLOBAL VAR %i AT LOCATION %X" % (varNum, evalPos))
print(" IS UNMAPPED IN EMULATOR MEMORY, THIS WRITE")
print(" WILL NOT HAVE HAPPENED MORE OR LESS")
else:
print("ERROR: UNKNOWN VARIABLE TYPE %i AT LOCATION %X" % (varType, evalPos))
raise ValueError
if pushBit:
push(value)
#Converts an int representing bytes to a float
#Example 0x3F800000 -> 1.0
def intToFloat(val):
return struct.unpack('>f', struct.pack('>L', val))[0]
#Converts a float to an int representing bytes
#Example 1.0 -> 0x3F800000
def floatToInt(val):
return struct.unpack('>L', struct.pack('>f', val))[0]
def printf(printString, args):
specifierLocs = [i for i,j in enumerate(printString) if j == '%' and i < len(printString) and printString[i+1] in ['x', 'X', 'i', 'f', '0']]
for i,j in enumerate(specifierLocs):
if printString[j+1] == 'f':
args[i] = intToFloat(args[i])
print(printString % tuple(args))
def evalCommand(command):
global mscFile,mscFileBytes,stack,functionStack,stackPos,localVarPos,evalPos,exceptionRegister,globalVars,executing,strings,linkRegister
if command == None or command.command == 0xFFFE:
if evalPos != None:
print("Error: Invalid command at %X" % evalPos)
quit()
else:
print("Error: Invalid command (And Invalid eval position)")
executing = False
return
#This is used for determining if to add command size to
isJump = False
c = command.command
cParams = command.parameters
pushBit = command.pushBit
if c == 0x0: #nop
pass
elif c == 0x1:
pass
elif c == 0x2: #begin
stackPos -= cParams[0]
functionStack.append(FunctionInfo(localVarPos, linkRegister, stackPos))
localVarPos = stackPos
stackPos += cParams[1]
elif c in [0x3, 0x6, 0x7, 0x8, 0x9]: #end or return
if len(functionStack) == 0:
executing = False
return
fInfo = functionStack.pop()
if fInfo.returnAddress == None:
executing = False
return
if c in [0x6, 0x8]: #return a value
v = pop()
stackPos = fInfo.stackPos
push(v)
localVarPos = fInfo.localVarPos
evalPos = fInfo.returnAddress
isJump = True
elif c in [0x4, 0x5, 0x36]:
isJump = True
evalPos = cParams[0]
elif c == 0xA or c == 0xD:
push(cParams[0], pushBit)
elif c == 0xB:
push(getVar(cParams[0], cParams[1]), pushBit)
elif c == 0xC:
pass
elif c == 0xE:
push(pop() + pop(), pushBit) #Add int
elif c == 0xF:
push((-pop()) + pop(), pushBit) #Subtract int
elif c == 0x10:
push(pop() * pop(), pushBit) #Multiply int
elif c == 0x11:
divideBy = pop()
push(pop() // divideBy, pushBit) #Divide int
elif c == 0x12:
divideBy = pop()
push(pop() % divideBy, pushBit) #Mod int
elif c == 0x13:
push(-pop(), pushBit) #Negate value
elif c == 0x14:
setVar(cParams[0], cParams[1], getVar(cParams[0], cParams[1]) + 1,pushBit) #Var++
elif c == 0x15:
setVar(cParams[0], cParams[1], getVar(cParams[0], cParams[1]) - 1,pushBit) #Var--
elif c == 0x16:
push(pop() & pop(), pushBit)#bitAnd
elif c == 0x17:
push(pop() | pop(), pushBit)#bitOr
elif c == 0x18:
push(pop() ^ 0xFFFFFFFF, pushBit)#bitNot
elif c == 0x19:
push(pop() ^ pop(), pushBit)#bitXor
elif c == 0x1A:
shiftBy = pop() #leftShift
push(pop() << shiftBy, pushBit)
elif c == 0x1B:
shiftBy = pop()
push(pop() >> shiftBy, pushBit)#rightShift
elif c == 0x1C:
setVar(cParams[0], cParams[1], pop(),pushBit) #setVar
elif c == 0x1D:
setVar(cParams[0], cParams[1], getVar(cParams[0], cParams[1]) + pop(),pushBit) #Var +=
elif c == 0x1E:
setVar(cParams[0], cParams[1], getVar(cParams[0], cParams[1]) - pop(),pushBit) #Var -=
elif c == 0x1F:
setVar(cParams[0], cParams[1], getVar(cParams[0], cParams[1]) * pop(),pushBit) #Var *=
elif c == 0x20:
setVar(cParams[0], cParams[1], getVar(cParams[0], cParams[1]) // pop(),pushBit) #Var /=
elif c == 0x21:
setVar(cParams[0], cParams[1], getVar(cParams[0], cParams[1]) % pop(),pushBit) #Var %=
elif c == 0x22:
setVar(cParams[0], cParams[1], getVar(cParams[0], cParams[1]) & pop(),pushBit) #Var &=
elif c == 0x23:
setVar(cParams[0], cParams[1], getVar(cParams[0], cParams[1]) | pop(),pushBit) #Var |=
elif c == 0x24:
setVar(cParams[0], cParams[1], getVar(cParams[0], cParams[1]) ^ pop(),pushBit) #Var ^=
elif c == 0x25:
push(int(pop() == pop()), pushBit) #equals
elif c == 0x26:
push(int(pop() != pop()), pushBit) #not equals
elif c == 0x27:
compareTo = pop()
push(int(pop() < compareTo), pushBit) #less than
elif c == 0x28:
compareTo = pop()
push(int(pop() <= compareTo), pushBit) #less than or equal
elif c == 0x29:
compareTo = pop()
push(int(pop() > compareTo), pushBit) #greater than
elif c == 0x2A:
compareTo = pop()
push(int(pop() >= compareTo), pushBit) #greater than or equal to
elif c == 0x2B:
push(0 if pop() != 0 else 1, pushBit)#logic not
elif c == 0x2C:
formatString = strings[pop()]
formatValues = []
for i in range(cParams[0]-1):
formatValues.insert(0, pop())
printf(formatString, formatValues)
elif c == 0x2D:
args = []
for i in range(cParams[0]):
args.insert(0, pop())
syscall(cParams[1], args, pushBit)
elif c == 0x2E:
exceptionRegister = cParams[0]
elif c in [0x2F, 0x30, 0x31]:
isJump = True
jumpPos = pop()
#paramList = [pop() for i in range(cParams[0])]
hitException = False
if c == 0x2F:
gottenScript = mscFile.getScriptAtLocation(jumpPos)
if gottenScript == None or gottenScript.getCommand(jumpPos).command != 0x2:
print("WARNING: at %X invalid function call, jumping to exception register (%X)" % (evalPos, exceptionRegister))
evalPos = exceptionRegister
hitException = True
isJump = True
if not hitException:
isJump = True
linkRegister = evalPos + len(command)
evalPos = jumpPos
elif c == 0x32:
v = pop()
push(v) #push, the essentially pushes the last return value
push(v)
push(v,pushBit)
elif c == 0x33:
push(pop(), pushBit)
elif c == 0x34:
if pop() == 0:
isJump = True
evalPos = cParams[0]
elif c == 0x35:
if pop() != 0:
isJump = True
evalPos = cParams[0]
elif c == 0x38:
convertToFloat = lambda i: floatToInt(float(i))
stack[stackPos - (1 + cParams[0])] = convertToFloat(stack[stackPos - (1 + cParams[0])]) # intToFloat
elif c == 0x39:
convertToInt = lambda f: int(intToFloat(f))
stack[stackPos - (1 + cParams[0])] = convertToInt(stack[stackPos - (1 + cParams[0])]) # floatToInt
elif c == 0x3A:
push(intToFloat(pop()) + intToFloat(pop()), pushBit)
elif c == 0x3B:
v = intToFloat(pop())
push(intToFloat(pop()) - v, pushBit)
elif c == 0x3C:
push(intToFloat(pop()) * intToFloat(pop()), pushBit)
elif c == 0x3D:
v = intToFloat(pop())
push(intToFloat(pop()) / v, pushBit)
elif c == 0x3E:
push(-intToFloat(pop()), pushBit)
elif c == 0x3F:
setVar(cParams[0], cParams[1], floatToInt(intToFloat(getVar(cParams[0], cParams[1])) + 1),pushBit) #float Var++
elif c == 0x40:
setVar(cParams[0], cParams[1], floatToInt(intToFloat(getVar(cParams[0], cParams[1])) - 1),pushBit) #float Var--
elif c == 0x41:
setVar(cParams[0], cParams[1], pop(), pushBit) #setFloatVar
elif c == 0x42:
setVar(cParams[0], cParams[1], floatToInt(intToFloat(getVar(cParams[0], cParams[1])) + intToFloat(pop())),pushBit) #float Var+=
elif c == 0x43:
setVar(cParams[0], cParams[1], floatToInt(intToFloat(getVar(cParams[0], cParams[1])) - intToFloat(pop())),pushBit) #float Var-=
elif c == 0x44:
setVar(cParams[0], cParams[1], floatToInt(intToFloat(getVar(cParams[0], cParams[1])) * intToFloat(pop())),pushBit) #float Var*=
elif c == 0x45:
setVar(cParams[0], cParams[1], floatToInt(intToFloat(getVar(cParams[0], cParams[1])) / intToFloat(pop())),pushBit) #float Var/=
elif c == 0x46:
compTo = intToFloat(pop())
push(int(intToFloat(pop()) == compTo), pushBit)
elif c == 0x47:
compTo = intToFloat(pop())
push(int(intToFloat(pop()) != compTo), pushBit)
elif c == 0x48:
compTo = intToFloat(pop())
push(int(intToFloat(pop()) < compTo), pushBit)
elif c == 0x49:
push(int(intToFloat(pop()) <= intToFloat(pop())), pushBit) #float equals
elif c == 0x4A:
push(int(intToFloat(pop()) > intToFloat(pop())), pushBit) #float equals
elif c == 0x4B:
compTo = intToFloat(pop())
push(int(intToFloat(pop()) >= compTo), pushBit)
elif c == 0x4D:
executing = False
return
if not isJump:
evalPos += len(command)
def evalMscFile(mscFileObject):
global mscFile,mscFileBytes,stack,functionStack,stackPos,localVarPos,evalPos,exceptionRegister,globalVars,executing,strings,linkRegister,mainLoopFunc
mscFile = mscFileObject
strings = mscFile.strings
evalPos = mscFile.entryPoint
startScript = mscFile.getScriptAtLocation(mscFile.entryPoint)
if startScript != None:
executing = True
while executing:
currentExecutingScript = mscFile.getScriptAtLocation(evalPos)
if currentExecutingScript != None:
evalCommand(currentExecutingScript.getCommand(evalPos))
if executing:
executing = (evalPos != None)
else:
executing = False
def evalFile(filepath):
with open(filepath, 'rb') as f:
mscFile = MscFile().readFromFile(f)
evalMscFile(mscFile)
def evalText():
global stack, stackPos
mscFile = MscFile()
strs = []
scriptString = ""
print("+----------------------------------------------+")
print("| Text interpreter - Type in your script. |")
print("| Script input will stop after you type 'end' |")
print("+----------------------------------------------+")
nextLine = input()
while nextLine.strip().lower() != "end":
scriptString += nextLine + "\n"
nextLine = input()
scriptString += nextLine
print("------------------------------------------------")
scr = MscScript()
cmds = parseCommands(scriptString, mscStrings=strs)
cmdsSize = 0
for c in cmds:
cmdsSize += len(c)
scr.bounds = [0x10, 0x10+cmdsSize]
scr.cmds = cmds
scr.setStart(0x10)
scr.offset(0x10)
mscFile.entryPoint = 0x10
mscFile.strings = strs
mscFile.scripts.append(scr)
if scr[0].command == 0x2 and scr[0].parameters[0] > 0:
stackPos = scr[0].parameters[0]
print('Input %i parameter(s)' % scr[0].parameters[0])
for i in range(scr[0].parameters[0]):
p = input('Input parameter %i: ' % i).strip()
if p[-1] == 'f':
stack[i] = int(floatToInt(float(p[0 : len(p)-1])))
else:
stack[i] = int(p, 0)
evalMscFile(mscFile)
def load_fighter_param_common(filepath):
global sharedVars
p = openParam(filepath)
for i in range(len(p)):
val = p[i]
if isinstance(val, f32):
val = floatToInt(val)
elif not True in [isinstance(val, t) for t in [u8, s8, u16, s16, u32, s32]]:
continue
sharedVars[0x12000000 + i] = int(val)
sharedVars[0x02000000 + i] = int(val)
def load_fighter_param(filepath, entry):
global sharedVars
p = openParam(filepath)[0].entry(entry)
for i in range(len(p)):
val = p[i]
if isinstance(val, f32):
val = floatToInt(val)
elif not True in [isinstance(val, t) for t in [u8, s8, u16, s16, u32, s32]]:
continue
sharedVars[0x13000000 + i] = int(val)
sharedVars[0x03000000 + i] = int(val)
def main():
global mscFile,mscFileBytes,stack,functionStack,stackPos,localVarPos,evalPos,exceptionRegister,globalVars,executing,strings,linkRegister,sharedVars,mainLoopFunc
mscFile = None
mscFileBytes = None
mainLoopFunc = None
stack = [None] * 0x80
functionStack = []
stackPos = 0
localVarPos = 0
evalPos = 0
exceptionRegister = 0
linkRegister = None
globalVars = [None] * 0x8A #Note a lot of this is actually unused but is simulated for exploitation
executing = False
strings = []
sharedVars = {}
#Parse arguments
parse = ArgumentParser(description="Emulate MSC bytecode")
parse.add_argument("--fighter_param_common", action="store", dest="fighter_param_common", help="Path of fighter_param_common to load")
parse.add_argument("--fighter_param", action="store", dest="fighter_param", help="Path of fighter_param to load")
parse.add_argument("--character", action="store", dest="character", help="Name of character to load from fighter_param")
parse.add_argument("--character_list", action="store_true", dest="charLS", help="List character names")
parse.add_argument("mscFile", nargs='?', type=str, help="MSC File to emulate")
args = parse.parse_args()
charIds = {'miienemyf': 62, 'miienemys': 63, 'miienemyg': 64, 'littlemacg': 60, 'mariod': 36, 'pikmin': 26, 'sheik': 17, 'roy': 54, 'yoshi': 7, 'duckhunt': 45, 'koopajr': 46, 'pit': 24, 'metaknight': 23, 'cloud': 55, 'miifighter': 0, 'miiswordsman': 1, 'miigunner': 2, 'wiifit': 40, 'pacman': 49, 'gamewatch': 19, 'peach': 14, 'robot': 31, 'rockman': 50, 'fox': 9, 'zelda': 16, 'bayonetta': 56, 'purin': 35, 'donkey': 4, 'shulk': 47, 'ryu': 52, 'toonlink': 32, 'sonic': 34, 'lucariom': 61, 'lizardon': 33, 'littlemac': 41, 'kirby': 8, 'pikachu': 10, 'murabito': 42, 'ness': 13, 'palutena': 43, 'diddy': 27, 'mario': 3, 'wario': 22, 'link': 5, 'ike': 29, 'rosetta': 39, 'samus': 6, 'falcon': 12, 'mewtwo': 51, 'lucas': 53, 'ganon': 20, 'koopag': 58, 'gekkouga': 48, 'dedede': 28, 'pitb': 38, 'lucina': 37, 'warioman': 59, 'marth': 18, 'szerosuit': 25, 'koopa': 15, 'kamui': 57, 'lucario': 30, 'luigi': 11, 'reflet': 44, 'falco': 21}
if args.charLS:
print(list(charIds.keys()))
quit()
if args.fighter_param != None and isfile(args.fighter_param) and args.character in charIds:
print("loading fighter_param")
load_fighter_param(args.fighter_param, charIds[args.character])
if args.fighter_param_common != None and isfile(args.fighter_param_common):
load_fighter_param_common(args.fighter_param_common)
if args.mscFile == None:
evalText()
else:
evalFile(args.mscFile)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import queue
import logging
from pyflickr.core import oauth
from pyflickr.core.mapper import FileAppender
from pyflickr.core.request import Accessor
from pyflickr.core.manager import DateManager, Validator
VENDOR = "flickr"
CLASS = "photos"
METHOD = "search"
if __name__ == "__main__":
api = VENDOR + "." + CLASS + "." + METHOD
token = oauth.auth()
date_manager = DateManager("2016-1-1 00:00:00")
payload = {
"method": api,
"format": "json",
"nojsoncallback": 1,
"extras": "description, license, date_upload, date_taken"\
"owner_name, icon_server, original_format, last_update"\
"geo, tags, machine_tags, o_dims"\
"views, media path_alias, url_sq"\
"url_t, url_s, url_q, url_m"\
"url_n, url_z, url_c, url_l, url_o",
"per_page": 200,
"page": 1
}
queue = queue.Queue()
for min_date, max_date in date_manager:
payload["min_taken_date"] = min_date
payload["max_taken_date"] = max_date
notice = True
accessor = Accessor(queue, notice, payload, token)
appender = FileAppender(queue, notice, "data/" + min_date.split(" ")[0] + ".json")
accessor.start()
print("accessor")
appender.start()
print("appender")
accessor.join()
print("accessor")
appender.join()
print("appender")
|
# -*- coding: utf-8 -*-
'''
otsu.fun - SSWA Resources Docs String
@version: 0.1
@author: PurePeace
@time: 2020-01-07
@describe: docs string for api resources!!!
'''
demo = \
'''
演示接口
传参:{ foo }
---
- Nothing here
```
null
```
'''
# run? not.
if __name__ == '__main__':
print('only docs, so it doesnt work')
|
# Copyright (c) OpenMMLab. All rights reserved.
from torch._subclasses.fake_tensor import _is_tensor_constructor
from torch.utils._python_dispatch import TorchDispatchMode
class MetaTensorContext(TorchDispatchMode):
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
if _is_tensor_constructor(func):
device_idx = [arg.name
for arg in func._schema.arguments].index('device')
if len(args) > device_idx:
args = list(args)
args[device_idx] = 'meta'
else:
kwargs['device'] = 'meta'
return func(*args, **kwargs)
|
import turtle
def talloval(turtle, r): # Verticle Oval
turtle.left(45)
for loop in range(2): # Draws 2 halves of ellipse
turtle.circle(r,90) # Long curved part
turtle.circle(r/2,90) # Short curved part
def flatoval(turtle, r): # Horizontal Oval
turtle.right(45)
for loop in range(2):
turtle.circle(r,90)
turtle.circle(r/2,90)
def face_draw(face, face_color, face_shape, face_fill):
# Define the face color
face.color(face_color)
if (face_shape == "circle"):
# Circle face
face.begin_fill()
face.circle(200)
if (face_fill == True):
face.end_fill()
else:
raise Exception("Não existe o formato "+face_shape+" para a face!")
def speak_feedback(feedback_color, pen_color, feedback_shape):
# Creating feedback turtle
feedback = turtle.Turtle()
# Setting the width of the pen
feedback.width(20)
# Define the feedback color
feedback.color(feedback_color)
if (feedback_shape == "circle"):
# Circle feedback
pen_move(feedback, -20, -150, 0)
feedback.begin_fill()
feedback.circle(200)
feedback.clear()
feedback.color(pen_color)
elif (feedback_shape == "ellipse"):
#Ellipse feedback
pen_move(feedback, -40, -80, 0)
feedback.begin_fill()
flatoval(feedback, 30)
feedback.clear()
else:
raise Exception("Não existe o formato "+feedback_shape+" para o feedback de fala!")
def eye_draw(eye, eye_color, eye_shape, eye_fill):
# Define the eye color
eye.color(eye_color)
if (eye_shape == "square"):
# Square eye
eye.begin_fill()
for i in range(3):
eye.forward(100)
eye.left(90)
eye.forward(100)
if (eye_fill == True):
eye.end_fill()
elif (eye_shape == "circle"):
# Circle eye
eye.begin_fill()
eye.circle(50)
if (eye_fill == True):
eye.end_fill()
elif (eye_shape == "ellipse"):
#Ellipse eye
eye.begin_fill()
talloval(eye, 80)
if (eye_fill == True):
eye.end_fill()
else:
raise Exception("Não existe o formato "+eye_shape+" para os olhos!")
def mouth_draw(mouth, mouth_color, mouth_shape, mouth_fill):
# Define the mouth color
mouth.color(mouth_color)
if (mouth_shape == "trapeze"):
# Trapeze mouth
mouth.begin_fill()
mouth.left(45)
mouth.forward(100)
mouth.left(45)
mouth.forward(160)
mouth.left(45)
mouth.forward(100)
mouth.left(135)
mouth.forward(300)
if (mouth_fill == True):
mouth.end_fill()
elif (mouth_shape == "circle"):
# Circle mouth
mouth.begin_fill()
mouth.circle(20)
if (mouth_fill == True):
mouth.end_fill()
elif (mouth_shape == "ellipse"):
#Ellipse mouth
mouth.begin_fill()
flatoval(mouth, 30)
if (mouth_fill == True):
mouth.end_fill()
else:
raise Exception("Não existe o formato "+mouth_shape+" para a boca!")
def pen_move(face_element, x, y, angle):
face_element.penup()
# Coordinates
face_element.setx(x)
face_element.sety(y)
# Angles
face_element.left(angle)
face_element.pendown()
def full_face_draw(face_color, eyes_color, mouth_color, bg_color, face_shape, eyes_shape, mouth_shape, face_is_filled, eyes_is_filled, mouth_is_filled):
# Screen setup
screen = turtle.Screen()
screen.setup(width = 1.0, height = 1.0)
# Remove close, minimaze and maximaze buttons:
canvas = screen.getcanvas()
root = canvas.winfo_toplevel()
root.overrideredirect(1)
# Creating the turtles
face = turtle.Turtle()
right_eye = turtle.Turtle()
left_eye = turtle.Turtle()
mouth = turtle.Turtle()
turtle.bgcolor(bg_color)
# Setting the width of the pen
face.width(10)
right_eye.width(10)
left_eye.width(10)
mouth.width(10)
pen_move(face, -20, -150, 0)
face_draw(face, face_color, face_shape, face_is_filled)
pen_move(right_eye, 100, 0, 0)
eye_draw(right_eye, eyes_color, eyes_shape, eyes_is_filled)
pen_move(left_eye, -80, 0, 0)
eye_draw(left_eye, eyes_color, eyes_shape, eyes_is_filled)
pen_move(mouth, -40, -80, 0)
mouth_draw(mouth, mouth_color, mouth_shape, mouth_is_filled)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 1 12:55:28 2018
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from datetime import datetime
from collections import Counter
#import time
#from datetime import date,timedelta
#import requests
sns.set(color_codes='Dark')
#plt.style.use('fivethirtyeight')
#%% load data, method 2
url_LTC_pool = 'https://www.litecoinpool.org/pools'
# Returns list of all tables on page
LTC_pool_tables = pd.read_html(url_LTC_pool)
# Select the third table
LTC_table_3 = LTC_pool_tables[3]
# manipulations to turn table to useful form
LTC_tb = LTC_table_3.dropna(axis = 0, thresh = 3)
#LTC_tb = LTC_tb.drop([0])
LTC_tb = LTC_tb.iloc[:,:7]
#LTC_tb.columns = LTC_table_3.iloc[0]
LTC_tb = LTC_tb.iloc[::-1]
LTC_tb.index = np.arange(0,len(LTC_tb))
LTC_tb['Size'] = [int(x[:-2]) for x in LTC_tb['Size']]
LTC_tb['Txn'] = [int(x) for x in LTC_tb['Txn']]
LTC_tb['Height'] = [int(x) for x in LTC_tb['Height']]
#%%
fig_LTC = plt.figure(figsize=(17,9))
# subplot grid setup
ax_col = 6
ax_row = 3
ax_LTC_1 = plt.subplot2grid((ax_row, ax_col), (0, 0), colspan = 2)
ax_LTC_2 = plt.subplot2grid((ax_row, ax_col), (1, 0), colspan = 2)
ax_LTC_3 = plt.subplot2grid((ax_row, ax_col), (2, 0), colspan = 2)
ax_LTC_4 = plt.subplot2grid((ax_row, ax_col), (0, 2))
ax_LTC_5 = plt.subplot2grid((ax_row, ax_col), (1, 2))
ax_LTC_6 = plt.subplot2grid((ax_row, ax_col), (2, 2), colspan = 2)
ax_LTC_7 = plt.subplot2grid((ax_row, ax_col), (0, 3))
ax_LTC_8 = plt.subplot2grid((ax_row, ax_col), (1, 3))
ax_LTC_9 = plt.subplot2grid((ax_row, ax_col), (0, 4), colspan = 2)
ax_LTC_10 = plt.subplot2grid((ax_row,ax_col), (1, 4), colspan = 2)
ax_LTC_11 = plt.subplot2grid((ax_row, ax_col), (2, 4))
ax_LTC_12 = plt.subplot2grid((ax_row, ax_col), (2, 5))
plt.setp(ax_LTC_1.get_xticklabels(), visible=False)
plt.setp(ax_LTC_2.get_xticklabels(), visible=False)
#plt.setp(ax_LTC_4.get_xticklabels(), visible=False)
#plt.setp(ax_LTC_4.get_yticklabels(), visible=False)
#plt.setp(ax_LTC_5.get_xticklabels(), visible=False)
#plt.setp(ax_LTC_5.get_yticklabels(), visible=False)
#plt.setp(ax_LTC_6.get_xticklabels(), visible=False)
#plt.setp(ax_LTC_6.get_yticklabels(), visible=False)
plt.setp(ax_LTC_7.get_xticklabels(), visible=False)
plt.setp(ax_LTC_7.get_yticklabels(), visible=False)
#plt.setp(ax_LTC_8.get_xticklabels(), visible=False)
#plt.setp(ax_LTC_8.get_yticklabels(), visible=False)
#plt.setp(ax_LTC_9.get_xticklabels(), visible=False)
#plt.setp(ax_LTC_9.get_yticklabels(), visible=False)
plt.setp(ax_LTC_12.get_xticklabels(), visible=False)
plt.setp(ax_LTC_12.get_yticklabels(), visible=False)
#%% subplot 1 rolling average of block size
LTC_tb['size_mean_21'] = LTC_tb['Size'].rolling(
window=21,center=True,min_periods=1).mean()
ax_LTC_1.set_title('Mean block size of every adjac. 21 blks vs.'
+'block height',fontsize=11)
# Two curves on the same plot
ax_LTC_1.plot(LTC_tb['Height'],
LTC_tb['size_mean_21'],
linewidth=1.2, color='blue')
ax_LTC_1.set_xlim(min(LTC_tb['Height']),
max(LTC_tb['Height']))
ax_LTC_1.set_ylim(0, max(LTC_tb['size_mean_21'])*1.2)
ax_LTC_1.set_ylabel('block size in kB', fontsize=11)
#%%
# subplot 2
# transaction rolling average per 21 blocks
LTC_tb['txn_mean_21'] = LTC_tb['Txn'].rolling(
window=21,center=True,min_periods=1).mean()
# rolling average of transaction counts
ax_LTC_2.set_title('Mean txn count every adjac. 21 blks vs.'+
'block height',fontsize=11)
# Two curves on the same plot
ax_LTC_2.plot(LTC_tb['Height'],
LTC_tb['txn_mean_21'],
linewidth=1.2, color='r')
ax_LTC_2.set_xlim(min(LTC_tb['Height']),
max(LTC_tb['Height']))
ax_LTC_2.set_ylim(0, max(LTC_tb['txn_mean_21'])*1.2)
ax_LTC_2.set_ylabel('txn count',fontsize=11)
#%%
# subplot 3
# transaction rolling average per 21 blocks
LTC_tb['blksize_txn_ratio'] = (LTC_tb['Size']
/LTC_tb['Txn'])
LTC_tb['ratio_mean_21'] = LTC_tb['blksize_txn_ratio'].rolling(
window=21,center=True,min_periods=1).mean()
# rolling average of transaction counts
ax_LTC_3.set_title('Mean blksize / txn ratio, averaged every adjac.'+
'21 blks',fontsize=11)
# Two curves on the same plot
ax_LTC_3.plot(LTC_tb['Height'],
LTC_tb['ratio_mean_21'],
linewidth=1.2, color='green')
ax_LTC_3.set_xlim(min(LTC_tb['Height']),
max(LTC_tb['Height']))
ax_LTC_3.set_ylim(0, max(LTC_tb['ratio_mean_21'])*1.2)
ax_LTC_3.set_ylabel('blksize / txn ratio',fontsize=11)
ax_LTC_3.set_xlabel('block height',fontsize=11)
#%%
# subplot 4
# transaction distribution
sns.distplot(LTC_tb['Size'], kde = False, ax = ax_LTC_4,
color ='b', bins=40)
ax_LTC_4.set_title('size (kB) histogram',fontsize=11)
ax_LTC_4.set_xlabel('')
#%%
# subplot 5
# transaction distribution
sns.distplot(LTC_tb['Txn'], kde = False, ax = ax_LTC_5,
color='r', bins=40)
ax_LTC_5.set_title('transaction count histogram',fontsize=11)
ax_LTC_5.set_xlabel('')
# counting empty blocks
Em_Cn = LTC_tb['Txn'].value_counts().loc[1]
#%% Subplot 6 and 8, time info
# List Comprehension to alter time format
FMT = '%Y-%m-%d %H:%M'
del_t1 = [datetime.strptime(y, FMT) for y in LTC_tb['Timestamp (UTC)']]
del_t2 = [(z-del_t1[0]).seconds/60 for z in del_t1]
del_t3 = [del_t2[n] - del_t2[n-1] for n in range(1,len(del_t2))]
# del_t3 only has 499 elements, add in another at the begning, using
# "+" to combine lists
LTC_tb['del_t4'] = [0] + del_t3
LTC_tb['del_t5'] = LTC_tb['del_t4'].rolling(window=21,center=True,
min_periods=1).mean()
ax_LTC_6.set_title('delta_t btw adja blks(21 blk mean)'+
'21 blks',fontsize=11)
# Two curves on the same plot
# del_t5 is the 21 blokc average of the time difference between two
# blocks
ax_LTC_6.plot(LTC_tb['Height'],
LTC_tb['del_t5'],
linewidth = 1.2, color = 'purple')
ax_LTC_6.plot(LTC_tb['Height'],
[2.5 for y in range(0,len(LTC_tb))],
linewidth = 1.2, linestyle = '--', color = 'blue')
ax_LTC_6.set_xlim(min(LTC_tb['Height']),
max(LTC_tb['Height']))
ax_LTC_6.set_ylim(0, max(LTC_tb['del_t5'])*1.2)
ax_LTC_6.set_ylabel('minutes',fontsize=11)
ax_LTC_6.set_xlabel('block height',fontsize=11)
# time diff between adjacent blocks distribution
sns.distplot(LTC_tb['del_t4'], kde = False, ax = ax_LTC_8,
color='orange')
ax_LTC_8.set_title('delta_t btw adjac blks histogram',fontsize=11)
ax_LTC_8.set_xlabel('')
#ax_LTC_8.set_xlim(0,10)
#%%
# Subplot 7, some stats
yp = list(np.arange(7,-1,-1))
yp = [x/10 for x in yp]
alignment = {'horizontalalignment': 'left',
'verticalalignment': 'baseline'}
# positions for the stats:
StatsTexts = ['height: ',
'txns/blk, mean: ',
'txns/blk, median: ',
'txns/blk, max: ',
'txns, 500 blks',
'blk size, mean:',
'blk size, median: ',
'blk size, max: ']
alignment2 = {'horizontalalignment': 'right',
'verticalalignment': 'baseline'}
StatsTexts2 = [str(np.max(LTC_tb['Height'])),
str(format(np.mean(LTC_tb['Txn']),'.2f')),
str(np.median(LTC_tb['Txn'])),
str(np.max(LTC_tb['Txn'])),
str(np.sum(LTC_tb['Txn'])),
str(format(np.mean(LTC_tb['Size']),'.2f')),
str(np.median(LTC_tb['Size'])),
str(np.max(LTC_tb['Size']))]
#for k, ST1 in enumerate(StatsTexts):
# t = ax_LTC_7.text(0.1, yp[k]+0.15, StatsTexts[k],
# family='calibri', **alignment)
# advanced List Comprehension
t = [ax_LTC_7.text(0.1, yp[k]+0.15, StatsTexts[k],
family='calibri', **alignment, fontsize = 11)
for k,ST1 in enumerate(StatsTexts)]
# family='calibri', **alignment2, color = 'green')
T = [ax_LTC_7.text(
0.9,
yp[k]+0.15,
StatsTexts2[k],
family='calibri',
**alignment2,
color = 'black',
fontsize=11
)
if k != 5
else
ax_LTC_7.text(
0.9,
yp[k]+0.15,
StatsTexts2[k],
family='calibri',
**alignment2,
color = 'blue',
fontsize=11
)
for k,ST1 in enumerate(StatsTexts2)]
ax_LTC_7.grid(False)
#%% Subplot 9, using Seaborn module
# use List Comprehension to group empty/non-empty blocks
ind_of_common = 8
name_big_miner = [Counter(LTC_tb['Finder']).most_common(ind_of_common)[x][0]
for x in range(ind_of_common)]
LTC_tb['EMTY_stats'] = ['empty' if x == 1 else 'not empty'
for x in LTC_tb['Txn'] ]
LTC_tb['Finder2'] = [x if x in name_big_miner else 'other'
for x in LTC_tb['Finder']]
sns.countplot(x = 'Finder2', hue = 'EMTY_stats', data = LTC_tb,
order = name_big_miner + ['other'],
hue_order = ['not empty','empty'],
ax = ax_LTC_9);
sns.set_palette("husl")
ax_LTC_9.legend(loc=1, borderaxespad=0.)
ax_LTC_9.set_xticklabels(name_big_miner+['other'],rotation=30, fontsize = 8.5)
ax_LTC_9.set_xlabel('')
ax_LTC_9.set_ylabel('block count')
#%% Subplot 11 empty bar chart
ind2 = [1,2]
ax_LTC_11.bar(ind2,
[Em_Cn/len(LTC_tb)*100,(len(LTC_tb)-Em_Cn)/len(LTC_tb)*100],
width = 0.2,
color = ['chocolate','forestgreen'])
ax_LTC_11.set_ylabel('percent')
ax_LTC_11.set_xlabel('')
ax_LTC_11.set_xlim(0, 3)
ax_LTC_11.set_xticklabels(['','empty','non-empty'],rotation=0, fontsize = 8.5)
ax_LTC_11.set_yticks(np.arange(0, 110, 10))
ax_LTC_11.set_ylim(0, 100)
#%% percentage of empty blocks
LTC_pivoted = LTC_tb.pivot_table(index = 'Finder2', columns = 'EMTY_stats',
values = 'Txn',aggfunc='count').reset_index()
LTC_pivoted = LTC_pivoted.fillna(0)
LTC_pivoted['summed'] = [
LTC_pivoted['empty'].iloc[x] +
LTC_pivoted['not empty'].iloc[x]
for x in np.arange(0,len(LTC_pivoted))]
LTC_pivoted['EMTY_perc'] = [LTC_pivoted['empty'].iloc[x] /
LTC_pivoted['summed'].iloc[x]*100
for x in np.arange(0,len(LTC_pivoted))]
sns.barplot(x='Finder2', y='EMTY_perc', data=LTC_pivoted, ax = ax_LTC_10,
order = name_big_miner + ['other'],
color = 'chocolate')
ax_LTC_10.set_xticklabels(name_big_miner+['other'],rotation=30,fontsize = 8.5)
ax_LTC_10.set_xlabel('')
ax_LTC_10.set_ylabel('% blocks are empty')
#%%
mean_txn_tb = LTC_tb.pivot_table(index = 'Finder2',
aggfunc = {'mean','sum'})[
'Size'].sort_values('sum',ascending=False)
alignment = {'horizontalalignment': 'left',
'verticalalignment': 'baseline'}
alignment2 = {'horizontalalignment': 'right',
'verticalalignment': 'baseline'}
for i in range(0,len(mean_txn_tb)):
ax_LTC_12.text(0.5, (0.85 - 0.1*i), mean_txn_tb.index[i],
family='calibri', **alignment, fontsize = 11)
ax_LTC_12.text(3.5, (0.85 - 0.1*i),str(
format(mean_txn_tb['mean'].iloc[i],
'.2f')), family='calibri', **alignment2, fontsize = 11,
color = 'chocolate')
ax_LTC_12.set_ylabel('')
ax_LTC_12.set_xlim(0,4)
ax_LTC_12.set_title('Mean block size by pools')
ax_LTC_12.grid(False)
#%% set tight layout
fig_LTC.tight_layout()
mngr = plt.get_current_fig_manager()
mngr.window.setGeometry(100,90,1700,900)
fig_LTC.patch.set_facecolor('lightgrey')
#%%
sns.set(style="ticks")
# Initialize the figure with a logarithmic x axis
fig_LTC_2, ax_2 = plt.subplots(figsize=(7, 6))
# Plot the orbital period with horizontal boxes
sns.boxplot(x="Size", y="Finder2", data = LTC_tb,
whis = np.inf, palette = "coolwarm", ax = ax_2,
order = name_big_miner + ['other'])
# Add in points to show each observation
sns.swarmplot(x = "Size", y = "Finder2", data = LTC_tb,
size=2, color=".3", linewidth=0, ax = ax_2,
order = name_big_miner + ['other'])
# Tweak the visual presentation
ax_2.set_ylabel('')
ax_2.xaxis.grid(True)
ax_2.set_title('box- and swarm- plots for block size distributions ')
sns.despine(trim=True, left=True)
fig_LTC_2.tight_layout() |
#!/usr/bin/env python3
import re, sys
# organized as (pattern, replacement, is_recursive?)
substitutions = (
(r'\b([a-zA-Z)])(\d+,?)+\b', r'\1'), # remove most citation numbers
(r'([a-zA-Z)]+)(\d+,?)+\b', r'\1'), # (part of above)
(r'\[[0-9, -]+\]', r''), # remove [citations]
(r'www\.', r''), # www is implied in most addresses
(r'([a-zA-Z]+://)(\S+)\.(\S+)', r'\1\2 dot \3', True), # better web addr
(r'[a-zA-Z]+://', r''), # remove protocol from web addresses
(r'(\w+)/([\s)])', r'\1\2'), # removes trailing / from web addresses
(r'(\w+)/(\w+)', r'\1 slash \2', True), # say intermediate slashes
(r'- ', r'', True), # remove dangling hyphens
(r'-GUI', r'gooey'), # say GUI phonetically
(r'-gui', r'gooey'),
(r'CHARMM', r'charm'), # say CHARMM phonetically
(r'charmm', r'charm'),
(r'force-fields', r'force fields'), # with hyphen: pronounced wrong
)
with sys.stdin:
for line in sys.stdin:
for subst in substitutions:
if len(subst) == 3:
pattern, replacement, recursive = subst
else:
pattern, replacement = subst
recursive = False
if recursive:
prevline = None
while prevline != line:
prevline = line
line = re.sub(pattern, replacement, line)
else:
line = re.sub(pattern, replacement, line)
print(line, end='')
|
import math
import numpy as np
import torch
import torch.nn.functional as F
from utils import StaticEmbeddingExtractor
class Ranker:
def __init__(self, path_to_predictions, embedding_path, data_loader, all_labels, max_rank, y_label):
"""
This class stores the functionality to rank a prediction with respect to some gold standard representations and
to compute the precision at certain ranks or the quartiles
:param path_to_predictions: [String] The path to numpy array stored predictions (number_of_test_instances x
embedding_dim)
:param path_to_ranks: [String] the path were the computed ranks will be saved to
:param embedding_path: [String] the path to the embeddings
:param data_loader: [Dataloader] a data loader witch batchsize 1 that holds the test data
:param all_labels: [list(String)] a list of all unique labels that can occur in the test data
:param max_rank: [int] the worst possible rank (even if an instance would get a lower rank it is set to this
number)
:param y_label: [String] the column name of the label in the test data
"""
# load composed predictions
self._predicted_embeddings = np.load(path_to_predictions, allow_pickle=True)
self._embeddings = StaticEmbeddingExtractor(embedding_path)
data = next(iter(data_loader))
# the correct labels are stored here
self._true_labels = data[y_label]
self._max_rank = max_rank
# construct label embedding matrix, embeddings of labels are looked up in the original embeddings
all_labels = sorted(all_labels)
self._label_embeddings = self._embeddings.get_array_embeddings(all_labels)
self._label2index = dict(zip(all_labels, range(len(all_labels))))
# normalize predictions and label embedding matrix (in case they are not normalized)
self._label_embeddings = F.normalize(torch.from_numpy(np.array(self._label_embeddings)), p=2, dim=1)
self._predicted_embeddings = F.normalize(torch.from_numpy(np.array(self._predicted_embeddings)), p=2, dim=1)
# compute the ranks, quartiles and precision
self._ranks, self._gold_similarities, self._composed_similarities = self.get_target_based_rank()
self._quartiles, self._result = self.calculate_quartiles(self._ranks)
def get_target_based_rank(self):
"""
Computes the ranks of the composed representations, given a matrix of gold standard label embeddings.
The ordering is relative to the gold standard target/label representation.
:return: a list with the ranks for all the composed representations in the batch
"""
all_ranks = []
gold_similarities = []
composed_similarities = []
# get the index for each label in the true labels
target_idxs = [self.label2index[label] for label in self.true_labels]
# get a matrix, each row representing the gold representation of the corresponding label
target_repr = np.take(self.label_embeddings, target_idxs, axis=0)
# get the similarity between each label and each other possible label
# result: [labelsize x targetinstances] = for each instance a vector of cosine similarities to each label
target_dict_similarities = np.dot(self.label_embeddings, np.transpose(target_repr))
for i in range(self._predicted_embeddings.shape[0]):
# compute similarity between the target and the predicted vector
target_composed_similarity = np.dot(self.predicted_embeddings[i], target_repr[i])
composed_similarities.append(target_composed_similarity)
gold_similarities.append(target_dict_similarities[:, i])
# delete the similarity between the target label and itself
target_sims = np.delete(target_dict_similarities[:, i], target_idxs[i])
# the rank is the number of vectors with greater similarity that the one between
# the target representation and the composed one; no sorting is required, just
# the number of elements that are more similar
rank = np.count_nonzero(target_sims > target_composed_similarity) + 1
if rank > self.max_rank:
rank = self.max_rank
all_ranks.append(rank)
return all_ranks, gold_similarities, composed_similarities
def save_ranks(self, file_to_save):
with open(file_to_save, "w", encoding="utf8") as f:
for i in range(len(self._true_labels)):
f.write(self.true_labels[i] + " " + str(self.ranks[i]) + "\n")
print("ranks saved to file: " + file_to_save)
@staticmethod
def calculate_quartiles(ranks):
"""
get the quartiles for the data
:param ranks: a list of ranks
:return: the three quartiles we are interested in, string representation of percentage of data that are rank 1
and percentage of data that are
"""
sorted_data = sorted(ranks)
leq5 = sum([1 for rank in sorted_data if rank <= 5])
leq1 = sum([1 for rank in sorted_data if rank == 1])
if len(ranks) < 3:
return ranks, "%.2f%% of ranks = 1; %.2f%% of ranks <=5" % (
(100 * leq1 / float(len(sorted_data))), (100 * leq5 / float(len(sorted_data))))
mid_index = math.floor((len(sorted_data) - 1) / 2)
if len(sorted_data) % 2 != 0:
quartiles = list(map(np.median, [sorted_data[0:mid_index], sorted_data, sorted_data[mid_index + 1:]]))
else:
quartiles = list(map(np.median, [sorted_data[0:mid_index + 1], sorted_data, sorted_data[mid_index + 1:]]))
return quartiles, "%.2f%% of ranks = 1; %.2f%% of ranks <=5" % (
(100 * leq1 / float(len(sorted_data))), (100 * leq5 / float(len(sorted_data))))
@property
def predicted_embeddings(self):
return self._predicted_embeddings
@property
def embeddings(self):
return self._embeddings
@property
def true_labels(self):
return self._true_labels
@property
def max_rank(self):
return self._max_rank
@property
def label_embeddings(self):
return self._label_embeddings
@property
def label2index(self):
return self._label2index
@property
def ranks(self):
return self._ranks
@property
def quartiles(self):
return self._quartiles
@property
def result(self):
return self._result
@property
def gold_similarities(self):
return self._gold_similarities
@property
def composed_similarities(self):
return self._composed_similarities
|
# Generated by Django 3.0.7 on 2020-07-24 00:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0034_auto_20200722_0509'),
]
operations = [
migrations.AlterField(
model_name='order',
name='payment_method',
field=models.CharField(blank=True, default='CASH ON', max_length=12, null=True),
),
migrations.AlterField(
model_name='order',
name='payment_status',
field=models.CharField(blank=True, default='PENDING', max_length=12, null=True),
),
]
|
#!/usr/bin/python3
def soma(x, y):
return x + y
print(soma('daniel' , 'prata'))
#__________________________________________________________
def boas_vindas(nome):
return 'Seja bem vindo {}'.format(nome.title())
print(boas_vindas('daniel'))
#_________________________________________________________
def ler_arquivo(nome):
with open(nome, 'r') as arquivo:
conteudo = arquivo.read()
return conteudo
print(ler_arquivo('frutas.txt'))
#___________________________________________________
def troca(nome)
nome = nome.replace('a' , '@')
return 'Seja bem vindo {}'.format(nome.title())
print(troca(nomes)) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#dateTime:2019/3/5 0005 下午 15:25
#file:copyfile.py
#design: nchu xlm
#浅copy只会copy最顶层的数据,对于不可变的数据类型,只会copy它的引用
# 深拷贝它会递归拷贝,如果是不可变数据类型他只会引用不会拷贝,如果是可变数据类型,它会递归拷贝
# 1. copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
# 2. copy.deepcopy 深拷贝 拷贝对象及其子对象
import requests
url="https://www.baidu.com/img/baidu_resultlogo@2.png"
response=requests.get(url)
with open("baidu.jpg","wb") as f:
f.write(response.content) |
#!/usr/bin/python3
'''
Assuming a sorted list, search for a value in the list by repeatedly
bisecting it.
'''
def search_list(in_list, in_val):
list_len = len(in_list)
head = 0
tail = list_len - 1
while head <= tail:
idx = int((head + tail) / 2)
if in_list[idx] == in_val:
return idx
elif in_list[idx] > in_val:
tail = idx - 1
else:
# in_list[idx] < in_val
head = idx + 1
return None
def search_list_rec(in_list, in_val):
list_len = len(in_list)
head = 0
tail = list_len - 1
if head == tail:
if in_list[head] == in_val:
return 0
return None
if head < tail:
idx = int((head + tail) / 2)
if in_list[idx] == in_val:
return idx
elif in_list[idx] > in_val:
# slice the list at the midpoint,
# removing all values including idx.
# as the list has not changed from the head, the idx is still
# within [0, idx) so return directly from the recursive call.
return search_list_rec(in_list[:idx], in_val)
else:
# in_list[idx] < in_val
# slice the list at the head, removing all values including idx,
# and account for this offset with +1 on the output.
offset_idx = search_list_rec(in_list[idx+1:], in_val)
if offset_idx == None:
return None
return (idx + 1) + offset_idx
return None
|
Product of Current and Next Elements
Given an array of integers of size N as input, the program must print the product of current element and next element if the current element is greater than the next element. Else the program must print the current element without any modification.
Boundary Condition(s):
1 <= N <= 100
Input Format:
The first line contains the value of N.
The second line contains N integers separated by space(s).
Output Format:
The first line contains N integers separated by space(s).
Example Input/Output 1:
Input:
6
5 4 6 5 7 2
Output:
20 4 30 5 14 2
Explanation:
For 1st element, 5>4 so the output is 5*4=20
For 2nd element, 4<6 so the output is 4
For 3rd element, 6>5 so the output is 6*5=30
For 4th element, 5<7 so the output is 5
For 5th element, 7>2 so the output is 14
For 6th element there is no next element, so the output is 2
Example Input/Output 2:
Input:
5
22 21 30 2 5
Output:
462 21 60 2 5
Explanation:
For 1st element, 22>21 so the output is 22*21=462
For 2nd element, 21<30 so the output is 21
For 3rd element, 30>2 so the output is 30*2=60
For 4th element, 2<5 so the output is 2
For 5th element there is no next element, so the output is 5
n=int(input())
l=list(map(int,input().split()))
for i in range(n-1):
if(l[i]>l[i+1]):
print(l[i]*l[i+1],end=" ")
else:
print(l[i],end=" ")
print(l[n-1])
|
#!/usr/bin/python3
def common_elements(set_1, set_2):
if isinstance(set_1, set) and isinstance(set_2, set):
new_set = {e for e in set_1 if e in set_2}
return new_set
return set()
|
from fingerprint import add_song
import argparse
parser = argparse.ArgumentParser(description='Add a song or directory of songs to the reference database')
parser.add_argument('path', help='path/to/song/or/directory')
args = parser.parse_args()
add_song(args.path)
|
import Arena
#from connect4.Connect4Game import Connect4Game, display
#from connect4.Connect4Players import *
from tictactoe.TicTacToeGame import TicTacToeGame, display
from tictactoe.TicTacToePlayers import *
#from gobang.GobangGame import GobangGame, display
#from gobang.GobangPlayers import *
import numpy as np
from MCS import *
from MCTS import *
from Qlearning import *
from utils import *
"""
use this script to play any two agents against each other, or play manually with
any agent.
"""
#define games
#g = Connect4Game(4)
g = TicTacToeGame()
#g = GobangGame(7)
#define players
rp = RandomPlayer(g).play
mcsp = MCS(g,100).play
mctsp = MCTS(g,100).play
qlp = Qlearning(g, 100, 0.01, 0.9, 0.9).play
arena_rp_op = Arena.Arena(mcsp, rp, g, display=display)
print(arena_rp_op.playGames(10, verbose=False))
arena_rp_op = Arena.Arena(mctsp, rp, g, display=display)
print(arena_rp_op.playGames(10, verbose=False))
arena_rp_op = Arena.Arena(qlp, rp, g, display=display)
print(arena_rp_op.playGames(10, verbose=False))
|
# -*- coding: utf-8 -*-
import logging
from django.test.client import Client
from mock import patch
from networkapi.api_network.tasks import create_networkv6
from networkapi.api_network.tasks import deploy_networkv6
from networkapi.ip.models import NetworkIPv6
from networkapi.test.test_case import NetworkApiTestCase
from networkapi.usuario.models import Usuario
log = logging.getLogger(__name__)
class NetworkIPv6AsyncPostSuccessTestCase(NetworkApiTestCase):
def setUp(self):
self.client = Client()
def tearDown(self):
pass
@patch('networkapi.api_network.facade.v3.create_networkipv6')
@patch('networkapi.api_network.facade.v3.get_networkipv6_by_id')
@patch('networkapi.usuario.models.Usuario.objects.get')
@patch('networkapi.api_network.tasks.create_networkv6.update_state')
def test_task_id_create_in_post_one_netipv6_success(self, *args):
"""Test success of id task generate for netipv6 post success."""
mock_get_user = args[1]
mock_get_netv6 = args[2]
mock_create_netv6 = args[3]
user = Usuario(id=1, nome='test')
net = NetworkIPv6(id=1)
mock_create_netv6.return_value = net
mock_get_netv6.return_value = net
mock_get_user.return_value = user
create_networkv6({}, user.id)
mock_create_netv6.assert_called_with({}, user)
class NetworkIPv6AsyncPostErrorTestCase(NetworkApiTestCase):
def setUp(self):
self.client = Client()
def tearDown(self):
pass
def test_task_id_create_in_post_one_netipv6_error(self):
"""Test success of id task generate for netipv6 post error."""
pass
class NetworkIPv6AsyncPostDeploySuccessTestCase(NetworkApiTestCase):
def setUp(self):
self.client = Client()
def tearDown(self):
pass
@patch('networkapi.api_network.facade.v3.deploy_networkipv6')
@patch('networkapi.api_network.facade.v3.get_networkipv6_by_id')
@patch('networkapi.usuario.models.Usuario.objects.get')
@patch('networkapi.api_network.tasks.deploy_networkv6.update_state')
def test_task_id_create_in_post_deploy_one_netipv6_success(self, *args):
"""Test success of id task generate for netipv6 post deploy success."""
mock_get_user = args[1]
mock_get_netv6 = args[2]
mock_deploy_netv6 = args[3]
user = Usuario(id=1, nome='test')
net = NetworkIPv6(id=1)
mock_deploy_netv6.return_value = net
mock_get_netv6.return_value = net
mock_get_user.return_value = user
deploy_networkv6(net.id, user.id)
mock_deploy_netv6.assert_called_with(net.id, user)
class NetworkIPv6AsyncPostDeployErrorTestCase(NetworkApiTestCase):
def setUp(self):
self.client = Client()
def tearDown(self):
pass
def test_task_id_create_in_post_deploy_one_netipv6_error(self):
"""Test success of id task generate for netipv6 post deploy error."""
pass
|
import subprocess
import sys
import numpy as np
import scipy.stats as stats
from scipy.signal import detrend
from joblib import Parallel, delayed
#import nitime.algorithms as tsa
from multitaper_spectrogram import *
from bandpower import *
# this is python version of sample entropy which is very slow but runs on different OSs
#from sampen_python.sampen2 import sampen2 # https://sampen.readthedocs.io/en/latest/
# this is C++ version of sample entropy which is not slow but needs compilation on Linux
#SAMPEN_PATH = 'sampen_C/sampen' # https://www.physionet.org/physiotools/sampen/
def compute_features_each_seg(eeg_seg, Fs, NW, band_freq, band_names, total_freq_range, combined_channel_names=None, window_length=None, window_step=None, need_sampen=False):
"""
Compute features for each segment
eeg_seg: np.array, shape=(#channel, #sample points)
Fs: sampling frequency in Hz
NW: time-halfbandwidth product to control the freq resolution, NW = bandwidth/2 * window_time
band_freq: list of the frequencies of the bands, such as [[0.5,4],[4,8]] for delta and theta
band_names: list of band names, must have same length as band_freq
total_freq_range: list, the total freq range for relative power, such as [0.5,20] for sleep
combined_channel_names: optional, for sleep montage F3M2, F4M1, C3M2, C4M1, O1M2, O2M1 only, set to either None (default) or ['F','C','O']
window_length: window size for time-freq spectrogram inside this segment, specified in # of sample points. Default is None which equals to eeg_seg.shape[-1]
window_length: window step for time-freq spectrogram inside this segment, specified in # of sample points. Default is None which equals to eeg_seg.shape[-1]
need_sampen: bool, whether to compute sample entropy, which is slow. Default to False.
"""
assert len(band_freq)==len(band_names), 'band_names must have same length as band_freq'
if window_length is None or window_step is None:
window_length = eeg_seg.shape[-1]
window_step = eeg_seg.shape[-1]
# compute spectrogram
# spec, shape=(window_num, freq_point_num, channel_num)
# freq, shape=(freq_point_num,)
spec, freq = multitaper_spectrogram(eeg_seg, Fs, NW, window_length, window_step)
if combined_channel_names is not None:
# TODO assume left and right, left and right, ... channels
spec = (spec[:,:,::2]+spec[:,:,1::2])/2.0
# band power
bp, band_findex = bandpower(spec, freq, band_freq, total_freq_range=total_freq_range, relative=False)
## time domain features
# signal line length
f1 = np.abs(np.diff(eeg_seg,axis=1)).sum(axis=1)*1.0/eeg_seg.shape[-1]
# signal kurtosis
f2 = stats.kurtosis(eeg_seg,axis=1,nan_policy='propagate')
if need_sampen:
# signal sample entropy
f3 = []
for ci in range(len(eeg_seg)):
#Bruce, E. N., Bruce, M. C., & Vennelaganti, S. (2009).
#Sample entropy tracks changes in EEG power spectrum with sleep state and aging. Journal of clinical neurophysiology, 26(4), 257.
# python version (slow, for multiple OSs)
f3.append(sampen2(list(eeg_seg[ci]),mm=2,r=0.2,normalize=True)[-1][1]) # sample entropy
# C++ version (not slow, for Linux only)
#sp = subprocess.Popen([SAMPEN_PATH,'-m','2','-r','0.2','-n'],stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.STDOUT)#
## frequency domain features
f4 = [];f5 = [];f6 = [];f7 = [];f9 = []
band_num = len(band_freq)
for bi in range(band_num):
if band_names[bi].lower()!='sigma': # no need for sigma band
if len(spec)>1: # this segment is split into multiple sub-windows
# max, min, std of band power inside this segment
f4.extend(np.percentile(bp[bi],95,axis=0))
f5.extend(bp[bi].min(axis=0))
f7.extend(bp[bi].std(axis=0))
# mean band power inside this segment
f6.extend(bp[bi].mean(axis=0))
if len(spec)>1:
# spectral kurtosis as a rough density measure of transient events such as spindle
spec_flatten = spec[:,band_findex[bi],:].reshape(spec.shape[0]*len(band_findex[bi]),spec.shape[2])
f9.extend(stats.kurtosis(spec_flatten, axis=0, nan_policy='propagate'))
f10 = []
delta_theta = bp[0]/(bp[1]+1)
if len(spec)>1: # this segment is split into multiple sub-windows
# max, min, std, mean of delta/theta ratios inside this segment
f10.extend(np.percentile(delta_theta,95,axis=0))
f10.extend(np.min(delta_theta,axis=0))
f10.extend(np.mean(delta_theta,axis=0))
if len(spec)>1:
f10.extend(np.std(delta_theta,axis=0))
f11 = []
delta_alpha = bp[0]/(bp[2]+1)
if len(spec)>1: # this segment is split into multiple sub-windows
# max, min, std, mean of delta/alpha ratios inside this segment
f11.extend(np.percentile(delta_alpha,95,axis=0))
f11.extend(np.min(delta_alpha,axis=0))
f11.extend(np.mean(delta_alpha,axis=0))
if len(spec)>1:
f11.extend(np.std(delta_alpha,axis=0))
f12 = []
theta_alpha = bp[1]/(bp[2]+1)
# max, min, std, mean of theta/alpha ratios inside this segment
if len(spec)>1: # this segment is split into multiple sub-windows
f12.extend(np.percentile(theta_alpha,95,axis=0))
f12.extend(np.min(theta_alpha,axis=0))
f12.extend(np.mean(theta_alpha,axis=0))
if len(spec)>1:
f12.extend(np.std(theta_alpha,axis=0))
if need_sampen:
return np.r_[f1,f2,f3,f4,f5,f6,f7,f9,f10,f11,f12]
else:
return np.r_[f1,f2,f4,f5,f6,f7,f9,f10,f11,f12]
def extract_features(eeg_segs, Fs, channel_names, NW, sub_window_time=None, sub_window_step=None, return_feature_names=True, combined_channel_names=None, need_sampen=False, n_jobs=1, verbose=True):
"""
Extract features from EEG segments in parallel.
Arguments:
eeg_segs: np.ndarray, shape=(#seg, #channel, #sample points)
Fs: sampling frequency in Hz
channel_names: a list of channel names
NW: time-halfbandwidth product to control the freq resolution, NW = bandwidth/2 * window_time
sub_window_time: sub-window time in seconds for spectrogram inside each segment. Default is None which equals to eeg_seg.shape[-1]
window_length: window step for time-freq spectrogram inside this segment, specified in # of sample points. Default is None which equals to eeg_seg.shape[-1]
return_feature_names: bool, if to return feature names as a list, default True.
combined_channel_names: optional, for sleep montage F3M2, F4M1, C3M2, C4M1, O1M2, O2M1 only, set to either None (default) or ['F','C','O']
need_sampen: bool. need to compute sample entropy. default is False
n_jobs: number of CPUs to run in parallel, default is 1 (serial), set to -1 to use all CPUs
Outputs:
features from each segment in np.ndarray type, shape=(#seg, #feature)
a list of names of each feature
"""
seg_num = len(eeg_segs)
if seg_num <= 0:
return []
band_names = ['delta','theta','alpha','sigma']
band_freq = [[0.5,4],[4,8],[8,12],[12,20]] # [Hz]
tostudy_freq = [0.5, 20.] # [Hz]
sub_window_size = int(round(sub_window_time*Fs))
sub_step_size = int(round(sub_window_step*Fs))
#old_threshold = np.get_printoptions()['threshold']
#np.set_printoptions(threshold=np.nan)
with Parallel(n_jobs=n_jobs, verbose=verbose) as parallel:
features = parallel(delayed(compute_features_each_seg)(
eeg_segs[segi], Fs, NW,
band_freq, band_names, tostudy_freq,
combined_channel_names,
sub_window_size, sub_step_size, need_sampen) for segi in range(seg_num))
#np.set_printoptions(threshold=old_threshold)
if return_feature_names:
feature_names = ['line_length_%s'%chn for chn in channel_names]
feature_names += ['kurtosis_%s'%chn for chn in channel_names]
if need_sampen:
feature_names += ['sample_entropy_%s'%chn for chn in channel_names]
if sub_window_time is None or sub_window_step is None:
feats = ['mean']
else:
feats = ['max','min','mean','std','kurtosis']
for ffn in feats:
for bn in band_names:
if ffn=='kurtosis' or bn!='sigma': # no need for sigma band
feature_names += ['%s_bandpower_%s_%s'%(bn,ffn,chn) for chn in combined_channel_names]
power_ratios = ['delta/theta','delta/alpha','theta/alpha']
for pr in power_ratios:
if not (sub_window_time is None or sub_window_step is None):
feature_names += ['%s_max_%s'%(pr,chn) for chn in combined_channel_names]
feature_names += ['%s_min_%s'%(pr,chn) for chn in combined_channel_names]
feature_names += ['%s_mean_%s'%(pr,chn) for chn in combined_channel_names]
if not (sub_window_time is None or sub_window_step is None):
feature_names += ['%s_std_%s'%(pr,chn) for chn in combined_channel_names]
if return_feature_names:
return np.array(features), feature_names#, pxx_mts, freqs
else:
return np.array(features)#, pxx_mts, freqs
|
import pandas as pd
import matplotlib.pyplot as plt
from stats.frames import games, info, events
plays = games.query("type == 'play' & event != 'NP'")
plays.columns = ['type', 'inning', 'team', 'player', 'count', 'pitches', 'event', 'game_id', 'year']
pa = plays.loc[plays['player'].shift() != plays['player'],['year', 'game_id', 'inning', 'team', 'player']]
pa = pa.groupby(['year','game_id','team']).size().reset_index(name='PA')
events = events.set_index(['year', 'game_id', 'team', 'event_type'])
events = events.unstack().fillna(0).reset_index()
events.columns = events.columns.droplevel()
events.columns = ['year', 'game_id', 'team', 'BB', 'E', 'H', 'HBP', 'HR', 'ROE', 'SO']
events = events.rename_axis(None,axis='columns')
events_plus_pa = pd.merge(events, pa, how='outer', left_on=['year', 'game_id', 'team'], right_on=['year', 'game_id', 'team'])
defense = pd.merge(events_plus_pa, info)
# i used the below but the commit test failed
#defense['DER'] = defense.apply(lambda x: (1 - ((x['H'] + x['ROE']) / (x['PA'] - x['BB'] - x['SO'] - x['HBP'] - x['HR']))), axis=1)
#this is their solution for above
defense.loc[:, 'DER'] = 1 - ((defense['H'] + defense['ROE']) / (defense['PA'] - defense['BB'] - defense['SO'] - defense['HBP'] - defense['HR']))
defense.loc[:, 'year'] = pd.to_numeric(defense.loc[:, 'year'])
der = defense.loc[defense['year'] >= 1978,['year','defense','DER']]
der = der.pivot(index='year',columns='defense',values='DER')
der.plot(x_compat=True,xticks=range(1978,2018,4),rot=45)
plt.show()
|
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
import time
if __name__ == "__main__":
train_num = 20000
test_num = 30000
data = pd.read_csv('train.csv')
train_data = data.values[0:train_num, 1:]
train_label = data.values[0:train_num, 0]
test_data = data.values[train_num:test_num, 1:]
test_label = data.values[train_num:test_num, 0]
t = time.time()
pca = PCA(n_components=0.8)
train_x = pca.fit_transform(train_data)
test_x = pca.transform(test_data)
neighbors = KNeighborsClassifier(n_neighbors=4)
neighbors.fit(train_x, train_label)
pre = neighbors.predict(test_x)
acc = float((pre == test_label).sum()) / len(test_x)
print(u'精確度:%f,花費時間:%.2fs' % (acc, time.time() - t))
|
class Critter(object):
"""Virtual pet"""
def __init__(self,name,hunger=0,boredom=0):
self.name=name
self.hunger=hunger
self.boredom=boredom
def __pass_time(self):
self.hunger+=1
self.boredom+=1
@property
def mood(self):
unhappiness=self.hunger+self.boredom
if unhappiness<5:
m="fine"
elif 5<=unhappiness<=10:
m="not bat"
elif 11<=unhappiness<=15:
m="not so good"
else:
m="bad"
return m
def talk(self):
print("My nane is ", self.name,", and i feel ",self.mood," now\n")
self.__pass_time()
def eat(self,food=4):
print("Mrrr..thanx!")
self.hunger-=food
if self.hunger<0:
self.hunger=0
self.__pass_time()
def play(self,fun=4):
print("UWEE")
self.boredom-=fun
if self.boredom<0:
self.boredom=0
self.__pass_time()
def main():
crit_name=input("How would you name your pet?")
crit=Critter(crit_name)
choice=None
while choice!="0":
print(
"""
My PET
0-exit
1-Explore condition
2-Feed pet
3-Play with pet
"""
)
choice=input("Your choice: ")
print()
#exit
if choice=="0":
print("Goodbye")
#talk with pets
elif choice=="1":
crit.talk()
elif choice=="2":
crit.eat()
elif choice=="3":
crit.play()
#uknown nInput
else:
print("Sorry, uknown input: ", choice)
main()
input("\n\nPress enter to exit")
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2018/8/27 11:51
# @Author : zhangxingchen
# @Site : zxcser@163.com
# @File : test_rever.py
# @Software: PyCharm
def reverse(string):
return string[::-1]
def test_reverse():
string = "good"
assert reverse(string) == "doog"
another_string = "itest"
assert reverse(another_string) == "tseti"
|
"""Some waveguides make unnecessary crossings."""
import gdsfactory as gf
from gdsfactory.samples.big_device import big_device
if __name__ == "__main__":
c = big_device()
c = gf.routing.add_fiber_single(component=c)
c.show(show_ports=True)
|
import os
import datetime
import argparse
DEFAULT_ADDR = "127.0.1.1"
DEFAULT_PORT = "8338"
CMD_RL = "export CUDA_LAUNCH_BLOCKING=1 && \
export PYTHONPATH={}:$PYTHONPATH && \
python -u -m torch.distributed.launch \
--nproc_per_node={} \
--master_addr {} \
--master_port {} \
--use_env \
{} \
--task-type {} \
--noise {} \
--exp-config {} \
--run-type {} \
--n-gpu {} \
--cur-time {}"
CMD_VO = "export CUDA_LAUNCH_BLOCKING=1 && \
export PYTHONPATH={}:$PYTHONPATH && \
python {} \
--task-type {} \
--noise {} \
--exp-config {} \
--run-type {} \
--n-gpu {} \
--cur-time {}"
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--task-type",
choices=["rl", "vo"],
required=True,
help="Specify the category of the task",
)
parser.add_argument(
"--noise",
type=int,
required=True,
help="Whether adding noise into environment",
)
parser.add_argument(
"--run-type",
choices=["train", "eval"],
required=True,
help="run type of the experiment (train or eval)",
)
parser.add_argument(
"--repo-path", type=str, required=True, help="path to PointNav repo",
)
parser.add_argument(
"--n_gpus", type=int, required=True, help="path to PointNav repo",
)
parser.add_argument(
"--addr", type=str, required=True, help="master address",
)
parser.add_argument(
"--port", type=str, required=True, help="master port",
)
args = parser.parse_args()
cur_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S%f")
if args.task_type == "rl":
cur_config_f = os.path.join(args.repo_path, "configs/rl/ddppo_pointnav.yaml")
elif args.task_type == "vo":
cur_config_f = os.path.join(args.repo_path, "configs/vo/vo_pointnav.yaml")
else:
pass
if "rl" in args.task_type:
tmp_cmd = CMD_RL.format(
args.repo_path,
args.n_gpus,
args.addr,
args.port,
# {}/point_nav/run.py
os.path.join(args.repo_path, "pointnav_vo/run.py"),
args.task_type,
args.noise,
cur_config_f,
args.run_type,
args.n_gpus,
cur_time,
)
elif "vo" in args.task_type:
tmp_cmd = CMD_VO.format(
args.repo_path,
os.path.join(args.repo_path, "pointnav_vo/run.py"),
args.task_type,
args.noise,
cur_config_f,
args.run_type,
args.n_gpus,
cur_time,
)
else:
raise ValueError
print("\n", tmp_cmd, "\n")
os.system(tmp_cmd)
|
import numpy
from pyIEM import iemdb
i = iemdb.iemdb()
coop = i['coop']
maymin = []
aprgdd = []
rs = coop.query("SELECT year, min(low) from alldata WHERE month = 5 and stationid = 'ia0200' GROUP by year ORDER by year ASC").dictresult()
for i in range(len(rs)):
maymin.append( rs[i]['min'] )
rs = coop.query("SELECT year, sum(gdd50(high,low)) as sum from alldata WHERE month = 5 and stationid = 'ia0200' GROUP by year ORDER by year ASC").dictresult()
for i in range(len(rs)):
aprgdd.append( rs[i]['sum'] )
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
xy = ax.plot(maymin, aprgdd, 'd', markersize=8, markerfacecolor='blue')
fig.savefig("test.png")
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'F:\BE32001\pythonProject\alarm.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QDialog, QFileDialog
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
import os.path
import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt
import pyqtgraph as pg
from pyqtgraph import PlotWidget
from PyQt5.uic import loadUi
CURRENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
red = os.path.join(CURRENT_DIRECTORY, "image/red.jpg")
grey = os.path.join(CURRENT_DIRECTORY, "image/grey.jpg")
class Ui_Cellexus_CellMaker(QDialog):#obiject->dialog
def setupUi(self, Cellexus_CellMaker):
Cellexus_CellMaker.setObjectName("Cellexus_CellMaker")
Cellexus_CellMaker.resize(1600, 900)
Cellexus_CellMaker.setMaximumSize(QtCore.QSize(1600, 900))
font = QtGui.QFont()
font.setFamily("Arial")
Cellexus_CellMaker.setFont(font)
self.centralwidget = QtWidgets.QWidget(Cellexus_CellMaker)
self.centralwidget.setObjectName("centralwidget")
self.tab1 = QtWidgets.QTabWidget(self.centralwidget)
self.tab1.setGeometry(QtCore.QRect(10, 10, 1575, 850))
self.tab1.setMaximumSize(QtCore.QSize(1575, 850))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
self.tab1.setFont(font)
#self.tab1.setStyleSheet("background-color: rgb(255, 255, 255);")
self.tab1.setTabShape(QtWidgets.QTabWidget.Rounded)
self.tab1.setObjectName("tab1")
self.Main = QtWidgets.QWidget()
font = QtGui.QFont()
font.setFamily("Arial")
self.Main.setFont(font)
self.Main.setObjectName("Main")
self.horizontalLayoutWidget = QtWidgets.QWidget(self.Main)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 1031, 103))
self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.alarmbox = QtWidgets.QGroupBox(self.horizontalLayoutWidget)
self.alarmbox.setMinimumSize(QtCore.QSize(590, 100))
font = QtGui.QFont()
font.setFamily("Arial")
self.alarmbox.setFont(font)
#self.alarmbox.setStyleSheet("background-color: rgb(247, 247, 247);")
self.alarmbox.setObjectName("alarmbox")
self.layoutWidget = QtWidgets.QWidget(self.alarmbox)
self.layoutWidget.setGeometry(QtCore.QRect(10, 20, 577, 69))
self.layoutWidget.setObjectName("layoutWidget")
self.gridLayout_3 = QtWidgets.QGridLayout(self.layoutWidget)
self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
self.gridLayout_3.setSpacing(7)
self.gridLayout_3.setObjectName("gridLayout_3")
self.Press_led = QtWidgets.QLabel(self.layoutWidget)
self.Press_led.setMinimumSize(QtCore.QSize(0, 0))
self.Press_led.setMaximumSize(QtCore.QSize(30, 30))
self.Press_led.setObjectName("Press_led")
self.gridLayout_3.addWidget(self.Press_led, 0, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.pO2_alarm = QtWidgets.QLabel(self.layoutWidget)
self.pO2_alarm.setMinimumSize(QtCore.QSize(90, 0))
self.pO2_alarm.setMaximumSize(QtCore.QSize(90, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.pO2_alarm.setFont(font)
self.pO2_alarm.setAlignment(QtCore.Qt.AlignCenter)
self.pO2_alarm.setObjectName("pO2_alarm")
self.gridLayout_3.addWidget(self.pO2_alarm, 1, 5, 1, 1)
self.Press_alarm = QtWidgets.QLabel(self.layoutWidget)
self.Press_alarm.setMinimumSize(QtCore.QSize(90, 0))
self.Press_alarm.setMaximumSize(QtCore.QSize(90, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.Press_alarm.setFont(font)
self.Press_alarm.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
self.Press_alarm.setLayoutDirection(QtCore.Qt.LeftToRight)
self.Press_alarm.setTextFormat(QtCore.Qt.AutoText)
self.Press_alarm.setAlignment(QtCore.Qt.AlignCenter)
self.Press_alarm.setObjectName("Press_alarm")
self.gridLayout_3.addWidget(self.Press_alarm, 1, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.Temp_led = QtWidgets.QLabel(self.layoutWidget)
self.Temp_led.setMaximumSize(QtCore.QSize(30, 30))
self.Temp_led.setObjectName("Temp_led")
self.gridLayout_3.addWidget(self.Temp_led, 0, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.Airflow_led = QtWidgets.QLabel(self.layoutWidget)
self.Airflow_led.setMaximumSize(QtCore.QSize(30, 30))
self.Airflow_led.setObjectName("Airflow_led")
self.gridLayout_3.addWidget(self.Airflow_led, 0, 3, 1, 1, QtCore.Qt.AlignHCenter)
self.pO2_led = QtWidgets.QLabel(self.layoutWidget)
self.pO2_led.setMaximumSize(QtCore.QSize(30, 30))
self.pO2_led.setObjectName("pO2_led")
self.gridLayout_3.addWidget(self.pO2_led, 0, 5, 1, 1, QtCore.Qt.AlignHCenter)
self.Temp_alarm = QtWidgets.QLabel(self.layoutWidget)
self.Temp_alarm.setMinimumSize(QtCore.QSize(90, 0))
self.Temp_alarm.setMaximumSize(QtCore.QSize(90, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.Temp_alarm.setFont(font)
self.Temp_alarm.setAlignment(QtCore.Qt.AlignCenter)
self.Temp_alarm.setObjectName("Temp_alarm")
self.gridLayout_3.addWidget(self.Temp_alarm, 1, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.pH_led = QtWidgets.QLabel(self.layoutWidget)
self.pH_led.setMaximumSize(QtCore.QSize(30, 30))
self.pH_led.setObjectName("pH_led")
self.gridLayout_3.addWidget(self.pH_led, 0, 4, 1, 1, QtCore.Qt.AlignHCenter)
self.O2flow_led = QtWidgets.QLabel(self.layoutWidget)
self.O2flow_led.setMaximumSize(QtCore.QSize(30, 30))
self.O2flow_led.setObjectName("O2flow_led")
self.gridLayout_3.addWidget(self.O2flow_led, 0, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.Airflow_alarm = QtWidgets.QLabel(self.layoutWidget)
self.Airflow_alarm.setMinimumSize(QtCore.QSize(90, 0))
self.Airflow_alarm.setMaximumSize(QtCore.QSize(90, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.Airflow_alarm.setFont(font)
self.Airflow_alarm.setAlignment(QtCore.Qt.AlignCenter)
self.Airflow_alarm.setObjectName("Airflow_alarm")
self.gridLayout_3.addWidget(self.Airflow_alarm, 1, 4, 1, 1)
self.O2flow_alarm = QtWidgets.QLabel(self.layoutWidget)
self.O2flow_alarm.setMinimumSize(QtCore.QSize(90, 0))
self.O2flow_alarm.setMaximumSize(QtCore.QSize(90, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.O2flow_alarm.setFont(font)
self.O2flow_alarm.setAlignment(QtCore.Qt.AlignCenter)
self.O2flow_alarm.setObjectName("O2flow_alarm")
self.gridLayout_3.addWidget(self.O2flow_alarm, 1, 2, 1, 1)
self.pH_alarm = QtWidgets.QLabel(self.layoutWidget)
self.pH_alarm.setMinimumSize(QtCore.QSize(90, 0))
self.pH_alarm.setMaximumSize(QtCore.QSize(90, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.pH_alarm.setFont(font)
self.pH_alarm.setAlignment(QtCore.Qt.AlignCenter)
self.pH_alarm.setObjectName("pH_alarm")
self.gridLayout_3.addWidget(self.pH_alarm, 1, 3, 1, 1)
self.horizontalLayout.addWidget(self.alarmbox)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.modeBox = QtWidgets.QGroupBox(self.horizontalLayoutWidget)
self.modeBox.setMinimumSize(QtCore.QSize(320, 100))
#self.modeBox.setStyleSheet("background-color: rgb(247, 247, 247);")
self.modeBox.setTitle("")
self.modeBox.setObjectName("modeBox")
self.horizontalLayoutWidget_3 = QtWidgets.QWidget(self.modeBox)
self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(20, 10, 278, 80))
self.horizontalLayoutWidget_3.setObjectName("horizontalLayoutWidget_3")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_3)
self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.Mode = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
self.Mode.setMinimumSize(QtCore.QSize(120, 30))
self.Mode.setMaximumSize(QtCore.QSize(120, 30))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(12)
self.Mode.setFont(font)
self.Mode.setAlignment(QtCore.Qt.AlignCenter)
self.Mode.setObjectName("Mode")
self.verticalLayout.addWidget(self.Mode, 0, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.mode_choice = QtWidgets.QComboBox(self.horizontalLayoutWidget_3)
self.mode_choice.setMinimumSize(QtCore.QSize(120, 30))
self.mode_choice.setMaximumSize(QtCore.QSize(120, 30))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
self.mode_choice.setFont(font)
self.mode_choice.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
self.mode_choice.setLayoutDirection(QtCore.Qt.LeftToRight)
self.mode_choice.setAutoFillBackground(False)
#self.mode_choice.setStyleSheet("background-color: rgb(255, 255, 255);")
self.mode_choice.setInsertPolicy(QtWidgets.QComboBox.NoInsert)
self.mode_choice.setObjectName("mode_choice")
self.mode_choice.addItem("")
self.mode_choice.addItem("")
self.mode_choice.addItem("")
self.mode_choice.addItem("")
self.verticalLayout.addWidget(self.mode_choice, 0, QtCore.Qt.AlignVCenter)
self.horizontalLayout_3.addLayout(self.verticalLayout)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem1)
self.Run = QtWidgets.QPushButton(self.horizontalLayoutWidget_3)
self.Run.setMinimumSize(QtCore.QSize(120, 35))
self.Run.setMaximumSize(QtCore.QSize(100, 35))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setUnderline(False)
font.setWeight(50)
#run button
self.Run.setFont(font)
self.Run.setStyleSheet("background-color:rgba(255,255,255,133);border-color:rgba(0,0,0,255);color: rgba(0, 0, 0,255);border-style:solid;border-width:1px;border-radius:2px;")
self.Run.setCheckable(True)
self.Run.setAutoRepeat(True)
self.Run.setAutoDefault(True)
self.Run.setFlat(True)
self.Run.setObjectName("Run")
#button icon set
self.Run.setStyleSheet("QPushButton{border-image: url(image/button_off.png)}")##
# self.Run.setIcon(QtGui.QIcon('image\button_off.png'))###set icon need\ set picture need/
# self.Run.setIconSize(QtCore.QSize(120,35))##
self.horizontalLayout_3.addWidget(self.Run)
self.horizontalLayout.addWidget(self.modeBox)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
#main picture
self.Bioreactor_pic = QtWidgets.QLabel(self.Main)
self.Bioreactor_pic.setGeometry(QtCore.QRect(200, 170, 950, 580))#50->200 adjust the position
self.Bioreactor_pic.setFrameShape(QtWidgets.QFrame.NoFrame)
self.Bioreactor_pic.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.Bioreactor_pic.setObjectName("Bioreactor_pic")
self.setpointBox = QtWidgets.QGroupBox(self.Main)
self.setpointBox.setGeometry(QtCore.QRect(1360, 10, 181, 381))
font = QtGui.QFont()
font.setFamily("Arial")
self.setpointBox.setFont(font)
#self.setpointBox.setStyleSheet("background-color: rgb(247, 247, 247);")
self.setpointBox.setObjectName("setpointBox")
self.verticalLayoutWidget = QtWidgets.QWidget(self.setpointBox)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 20, 160, 351))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.Temp_SP = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
self.Temp_SP.setFont(font)
self.Temp_SP.setAlignment(QtCore.Qt.AlignCenter)
self.Temp_SP.setObjectName("Temp_SP")
self.verticalLayout_2.addWidget(self.Temp_SP)
self.Temp_SPvalue = QtWidgets.QDoubleSpinBox(self.verticalLayoutWidget)
self.Temp_SPvalue.setMinimumSize(QtCore.QSize(0, 30))
self.Temp_SPvalue.setMaximumSize(QtCore.QSize(16777215, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.Temp_SPvalue.setFont(font)
self.Temp_SPvalue.setLayoutDirection(QtCore.Qt.LeftToRight)
self.Temp_SPvalue.setStyleSheet("QDoubleSpinBox::up-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:left; \n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"QDoubleSpinBox::down-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:right;\n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"background-color: rgb(239, 239, 239);")
self.Temp_SPvalue.setFrame(True)
self.Temp_SPvalue.setAlignment(QtCore.Qt.AlignCenter)
self.Temp_SPvalue.setReadOnly(False)
self.Temp_SPvalue.setButtonSymbols(QtWidgets.QAbstractSpinBox.UpDownArrows)
self.Temp_SPvalue.setAccelerated(False)
self.Temp_SPvalue.setCorrectionMode(QtWidgets.QAbstractSpinBox.CorrectToPreviousValue)
self.Temp_SPvalue.setProperty("showGroupSeparator", False)
self.Temp_SPvalue.setDecimals(0)
self.Temp_SPvalue.setObjectName("Temp_SPvalue")
self.verticalLayout_2.addWidget(self.Temp_SPvalue)
spacerItem3 = QtWidgets.QSpacerItem(20, 50, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem3)
self.O2flow_SP = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
self.O2flow_SP.setFont(font)
self.O2flow_SP.setAlignment(QtCore.Qt.AlignCenter)
self.O2flow_SP.setObjectName("O2flow_SP")
self.verticalLayout_2.addWidget(self.O2flow_SP)
self.O2flow_SPvalue = QtWidgets.QDoubleSpinBox(self.verticalLayoutWidget)
self.O2flow_SPvalue.setMinimumSize(QtCore.QSize(0, 30))
self.O2flow_SPvalue.setMaximumSize(QtCore.QSize(16777215, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.O2flow_SPvalue.setFont(font)
self.O2flow_SPvalue.setLayoutDirection(QtCore.Qt.LeftToRight)
self.O2flow_SPvalue.setStyleSheet("QDoubleSpinBox::up-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:left; \n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"QDoubleSpinBox::down-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:right;\n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"background-color: rgb(239, 239, 239);")
self.O2flow_SPvalue.setFrame(True)
self.O2flow_SPvalue.setAlignment(QtCore.Qt.AlignCenter)
self.O2flow_SPvalue.setReadOnly(False)
self.O2flow_SPvalue.setButtonSymbols(QtWidgets.QAbstractSpinBox.UpDownArrows)
self.O2flow_SPvalue.setAccelerated(False)
self.O2flow_SPvalue.setCorrectionMode(QtWidgets.QAbstractSpinBox.CorrectToPreviousValue)
self.O2flow_SPvalue.setProperty("showGroupSeparator", False)
self.O2flow_SPvalue.setDecimals(0)
self.O2flow_SPvalue.setObjectName("O2flow_SPvalue")
self.verticalLayout_2.addWidget(self.O2flow_SPvalue)
self.O2flow_value = QtWidgets.QDoubleSpinBox(self.verticalLayoutWidget)
self.O2flow_value.setMinimumSize(QtCore.QSize(0, 30))
self.O2flow_value.setMaximumSize(QtCore.QSize(16777215, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.O2flow_value.setFont(font)
self.O2flow_value.setStyleSheet("background-color:rgba(0,0,0,0);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;")
self.O2flow_value.setAlignment(QtCore.Qt.AlignCenter)
self.O2flow_value.setReadOnly(True)
self.O2flow_value.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.O2flow_value.setDecimals(3)
self.O2flow_value.setObjectName("O2flow_value")
self.verticalLayout_2.addWidget(self.O2flow_value)
spacerItem4 = QtWidgets.QSpacerItem(20, 50, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem4)
self.Airflow_SP = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
self.Airflow_SP.setFont(font)
self.Airflow_SP.setAlignment(QtCore.Qt.AlignCenter)
self.Airflow_SP.setObjectName("Airflow_SP")
self.verticalLayout_2.addWidget(self.Airflow_SP)
self.Airflow_SPvalue = QtWidgets.QDoubleSpinBox(self.verticalLayoutWidget)
self.Airflow_SPvalue.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.Airflow_SPvalue.setFont(font)
self.Airflow_SPvalue.setStyleSheet("QDoubleSpinBox::up-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:left; \n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"QDoubleSpinBox::down-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:right;\n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"background-color: rgb(239, 239, 239);")
self.Airflow_SPvalue.setAlignment(QtCore.Qt.AlignCenter)
self.Airflow_SPvalue.setDecimals(0)
self.Airflow_SPvalue.setObjectName("Airflow_SPvalue")
self.verticalLayout_2.addWidget(self.Airflow_SPvalue)
self.Airflow_value = QtWidgets.QDoubleSpinBox(self.verticalLayoutWidget)
self.Airflow_value.setMinimumSize(QtCore.QSize(0, 30))
self.Airflow_value.setMaximumSize(QtCore.QSize(16777215, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.Airflow_value.setFont(font)
self.Airflow_value.setStyleSheet("background-color:rgba(0,0,0,0);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;")
self.Airflow_value.setAlignment(QtCore.Qt.AlignCenter)
self.Airflow_value.setReadOnly(True)
self.Airflow_value.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.Airflow_value.setDecimals(3)
self.Airflow_value.setObjectName("Airflow_value")
self.verticalLayout_2.addWidget(self.Airflow_value)
#automatic pump tool box
self.Automatic_Pump = QtWidgets.QToolBox(self.Main)
self.Automatic_Pump.setGeometry(QtCore.QRect(10, 130, 331, 301))##
font = QtGui.QFont()
font.setFamily("Arial")
self.Automatic_Pump.setFont(font)
self.Automatic_Pump.setStyleSheet("")
self.Automatic_Pump.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.Automatic_Pump.setFrameShadow(QtWidgets.QFrame.Sunken)
self.Automatic_Pump.setObjectName("Automatic_Pump")
self.Automatic_pH = QtWidgets.QWidget()
self.Automatic_pH.setGeometry(QtCore.QRect(0, 0, 310, 161))##
self.Automatic_pH.setObjectName("Automatic_pH")
self.AutopHFrame = QtWidgets.QFrame(self.Automatic_pH)
self.AutopHFrame.setGeometry(QtCore.QRect(10, 0, 310, 161))##
self.AutopHFrame.setStyleSheet("")
self.AutopHFrame.setObjectName("AutopHFrame")
self.gridLayout = QtWidgets.QGridLayout(self.AutopHFrame)
self.gridLayout.setObjectName("gridLayout")
self.gridLayout_2 = QtWidgets.QGridLayout()
self.gridLayout_2.setObjectName("gridLayout_2")
self.pHSP_value = QtWidgets.QDoubleSpinBox(self.AutopHFrame)
self.pHSP_value.setMinimumSize(QtCore.QSize(90, 25))
font = QtGui.QFont()
font.setFamily("Arial")
self.pHSP_value.setFont(font)
self.pHSP_value.setStyleSheet("QDoubleSpinBox::up-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:left; \n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"QDoubleSpinBox::down-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:right;\n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"")
self.pHSP_value.setAlignment(QtCore.Qt.AlignCenter)
self.pHSP_value.setDecimals(1)
self.pHSP_value.setObjectName("pHSP_value")
self.gridLayout_2.addWidget(self.pHSP_value, 2, 2, 1, 1)
#acid button
self.acid_button = QtWidgets.QPushButton(self.AutopHFrame)
self.acid_button.setMinimumSize(QtCore.QSize(90, 30))##
font = QtGui.QFont()
font.setFamily("Arial")
self.acid_button.setFont(font)
#self.acid_button.setStyleSheet("background-color:rgba(255,255,255,133);border-color:rgba(0,0,0,255);color: rgba(0, 0, 0,255);border-style:solid;border-width:1px;border-radius:2px;")
self.acid_button.setCheckable(True)
self.acid_button.setAutoRepeat(True)
self.acid_button.setAutoDefault(True)
self.acid_button.setObjectName("acid_button")
#button icon set
self.acid_button.setStyleSheet("QPushButton{border-image: url(image/button_off.png)}")##
# self.acid_button.setIcon(QtGui.QIcon('image\button_off.png'))###set icon need\ set picture need/
# self.acid_button.setIconSize(QtCore.QSize(90,25))##
self.gridLayout_2.addWidget(self.acid_button, 1, 0, 1, 1)
#base button
self.base_button = QtWidgets.QPushButton(self.AutopHFrame)
self.base_button.setMinimumSize(QtCore.QSize(90, 30))##
font = QtGui.QFont()
font.setFamily("Arial")
self.base_button.setFont(font)
#self.base_button.setStyleSheet("background-color:rgba(255,255,255,133);border-color:rgba(0,0,0,255);color: rgba(0, 0, 0,255);border-style:solid;border-width:1px;border-radius:2px;")
self.base_button.setCheckable(True)
self.base_button.setAutoRepeat(True)
self.base_button.setAutoDefault(True)
self.base_button.setObjectName("base_button")
#button icon set
self.base_button.setStyleSheet("QPushButton{border-image: url(image/button_off.png)}")##
# self.base_button.setIcon(QtGui.QIcon('image\button_off.png'))###set icon need\ set picture need/
# self.base_button.setIconSize(QtCore.QSize(90,25))##
self.gridLayout_2.addWidget(self.base_button, 2, 0, 1, 1)
spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_2.addItem(spacerItem5, 1, 1, 1, 1)
self.pHSP_label = QtWidgets.QLabel(self.AutopHFrame)
self.pHSP_label.setMinimumSize(QtCore.QSize(90, 25))
font = QtGui.QFont()
font.setFamily("Arial")
self.pHSP_label.setFont(font)
self.pHSP_label.setAlignment(QtCore.Qt.AlignCenter)
self.pHSP_label.setObjectName("pHSP_label")
self.gridLayout_2.addWidget(self.pHSP_label, 1, 2, 1, 1)
spacerItem6 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
#autopH WINDOW
self.gridLayout_2.addItem(spacerItem6, 0, 1, 1, 1)
self.gridLayout.addLayout(self.gridLayout_2, 1, 2, 1, 1)
self.AutopHBox = QtWidgets.QGroupBox(self.AutopHFrame)
self.AutopHBox.setMinimumSize(QtCore.QSize(240, 70))
font = QtGui.QFont()
font.setFamily("Arial")
self.AutopHBox.setFont(font)
self.AutopHBox.setAlignment(QtCore.Qt.AlignCenter)
self.AutopHBox.setObjectName("AutopHBox")
self.horizontalLayoutWidget_2 = QtWidgets.QWidget(self.AutopHBox)
self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(80, 20, 121, 41))##
self.horizontalLayoutWidget_2.setObjectName("horizontalLayoutWidget_2")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.AutopH_switchlabel1 = QtWidgets.QLabel(self.horizontalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
self.AutopH_switchlabel1.setFont(font)
self.AutopH_switchlabel1.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.AutopH_switchlabel1.setObjectName("AutopH_switchlabel1")
self.horizontalLayout_2.addWidget(self.AutopH_switchlabel1)
#AutopH switch
self.AutopH_switch = QtWidgets.QPushButton(self.horizontalLayoutWidget_2)
self.AutopH_switch.setMinimumSize(QtCore.QSize(60, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.AutopH_switch.setFont(font)
self.AutopH_switch.setStyleSheet("QPushButton\n"
"{\n"
"border: none; \n"
"}\n"
"")
self.AutopH_switch.setCheckable(True)
self.AutopH_switch.setAutoRepeat(True)
self.AutopH_switch.setAutoDefault(True)
self.AutopH_switch.setFlat(True)
self.AutopH_switch.setObjectName("AutopH_switch")
#button icon set
self.AutopH_switch.setIcon(QtGui.QIcon('image\off.png'))###set icon need\ set picture need/
self.AutopH_switch.setIconSize(QtCore.QSize(50,50))##
self.horizontalLayout_2.addWidget(self.AutopH_switch)
self.AutopH_switchlabel2 = QtWidgets.QLabel(self.horizontalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
self.AutopH_switchlabel2.setFont(font)
self.AutopH_switchlabel2.setObjectName("AutopH_switchlabel2")
self.horizontalLayout_2.addWidget(self.AutopH_switchlabel2)
self.gridLayout.addWidget(self.AutopHBox, 0, 2, 1, 1)
self.Automatic_Pump.addItem(self.Automatic_pH, "")
#auto DO window
self.Automatic_DO = QtWidgets.QWidget()
self.Automatic_DO.setGeometry(QtCore.QRect(0, 0, 310, 161))##
self.Automatic_DO.setObjectName("Automatic_DO")
self.AutoDOFrame = QtWidgets.QFrame(self.Automatic_DO)
self.AutoDOFrame.setGeometry(QtCore.QRect(10, 0, 310, 161))##
self.AutoDOFrame.setStyleSheet("")
self.AutoDOFrame.setObjectName("AutoDOFrame")
self.gridLayout_5 = QtWidgets.QGridLayout(self.AutoDOFrame)
self.gridLayout_5.setObjectName("gridLayout_5")
self.AutoDOBox = QtWidgets.QGroupBox(self.AutoDOFrame)
self.AutoDOBox.setMinimumSize(QtCore.QSize(240, 70))
font = QtGui.QFont()
font.setFamily("Arial")
self.AutoDOBox.setFont(font)
self.AutoDOBox.setAlignment(QtCore.Qt.AlignCenter)
self.AutoDOBox.setObjectName("AutoDOBox")
self.horizontalLayoutWidget_4 = QtWidgets.QWidget(self.AutoDOBox)
self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(80, 20, 121, 41))##
self.horizontalLayoutWidget_4.setObjectName("horizontalLayoutWidget_4")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_4)
self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.AutoDO_switchlabel1 = QtWidgets.QLabel(self.horizontalLayoutWidget_4)
font = QtGui.QFont()
font.setFamily("Arial")
self.AutoDO_switchlabel1.setFont(font)
self.AutoDO_switchlabel1.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.AutoDO_switchlabel1.setObjectName("AutoDO_switchlabel1")
self.horizontalLayout_4.addWidget(self.AutoDO_switchlabel1)
self.AutoDO_switch = QtWidgets.QPushButton(self.horizontalLayoutWidget_4)
self.AutoDO_switch.setMinimumSize(QtCore.QSize(60, 30))
self.AutoDO_switch.setStyleSheet("QPushButton\n"
"{\n"
"border: none; \n"
"}\n"
"")
self.AutoDO_switch.setCheckable(True)
self.AutoDO_switch.setAutoRepeat(True)
self.AutoDO_switch.setAutoDefault(True)
self.AutoDO_switch.setFlat(True)
self.AutoDO_switch.setObjectName("AutoDO_switch")
#button icon set
self.AutoDO_switch.setIcon(QtGui.QIcon('image\off.png'))###set icon need\ set picture need/
self.AutoDO_switch.setIconSize(QtCore.QSize(50,50))##
self.horizontalLayout_4.addWidget(self.AutoDO_switch)
self.AutoDO_switchlabel2 = QtWidgets.QLabel(self.horizontalLayoutWidget_4)
font = QtGui.QFont()
font.setFamily("Arial")
self.AutoDO_switchlabel2.setFont(font)
self.AutoDO_switchlabel2.setObjectName("AutoDO_switchlabel2")
self.horizontalLayout_4.addWidget(self.AutoDO_switchlabel2)
self.layoutWidget1 = QtWidgets.QWidget(self.AutoDOBox)
self.layoutWidget1.setGeometry(QtCore.QRect(30, 70, 249, 64))##
self.layoutWidget1.setObjectName("layoutWidget1")
self.gridLayout_6 = QtWidgets.QGridLayout(self.layoutWidget1)
self.gridLayout_6.setContentsMargins(0, 0, 0, 0)
self.gridLayout_6.setObjectName("gridLayout_6")
spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_6.addItem(spacerItem7, 1, 1, 1, 1)
self.AutoDO_gaslabel = QtWidgets.QLabel(self.layoutWidget1)
self.AutoDO_gaslabel.setMinimumSize(QtCore.QSize(90, 25))
font = QtGui.QFont()
font.setFamily("Arial")
self.AutoDO_gaslabel.setFont(font)
self.AutoDO_gaslabel.setAlignment(QtCore.Qt.AlignCenter)
self.AutoDO_gaslabel.setObjectName("AutoDO_gaslabel")
self.gridLayout_6.addWidget(self.AutoDO_gaslabel, 1, 2, 1, 1)
self.AutoDO_O2label = QtWidgets.QLabel(self.layoutWidget1)
self.AutoDO_O2label.setMinimumSize(QtCore.QSize(90, 25))
font = QtGui.QFont()
font.setFamily("Arial")
self.AutoDO_O2label.setFont(font)
self.AutoDO_O2label.setAlignment(QtCore.Qt.AlignCenter)
self.AutoDO_O2label.setObjectName("AutoDO_O2label")
self.gridLayout_6.addWidget(self.AutoDO_O2label, 1, 0, 1, 1)
self.AutoDO_O2value = QtWidgets.QDoubleSpinBox(self.layoutWidget1)
self.AutoDO_O2value.setMinimumSize(QtCore.QSize(90, 25))
font = QtGui.QFont()
font.setFamily("Arial")
self.AutoDO_O2value.setFont(font)
self.AutoDO_O2value.setStyleSheet("QDoubleSpinBox::up-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:left; \n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"QDoubleSpinBox::down-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:right;\n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"")
self.AutoDO_O2value.setAlignment(QtCore.Qt.AlignCenter)
self.AutoDO_O2value.setDecimals(0)
self.AutoDO_O2value.setObjectName("AutoDO_O2value")
self.gridLayout_6.addWidget(self.AutoDO_O2value, 2, 0, 1, 1)
self.AutoDO_gasswitch = QtWidgets.QPushButton(self.layoutWidget1)
self.AutoDO_gasswitch.setMinimumSize(QtCore.QSize(60, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.AutoDO_gasswitch.setFont(font)
self.AutoDO_gasswitch.setStyleSheet("QPushButton\n"
"{\n"
"border: none; \n"
"}\n"
"")
self.AutoDO_gasswitch.setCheckable(True)
self.AutoDO_gasswitch.setAutoRepeat(True)
self.AutoDO_gasswitch.setAutoDefault(True)
self.AutoDO_gasswitch.setFlat(True)
self.AutoDO_gasswitch.setObjectName("AutoDO_gasswitch")
#button icon set
self.AutoDO_gasswitch.setIcon(QtGui.QIcon('image\off.png'))###set icon need\ set picture need/
self.AutoDO_gasswitch.setIconSize(QtCore.QSize(50,50))##
self.gridLayout_6.addWidget(self.AutoDO_gasswitch, 2, 2, 1, 1)
self.gridLayout_5.addWidget(self.AutoDOBox, 0, 1, 1, 1)
self.Automatic_Pump.addItem(self.Automatic_DO, "")
#feed pump window
self.Feed_Pump = QtWidgets.QWidget()
self.Feed_Pump.setGeometry(QtCore.QRect(0, 0, 310, 161))##
self.Feed_Pump.setObjectName("Feed_Pump")
self.AutoDOFrame_2 = QtWidgets.QFrame(self.Feed_Pump)
self.AutoDOFrame_2.setGeometry(QtCore.QRect(10, 0, 310, 161))##
self.AutoDOFrame_2.setStyleSheet("")
self.AutoDOFrame_2.setObjectName("AutoDOFrame_2")
self.gridLayout_7 = QtWidgets.QGridLayout(self.AutoDOFrame_2)
self.gridLayout_7.setObjectName("gridLayout_7")
self.FeedPumpbox = QtWidgets.QGroupBox(self.AutoDOFrame_2)
self.FeedPumpbox.setMinimumSize(QtCore.QSize(240, 70))
font = QtGui.QFont()
font.setFamily("Arial")
self.FeedPumpbox.setFont(font)
self.FeedPumpbox.setAlignment(QtCore.Qt.AlignCenter)
self.FeedPumpbox.setObjectName("FeedPumpbox")
self.horizontalLayoutWidget_5 = QtWidgets.QWidget(self.FeedPumpbox)
self.horizontalLayoutWidget_5.setGeometry(QtCore.QRect(80, 20, 121, 41))##
self.horizontalLayoutWidget_5.setObjectName("horizontalLayoutWidget_5")
self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_5)
self.horizontalLayout_5.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.FeedPump_switchlabel1 = QtWidgets.QLabel(self.horizontalLayoutWidget_5)
font = QtGui.QFont()
font.setFamily("Arial")
self.FeedPump_switchlabel1.setFont(font)
self.FeedPump_switchlabel1.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.FeedPump_switchlabel1.setObjectName("FeedPump_switchlabel1")
self.horizontalLayout_5.addWidget(self.FeedPump_switchlabel1)
self.FeedPump_switch = QtWidgets.QPushButton(self.horizontalLayoutWidget_5)
self.FeedPump_switch.setMinimumSize(QtCore.QSize(60, 30))
self.FeedPump_switch.setStyleSheet("QPushButton\n"
"{\n"
"border: none; \n"
"}\n"
"")
self.FeedPump_switch.setCheckable(True)
self.FeedPump_switch.setAutoRepeat(True)
self.FeedPump_switch.setAutoDefault(True)
self.FeedPump_switch.setFlat(True)
self.FeedPump_switch.setObjectName("FeedPump_switch")
#button icon set
self.FeedPump_switch.setIcon(QtGui.QIcon('image\off.png'))###set icon need\ set picture need/
self.FeedPump_switch.setIconSize(QtCore.QSize(50,50))##
self.horizontalLayout_5.addWidget(self.FeedPump_switch)
self.FeedPump_switchlabel2 = QtWidgets.QLabel(self.horizontalLayoutWidget_5)
font = QtGui.QFont()
font.setFamily("Arial")
self.FeedPump_switchlabel2.setFont(font)
self.FeedPump_switchlabel2.setObjectName("FeedPump_switchlabel2")
self.horizontalLayout_5.addWidget(self.FeedPump_switchlabel2)
self.gridLayout_7.addWidget(self.FeedPumpbox, 0, 1, 1, 1)
self.verticalLayout_3 = QtWidgets.QVBoxLayout()
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.RPM_label = QtWidgets.QLabel(self.AutoDOFrame_2)
self.RPM_label.setMinimumSize(QtCore.QSize(90, 25))
font = QtGui.QFont()
font.setFamily("Arial")
self.RPM_label.setFont(font)
self.RPM_label.setAlignment(QtCore.Qt.AlignCenter)
self.RPM_label.setObjectName("RPM_label")
self.verticalLayout_3.addWidget(self.RPM_label)
self.gridLayout_7.addLayout(self.verticalLayout_3, 1, 1, 1, 1)
self.RPM_value = QtWidgets.QDoubleSpinBox(self.AutoDOFrame_2)
self.RPM_value.setMinimumSize(QtCore.QSize(90, 25))
font = QtGui.QFont()
font.setFamily("Arial")
self.RPM_value.setFont(font)
self.RPM_value.setStyleSheet("QDoubleSpinBox::up-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:left; \n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"QDoubleSpinBox::down-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:right;\n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"")
self.RPM_value.setAlignment(QtCore.Qt.AlignCenter)
self.RPM_value.setDecimals(0)
self.RPM_value.setObjectName("RPM_value")
self.gridLayout_7.addWidget(self.RPM_value, 2, 1, 1, 1)
self.Automatic_Pump.addItem(self.Feed_Pump, "")
#acid base pump window
self.Acid_Base_Pump = QtWidgets.QWidget()
self.Acid_Base_Pump.setGeometry(QtCore.QRect(0, 0, 310, 161))##
self.Acid_Base_Pump.setObjectName("Acid_Base_Pump")
self.AutoDOFrame_3 = QtWidgets.QFrame(self.Acid_Base_Pump)
self.AutoDOFrame_3.setGeometry(QtCore.QRect(10, 0, 310, 161))##
self.AutoDOFrame_3.setStyleSheet("")
self.AutoDOFrame_3.setObjectName("AutoDOFrame_3")
self.gridLayout_9 = QtWidgets.QGridLayout(self.AutoDOFrame_3)
self.gridLayout_9.setObjectName("gridLayout_9")
self.DosingBox = QtWidgets.QGroupBox(self.AutoDOFrame_3)
self.DosingBox.setMinimumSize(QtCore.QSize(240, 70))
font = QtGui.QFont()
font.setFamily("Arial")
self.DosingBox.setFont(font)
self.DosingBox.setAlignment(QtCore.Qt.AlignCenter)
self.DosingBox.setObjectName("DosingBox")
self.horizontalLayoutWidget_6 = QtWidgets.QWidget(self.DosingBox)
self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(80, 20, 121, 41))##
self.horizontalLayoutWidget_6.setObjectName("horizontalLayoutWidget_6")
self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_6)
self.horizontalLayout_6.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
self.Dosing_switchlabel1 = QtWidgets.QLabel(self.horizontalLayoutWidget_6)
font = QtGui.QFont()
font.setFamily("Arial")
self.Dosing_switchlabel1.setFont(font)
self.Dosing_switchlabel1.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.Dosing_switchlabel1.setObjectName("Dosing_switchlabel1")
self.horizontalLayout_6.addWidget(self.Dosing_switchlabel1)
self.Dosing_switch = QtWidgets.QPushButton(self.horizontalLayoutWidget_6)
self.Dosing_switch.setMinimumSize(QtCore.QSize(60, 30))
self.Dosing_switch.setStyleSheet("QPushButton\n"
"{\n"
"border: none; \n"
"}\n"
"")
self.Dosing_switch.setCheckable(True)
self.Dosing_switch.setAutoRepeat(True)
self.Dosing_switch.setAutoDefault(True)
self.Dosing_switch.setFlat(True)
self.Dosing_switch.setObjectName("Dosing_switch")
#button icon set
self.Dosing_switch.setIcon(QtGui.QIcon('image\off.png'))###set icon need\ set picture need/
self.Dosing_switch.setIconSize(QtCore.QSize(50,50))##
self.horizontalLayout_6.addWidget(self.Dosing_switch)
self.Dosing_switchlabel2 = QtWidgets.QLabel(self.horizontalLayoutWidget_6)
font = QtGui.QFont()
font.setFamily("Arial")
self.Dosing_switchlabel2.setFont(font)
self.Dosing_switchlabel2.setObjectName("Dosing_switchlabel2")
self.horizontalLayout_6.addWidget(self.Dosing_switchlabel2)
self.layoutWidget_3 = QtWidgets.QWidget(self.DosingBox)
self.layoutWidget_3.setGeometry(QtCore.QRect(5, 70, 275, 64))##
self.layoutWidget_3.setObjectName("layoutWidget_3")
self.gridLayout_10 = QtWidgets.QGridLayout(self.layoutWidget_3)
self.gridLayout_10.setContentsMargins(0, 0, 0, 0)
self.gridLayout_10.setObjectName("gridLayout_10")
self.Base_timevalue = QtWidgets.QDoubleSpinBox(self.layoutWidget_3)
self.Base_timevalue.setMinimumSize(QtCore.QSize(100, 25))##
font = QtGui.QFont()
font.setFamily("Arial")
self.Base_timevalue.setFont(font)
self.Base_timevalue.setStyleSheet("QDoubleSpinBox::up-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:left; \n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"QDoubleSpinBox::down-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:right;\n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"")
self.Base_timevalue.setAlignment(QtCore.Qt.AlignCenter)
self.Base_timevalue.setDecimals(0)
self.Base_timevalue.setObjectName("Base_timevalue")
self.gridLayout_10.addWidget(self.Base_timevalue, 2, 1, 1, 1)
self.Acid_timelabel = QtWidgets.QLabel(self.layoutWidget_3)
self.Acid_timelabel.setMinimumSize(QtCore.QSize(100, 25))##
font = QtGui.QFont()
font.setFamily("Arial")
self.Acid_timelabel.setFont(font)
self.Acid_timelabel.setAlignment(QtCore.Qt.AlignCenter)
self.Acid_timelabel.setObjectName("Acid_timelabel")
self.gridLayout_10.addWidget(self.Acid_timelabel, 1, 0, 1, 1)
self.Base_timelabel = QtWidgets.QLabel(self.layoutWidget_3)
self.Base_timelabel.setMinimumSize(QtCore.QSize(100, 25))##
font = QtGui.QFont()
font.setFamily("Arial")
self.Base_timelabel.setFont(font)
self.Base_timelabel.setAlignment(QtCore.Qt.AlignCenter)
self.Base_timelabel.setObjectName("Base_timelabel")
self.gridLayout_10.addWidget(self.Base_timelabel, 1, 1, 1, 1)
self.Acid_timevalue = QtWidgets.QDoubleSpinBox(self.layoutWidget_3)
self.Acid_timevalue.setMinimumSize(QtCore.QSize(100, 25))##
font = QtGui.QFont()
font.setFamily("Arial")
self.Acid_timevalue.setFont(font)
self.Acid_timevalue.setStyleSheet("QDoubleSpinBox::up-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:left; \n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"QDoubleSpinBox::down-button\n"
" {subcontrol-origin:border;\n"
" subcontrol-position:right;\n"
" width: 22px;\n"
" height: 20px; \n"
" }\n"
"")
self.Acid_timevalue.setAlignment(QtCore.Qt.AlignCenter)
self.Acid_timevalue.setDecimals(0)
self.Acid_timevalue.setObjectName("Acid_timevalue")
self.gridLayout_10.addWidget(self.Acid_timevalue, 2, 0, 1, 1)
self.gridLayout_9.addWidget(self.DosingBox, 0, 0, 1, 2)
self.Automatic_Pump.addItem(self.Acid_Base_Pump, "")
#pic comment(acid and base time)
self.formLayoutWidget = QtWidgets.QWidget(self.Main)
self.formLayoutWidget.setGeometry(QtCore.QRect(640, 305, 170, 210))##
self.formLayoutWidget.setObjectName("formLayoutWidget")
self.formLayout = QtWidgets.QFormLayout(self.formLayoutWidget)
self.formLayout.setContentsMargins(0, 0, 0, 0)
self.formLayout.setObjectName("formLayout")
self.Bioreactor_pic_acid = QtWidgets.QRadioButton(self.formLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
self.Bioreactor_pic_acid.setFont(font)
self.Bioreactor_pic_acid.setLayoutDirection(QtCore.Qt.RightToLeft)
self.Bioreactor_pic_acid.setAutoRepeat(True)
self.Bioreactor_pic_acid.setAutoExclusive(False)
self.Bioreactor_pic_acid.setObjectName("Bioreactor_pic_acid")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.Bioreactor_pic_acid)
self.acid_time = QtWidgets.QTimeEdit(self.formLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
self.acid_time.setFont(font)
self.acid_time.setStyleSheet("background-color:rgba(0,0,0,0);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;\n"
"")
self.acid_time.setAlignment(QtCore.Qt.AlignCenter)
self.acid_time.setReadOnly(True)
self.acid_time.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.acid_time.setCurrentSection(QtWidgets.QDateTimeEdit.HourSection)
self.acid_time.setCalendarPopup(False)
self.acid_time.setObjectName("acid_time")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.acid_time)
self.Bioreactor_pic_base = QtWidgets.QRadioButton(self.formLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
self.Bioreactor_pic_base.setFont(font)
self.Bioreactor_pic_base.setLayoutDirection(QtCore.Qt.RightToLeft)
self.Bioreactor_pic_base.setAutoRepeat(True)
self.Bioreactor_pic_base.setAutoExclusive(False)
self.Bioreactor_pic_base.setObjectName("Bioreactor_pic_base")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.Bioreactor_pic_base)
#space between base and heating
spacerItem8 = QtWidgets.QSpacerItem(20, 85, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)##100->85
self.formLayout.setItem(4, QtWidgets.QFormLayout.FieldRole, spacerItem8)
self.Bioreactor_pic_heating = QtWidgets.QRadioButton(self.formLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
self.Bioreactor_pic_heating.setFont(font)
self.Bioreactor_pic_heating.setLayoutDirection(QtCore.Qt.RightToLeft)
self.Bioreactor_pic_heating.setAutoRepeat(True)
self.Bioreactor_pic_heating.setAutoExclusive(False)
self.Bioreactor_pic_heating.setObjectName("Bioreactor_pic_heating")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.Bioreactor_pic_heating)
self.Bioreactor_pic_cooling = QtWidgets.QRadioButton(self.formLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
self.Bioreactor_pic_cooling.setFont(font)
self.Bioreactor_pic_cooling.setLayoutDirection(QtCore.Qt.RightToLeft)
self.Bioreactor_pic_cooling.setAutoRepeat(True)
self.Bioreactor_pic_cooling.setAutoExclusive(False)
self.Bioreactor_pic_cooling.setObjectName("Bioreactor_pic_cooling")
self.formLayout.setWidget(7, QtWidgets.QFormLayout.FieldRole, self.Bioreactor_pic_cooling)
self.base_time = QtWidgets.QTimeEdit(self.formLayoutWidget)
font = QtGui.QFont()
font.setFamily("Arial")
self.base_time.setFont(font)
self.base_time.setStyleSheet("background-color:rgba(0,0,0,0);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;")
self.base_time.setAlignment(QtCore.Qt.AlignCenter)
self.base_time.setReadOnly(True)
self.base_time.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.base_time.setCurrentSection(QtWidgets.QDateTimeEdit.HourSection)
self.base_time.setCalendarPopup(False)
self.base_time.setObjectName("base_time")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.base_time)
#spacerItem9 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
#self.formLayout.setItem(2, QtWidgets.QFormLayout.FieldRole, spacerItem9)
#space between heating and cooling
spacerItem10 = QtWidgets.QSpacerItem(20, 35, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)##
self.formLayout.setItem(6, QtWidgets.QFormLayout.FieldRole, spacerItem10)
#pic comment (pH pO2...)
self.verticalLayoutWidget_2 = QtWidgets.QWidget(self.Main)
self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(1150, 410, 131, 335))##380->410
self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2")
self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)
self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.biopic_pHlabel = QtWidgets.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
self.biopic_pHlabel.setFont(font)
self.biopic_pHlabel.setAlignment(QtCore.Qt.AlignCenter)
self.biopic_pHlabel.setObjectName("biopic_pHlabel")
self.verticalLayout_4.addWidget(self.biopic_pHlabel)
self.biopic_pHvalue = QtWidgets.QDoubleSpinBox(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
self.biopic_pHvalue.setFont(font)
self.biopic_pHvalue.setStyleSheet("background-color:rgba(0,0,0,0);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;")
self.biopic_pHvalue.setAlignment(QtCore.Qt.AlignCenter)
self.biopic_pHvalue.setReadOnly(True)
self.biopic_pHvalue.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.biopic_pHvalue.setDecimals(3)
self.biopic_pHvalue.setObjectName("biopic_pHvalue")
self.verticalLayout_4.addWidget(self.biopic_pHvalue)
spacerItem11 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_4.addItem(spacerItem11)
self.biopic_pO2label = QtWidgets.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
self.biopic_pO2label.setFont(font)
self.biopic_pO2label.setAlignment(QtCore.Qt.AlignCenter)
self.biopic_pO2label.setObjectName("biopic_pO2label")
self.verticalLayout_4.addWidget(self.biopic_pO2label)
self.biopic_pO2value = QtWidgets.QDoubleSpinBox(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
self.biopic_pO2value.setFont(font)
self.biopic_pO2value.setStyleSheet("background-color:rgba(0,0,0,0);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;")
self.biopic_pO2value.setAlignment(QtCore.Qt.AlignCenter)
self.biopic_pO2value.setReadOnly(True)
self.biopic_pO2value.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.biopic_pO2value.setDecimals(3)
self.biopic_pO2value.setObjectName("biopic_pO2value")
self.verticalLayout_4.addWidget(self.biopic_pO2value)
spacerItem12 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_4.addItem(spacerItem12)
self.biopic_templabel = QtWidgets.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
self.biopic_templabel.setFont(font)
self.biopic_templabel.setAlignment(QtCore.Qt.AlignCenter)
self.biopic_templabel.setObjectName("biopic_templabel")
self.verticalLayout_4.addWidget(self.biopic_templabel)
self.biopic_tempvalue = QtWidgets.QDoubleSpinBox(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
self.biopic_tempvalue.setFont(font)
self.biopic_tempvalue.setStyleSheet("background-color:rgba(0,0,0,0);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;")
self.biopic_tempvalue.setAlignment(QtCore.Qt.AlignCenter)
self.biopic_tempvalue.setReadOnly(True)
self.biopic_tempvalue.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.biopic_tempvalue.setDecimals(3)
self.biopic_tempvalue.setObjectName("biopic_tempvalue")
self.verticalLayout_4.addWidget(self.biopic_tempvalue)
#space between temperature and pressure
spacerItem13 = QtWidgets.QSpacerItem(20, 90, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)##
self.verticalLayout_4.addItem(spacerItem13)
self.biopic_pressurelabel = QtWidgets.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
self.biopic_pressurelabel.setFont(font)
self.biopic_pressurelabel.setAlignment(QtCore.Qt.AlignCenter)
self.biopic_pressurelabel.setObjectName("biopic_pressurelabel")
self.verticalLayout_4.addWidget(self.biopic_pressurelabel)
self.biopic_pressurevalue = QtWidgets.QDoubleSpinBox(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setFamily("Arial")
self.biopic_pressurevalue.setFont(font)
self.biopic_pressurevalue.setStyleSheet("background-color:rgba(0,0,0,0);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;")
self.biopic_pressurevalue.setAlignment(QtCore.Qt.AlignCenter)
self.biopic_pressurevalue.setReadOnly(True)
self.biopic_pressurevalue.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.biopic_pressurevalue.setDecimals(3)
self.biopic_pressurevalue.setObjectName("biopic_pressurevalue")
self.verticalLayout_4.addWidget(self.biopic_pressurevalue)
self.device_box = QtWidgets.QComboBox(self.Main)
self.device_box.setGeometry(QtCore.QRect(1410, 740, 131, 41))
self.device_box.setMaximumSize(QtCore.QSize(131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(15)
self.device_box.setFont(font)
self.device_box.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
self.device_box.setLayoutDirection(QtCore.Qt.LeftToRight)
self.device_box.setAutoFillBackground(True)
self.device_box.setStyleSheet("background-color:rgba(0,0,0,0);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;\n"
"QComboBox::drop-down\n"
"{\n"
" border-style: none;\n"
"}")
self.device_box.setEditable(False)
self.device_box.setInsertPolicy(QtWidgets.QComboBox.InsertAtBottom)
self.device_box.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContentsOnFirstShow)
self.device_box.setIconSize(QtCore.QSize(20, 20))
self.device_box.setDuplicatesEnabled(False)
self.device_box.setObjectName("device_box")
self.device_box.addItem("")
self.device_box.addItem("")
self.device_box.addItem("")
#minmax limit comment
self.gridLayoutWidget = QtWidgets.QWidget(self.Main)
self.gridLayoutWidget.setGeometry(QtCore.QRect(120, 455, 280, 290))##
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout_4 = QtWidgets.QGridLayout(self.gridLayoutWidget)
self.gridLayout_4.setContentsMargins(0, 0, 0, 0)
#self.gridLayout_4.
self.gridLayout_4.setObjectName("gridLayout_4")
#O2minmaxflow_value box
self.O2minmaxflow_value = QtWidgets.QDoubleSpinBox(self.gridLayoutWidget)
self.O2minmaxflow_value.setMinimumSize(QtCore.QSize(90, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.O2minmaxflow_value.setFont(font)
self.O2minmaxflow_value.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;")##bg color changed
self.O2minmaxflow_value.setAlignment(QtCore.Qt.AlignCenter)
self.O2minmaxflow_value.setReadOnly(True)
self.O2minmaxflow_value.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.O2minmaxflow_value.setDecimals(3)
self.O2minmaxflow_value.setObjectName("O2minmaxflow_value")
self.gridLayout_4.addWidget(self.O2minmaxflow_value, 1, 2, 1, 1)##
#Airlimit_button
self.Airlimit_button = QtWidgets.QPushButton(self.gridLayoutWidget)
self.Airlimit_button.setMinimumSize(QtCore.QSize(90, 40))##
font = QtGui.QFont()
font.setFamily("Arial")
self.Airlimit_button.setFont(font)
self.Airlimit_button.setCheckable(True)
self.Airlimit_button.setAutoRepeat(True)
self.Airlimit_button.setAutoDefault(True)
self.Airlimit_button.setFlat(True)
self.Airlimit_button.setObjectName("Airlimit_button")
self.Airlimit_button.setStyleSheet("QPushButton{border-image: url(image/button_off.png)}")##
self.gridLayout_4.addWidget(self.Airlimit_button, 4, 0, 1, 1)##
#othergas_button
self.othergas_button = QtWidgets.QPushButton(self.gridLayoutWidget)
self.othergas_button.setMinimumSize(QtCore.QSize(90, 40))##
font = QtGui.QFont()
font.setFamily("Arial")
self.othergas_button.setFont(font)
self.othergas_button.setCheckable(True)
self.othergas_button.setAutoRepeat(True)
self.othergas_button.setAutoDefault(True)
self.othergas_button.setFlat(True)
self.othergas_button.setObjectName("othergas_button")
self.othergas_button.setStyleSheet("QPushButton{border-image: url(image/button_off.png)}")##
self.gridLayout_4.addWidget(self.othergas_button, 6, 0, 1, 1)##
#N2_button
self.N2_button = QtWidgets.QPushButton(self.gridLayoutWidget)
self.N2_button.setMinimumSize(QtCore.QSize(90, 40))##
font = QtGui.QFont()
font.setFamily("Arial")
self.N2_button.setFont(font)
self.N2_button.setCheckable(True)
self.N2_button.setAutoRepeat(True)
self.N2_button.setAutoDefault(True)
self.N2_button.setFlat(True)
self.N2_button.setObjectName("N2_button")
self.N2_button.setStyleSheet("QPushButton{border-image: url(image/button_off.png)}")##
self.gridLayout_4.addWidget(self.N2_button, 8, 0, 1, 1)##
#O2flow_label
self.O2flow_label = QtWidgets.QLabel(self.gridLayoutWidget)
self.O2flow_label.setMaximumSize(QtCore.QSize(100, 15))##
font = QtGui.QFont()
font.setFamily("Arial")
self.O2flow_label.setFont(font)
self.O2flow_label.setAlignment(QtCore.Qt.AlignCenter)
self.O2flow_label.setObjectName("O2flow_label")
self.gridLayout_4.addWidget(self.O2flow_label, 0, 2, 1, 1)##
#O2limit_button
self.O2limit_button = QtWidgets.QPushButton(self.gridLayoutWidget)
self.O2limit_button.setMinimumSize(QtCore.QSize(90, 40))##
font = QtGui.QFont()
font.setFamily("Arial")
self.O2limit_button.setFont(font)
self.O2limit_button.setCheckable(True)
self.O2limit_button.setAutoRepeat(True)
self.O2limit_button.setAutoDefault(True)
self.O2limit_button.setFlat(True)
self.O2limit_button.setObjectName("O2limit_button")
self.O2limit_button.setStyleSheet("QPushButton{border-image: url(image/button_off.png)}")##
self.gridLayout_4.addWidget(self.O2limit_button, 1, 0, 1, 1)##
#Air_MinMaxlabel
self.Air_MinMaxlabel = QtWidgets.QLabel(self.gridLayoutWidget)
self.Air_MinMaxlabel.setMaximumSize(QtCore.QSize(80, 15))##
font = QtGui.QFont()
font.setFamily("Arial")
self.Air_MinMaxlabel.setFont(font)
self.Air_MinMaxlabel.setAlignment(QtCore.Qt.AlignCenter)
self.Air_MinMaxlabel.setObjectName("Air_MinMaxlabel")
self.gridLayout_4.addWidget(self.Air_MinMaxlabel, 3, 0, 1, 1)##
#Airflow_label
self.Airflow_label = QtWidgets.QLabel(self.gridLayoutWidget)
self.Airflow_label.setMaximumSize(QtCore.QSize(100, 15))##
font = QtGui.QFont()
font.setFamily("Arial")
self.Airflow_label.setFont(font)
self.Airflow_label.setObjectName("Airflow_label")
self.gridLayout_4.addWidget(self.Airflow_label, 3, 2, 1, 1)##
#O2minmax_label
self.O2minmax_label = QtWidgets.QLabel(self.gridLayoutWidget)
self.O2minmax_label.setMaximumSize(QtCore.QSize(80, 15))##
font = QtGui.QFont()
font.setFamily("Arial")
self.O2minmax_label.setFont(font)
self.O2minmax_label.setAlignment(QtCore.Qt.AlignCenter)
self.O2minmax_label.setObjectName("O2minmax_label")
self.gridLayout_4.addWidget(self.O2minmax_label, 0, 0, 1, 1)##
###add three spaces
#horizontal
spacerItem14 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_4.addItem(spacerItem14, 1, 1, 1, 1)
spacerItem15 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_4.addItem(spacerItem15, 4, 1, 1, 1)
#vertical
spacerItem16 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)##
self.gridLayout_4.addItem(spacerItem16, 2, 0, 1, 1)
spacerItem17 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)##
self.gridLayout_4.addItem(spacerItem17, 5, 0, 1, 1)
spacerItem18 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)##
self.gridLayout_4.addItem(spacerItem18, 7, 0, 1, 1)
###
self.Airminmaxflow_value = QtWidgets.QDoubleSpinBox(self.gridLayoutWidget)
self.Airminmaxflow_value.setMinimumSize(QtCore.QSize(90, 30))
font = QtGui.QFont()
font.setFamily("Arial")
self.Airminmaxflow_value.setFont(font)
self.Airminmaxflow_value.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-color:rgba(111,111,170,255);\n"
"color: rgba(0, 0, 0,255);\n"
"border-style:double;\n"
"border-width:4px;\n"
"border-radius:8px;")##bg color changed
self.Airminmaxflow_value.setAlignment(QtCore.Qt.AlignCenter)
self.Airminmaxflow_value.setReadOnly(True)
self.Airminmaxflow_value.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
self.Airminmaxflow_value.setDecimals(3)
self.Airminmaxflow_value.setObjectName("Airminmaxflow_value")
self.gridLayout_4.addWidget(self.Airminmaxflow_value, 4, 2, 1, 1)##
self.cellexuspic = QtWidgets.QLabel(self.Main)
self.cellexuspic.setGeometry(QtCore.QRect(10, 690, 511, 111))
self.cellexuspic.setText("")
self.cellexuspic.setObjectName("cellexuspic")
self.Bioreactor_pic.raise_()
self.horizontalLayoutWidget.raise_()
self.setpointBox.raise_()
self.Automatic_Pump.raise_()
self.formLayoutWidget.raise_()
self.verticalLayoutWidget_2.raise_()
self.device_box.raise_()
self.gridLayoutWidget.raise_()
self.cellexuspic.raise_()
self.tab1.addTab(self.Main, "")
#charts tab
self.Charts = QtWidgets.QWidget()
self.Charts.setObjectName("Charts")
self.tab1.addTab(self.Charts, "")
#"Ellie's code here"
self.verticalLayoutWidget = QtWidgets.QWidget(self.Charts)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(1320, 20, 181, 401))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.checkBoxTemp = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.checkBoxTemp.setEnabled(True)
self.checkBoxTemp.setObjectName("checkBoxTemp")
self.checkBoxTemp.stateChanged.connect(self.checked_item)
self.verticalLayout.addWidget(self.checkBoxTemp)
self.checkBoxPres = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.checkBoxPres.setObjectName("checkBoxPres")
self.checkBoxPres.stateChanged.connect(self.checked_item)
self.verticalLayout.addWidget(self.checkBoxPres)
self.checkBoxPH = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.checkBoxPH.setObjectName("checkBoxPH")
self.checkBoxPH.stateChanged.connect(self.checked_item)
self.verticalLayout.addWidget(self.checkBoxPH)
self.checkBoxDO2 = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.checkBoxDO2.setObjectName("checkBoxDO2")
self.checkBoxDO2.stateChanged.connect(self.checked_item)
self.verticalLayout.addWidget(self.checkBoxDO2)
self.checkBoxAIR = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.checkBoxAIR.setObjectName("checkBoxAIR")
self.checkBoxAIR.stateChanged.connect(self.checked_item)
self.verticalLayout.addWidget(self.checkBoxAIR)
self.checkBoxO2 = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.checkBoxO2.setObjectName("checkBoxO2")
self.checkBoxO2.stateChanged.connect(self.checked_item)
self.verticalLayout.addWidget(self.checkBoxO2)
self.checkBoxCO2 = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.checkBoxCO2.setObjectName("checkBoxCO2")
self.checkBoxCO2.stateChanged.connect(self.checked_item)
self.verticalLayout.addWidget(self.checkBoxCO2)
self.widget1 = PlotWidget(self.Charts)
self.widget1.setGeometry(QtCore.QRect(60, 30, 1201, 651))
self.widget1.setObjectName("widget")
self.widget1.setBackground('w')
self.horizontalScrollBar = QtWidgets.QScrollBar(self.Charts)
self.horizontalScrollBar.setGeometry(QtCore.QRect(60, 700, 1191, 20))
self.horizontalScrollBar.setOrientation(QtCore.Qt.Horizontal)
self.horizontalScrollBar.setObjectName("horizontalScrollBar")
self.pushButton = QtWidgets.QPushButton(self.Charts)
self.pushButton.setGeometry(QtCore.QRect(1360, 550, 112, 34))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.browsefiles)
self.pushButton_2 = QtWidgets.QPushButton(self.Charts)
self.pushButton_2.setGeometry(QtCore.QRect(1360, 630, 112, 34))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_2.clicked.connect(self.cleargraph)
self.verticalScrollBar = QtWidgets.QScrollBar(self.Charts)
self.verticalScrollBar.setGeometry(QtCore.QRect(1280, 30, 20, 641))
self.verticalScrollBar.setOrientation(QtCore.Qt.Vertical)
self.verticalScrollBar.setObjectName("verticalScrollBar")
#manual log tab
self.Manual_Log = QtWidgets.QWidget()
self.Manual_Log.setObjectName("Manual_Log")
self.tab1.addTab(self.Manual_Log, "")
#
#Individual controls
self.spinBox = QtWidgets.QSpinBox(self.Manual_Log)
self.spinBox.setGeometry(QtCore.QRect(210, 180, 141, 24))
self.spinBox.setObjectName("spinBox")
self.interval = QtWidgets.QLabel(self.Manual_Log)
self.interval.setGeometry(QtCore.QRect(210, 160, 91, 16))
self.interval.setObjectName("interval")
self.Open_file = QtWidgets.QPushButton(self.Manual_Log)
self.Open_file.setGeometry(QtCore.QRect(200, 110, 141, 32))
self.Open_file.setObjectName("Open_file")
self.Open_file.clicked.connect(self.browsefiles_1) #open file browser
#file saving
self.gridLayoutWidget_2 = QtWidgets.QWidget(self.Manual_Log)
self.gridLayoutWidget_2.setGeometry(QtCore.QRect(928, 110, 151, 94))
self.gridLayoutWidget_2.setObjectName("gridLayoutWidget_2")
self.File_grid_layout = QtWidgets.QGridLayout(self.gridLayoutWidget_2)
self.File_grid_layout.setContentsMargins(0, 0, 0, 0)
self.File_grid_layout.setObjectName("File_grid_layout")
self.filename = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.filename.setObjectName("filename")
self.File_grid_layout.addWidget(self.filename, 2, 0, 1, 1)
self.log = QtWidgets.QPushButton(self.gridLayoutWidget_2)
self.log.setObjectName("log")
self.File_grid_layout.addWidget(self.log, 3, 0, 1, 1)
self.file_name = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.file_name.setObjectName("file_name")
self.File_grid_layout.addWidget(self.file_name, 1, 0, 1, 1)
#main section titles
self.gridLayoutWidget = QtWidgets.QWidget(self.Manual_Log)
self.gridLayoutWidget.setGeometry(QtCore.QRect(210, 210, 871, 108))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.title_grid = QtWidgets.QGridLayout(self.gridLayoutWidget)
self.title_grid.setContentsMargins(0, 0, 0, 0)
self.title_grid.setObjectName("title_grid")
self.gridLayoutWidget.setStyleSheet("background-color:rgb(219, 219, 219);")
self.do2 = QtWidgets.QLabel(self.gridLayoutWidget)
self.do2.setObjectName("do2")
self.title_grid.addWidget(self.do2, 2, 4, 1, 1)
self.test = QtWidgets.QLabel(self.gridLayoutWidget)
self.test.setObjectName("test")
self.title_grid.addWidget(self.test, 0, 1, 1, 1)
self.temperature = QtWidgets.QLabel(self.gridLayoutWidget)
self.temperature.setObjectName("temperature")
self.title_grid.addWidget(self.temperature, 2, 1, 1, 1)
self.pH = QtWidgets.QLabel(self.gridLayoutWidget)
self.pH.setObjectName("pH")
self.title_grid.addWidget(self.pH, 2, 3, 1, 1)
self.co2flow = QtWidgets.QLabel(self.gridLayoutWidget)
self.co2flow.setObjectName("co2flow")
self.title_grid.addWidget(self.co2flow, 2, 7, 1, 1)
self.pressure = QtWidgets.QLabel(self.gridLayoutWidget)
self.pressure.setObjectName("pressure")
self.title_grid.addWidget(self.pressure, 2, 2, 1, 1)
self.date = QtWidgets.QLabel(self.gridLayoutWidget)
self.date.setObjectName("date")
self.title_grid.addWidget(self.date, 0, 0, 1, 1)
self.motor = QtWidgets.QLabel(self.gridLayoutWidget)
self.motor.setObjectName("motor")
self.title_grid.addWidget(self.motor, 2, 8, 1, 1)
self.o2flow = QtWidgets.QLabel(self.gridLayoutWidget)
self.o2flow.setObjectName("o2flow")
self.title_grid.addWidget(self.o2flow, 2, 6, 1, 1)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.title_grid.addItem(spacerItem, 1, 6, 1, 1)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.title_grid.addItem(spacerItem1, 1, 7, 1, 1)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.title_grid.addItem(spacerItem2, 1, 4, 1, 1)
spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.title_grid.addItem(spacerItem3, 1, 5, 1, 1)
self.group = QtWidgets.QLabel(self.gridLayoutWidget)
self.group.setObjectName("group")
self.title_grid.addWidget(self.group, 0, 3, 1, 1)
spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.title_grid.addItem(spacerItem4, 1, 8, 1, 1)
self.datetime = QtWidgets.QLabel(self.gridLayoutWidget)
self.datetime.setObjectName("datetime")
self.title_grid.addWidget(self.datetime, 2, 0, 1, 1)
self.airflow = QtWidgets.QLabel(self.gridLayoutWidget)
self.airflow.setObjectName("airflow")
self.title_grid.addWidget(self.airflow, 2, 5, 1, 1)
self.operator_2 = QtWidgets.QLabel(self.gridLayoutWidget)
self.operator_2.setObjectName("operator_2")
self.title_grid.addWidget(self.operator_2, 0, 2, 1, 1)
self.dateEdit = QtWidgets.QDateEdit(self.gridLayoutWidget)
self.dateEdit.setMinimumSize(QtCore.QSize(141, 0))
self.dateEdit.setObjectName("dateEdit")
self.title_grid.addWidget(self.dateEdit, 1, 0, 1, 1)
self.dateEdit.setStyleSheet("background-color:white;")
self.lineEdit_2 = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.lineEdit_2.setMinimumSize(QtCore.QSize(81, 0))
self.lineEdit_2.setMaximumSize(QtCore.QSize(81, 16777215))
self.lineEdit_2.setObjectName("lineEdit_2")
self.title_grid.addWidget(self.lineEdit_2, 1, 1, 1, 1)
self.lineEdit_2.setStyleSheet("background-color:white;")
self.lineEdit_3 = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.lineEdit_3.setMaximumSize(QtCore.QSize(81, 16777215))
self.lineEdit_3.setObjectName("lineEdit_3")
self.title_grid.addWidget(self.lineEdit_3, 1, 2, 1, 1)
self.lineEdit_3.setStyleSheet("background-color:white;")
self.lineEdit_4 = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.lineEdit_4.setMaximumSize(QtCore.QSize(81, 16777215))
self.lineEdit_4.setObjectName("lineEdit_4")
self.title_grid.addWidget(self.lineEdit_4, 1, 3, 1, 1)
self.lineEdit_4.setStyleSheet("background-color:white;")
#scroll area
self.scrollArea = QtWidgets.QScrollArea(self.Manual_Log)
self.scrollArea.setGeometry(QtCore.QRect(208, 320, 875, 350))
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollArea.setWidgetResizable(False)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 871, 410))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.gridLayoutWidget_3 = QtWidgets.QWidget(self.scrollAreaWidgetContents)
self.gridLayoutWidget_3.setGeometry(QtCore.QRect(0, 0, 871, 400))
self.gridLayoutWidget_3.setObjectName("gridLayoutWidget_3")
self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget_3)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.scrollArea.setStyleSheet("background-color:white;")
#text and date/time boxes
self.lineEdit_108 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_108.setObjectName("lineEdit_108")
self.gridLayout.addWidget(self.lineEdit_108, 13, 1, 1, 1)
self.lineEdit_109 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_109.setObjectName("lineEdit_109")
self.gridLayout.addWidget(self.lineEdit_109, 13, 2, 1, 1)
self.lineEdit_110 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_110.setObjectName("lineEdit_110")
self.gridLayout.addWidget(self.lineEdit_110, 13, 3, 1, 1)
self.lineEdit_111 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_111.setObjectName("lineEdit_111")
self.gridLayout.addWidget(self.lineEdit_111, 13, 4, 1, 1)
self.lineEdit_112 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_112.setObjectName("lineEdit_112")
self.gridLayout.addWidget(self.lineEdit_112, 13, 5, 1, 1)
self.lineEdit_113 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_113.setObjectName("lineEdit_113")
self.gridLayout.addWidget(self.lineEdit_113, 13, 6, 1, 1)
self.lineEdit_114 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_114.setObjectName("lineEdit_114")
self.gridLayout.addWidget(self.lineEdit_114, 13, 7, 1, 1)
self.lineEdit_115 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_115.setObjectName("lineEdit_115")
self.gridLayout.addWidget(self.lineEdit_115, 13, 8, 1, 1)
self.lineEdit_116 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_116.setObjectName("lineEdit_116")
self.gridLayout.addWidget(self.lineEdit_116, 13, 1, 1, 1)
self.lineEdit_117 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_117.setObjectName("lineEdit_117")
self.gridLayout.addWidget(self.lineEdit_117, 13, 2, 1, 1)
self.lineEdit_118 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_118.setObjectName("lineEdit_118")
self.gridLayout.addWidget(self.lineEdit_118, 13, 3, 1, 1)
self.lineEdit_119 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_119.setObjectName("lineEdit_119")
self.gridLayout.addWidget(self.lineEdit_119, 13, 4, 1, 1)
self.lineEdit_120 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_120.setObjectName("lineEdit_120")
self.gridLayout.addWidget(self.lineEdit_120, 13, 5, 1, 1)
self.lineEdit_121 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_121.setObjectName("lineEdit_121")
self.gridLayout.addWidget(self.lineEdit_121, 13, 6, 1, 1)
self.lineEdit_122 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_122.setObjectName("lineEdit_122")
self.gridLayout.addWidget(self.lineEdit_122, 13, 7, 1, 1)
self.lineEdit_123 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_123.setObjectName("lineEdit_123")
self.gridLayout.addWidget(self.lineEdit_123, 13, 8, 1, 1)
self.dateTimeEdit_13 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_13.setObjectName("dateTimeEdit_13")
self.gridLayout.addWidget(self.dateTimeEdit_13, 13, 0, 1, 1)
self.lineEdit_68 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_68.setObjectName("lineEdit_68")
self.gridLayout.addWidget(self.lineEdit_68, 7, 5, 1, 1)
self.lineEdit_67 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_67.setObjectName("lineEdit_67")
self.gridLayout.addWidget(self.lineEdit_67, 7, 4, 1, 1)
self.lineEdit_70 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_70.setObjectName("lineEdit_70")
self.gridLayout.addWidget(self.lineEdit_70, 8, 3, 1, 1)
self.lineEdit_81 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_81.setObjectName("lineEdit_81")
self.gridLayout.addWidget(self.lineEdit_81, 9, 6, 1, 1)
self.lineEdit_72 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_72.setObjectName("lineEdit_72")
self.gridLayout.addWidget(self.lineEdit_72, 8, 5, 1, 1)
self.lineEdit_88 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_88.setObjectName("lineEdit_88")
self.gridLayout.addWidget(self.lineEdit_88, 10, 5, 1, 1)
self.lineEdit_77 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_77.setObjectName("lineEdit_77")
self.gridLayout.addWidget(self.lineEdit_77, 9, 1, 1, 1)
self.lineEdit_78 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_78.setObjectName("lineEdit_78")
self.gridLayout.addWidget(self.lineEdit_78, 9, 2, 1, 1)
self.lineEdit_64 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_64.setObjectName("lineEdit_64")
self.gridLayout.addWidget(self.lineEdit_64, 6, 3, 1, 1)
self.lineEdit_46 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_46.setObjectName("lineEdit_46")
self.gridLayout.addWidget(self.lineEdit_46, 5, 3, 1, 1)
self.lineEdit_83 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_83.setObjectName("lineEdit_83")
self.gridLayout.addWidget(self.lineEdit_83, 9, 8, 1, 1)
self.lineEdit_85 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_85.setObjectName("lineEdit_85")
self.gridLayout.addWidget(self.lineEdit_85, 10, 2, 1, 1)
self.lineEdit_57 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_57.setObjectName("lineEdit_57")
self.gridLayout.addWidget(self.lineEdit_57, 6, 6, 1, 1)
self.lineEdit_65 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_65.setObjectName("lineEdit_65")
self.gridLayout.addWidget(self.lineEdit_65, 7, 2, 1, 1)
self.lineEdit_62 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_62.setObjectName("lineEdit_62")
self.gridLayout.addWidget(self.lineEdit_62, 7, 8, 1, 1)
self.lineEdit_59 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_59.setObjectName("lineEdit_59")
self.gridLayout.addWidget(self.lineEdit_59, 6, 7, 1, 1)
self.lineEdit_58 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_58.setObjectName("lineEdit_58")
self.gridLayout.addWidget(self.lineEdit_58, 6, 5, 1, 1)
self.lineEdit_48 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_48.setObjectName("lineEdit_48")
self.gridLayout.addWidget(self.lineEdit_48, 5, 5, 1, 1)
self.lineEdit_79 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_79.setObjectName("lineEdit_79")
self.gridLayout.addWidget(self.lineEdit_79, 9, 4, 1, 1)
self.lineEdit_61 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_61.setObjectName("lineEdit_61")
self.gridLayout.addWidget(self.lineEdit_61, 7, 7, 1, 1)
self.lineEdit_84 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_84.setObjectName("lineEdit_84")
self.gridLayout.addWidget(self.lineEdit_84, 10, 1, 1, 1)
self.lineEdit_56 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_56.setObjectName("lineEdit_56")
self.gridLayout.addWidget(self.lineEdit_56, 6, 4, 1, 1)
self.lineEdit_63 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_63.setObjectName("lineEdit_63")
self.gridLayout.addWidget(self.lineEdit_63, 7, 6, 1, 1)
self.lineEdit_90 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_90.setObjectName("lineEdit_90")
self.gridLayout.addWidget(self.lineEdit_90, 10, 7, 1, 1)
self.lineEdit_82 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_82.setObjectName("lineEdit_82")
self.gridLayout.addWidget(self.lineEdit_82, 9, 7, 1, 1)
self.lineEdit_86 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_86.setObjectName("lineEdit_86")
self.gridLayout.addWidget(self.lineEdit_86, 10, 3, 1, 1)
self.lineEdit_39 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_39.setObjectName("lineEdit_39")
self.gridLayout.addWidget(self.lineEdit_39, 4, 7, 1, 1)
self.lineEdit_43 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_43.setObjectName("lineEdit_43")
self.gridLayout.addWidget(self.lineEdit_43, 4, 3, 1, 1)
self.lineEdit_38 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_38.setObjectName("lineEdit_38")
self.gridLayout.addWidget(self.lineEdit_38, 4, 8, 1, 1)
self.lineEdit_36 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_36.setObjectName("lineEdit_36")
self.gridLayout.addWidget(self.lineEdit_36, 3, 7, 1, 1)
self.lineEdit_71 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_71.setObjectName("lineEdit_71")
self.gridLayout.addWidget(self.lineEdit_71, 8, 4, 1, 1)
self.lineEdit_89 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_89.setObjectName("lineEdit_89")
self.gridLayout.addWidget(self.lineEdit_89, 10, 6, 1, 1)
self.lineEdit_80 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_80.setObjectName("lineEdit_80")
self.gridLayout.addWidget(self.lineEdit_80, 9, 5, 1, 1)
self.lineEdit_52 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_52.setObjectName("lineEdit_52")
self.gridLayout.addWidget(self.lineEdit_52, 6, 1, 1, 1)
self.lineEdit_8 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_8.setObjectName("lineEdit_8")
self.gridLayout.addWidget(self.lineEdit_8, 1, 6, 1, 1)
self.lineEdit_12 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_12.setObjectName("lineEdit_12")
self.gridLayout.addWidget(self.lineEdit_12, 0, 1, 1, 1)
self.lineEdit_9 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_9.setObjectName("lineEdit_9")
self.gridLayout.addWidget(self.lineEdit_9, 1, 5, 1, 1)
self.lineEdit_26 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_26.setObjectName("lineEdit_26")
self.gridLayout.addWidget(self.lineEdit_26, 2, 5, 1, 1)
self.lineEdit_20 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_20.setObjectName("lineEdit_20")
self.gridLayout.addWidget(self.lineEdit_20, 0, 6, 1, 1)
self.lineEdit_87 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_87.setObjectName("lineEdit_87")
self.gridLayout.addWidget(self.lineEdit_87, 10, 4, 1, 1)
self.lineEdit_49 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_49.setObjectName("lineEdit_49")
self.gridLayout.addWidget(self.lineEdit_49, 5, 6, 1, 1)
self.lineEdit_66 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_66.setObjectName("lineEdit_66")
self.gridLayout.addWidget(self.lineEdit_66, 7, 3, 1, 1)
self.dateTimeEdit_7 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_7.setObjectName("dateTimeEdit_7")
self.gridLayout.addWidget(self.dateTimeEdit_7, 8, 0, 1, 1)
self.dateTimeEdit_4 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_4.setObjectName("dateTimeEdit_4")
self.gridLayout.addWidget(self.dateTimeEdit_4, 3, 0, 1, 1)
self.lineEdit_51 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_51.setObjectName("lineEdit_51")
self.gridLayout.addWidget(self.lineEdit_51, 5, 8, 1, 1)
self.lineEdit_44 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_44.setObjectName("lineEdit_44")
self.gridLayout.addWidget(self.lineEdit_44, 5, 1, 1, 1)
self.lineEdit_27 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_27.setObjectName("lineEdit_27")
self.gridLayout.addWidget(self.lineEdit_27, 2, 6, 1, 1)
self.lineEdit = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit.setObjectName("lineEdit")
self.gridLayout.addWidget(self.lineEdit, 1, 8, 1, 1)
self.dateTimeEdit_11 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_11.setObjectName("dateTimeEdit_11")
self.gridLayout.addWidget(self.dateTimeEdit_11, 5, 0, 1, 1)
self.lineEdit_25 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_25.setObjectName("lineEdit_25")
self.gridLayout.addWidget(self.lineEdit_25, 2, 4, 1, 1)
self.dateTimeEdit = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit.setObjectName("dateTimeEdit")
self.gridLayout.addWidget(self.dateTimeEdit, 0, 0, 1, 1)
self.lineEdit_17 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_17.setObjectName("lineEdit_17")
self.gridLayout.addWidget(self.lineEdit_17, 4, 1, 1, 1)
self.lineEdit_7 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_7.setObjectName("lineEdit_7")
self.gridLayout.addWidget(self.lineEdit_7, 1, 2, 1, 1)
self.lineEdit_22 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_22.setObjectName("lineEdit_22")
self.gridLayout.addWidget(self.lineEdit_22, 0, 8, 1, 1)
self.lineEdit_21 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_21.setObjectName("lineEdit_21")
self.gridLayout.addWidget(self.lineEdit_21, 0, 7, 1, 1)
self.lineEdit_10 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_10.setObjectName("lineEdit_10")
self.gridLayout.addWidget(self.lineEdit_10, 1, 4, 1, 1)
self.lineEdit_69 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_69.setObjectName("lineEdit_69")
self.gridLayout.addWidget(self.lineEdit_69, 8, 2, 1, 1)
self.lineEdit_14 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_14.setObjectName("lineEdit_14")
self.gridLayout.addWidget(self.lineEdit_14, 0, 3, 1, 1)
self.lineEdit_29 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_29.setObjectName("lineEdit_29")
self.gridLayout.addWidget(self.lineEdit_29, 2, 8, 1, 1)
self.lineEdit_11 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_11.setObjectName("lineEdit_11")
self.gridLayout.addWidget(self.lineEdit_11, 1, 3, 1, 1)
self.lineEdit_30 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_30.setObjectName("lineEdit_30")
self.gridLayout.addWidget(self.lineEdit_30, 3, 2, 1, 1)
self.lineEdit_76 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_76.setObjectName("lineEdit_76")
self.gridLayout.addWidget(self.lineEdit_76, 9, 3, 1, 1)
self.lineEdit_60 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_60.setObjectName("lineEdit_60")
self.gridLayout.addWidget(self.lineEdit_60, 6, 8, 1, 1)
self.lineEdit_74 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_74.setObjectName("lineEdit_74")
self.gridLayout.addWidget(self.lineEdit_74, 8, 7, 1, 1)
self.lineEdit_40 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_40.setObjectName("lineEdit_40")
self.gridLayout.addWidget(self.lineEdit_40, 4, 6, 1, 1)
self.lineEdit_55 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_55.setObjectName("lineEdit_55")
self.gridLayout.addWidget(self.lineEdit_55, 6, 2, 1, 1)
self.lineEdit_32 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_32.setObjectName("lineEdit_32")
self.gridLayout.addWidget(self.lineEdit_32, 4, 2, 1, 1)
self.lineEdit_15 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_15.setObjectName("lineEdit_15")
self.gridLayout.addWidget(self.lineEdit_15, 2, 1, 1, 1)
self.lineEdit_91 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_91.setObjectName("lineEdit_91")
self.gridLayout.addWidget(self.lineEdit_91, 10, 8, 1, 1)
self.lineEdit_19 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_19.setObjectName("lineEdit_19")
self.gridLayout.addWidget(self.lineEdit_19, 0, 5, 1, 1)
self.lineEdit_18 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_18.setObjectName("lineEdit_18")
self.gridLayout.addWidget(self.lineEdit_18, 0, 4, 1, 1)
self.dateTimeEdit_2 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_2.setObjectName("dateTimeEdit_2")
self.gridLayout.addWidget(self.dateTimeEdit_2, 1, 0, 1, 1)
self.lineEdit_75 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_75.setObjectName("lineEdit_75")
self.gridLayout.addWidget(self.lineEdit_75, 8, 8, 1, 1)
self.dateTimeEdit_9 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_9.setObjectName("dateTimeEdit_9")
self.gridLayout.addWidget(self.dateTimeEdit_9, 9, 0, 1, 1)
self.dateTimeEdit_8 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_8.setObjectName("dateTimeEdit_8")
self.gridLayout.addWidget(self.dateTimeEdit_8, 10, 0, 1, 1)
self.dateTimeEdit_10 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_10.setObjectName("dateTimeEdit_10")
self.gridLayout.addWidget(self.dateTimeEdit_10, 6, 0, 1, 1)
self.lineEdit_5 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_5.setObjectName("lineEdit_5")
self.gridLayout.addWidget(self.lineEdit_5, 1, 7, 1, 1)
self.lineEdit_42 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_42.setObjectName("lineEdit_42")
self.gridLayout.addWidget(self.lineEdit_42, 4, 4, 1, 1)
self.lineEdit_6 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_6.setObjectName("lineEdit_6")
self.gridLayout.addWidget(self.lineEdit_6, 1, 1, 1, 1)
self.lineEdit_16 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_16.setObjectName("lineEdit_16")
self.gridLayout.addWidget(self.lineEdit_16, 3, 1, 1, 1)
self.lineEdit_54 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_54.setObjectName("lineEdit_54")
self.gridLayout.addWidget(self.lineEdit_54, 8, 1, 1, 1)
self.lineEdit_33 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_33.setObjectName("lineEdit_33")
self.gridLayout.addWidget(self.lineEdit_33, 3, 4, 1, 1)
self.lineEdit_35 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_35.setObjectName("lineEdit_35")
self.gridLayout.addWidget(self.lineEdit_35, 3, 6, 1, 1)
self.lineEdit_47 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_47.setObjectName("lineEdit_47")
self.gridLayout.addWidget(self.lineEdit_47, 5, 4, 1, 1)
self.lineEdit_37 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_37.setObjectName("lineEdit_37")
self.gridLayout.addWidget(self.lineEdit_37, 3, 8, 1, 1)
self.lineEdit_45 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_45.setObjectName("lineEdit_45")
self.gridLayout.addWidget(self.lineEdit_45, 5, 2, 1, 1)
self.lineEdit_34 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_34.setObjectName("lineEdit_34")
self.gridLayout.addWidget(self.lineEdit_34, 3, 5, 1, 1)
self.lineEdit_28 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_28.setObjectName("lineEdit_28")
self.gridLayout.addWidget(self.lineEdit_28, 2, 7, 1, 1)
self.lineEdit_13 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_13.setObjectName("lineEdit_13")
self.gridLayout.addWidget(self.lineEdit_13, 0, 2, 1, 1)
self.lineEdit_31 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_31.setObjectName("lineEdit_31")
self.gridLayout.addWidget(self.lineEdit_31, 3, 3, 1, 1)
self.dateTimeEdit_3 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_3.setObjectName("dateTimeEdit_3")
self.gridLayout.addWidget(self.dateTimeEdit_3, 2, 0, 1, 1)
self.lineEdit_23 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_23.setObjectName("lineEdit_23")
self.gridLayout.addWidget(self.lineEdit_23, 2, 2, 1, 1)
self.dateTimeEdit_5 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_5.setObjectName("dateTimeEdit_5")
self.gridLayout.addWidget(self.dateTimeEdit_5, 4, 0, 1, 1)
self.lineEdit_24 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_24.setObjectName("lineEdit_24")
self.gridLayout.addWidget(self.lineEdit_24, 2, 3, 1, 1)
self.lineEdit_41 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_41.setObjectName("lineEdit_41")
self.gridLayout.addWidget(self.lineEdit_41, 4, 5, 1, 1)
self.lineEdit_50 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_50.setObjectName("lineEdit_50")
self.gridLayout.addWidget(self.lineEdit_50, 5, 7, 1, 1)
self.dateTimeEdit_6 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_6.setObjectName("dateTimeEdit_6")
self.gridLayout.addWidget(self.dateTimeEdit_6, 7, 0, 1, 1)
self.lineEdit_53 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_53.setObjectName("lineEdit_53")
self.gridLayout.addWidget(self.lineEdit_53, 7, 1, 1, 1)
self.lineEdit_73 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_73.setObjectName("lineEdit_73")
self.gridLayout.addWidget(self.lineEdit_73, 8, 6, 1, 1)
self.dateTimeEdit_12 = QtWidgets.QDateTimeEdit(self.gridLayoutWidget_3)
self.dateTimeEdit_12.setObjectName("dateTimeEdit_12")
self.gridLayout.addWidget(self.dateTimeEdit_12, 11, 0, 1, 1)
self.lineEdit_92 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_92.setObjectName("lineEdit_92")
self.gridLayout.addWidget(self.lineEdit_92, 11, 1, 1, 1)
self.lineEdit_93 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_93.setObjectName("lineEdit_93")
self.gridLayout.addWidget(self.lineEdit_93, 11, 2, 1, 1)
self.lineEdit_94 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_94.setObjectName("lineEdit_94")
self.gridLayout.addWidget(self.lineEdit_94, 11, 3, 1, 1)
self.lineEdit_95 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_95.setObjectName("lineEdit_95")
self.gridLayout.addWidget(self.lineEdit_95, 11, 4, 1, 1)
self.lineEdit_96 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_96.setObjectName("lineEdit_96")
self.gridLayout.addWidget(self.lineEdit_96, 11, 5, 1, 1)
self.lineEdit_97 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_97.setObjectName("lineEdit_97")
self.gridLayout.addWidget(self.lineEdit_97, 11, 6, 1, 1)
self.lineEdit_98 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_98.setObjectName("lineEdit_98")
self.gridLayout.addWidget(self.lineEdit_98, 11, 7, 1, 1)
self.lineEdit_99 = QtWidgets.QLineEdit(self.gridLayoutWidget_3)
self.lineEdit_99.setObjectName("lineEdit_99")
self.gridLayout.addWidget(self.lineEdit_99, 11, 8, 1, 1)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
widget2.addTab(self.Manual_Log, "")
#set point controls
self.formLayoutWidget = QtWidgets.QWidget(self.Manual_Log)
self.formLayoutWidget.setGeometry(QtCore.QRect(1100, 110, 139, 541))
self.formLayoutWidget.setObjectName("formLayoutWidget")
self.setpoint_grid_layout = QtWidgets.QGridLayout(self.formLayoutWidget)
self.setpoint_grid_layout.setContentsMargins(0, 0, 0, 0)
self.setpoint_grid_layout.setObjectName("setpoint_grid_layout")
spacerItem5 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.setpoint_grid_layout.addItem(spacerItem5, 12, 0, 1, 1)
self.O2_flow = QtWidgets.QLabel(self.formLayoutWidget)
self.O2_flow.setObjectName("O2_flow")
self.setpoint_grid_layout.addWidget(self.O2_flow, 13, 0, 1, 1)
self.feedpump_control = QtWidgets.QSpinBox(self.formLayoutWidget)
self.feedpump_control.setObjectName("feedpump_control")
self.setpoint_grid_layout.addWidget(self.feedpump_control, 8, 0, 1, 1)
spacerItem6 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.setpoint_grid_layout.addItem(spacerItem6, 5, 0, 1, 1)
self.airflow_control = QtWidgets.QSpinBox(self.formLayoutWidget)
self.airflow_control.setObjectName("airflow_control")
self.setpoint_grid_layout.addWidget(self.airflow_control, 18, 0, 1, 1)
spacerItem7 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.setpoint_grid_layout.addItem(spacerItem7, 16, 0, 1, 1)
self.airflow_num = QtWidgets.QLCDNumber(self.formLayoutWidget)
self.airflow_num.setStyleSheet("QLCDNumber{\n"
" background-color: rgb(96, 95, 97);\n"
"}")
self.airflow_num.setObjectName("airflow_num")
self.setpoint_grid_layout.addWidget(self.airflow_num, 19, 0, 1, 1)
self.feed_pump = QtWidgets.QPushButton(self.formLayoutWidget)
self.feed_pump.setObjectName("feed_pump")
self.setpoint_grid_layout.addWidget(self.feed_pump, 6, 0, 1, 1)
self.Mode = QtWidgets.QLabel(self.formLayoutWidget)
self.Mode.setObjectName("Mode")
self.setpoint_grid_layout.addWidget(self.Mode, 2, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.Temperature = QtWidgets.QLabel(self.formLayoutWidget)
self.Temperature.setObjectName("Temperature")
self.setpoint_grid_layout.addWidget(self.Temperature, 10, 0, 1, 1)
self.Airflow = QtWidgets.QLabel(self.formLayoutWidget)
self.Airflow.setObjectName("Airflow")
self.setpoint_grid_layout.addWidget(self.Airflow, 17, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.O2flow_control = QtWidgets.QSpinBox(self.formLayoutWidget)
self.O2flow_control.setObjectName("O2flow_control")
self.setpoint_grid_layout.addWidget(self.O2flow_control, 14, 0, 1, 1)
self.O2flow_num = QtWidgets.QLCDNumber(self.formLayoutWidget)
self.O2flow_num.setStyleSheet("QLCDNumber{\n"
" background-color: rgb(96, 95, 97);\n"
"}")
self.O2flow_num.setObjectName("O2flow_num")
self.setpoint_grid_layout.addWidget(self.O2flow_num, 15, 0, 1, 1)
self.mode = QtWidgets.QComboBox(self.formLayoutWidget)
self.mode.setObjectName("mode")
self.mode.addItem("")
self.mode.addItem("")
self.setpoint_grid_layout.addWidget(self.mode, 3, 0, 1, 1)
self.temperature_control = QtWidgets.QSpinBox(self.formLayoutWidget)
self.temperature_control.setObjectName("temperature_control")
self.setpoint_grid_layout.addWidget(self.temperature_control, 11, 0, 1, 1)
self.feed_pump_2 = QtWidgets.QLabel(self.formLayoutWidget)
self.feed_pump_2.setObjectName("feed_pump_2")
self.setpoint_grid_layout.addWidget(self.feed_pump_2, 7, 0, 1, 1, QtCore.Qt.AlignHCenter)
spacerItem8 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.setpoint_grid_layout.addItem(spacerItem8, 9, 0, 1, 1)
self.run = QtWidgets.QPushButton(self.formLayoutWidget)
self.run.setObjectName("run")
self.setpoint_grid_layout.addWidget(self.run, 4, 0, 1, 1)
self.retranslateUi(widget2)
widget2.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(widget2)
#
self.Auto_Log = QtWidgets.QWidget()
self.Auto_Log.setObjectName("Auto_Log")
self.tab1.addTab(self.Auto_Log, "")
self.Events = QtWidgets.QWidget()
self.Events.setObjectName("Events")
self.tab1.addTab(self.Events, "")
self.Comments = QtWidgets.QWidget()
self.Comments.setObjectName("Comments")
self.tab1.addTab(self.Comments, "")
#recipe tab
self.Recipe = QtWidgets.QWidget()
self.Recipe.setObjectName("Recipe")
self.tab1.addTab(self.Recipe, "")
#
"Qian's code here"
#
Cellexus_CellMaker.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(Cellexus_CellMaker)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1600, 26))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuControl = QtWidgets.QMenu(self.menubar)
self.menuControl.setObjectName("menuControl")
self.menuAlarms = QtWidgets.QMenu(self.menubar)
self.menuAlarms.setObjectName("menuAlarms")
self.menuSecurity = QtWidgets.QMenu(self.menubar)
self.menuSecurity.setObjectName("menuSecurity")
self.menuEngineering = QtWidgets.QMenu(self.menubar)
self.menuEngineering.setObjectName("menuEngineering")
Cellexus_CellMaker.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(Cellexus_CellMaker)
self.statusbar.setObjectName("statusbar")
Cellexus_CellMaker.setStatusBar(self.statusbar)
self.actionsecurity = QtWidgets.QAction(Cellexus_CellMaker)
self.actionsecurity.setObjectName("actionsecurity")
self.actionPressure = QtWidgets.QAction(Cellexus_CellMaker)
self.actionPressure.setObjectName("actionPressure")
self.actionpH = QtWidgets.QAction(Cellexus_CellMaker)
self.actionpH.setObjectName("actionpH")
self.actionpO2 = QtWidgets.QAction(Cellexus_CellMaker)
self.actionpO2.setObjectName("actionpO2")
self.actionO2 = QtWidgets.QAction(Cellexus_CellMaker)
self.actionO2.setObjectName("actionO2")
self.actionO2_Flow = QtWidgets.QAction(Cellexus_CellMaker)
self.actionO2_Flow.setObjectName("actionO2_Flow")
self.actionAir_FLOW = QtWidgets.QAction(Cellexus_CellMaker)
self.actionAir_FLOW.setObjectName("actionAir_FLOW")
self.actionNew = QtWidgets.QAction(Cellexus_CellMaker)
self.actionNew.setObjectName("actionNew")
self.actionOpen = QtWidgets.QAction(Cellexus_CellMaker)
self.actionOpen.setObjectName("actionOpen")
self.actionSave = QtWidgets.QAction(Cellexus_CellMaker)
self.actionSave.setObjectName("actionSave")
self.actionExit = QtWidgets.QAction(Cellexus_CellMaker)
self.actionExit.setCheckable(False)
self.actionExit.setObjectName("actionExit")
self.menuFile.addAction(self.actionNew)
self.menuFile.addAction(self.actionOpen)
self.menuFile.addAction(self.actionSave)
self.menuFile.addAction(self.actionExit)
self.menuAlarms.addAction(self.actionsecurity)
self.menuAlarms.addAction(self.actionPressure)
self.menuAlarms.addAction(self.actionpH)
self.menuAlarms.addAction(self.actionpO2)
self.menuAlarms.addAction(self.actionO2)
self.menuAlarms.addAction(self.actionO2_Flow)
self.menuAlarms.addAction(self.actionAir_FLOW)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuControl.menuAction())
self.menubar.addAction(self.menuAlarms.menuAction())
self.menubar.addAction(self.menuSecurity.menuAction())
self.menubar.addAction(self.menuEngineering.menuAction())
#button change function connect
self.retranslateUi(Cellexus_CellMaker)
self.tab1.setCurrentIndex(0)
self.Automatic_Pump.setCurrentIndex(0)
#button
self.Run.clicked[bool].connect(self.bticon)#form->self, link to the change function
self.acid_button.clicked[bool].connect(self.bticon)#form->self, link to the change function
self.base_button.clicked[bool].connect(self.bticon)#form->self, link to the change function
self.O2limit_button.clicked[bool].connect(self.bticon)#form->self, link to the change function
self.Airlimit_button.clicked[bool].connect(self.bticon)#form->self, link to the change function
self.N2_button.clicked[bool].connect(self.bticon)#form->self, link to the change function
self.othergas_button.clicked[bool].connect(self.bticon)#form->self, link to the change function
#switch
self.AutopH_switch.clicked[bool].connect(self.swicon)#form->self, link to the change function
self.AutoDO_switch.clicked[bool].connect(self.swicon)#form->self, link to the change function
self.AutoDO_gasswitch.clicked[bool].connect(self.swicon)#form->self, link to the change function
self.FeedPump_switch.clicked[bool].connect(self.swicon)#form->self, link to the change function
self.Dosing_switch.clicked[bool].connect(self.swicon)#form->self, link to the change function
QtCore.QMetaObject.connectSlotsByName(Cellexus_CellMaker)
#signal and slot function here
#
def retranslateUi(self, Cellexus_CellMaker):
_translate = QtCore.QCoreApplication.translate
Cellexus_CellMaker.setWindowTitle(_translate("Cellexus_CellMaker", "Cellexus CellMaker"))
self.alarmbox.setTitle(_translate("Cellexus_CellMaker", "Alarm"))
self.Press_led.setText(_translate("Cellexus_CellMaker", "Press_led"))
self.pO2_alarm.setText(_translate("Cellexus_CellMaker", "pO2"))
self.Press_alarm.setText(_translate("Cellexus_CellMaker", "Pressure"))
self.Temp_led.setText(_translate("Cellexus_CellMaker", "Temp_led"))
self.Airflow_led.setText(_translate("Cellexus_CellMaker", "Airflow_led"))
self.pO2_led.setText(_translate("Cellexus_CellMaker", "pO2_led"))
self.Temp_alarm.setText(_translate("Cellexus_CellMaker", "Temperature"))
self.pH_led.setText(_translate("Cellexus_CellMaker", "pH_led"))
self.O2flow_led.setText(_translate("Cellexus_CellMaker", "O2flow_led"))
self.Airflow_alarm.setText(_translate("Cellexus_CellMaker", "Air Flow"))
self.O2flow_alarm.setText(_translate("Cellexus_CellMaker", "O2 Flow"))
self.pH_alarm.setText(_translate("Cellexus_CellMaker", "pH"))
self.Mode.setText(_translate("Cellexus_CellMaker", "Mode"))
self.mode_choice.setItemText(0, _translate("Cellexus_CellMaker", "Setpoint"))
self.mode_choice.setItemText(1, _translate("Cellexus_CellMaker", "Recipe 1"))
self.mode_choice.setItemText(2, _translate("Cellexus_CellMaker", "Recipe 2"))
self.mode_choice.setItemText(3, _translate("Cellexus_CellMaker", "Recipe 3"))
self.Run.setText(_translate("Cellexus_CellMaker", "Run"))
self.Bioreactor_pic.setText(_translate("Cellexus_CellMaker", "bio"))
self.setpointBox.setTitle(_translate("Cellexus_CellMaker", "Setpoint"))
self.Temp_SP.setText(_translate("Cellexus_CellMaker", "Temperature(℃) SP"))
self.O2flow_SP.setText(_translate("Cellexus_CellMaker", "O2 Flow (lpm) SP"))
self.Airflow_SP.setText(_translate("Cellexus_CellMaker", "Air Flow (lpm) SP"))
self.acid_button.setText(_translate("Cellexus_CellMaker", "ACID"))
self.base_button.setText(_translate("Cellexus_CellMaker", "BASE"))
self.pHSP_label.setText(_translate("Cellexus_CellMaker", "pH SP"))
self.AutopHBox.setTitle(_translate("Cellexus_CellMaker", "Automatic pH"))
self.AutopH_switchlabel1.setText(_translate("Cellexus_CellMaker", "Off"))
self.AutopH_switch.setText(_translate("Cellexus_CellMaker", ""))##
self.AutopH_switchlabel2.setText(_translate("Cellexus_CellMaker", "On"))
self.Automatic_Pump.setItemText(self.Automatic_Pump.indexOf(self.Automatic_pH), _translate("Cellexus_CellMaker", "Automatic pH"))
self.AutoDOBox.setTitle(_translate("Cellexus_CellMaker", "Automatic DO"))
self.AutoDO_switchlabel1.setText(_translate("Cellexus_CellMaker", "Off"))
self.AutoDO_switch.setText(_translate("Cellexus_CellMaker", ""))##
self.AutoDO_switchlabel2.setText(_translate("Cellexus_CellMaker", "On"))
self.AutoDO_gaslabel.setText(_translate("Cellexus_CellMaker", "Gas"))
self.AutoDO_O2label.setText(_translate("Cellexus_CellMaker", "pO2(%) SP"))
self.AutoDO_gasswitch.setText(_translate("Cellexus_CellMaker", ""))##
self.Automatic_Pump.setItemText(self.Automatic_Pump.indexOf(self.Automatic_DO), _translate("Cellexus_CellMaker", "Automatic DO"))
self.FeedPumpbox.setTitle(_translate("Cellexus_CellMaker", "Feed Pump"))
self.FeedPump_switchlabel1.setText(_translate("Cellexus_CellMaker", "Off"))
self.FeedPump_switch.setText(_translate("Cellexus_CellMaker", ""))##
self.FeedPump_switchlabel2.setText(_translate("Cellexus_CellMaker", "On"))
self.RPM_label.setText(_translate("Cellexus_CellMaker", "Feed Pump RPM"))
self.Automatic_Pump.setItemText(self.Automatic_Pump.indexOf(self.Feed_Pump), _translate("Cellexus_CellMaker", "Feed Pump"))
self.DosingBox.setTitle(_translate("Cellexus_CellMaker", "Dosing Limits"))
self.Dosing_switchlabel1.setText(_translate("Cellexus_CellMaker", "Off"))
self.Dosing_switch.setText(_translate("Cellexus_CellMaker", ""))##
self.Dosing_switchlabel2.setText(_translate("Cellexus_CellMaker", "On"))
self.Acid_timelabel.setText(_translate("Cellexus_CellMaker", "Acid % cycle time"))
self.Base_timelabel.setText(_translate("Cellexus_CellMaker", "Base % cycle time"))
self.Automatic_Pump.setItemText(self.Automatic_Pump.indexOf(self.Acid_Base_Pump), _translate("Cellexus_CellMaker", "Acid\\Base Pumps"))
self.Bioreactor_pic_acid.setText(_translate("Cellexus_CellMaker", "Acid"))
self.acid_time.setDisplayFormat(_translate("Cellexus_CellMaker", "H:mm:ss"))
self.Bioreactor_pic_base.setText(_translate("Cellexus_CellMaker", "Base"))
self.Bioreactor_pic_heating.setText(_translate("Cellexus_CellMaker", "Heating"))
self.Bioreactor_pic_cooling.setText(_translate("Cellexus_CellMaker", "Cooling"))
self.base_time.setDisplayFormat(_translate("Cellexus_CellMaker", "H:mm:ss"))
self.biopic_pHlabel.setText(_translate("Cellexus_CellMaker", "pH"))
self.biopic_pO2label.setText(_translate("Cellexus_CellMaker", "pO2 (%air sat)"))
self.biopic_templabel.setText(_translate("Cellexus_CellMaker", "Temperature(℃) "))
self.biopic_pressurelabel.setText(_translate("Cellexus_CellMaker", "Pressure(mbar)"))
self.device_box.setItemText(0, _translate("Cellexus_CellMaker", "Device 1"))
self.device_box.setItemText(1, _translate("Cellexus_CellMaker", "Device 2"))
self.device_box.setItemText(2, _translate("Cellexus_CellMaker", "Device 3"))
self.Airlimit_button.setText(_translate("Cellexus_CellMaker", "Limits"))#
self.othergas_button.setText(_translate("Cellexus_CellMaker", "Other Gas"))#
self.N2_button.setText(_translate("Cellexus_CellMaker", "N2"))#
self.O2flow_label.setText(_translate("Cellexus_CellMaker", "O2 Flow (lpm)"))
self.O2limit_button.setText(_translate("Cellexus_CellMaker", "Limits"))
self.Air_MinMaxlabel.setText(_translate("Cellexus_CellMaker", "Air MinMax"))#
self.Airflow_label.setText(_translate("Cellexus_CellMaker", "Air Flow (lpm)"))#
self.O2minmax_label.setText(_translate("Cellexus_CellMaker", "O2 MinMax"))
self.tab1.setTabText(self.tab1.indexOf(self.Main), _translate("Cellexus_CellMaker", "Main"))
self.tab1.setTabText(self.tab1.indexOf(self.Charts), _translate("Cellexus_CellMaker", "Charts"))
self.tab1.setTabText(self.tab1.indexOf(self.Manual_Log), _translate("Cellexus_CellMaker", "Manual Log"))
self.tab1.setTabText(self.tab1.indexOf(self.Auto_Log), _translate("Cellexus_CellMaker", "Auto Log"))
self.tab1.setTabText(self.tab1.indexOf(self.Events), _translate("Cellexus_CellMaker", "Events"))
self.tab1.setTabText(self.tab1.indexOf(self.Comments), _translate("Cellexus_CellMaker", "Comments"))
self.tab1.setTabText(self.tab1.indexOf(self.Recipe), _translate("Cellexus_CellMaker", "Recipe"))
self.menuFile.setTitle(_translate("Cellexus_CellMaker", "File"))
self.menuControl.setTitle(_translate("Cellexus_CellMaker", "Control"))
self.menuAlarms.setTitle(_translate("Cellexus_CellMaker", "Alarms"))
self.menuSecurity.setTitle(_translate("Cellexus_CellMaker", "Security"))
self.menuEngineering.setTitle(_translate("Cellexus_CellMaker", "Engineering"))
self.actionsecurity.setText(_translate("Cellexus_CellMaker", "Temperature"))
self.actionPressure.setText(_translate("Cellexus_CellMaker", "Pressure"))
self.actionpH.setText(_translate("Cellexus_CellMaker", "pH"))
self.actionpO2.setText(_translate("Cellexus_CellMaker", "pO2"))
self.actionO2.setText(_translate("Cellexus_CellMaker", "O2"))
self.actionO2_Flow.setText(_translate("Cellexus_CellMaker", "O2 Flow"))
self.actionAir_FLOW.setText(_translate("Cellexus_CellMaker", "Air FLOW"))
self.actionNew.setText(_translate("Cellexus_CellMaker", "New"))
self.actionOpen.setText(_translate("Cellexus_CellMaker", "Open"))
self.actionSave.setText(_translate("Cellexus_CellMaker", "Save"))
self.actionExit.setText(_translate("Cellexus_CellMaker", "Exit"))
self.checkBoxTemp.setText(_translate("Cellexus_CellMaker", "Temperature - Red"))
self.checkBoxPres.setText(_translate("Cellexus_CellMaker", "Pressure - Orange"))
self.checkBoxPH.setText(_translate("Cellexus_CellMaker", "pH - Yellow"))
self.checkBoxDO2.setText(_translate("Cellexus_CellMaker", "dO2 - Green"))
self.checkBoxAIR.setText(_translate("Cellexus_CellMaker", "Airflow - Blue"))
self.checkBoxO2.setText(_translate("Cellexus_CellMaker", "O2 Flow - Purple"))
self.checkBoxCO2.setText(_translate("Cellexus_CellMaker", "CO2 Flow - Pink"))
self.pushButton.setText(_translate("Cellexus_CellMaker", "Export"))
self.pushButton_2.setText(_translate("Cellexus_CellMaker", "Clear"))
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("Cellexus_Cellmaker", "Cellexus_Cellmaker"))
self.do2.setText(_translate("Cellexus_Cellmaker", "dO2"))
self.test.setText(_translate("Cellexus_Cellmaker", "Test"))
self.temperature.setText(_translate("Cellexus_Cellmaker", "Temperature"))
self.pH.setText(_translate("Cellexus_Cellmaker", "pH"))
self.co2flow.setText(_translate("Cellexus_Cellmaker", "CO2 Flow"))
self.pressure.setText(_translate("Cellexus_Cellmaker", "Pressure"))
self.date.setText(_translate("Cellexus_Cellmaker", "Date"))
self.motor.setText(_translate("Cellexus_Cellmaker", "Motor"))
self.o2flow.setText(_translate("Cellexus_Cellmaker", "O2 Flow"))
self.group.setText(_translate("Cellexus_Cellmaker", "Group"))
self.datetime.setText(_translate("Cellexus_Cellmaker", "Date/Time"))
self.airflow.setText(_translate("Cellexus_Cellmaker", "Air Flow"))
self.operator_2.setText(_translate("Cellexus_Cellmaker", "Operator"))
self.filename.setText(_translate("Cellexus_Cellmaker", "Manual Log"))
self.log.setText(_translate("Cellexus_Cellmaker", "Log"))
self.file_name.setText(_translate("Cellexus_Cellmaker", "Manual Log File Name "))
self.interval.setText(_translate("Cellexus_Cellmaker", "Interval (s)"))
self.O2_flow.setText(_translate("Cellexus_Cellmaker", "O2 Flow (lpm) SP"))
self.feed_pump.setText(_translate("Cellexus_Cellmaker", "Feed Pump ON"))
self.Mode.setText(_translate("Cellexus_Cellmaker", "Mode"))
self.Temperature.setText(_translate("Cellexus_Cellmaker", "Temperature (ºC) SP"))
self.Airflow.setText(_translate("Cellexus_Cellmaker", "Air Flow (lpm) SP"))
self.mode.setItemText(0, _translate("Cellexus_Cellmaker", "Setpoint"))
self.mode.setItemText(1, _translate("Cellexus_Cellmaker", "Recipe"))
self.feed_pump_2.setText(_translate("Cellexus_Cellmaker", "Feed Pump RPM"))
self.run.setText(_translate("Cellexus_Cellmaker", "RUN"))
self.openFileButton.setText(_translate("Cellexus_Cellmaker", "Open file"))
self.tab1.setTabText(self.tab1.indexOf(self.Manual_Log), _translate("Cellexus_CellMaker", "Manual Log"))
#vickys bits
def retranslateUi(self, widget2):
_translate = QtCore.QCoreApplication.translate
widget2.setWindowTitle(_translate("widget2", "manual_log"))
self.filename.setText(_translate("widget2", "Manual Log"))
self.log.setText(_translate("widget2", "Log"))
self.file_name.setText(_translate("widget2", "Manual Log File Name "))
self.Open_file.setText(_translate("widget2", "Open file"))
self.do2.setText(_translate("widget2", "dO2"))
self.test.setText(_translate("widget2", "Test"))
self.temperature.setText(_translate("widget2", "Temperature"))
self.pH.setText(_translate("widget2", "pH"))
self.co2flow.setText(_translate("widget2", "CO2 Flow"))
self.pressure.setText(_translate("widget2", "Pressure"))
self.date.setText(_translate("widget2", "Date"))
self.motor.setText(_translate("widget2", "Motor"))
self.o2flow.setText(_translate("widget2", "O2 Flow"))
self.group.setText(_translate("widget2", "Group"))
self.datetime.setText(_translate("widget2", "Date/Time"))
self.airflow.setText(_translate("widget2", "Air Flow"))
self.operator_2.setText(_translate("widget2", "Operator"))
self.O2_flow.setText(_translate("widget2", "O2 Flow (lpm) SP"))
self.feed_pump.setText(_translate("widget2", "Feed Pump ON"))
self.Mode.setText(_translate("widget2", "Mode"))
self.Temperature.setText(_translate("widget2", "Temperature (ºC) SP"))
self.Airflow.setText(_translate("widget2", "Air Flow (lpm) SP"))
self.mode.setItemText(0, _translate("widget2", "Setpoint"))
self.mode.setItemText(1, _translate("widget2", "Recipe"))
self.feed_pump_2.setText(_translate("widget2", "Feed Pump RPM"))
self.run.setText(_translate("widget2", "RUN"))
self.interval.setText(_translate("widget2", "Interval (s)"))
widget2.setTabText(widget2.indexOf(self.Manual_Log), _translate("widget2", "Manual Log"))
def buttonon(self):
#on picture when cilcked it
button=self.sender()##sender() is used to judge which button was clicked
button.setStyleSheet("QPushButton{border-image: url(image/button_on.png)}")##
def buttonoff(self):
#off picture when clicked it again
button=self.sender()
button.setStyleSheet("QPushButton{border-image: url(image/button_off.png)}")##
def bticon(self,pressed):
# when push the button
if pressed:
self.buttonon()
else:
self.buttonoff()
def switchon(self):
#on picture when cilcked it
button=self.sender()##sender() is used to judge which button was clicked
button.setIcon(QtGui.QIcon('image\on.png'))##
button.setIconSize(QtCore.QSize(50,50))##
def switchoff(self):
#off picture when clicked it again
button=self.sender()
button.setIcon(QtGui.QIcon('image\off.png'))##
button.setIconSize(QtCore.QSize(50,50))##
def swicon(self,pressed):
# when push the button
if pressed:
self.switchon()
else:
self.switchoff()
# other functions in the class here
def browsefiles_1(self):
fname = QFileDialog.getSaveFileName(self, 'Open File', 'D:\Documents')
def cleargraph(self):
if self.checkBoxTemp.isChecked():
self.checkBoxTemp.setCheckState(0)
self.widget1.clear()
if self.checkBoxPres.isChecked():
self.checkBoxPres.setCheckState(0)
self.widget1.clear()
if self.checkBoxPH.isChecked():
self.checkBoxPH.setCheckState(0)
self.widget1.clear()
if self.checkBoxDO2.isChecked():
self.checkBoxDO2.setCheckState(0)
self.widget1.clear()
if self.checkBoxAIR.isChecked():
self.checkBoxAIR.setCheckState(0)
self.widget1.clear()
if self.checkBoxO2.isChecked():
self.checkBoxO2.setCheckState(0)
self.widget1.clear()
if self.checkBoxCO2.isChecked():
self.checkBoxCO2.setCheckState(0)
self.widget1.clear()
def checked_item(self):
if self.checkBoxTemp.isChecked():
x=[1,2,3]
y=[2,3,4]
pen = pg.mkPen(color=(255, 0, 0), width=3)
self.widget1.plot(x, y, pen=pen)
if self.checkBoxPres.isChecked():
x=[2,3,4]
y=[2,3,4]
pen = pg.mkPen(color=(255, 155, 55), width=3)
self.widget1.plot(x, y, pen=pen)
if self.checkBoxPH.isChecked():
x=[3,4,5]
y=[2,3,4]
pen = pg.mkPen(color=(255, 255, 0), width=3)
self.widget1.plot(x, y, pen=pen)
if self.checkBoxDO2.isChecked():
x=[4,5,6]
y=[2,3,4]
pen = pg.mkPen(color=(100, 200, 50), width=3)
self.widget1.plot(x, y, pen=pen)
if self.checkBoxAIR.isChecked():
x=[5,6,7]
y=[2,3,4]
pen = pg.mkPen(color=(0, 0, 255), width=3)
self.widget1.plot(x, y, pen=pen)
if self.checkBoxO2.isChecked():
x=[6,7,8]
y=[2,3,4]
pen = pg.mkPen(color=(200, 0, 255), width=3)
self.widget1.plot(x, y, pen=pen)
if self.checkBoxCO2.isChecked():
x=[7,8,9]
y=[2,3,4]
pen = pg.mkPen(color=(248, 24, 148), width=3)
self.widget1.plot(x, y, pen=pen)
#manual log tab browse files
def browsefiles(self):
fname = QFileDialog.getOpenFileName(self, 'Open File', 'D:\Documents')
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
widget = QtWidgets.QMainWindow() #widget->maindow
ui = Ui_Cellexus_CellMaker() # CLASS NAME
ui.setupUi(widget)
widget.show()
#adding this whole section as im not sure whats needed
#if __name__ == "__main__":
#import sys
#app = QtWidgets.QApplication(sys.argv)
widget2 = QtWidgets.QTabWidget()
ui = Ui_widget2()
ui.setupUi(widget2)
widget2.show()
#sys.exit(app.exec_())
#bioreactor picture in main tab
ui.Bioreactor_pic.setPixmap(QPixmap('image/bio.png'))
ui.Bioreactor_pic.setScaledContents(True)
#Setpoint=[Temp_setpoint, Press_setpoint, O2flow_setpoint, Airflow_setpoint, pH_setpoint, pO2_setpoint,]
#alarm function
#it may too complex and edious, also need to improve and maybe put this function to another py document
#the led picture seems odd, also need some adjustment
def ALARM(Temp_setpoint, Temp_measurement, Press_setpoint, Press_measurement, O2flow_setpoint, O2flow_measurement, Airflow_setpoint, Airflow_measurement, pH_setpoint, pH_measurement, pO2_setpoint, pO2_measurement):
#clear the text
#ui.Temp_led.setText("")
red=QPixmap('image/red.jpg')
grey=QPixmap('image/grey.jpg')
#decide if it needs a alarm on
if Temp_measurement > Temp_setpoint :
ui.Temp_led.setPixmap(red)
ui.Temp_led.setScaledContents(True)
else :
ui.Temp_led.setPixmap(grey)
ui.Temp_led.setScaledContents(True)
if Press_measurement > Press_setpoint :
ui.Press_led.setPixmap(red)
ui.Press_led.setScaledContents(True)
else :
ui.Press_led.setPixmap(grey)
ui.Press_led.setScaledContents(True)
if O2flow_measurement > O2flow_setpoint :
ui.O2flow_led.setPixmap(red)
ui.O2flow_led.setScaledContents(True)
else :
ui.O2flow_led.setPixmap(grey)
ui.O2flow_led.setScaledContents(True)
if Airflow_measurement > Airflow_setpoint :
ui.Airflow_led.setPixmap(red)
ui.Airflow_led.setScaledContents(True)
else :
ui.Airflow_led.setPixmap(grey)
ui.Airflow_led.setScaledContents(True)
if pH_measurement > pH_setpoint :
ui.pH_led.setPixmap(red)
ui.pH_led.setScaledContents(True)
else :
ui.pH_led.setPixmap(grey)
ui.pH_led.setScaledContents(True)
if pO2_measurement > pO2_setpoint :
ui.pO2_led.setPixmap(red)
ui.pO2_led.setScaledContents(True)
else :
ui.pO2_led.setPixmap(grey)
ui.pO2_led.setScaledContents(True)
ALARM(38,39,1,0,1,0,1,2,1,0,1,2)
sys.exit(app.exec_())
|
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
from IPython import get_ipython
# %% [markdown]
# # Prepare Titanic Model for Web / API
#
# Final result on Heroku:
# https://titanic-model-app.herokuapp.com/
#
# Sources:
# 1. https://www.kaggle.com/c/titanic/data
#
# 2. https://towardsdatascience.com/create-an-api-to-deploy-machine-learning-models-using-flask-and-heroku-67a011800c50?gi=30b632ffd17d
#
# 2. https://blog.cambridgespark.com/deploying-a-machine-learning-model-to-the-web-725688b851c7
#
# %%
get_ipython().run_cell_magic('html', '', '<style>\n table {margin-left: 0 !important;}\n</style>\n# Align table to left')
# %% [markdown]
# ## Version Control
# | Version | Date | Person | Description
# | :- |:------------- | :- | :-
# |1.00 | 2/3/2020 | SW| added version control and released to production
# |1.01 | 2/6/2020 | SW | added cross validation score
# |1.02 | 2/8/2020 | SW | added hyperparameter tuning for logistic
# |1.03 | 2/16/2020 | SW | tested multiple models, including cross validation
# |1.04 | 2/26/2020 | SW | ran against test, exported submission, added feature importance and partial dependence to evaluate model
# |1.05 | 2/28/2020 | SW | added standard scaler to model and app
# |1.06 | 3/14/2020 | SW | updated feature importance graph
# %%
# last updated
from datetime import datetime
print("last updated: " + str(datetime.now()))
# %% [markdown]
# ## Import modules / libraries and data
# %%
import pandas as pd # data manipulation
import seaborn as sns # for data exploration
import numpy as np
from sklearn.preprocessing import StandardScaler # for scaling inputs
from sklearn.linear_model import LogisticRegression # model: logistic regression
from sklearn.svm import SVC # model: SVC / support vector machine
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import GridSearchCV # for hyperparameter tuning
from sklearn.model_selection import cross_val_score # for cross validation
from sklearn.inspection import plot_partial_dependence # for model evaluation and understanding
from pdpbox import pdp, get_dataset, info_plots # partial dependence 2 , may need need pip install pdpbox
import json # for exporting data
# %%
# create df,
data = pd.read_csv('titanic_train.csv') # change file path as necessary
# %% [markdown]
# ## Data exploration, including creating sub-training set
# %%
data.shape
# %%
data.dtypes
# %%
data.describe(include='all')
# %%
# see which is na
data.isna().sum()
# %%
# drop non-numeric & not relevant data
data = data.drop(['Name','Cabin','Embarked','Ticket'],axis = 1)
data.shape
# %%
# non Numeric data
# one-hot coding
from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder(handle_unknown='ignore',sparse = False)
nonNumData = data.select_dtypes(exclude = ['int64','float64'])
print(nonNumData.dtypes)
# %%
# transformed data is ok because we've removed na's
nonNumDataEncArray = enc.fit_transform(nonNumData)
nonNumDataEnc = pd.DataFrame(data = nonNumDataEncArray)
# %%
print(list(nonNumDataEnc.columns))
featuresNonNumeric = ['Sex-' + str(x) for x in list(nonNumDataEnc.columns)]
print(enc.categories_)
print(featuresNonNumeric)
nonNumDataEnc.columns = featuresNonNumeric
# %%
# add new data back to dataset (Sex-0 is 1 for females, Sex-1 is 1 for males)
data = pd.concat([data, nonNumDataEnc], axis=1)
# %% [markdown]
# ## Feature selection
# %%
# features and target
target = ['Survived']
features = ['Pclass', 'Age', 'SibSp', 'Fare'] + featuresNonNumeric # X matrix, y vector
# %%
# pairplot
allfeat = target + features
sns.pairplot(data, vars=allfeat)
# %% [markdown]
# ## Create and train model
# %%
# data is encoded with one-hot, ready for analysis
train = data
# %%
# drop null values
train.dropna(inplace=True)
# %%
# select data set for modeling
X = train[features]
X_orig = X
# scale inputs
scaler = StandardScaler()
X = scaler.fit_transform(X)
y = train[target].values.ravel() # model , covert to 1d array for easy fitting
# %%
#creat models for selection
logistic = LogisticRegression(solver='lbfgs',max_iter = 1000)
svc = SVC(gamma='auto')
randforest = RandomForestClassifier(n_estimators=100)
knn = KNeighborsClassifier()
gbc = GradientBoostingClassifier()
# svc = LinearSVC(max_iter = 1000) # doesn't work
# %%
model_set = [logistic, svc , randforest, knn, gbc]
model_set_results = {}
# %%
#see which model scores best, using cross validation to remove overfitting
for mdl in model_set:
scores = cross_val_score(mdl, X, y, cv=5)
model_set_results[str(mdl)[0:20]] = np.mean(scores)
# %%
df = pd.DataFrame(model_set_results.items(), columns=["model", "score"])
print(df)
# %% [markdown]
# Gradient boost is best, accounting for cross validation
# %%
# logistic.get_params().keys()
# %%
# hyperparameter tuning after model selection
# # Create regularization penalty space
# penalty = ['l2']
# # Create regularization hyperparameter space
# C = [0.1,1,10]
# # Create hyperparameter options
# hyperparameters = dict(C=C, penalty=penalty)
# # Create grid search using 5-fold cross validation
# clf = GridSearchCV(logistic, hyperparameters, cv=5, verbose=0)
# %%
#Conduct Grid Search
# # Fit grid search
# best_model = clf.fit(X, y)
# #View Hyperparameter Values Of Best Model
# # View best hyperparameters
# print('Best Penalty:', best_model.best_estimator_.get_params()['penalty'])
# print('Best C:', best_model.best_estimator_.get_params()['C'])
# %%
# select model
model = gbc
model.fit(X,y)
# %% [markdown]
# ## Evaluate model
# %%
# roc curve
from sklearn.metrics import roc_curve, auc
fpr, tpr, _ = roc_curve(y,model.predict(X) ) # roc_curve(actual, expected)
roc_auc = auc(fpr, tpr)
# %%
# plot roc curve
import matplotlib.pyplot as plt
plt.figure(figsize = [6.4*1.25, 4.8*1.25])
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label='ROC curve (area = %0.4f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
# %%
#feature importance
model_importances_table = pd.DataFrame(data = {
'Feature' : X_orig.columns ,
'Importance' : model.feature_importances_
})
model_importances_table.sort_values(by='Importance', inplace=True, ascending=False)
plt.figure(figsize=(5, 10))
sns.barplot(x='Importance', y='Feature', data=model_importances_table)
plt.xlabel('')
plt.tick_params(axis='x', labelsize=10)
plt.tick_params(axis='y', labelsize=10)
plt.title('Gradient Boosting Classifier', size=10)
plt.show()
#Sex-0 is female
# %%
#partial dependence plot 1
pdp_features = ['Sex-0','Pclass','Age' ,('Sex-0','Pclass')] #selected
pdp_feature_names = ['Pclass', 'Age', 'SibSp', 'Fare', 'Sex-0', 'Sex-1'] #based on columns of X, sex-0 is female
plot_partial_dependence(model, X, features=pdp_features, feature_names = pdp_feature_names)
# %%
X_df = pd.DataFrame(data = X, columns = X_orig.columns)
# %%
# partial depedence plot detailed, from Kaggle explainability
# Create the data that we will plot
pdp_sex_0 = pdp.pdp_isolate(model=model, dataset=X_df, model_features=pdp_feature_names, feature='Sex-0')
# plot it
pdp.pdp_plot(pdp_sex_0, 'Sex-0', figsize = (10,5))
plt.show()
# %%
pdp_pclass = pdp.pdp_isolate(model=model, dataset=X_df, model_features=pdp_feature_names, feature='Pclass')
# plot it
pdp.pdp_plot(pdp_pclass, 'Pclass', figsize = (10,5))
plt.show()
#normalized x-axis bc is transformed
# %%
pdp_age = pdp.pdp_isolate(model=model, dataset=X_df, model_features=pdp_feature_names, feature='Age')
# plot it
pdp.pdp_plot(pdp_pclass, 'Age', figsize = (10,5))
plt.show()
#normalized x-axis bc is transformed
# %% [markdown]
# ## Run Model on Test Data for Kaggle Submission
# %%
data_test = pd.read_csv('test.csv')
print(data.dtypes)
# %%
data_test.describe(include='all')
# %%
print(featuresNonNumeric)
# %%
#add columns to dictionary
data_test = data_test.assign(**dict.fromkeys(featuresNonNumeric, 0))
# %%
#update NonNumeric columns
data_test.loc[data_test['Sex'] == 'male', 'Sex-1'] = 1 # female 1 or male 1
data_test.loc[data_test['Sex'] == 'female', 'Sex-0'] = 0 # female 1 or male 1
# %%
X_predict = data_test[features] # see feature selection above
#clean up na's
X_predict = X_predict.fillna(X_predict.mean())
#transform for fitting
X_predict = scaler.transform(X_predict)
# %%
# result for submission
Y_test = model.predict(X_predict)
# %%
# save submission
final_submission = pd.DataFrame({'PassengerID': data_test['PassengerId'], 'Survived': Y_test})
# %%
# export submission
final_submission.to_csv('final_submission.csv',index=False, header= True)
# %% [markdown]
# ## Save model and transformer as pickle
# %%
import pickle
pickle.dump(model, open('model.pkl', 'wb'))
pickle.dump(scaler, open('scaler.pkl', 'wb'))
# %% [markdown]
# ## Run app.py
# %% [markdown]
# type "python app.py" in console while in folder
# %% [markdown]
# ## Test app web interface
# Type "flask run" in terminal, once in this directory
# %% [markdown]
# ## Test app API
#
# %%
# type "flask run" in command line while in parent directory (within anaconda env)
# local url
url = 'http://127.0.0.1:5000'
# %%
# sample data
input_sample = {'Pclass': 3
, 'Age': 2
, 'SibSp': 1
, 'Fare': 50}
input_sample = json.dumps(input_sample)
# %%
import requests, json
#send_request = requests.post(url, input_sample)
#print(send_request)
# %%
# check actual result
#print(send_request.json())
# %% [markdown]
# to stop app, press ctrl+c in console
# %% [markdown]
# ## Then create Procfile for Heroku app
# %% [markdown]
# ## Then create requirements.txt
# %% [markdown]
# Use:
# Flask==1.1.1
# gunicorn==19.9.0
# pandas==0.25.0
# requests==2.22.0
# scikit-learn==0.21.2
# scipy==1.3.1
#
# More generally, can do:
# pip freeze > requirements.txt
# %% [markdown]
# ## Deploy on Heroku
# %% [markdown]
# ## Check Heroku
# %%
# heroku url
heroku_url = 'https://titanic-model-app.herokuapp.com/' # change to your app name# sample data
input_sample_api = { 'Pclass': 3
, 'Age': 2
, 'SibSp': 1
, 'Fare': 50}
input_sample_api = json.dumps(input_sample_api)
# %%
# may need to disable firewall for this
#send_request = requests.post(heroku_url, data)
#print(send_request)
# %%
#print(send_request.json())
# %% [markdown]
# ## Exporting Options
# 1. From vscode, can export into jupyter notebook using vscode's jupyter interactive window
# 1. From Jupyter notebook/lab , can export notebook into html
# 1. From command line, can can convert using nbconvert to html ($ jupyter nbconvert --to FORMAT notebook.ipynb)
#
# %%
|
# Generated by Django 2.0.1 on 2018-01-21 14:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('test_app', '0012_add_decimal'),
]
operations = [
migrations.AddField(
model_name='secondobject',
name='elapsed',
field=models.DurationField(null=True),
),
]
|
from setuptools import setup, find_packages
PACKAGE = "fastapi-sqlalchemy"
VERSION = "0.9.0"
setup(
name=PACKAGE,
version=VERSION,
author="Matthew Laue",
author_email="matt@zuar.com",
url="https://github.com/zuarbase/fastapi-sqlalchemy",
packages=find_packages(exclude=["tests"]),
include_package_data=True,
install_requires=[
"email-validator",
"fastapi >= 0.52.0, < 0.53.0",
"pydantic >= 1.4, < 1.5",
"passlib",
"python-dateutil",
"python-multipart",
"pyjwt",
"sqlalchemy",
"sqlalchemy-filters",
"tzlocal",
"itsdangerous",
],
extras_require={
"dev": [
"coverage",
"pylint",
"pytest",
"pytest-cov",
"pytest-env",
"pytest-mock",
"requests",
"flake8",
"flake8-quotes",
],
"prod": [
"uvicorn",
"gunicorn",
]
}
)
|
from django.db import models
from tinymce.models import HTMLField
# Create your models here.
class HomeSlider(models.Model):
Name = models.CharField(max_length=120)
Image =models.ImageField(upload_to='slider/')
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
class HomeSlider2(models.Model):
Name = models.CharField(max_length=120)
Name2 = models.CharField(max_length=120)
Text = models.CharField(max_length=300)
Image = models.ImageField(upload_to='slider2/')
def __str__(self):
return self.Name
class Homeslide3(models.Model):
Name = models.CharField(max_length=120)
Image = models.ImageField(upload_to='slider3/')
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
class ContactUs(models.Model):
NAME = models.CharField(max_length=120)
COMPANY = models.CharField(max_length=120)
TELEPHONE = models.CharField(max_length=120)
EMAIL = models.EmailField(max_length=120)
MESSAGE = models.CharField(max_length=300)
class Meta:
ordering = ('NAME',)
def __str__(self):
return self.NAME
class JoinUs(models.Model):
NAME = models.CharField(max_length=120)
COMPANY = models.CharField(max_length=120)
TELEPHONE = models.CharField(max_length=120)
EMAIL = models.EmailField(max_length=120)
MESSAGE = models.CharField(max_length=300)
IMAGE = models.ImageField(upload_to='joinus', blank=True)
class Meta:
ordering = ('NAME',)
def __str__(self):
return self.NAME
class RequestQuote(models.Model):
NAME = models.CharField(max_length=120)
COMPANY = models.CharField(max_length=120)
TELEPHONE = models.CharField(max_length=120)
EMAIL = models.EmailField(max_length=120)
MESSAGE = models.CharField(max_length=300)
CART_ID = models.IntegerField()
IMAGE = models.ImageField(upload_to='joinus', blank=True)
class Meta:
ordering = ('NAME',)
def __str__(self):
return self.NAME
class HomeS1(models.Model):
Name = models.CharField(max_length=120)
Image =models.ImageField(upload_to='s1/')
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
class HomeS2(models.Model):
Name = models.CharField(max_length=120)
Name2 = models.CharField(max_length=120)
Text = models.CharField(max_length=300)
Image = models.ImageField(upload_to='s2/')
def __str__(self):
return self.Name
class Homes3(models.Model):
Name = models.CharField(max_length=120)
Image = models.ImageField(upload_to='s3/')
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
class AboutUs(models.Model):
Name = models.CharField(max_length=120)
Email = models.EmailField(max_length=120)
Comment = models.CharField(max_length=300)
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
class AboutUsSlider(models.Model):
Name = models.CharField(max_length=120)
Image = models.ImageField(upload_to='s1/')
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
class SpecialtiesSlider(models.Model):
Name = models.CharField(max_length=120)
Image =models.ImageField(upload_to='s1/')
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
class JoinUsSlider(models.Model):
Name = models.CharField(max_length=120)
Image =models.ImageField(upload_to='s1/')
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
# class ProductSlider(models.Model):
# Name = models.CharField(max_length=120)
# Image =models.ImageField(upload_to='s1/')
# class Meta:
# ordering = ('Name',)
# def __str__(self):
# return self.Name
# class ProductSlider1(models.Model):
# Name = models.CharField(max_length=120)
# Image =models.ImageField(upload_to='s1/')
# class Meta:
# ordering = ('Name',)
# def __str__(self):
# return self.Name
class ProductCategory(models.Model):
Name = models.CharField(max_length=120)
Image =models.ImageField(upload_to='s1/')
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
class ProductSubCategory(models.Model):
Name = models.CharField(max_length=120)
Category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE)
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
class ProductsList(models.Model):
Name = models.CharField(max_length=120)
# unit_price= models.DecimalField(default= 0.0, max_digits=6, decimal_places=2)
# quantity=models.IntegerField(default=0)
Category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE)
SubCategory = models.ForeignKey(ProductSubCategory,blank=True,null=True, on_delete=models.CASCADE)
# content=models.TextField(blank=True, null=True)
content= HTMLField(blank=True, null=True)
class Meta:
ordering = ('Name',)
def __str__(self):
return self.Name
@property
def images(self):
return self.ProductImages_set.all()
class ProductImages(models.Model):
Category = models.ForeignKey(ProductsList, related_name='images', on_delete=models.CASCADE)
unit_price= models.DecimalField(default= 0.0, max_digits=6, decimal_places=2)
quantity=models.IntegerField(default=0)
Description=models.CharField(max_length=120)
Item_number= models.CharField(max_length=50)
Image = models.ImageField(upload_to='ProductsImages/')
class BecomeDistributer(models.Model):
NAME = models.CharField(max_length=120)
COMPANY = models.CharField(max_length=120)
TELEPHONE = models.CharField(max_length=120)
EMAIL = models.EmailField(max_length=120)
MESSAGE = models.CharField(max_length=300)
IMAGE = models.ImageField(upload_to='distributer', blank=True)
class Meta:
ordering = ('NAME',)
def __str__(self):
return self.NAME |
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import requests
print("Initializing driver...")
browser = webdriver.Firefox() # executable_path='geckodriver.exe')
browser.get('http://o2tvseries.com/Madam-Secretary-8/Season-04/index.html')
elements = browser.find_element_by_class_name(
'data_list').find_elements_by_xpath("//a[@href]")
print("Populating episode list...")
episodes = []
for element in elements:
if 'Episode' in element.get_attribute("href"):
episodes.append(element.get_attribute("href"))
print("Processing redirected urls...")
download_list = []
for episode in episodes:
per_episode = webdriver.Firefox() # executable_path='geckodriver.exe')
print("Episode is:", episode)
per_episode.get(episode)
elem_episodes = per_episode.find_element_by_class_name(
'data_list').find_elements_by_xpath("//a[@href]")
for elem_episode in elem_episodes:
if 'HD (TvShows4Mobile.Com).mp4' in elem_episode.text:
print("ELEM EPI:", elem_episode)
download_list.append('http://d5.o2tvseries.com/' + 'Madam%20Secretary/' + 'Season%2004/' +
elem_episode.text.replace(' ', '%20'))
print(elem_episode.get_attribute('href').replace(
'http', 'https'), elem_episode.text)
per_episode.close()
for download in download_list:
episode = download[-38:].replace('%20', ' ')
r = requests.get(download, allow_redirects=True)
open(episode, 'wb').write(r.content)
print('downloaded this Episode : ' + episode)
break
|
class Person:
def __init__(self, name, address):
self.name = name
self.address = address
def getName(self):
return self.name
def getAddress(self):
return self.address
def setAddress(self, address):
self.address = address
def __str__(self):
return f'{self.name}({self.address})'
class Student(Person):
numCourses = 0
courses = []
grades = []
def __init__(self, name, address):
super().__init__(name, address)
def addCourseGrade(self, course:str, grade:int):
if course not in self.courses:
self.courses.append(course)
self.grades.append(grade)
else:
self.grades.append(grade)
self.numCourses += 1
def printGrades(self):
for i in range(len(self.courses)):
print(f'{self.courses[i]}: {self.grades[i]}')
def getAverageGrade(self):
average = sum(self.grades) / self.numCourses
return average
def __str__(self):
return f'Student: {super().__str__()}'
class Teacher(Person):
numCourses = 0
courses = []
def __init__(self, name, address):
super().__init__(name, address)
def __str__(self):
return f'Teacher: {super().__str__()}'
def addCourse(self, course):
if course not in self.courses:
self.courses.append(course)
self.numCourses += 1
else:
return False
def removeCourse(self, course):
if course in self.courses:
self.courses.remove(course)
else:
return False
def teacher_page():
for_input = input('Do you have an account yet?(Yes/No): ')
if for_input == 'No':
name = input('Your name: ')
address = input('Your address: ')
teacher = Teacher(name=name, address=address)
teacher_list.append(name)
print(teacher.__str__())
teacher_service(teacher)
if for_input == 'Yes':
print('Fill in the data below')
teacher_name = input('Your name: ')
if teacher_name in teacher_list:
print(f'Welcome {teacher_name}')
teacher_service(teacher)
def teacher_service(teacher):
print('What are you trying to do today?')
print('1. Add course''\n''2. Remove course')
inputs = input('Your choice(1/2): ')
if inputs == '1':
course_name = str(input("Course: "))
teacher.addCourse(course=course_name)
print('Number of course: ', teacher.numCourses)
answer = input('Do you want to do another action?(Yes/No): ')
if answer == 'Yes':
teacher_service(teacher)
if answer == 'No':
main()
if inputs == '2':
del_course = str(input('Course: '))
teacher.removeCourse(course=del_course)
print('Current list of courses: ', teacher.courses)
answer = input('Do you want to do another action?(Yes/No): ')
if answer == 'Yes':
teacher_service(teacher)
if answer == 'No':
main()
def student_page():
for_input = input('Do you have an account yet?(Yes/No): ')
if for_input == 'No':
name = input('Your name: ')
address = input('Your address: ')
student = Student(name=name, address=address)
student_list.append(student)
print(student.__str__())
student_service(student)
if for_input == 'Yes':
print('Fill in the data below')
student_name = input('Your name: ')
if student_name in student_list:
print(f'Welcome {student_name}')
student_service(student)
def student_service(student):
print('What are you trying to do today?')
print('1. Add course and grade''\n''2. Print grades''\n''3. Average grade')
inputs = input('Your choice(1/2/3): ')
if inputs == '1':
course = input('Course: ')
grade = int(input('Grade: '))
student.addCourseGrade(course=course, grade=grade)
print('Collection of courses: ', student.courses)
print('Collection of grades: ', student.grades)
answer = input('Do you want to do another action?(Yes/No): ')
if answer == 'Yes':
student_service(student)
if answer == 'No':
main()
if inputs == '2':
print('All of your grades: ')
student.printGrades()
answer = input('Do you want to do another action?(Yes/No): ')
if answer == 'Yes':
student_service(student)
if answer == 'No':
main()
if inputs == '3':
print('Your average grade: ', student.getAverageGrade())
answer = input('Do you want to do another action?(Yes/No): ')
if answer == 'Yes':
student_service(student)
if answer == 'No':
main()
def main():
print('Welcome to School!')
for_input = input("Are you a 'Teacher' or a 'Student': ")
if for_input == 'Teacher':
print('Welcome to Teacher Page!')
teacher_page()
elif for_input == 'Student':
print('Welcome to Student Page!')
student_page()
else:
main()
if __name__ == '__main__':
teacher_list = []
student_list = []
main()
|
# -*- coding: utf-8 -*-
"""
@Time : 2020/5/22 16:28
@Author : QDY
@FileName: 123. 买卖股票的最佳时机 III_动态规划_hard.py
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [3,3,5,0,0,3,1,4]
输出: 6
解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。
示例 2:
输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
示例 3:
输入: [7,6,4,3,1]
输出: 0
解释: 在这个情况下, 没有交易完成, 所以最大利润为 0。
"""
class Solution:
def maxProfit(self, prices):
# 动态规划
# dp[i][j][0] 表示在第i天,交易了j次,不持有股票的利润
# dp[i][j][1] 表示在第i天,交易了j次,持有股票的利润
# dp[i][j][0] = max(dp[i-1][j][0],dp[i-1][j][1]+prices[i-1]) #在第i天卖出
# dp[i][j][1] = max(dp[i-1][j][1],dp[i-1][j-1][0]-prices[i-1]) # 在第i天买进
dp = [[0, -float('inf')] for i in range(3)]
for i in range(len(prices)):
for j in range(2, 0, -1): # 压缩至3x2维数组,O(1)
dp[j][0], dp[j][1] = max(dp[j][0], dp[j][1] + prices[i]), max(dp[j][1], dp[j - 1][0] - prices[i])
return dp[-1][0]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.