blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2
values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220
values | src_encoding stringclasses 30
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 2 10.3M | extension stringclasses 257
values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3694eeaaf097d04a21fbf0aabbffbeded8ac2afd | 327d3c1b4f7cc7565da6b2f157e8fdfaf10ef953 | /Hill_function.py | 1b425a73d68e26eff9c7aa70e440bb18a3ffc3f7 | [] | no_license | mircobial-evolution-dynamic/governing-equations | 3937a3c8309bf8b6c4c3248654bed6b55d7752d7 | 765f54f2635fbebae3211e1de91c3f620717ba69 | refs/heads/master | 2021-01-09T16:13:54.279437 | 2020-08-27T11:05:00 | 2020-08-27T11:05:00 | 242,367,994 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,921 | py | import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
from scipy import linalg
from sklearn.preprocessing import normalize
import csv
from sklearn.linear_model import lasso_path
# system size
n = 1
# parameters
def hillfunc(t, x):
k = 1
return np.divide(x**4, (2**4 + x**4))*x
def new_hillfunc(t, x):
return np.divide((0.756*(x**4) + 0.378), (0.378 + 0.378 * (x**4)))
tspan = np.linspace(0.01, 10, num=1000)
dt = 0.01
ini = [0.001]
sol = integrate.solve_ivp(hillfunc, [tspan[0], tspan[-1]], ini, method='RK45', t_eval=tspan)
sol2 = integrate.solve_ivp(new_hillfunc, [tspan[0], tspan[-1]], ini, method='RK45', t_eval=tspan)
plt.plot(sol.y[0],linewidth=2, label='Ground Truth', color='orange')
plt.plot(sol2.y[0],linestyle='dashed', label='Identified Value', color='black')
plt.xticks(fontsize=13)
plt.yticks(fontsize=13)
plt.xlabel('Time Steps', fontsize= 18)
plt.ylabel('Substrate Concentration', fontsize = 18)
plt.legend(fontsize = 18)
plt.show()
sol_dx = hillfunc(sol.t, sol.y)
plt.show()
exp_data = sol_dx
def data_aug(sol_):
n = len(sol_)
m = sol_.size
for i in range(n):
sol_ = np.vstack((sol_, sol_[i]**2))
for i in range(n):
for j in range(i+1, n):
sol_ = np.vstack((sol_, sol_[i]*sol_[j]))
for i in range(n):
for j in range(n, 2*n):
sol_ = np.vstack((sol_, sol_[i]*sol_[j]))
for i in range(n):
for j in range(2*n, 3*n):
sol_ = np.vstack((sol_, sol_[i]*sol_[j]))
sol_ = np.vstack((np.ones((1, m)), sol_))
return sol_
def data_derivative(sol_,d_sol_):
n = len(sol_)
for i in range(n):
sol_ = np.vstack((sol_, np.multiply(sol_[i], d_sol_)))
return sol_
term_lib = data_aug(sol.y)
term_lib = data_derivative(term_lib, sol_dx).T
def soft_thresholding(X, lambda_):
temp_compare = X.T.copy()
for i in range(len(X)):
if abs(X[i]) - lambda_ < 0:
temp_compare[:,[i]]= 0
else:
temp_compare[:, [i]] = abs(X[i]) - lambda_
# tmp_compare = X[np.where(abs(X) - lambda_ > 0)]
# tmp_compare = np.expand_dims(tmp_compare, axis =1)
return np.multiply(np.sign(X), temp_compare.T)
def ADM(lib_null,q_init,lambda_,MaxIter, tol):
q = q_init.copy()
for i in range(MaxIter):
q_old = q.copy()
x = soft_thresholding(lib_null @ q_init, lambda_)
temp_ = lib_null.T @ x
if np.linalg.norm(temp_,2) == 0:
q = temp_
else:
q = temp_/ np.linalg.norm(temp_, 2)
res_q = np.linalg.norm(q_old - q ,2)
if res_q <= tol:
return q
def ADMinitvary(lib_null, lambda_, MaxIter, tol, pflag):
lib_null_norm = lib_null.copy()
for i in range(len(lib_null[0])):
lib_null_norm[:,i] = lib_null[:,i]/lib_null[:,i].mean()
q_final = np.empty_like(lib_null.T)
out = np.zeros((len(lib_null), len(lib_null)))
nzeros = np.zeros((1, len(lib_null)))
for i in range(len(lib_null_norm)):
q_ini = lib_null_norm[[i],:].T
temp_q = ADM(lib_null, q_ini, lambda_, MaxIter, tol)
q_final[:,[i]] = temp_q
temp_out = np.matmul(lib_null, temp_q)
out[:,[i]] = temp_out
nzeros_temp = sum(list((abs(temp_out) < lambda_)))
nzeros[:,[i]] = float(nzeros_temp)
idx_sparse = np.where(nzeros == max(np.squeeze(nzeros)))[0]
ind_lib = np.where(abs(out[:, idx_sparse[0]]) >= lambda_)[0]
Xi = out[:, idx_sparse[0]]
small_idx = np.where(abs(out[:, idx_sparse[0]]) < lambda_)[0]
Xi[small_idx] = 0
numterms = len(ind_lib)
return ind_lib, Xi, numterms
def ADMpareto(term_lib, tol, pflag):
lib_null = linalg.null_space(term_lib)
num = 1
lambda_ = 1e-9
MaxIter = 50000
dic_lib = {}
dic_Xi = {}
dic_num = {}
dic_error = {}
dic_lambda = {}
ii = 0
while num > 0:
temp_ind_lib, temp_Xi, temp_numterms = ADMinitvary(lib_null, lambda_, MaxIter, tol, pflag)
dic_lib[ii] = temp_ind_lib
dic_Xi[ii] = temp_Xi
dic_num[ii] = temp_numterms
error_temp = sum(np.matmul(term_lib, dic_Xi[ii]))
dic_error[ii] = error_temp
dic_lambda[ii] = lambda_
lambda_ *= 1.2
print(lambda_)
num = dic_num[ii]
ii += 1
if lambda_ > 3:
break
return dic_Xi, dic_lib, dic_lambda, dic_num, dic_error
tol, pflag = 1e-6,1
dic_Xi, dic_lib, dic_lambda, dic_num, dic_error = ADMpareto(term_lib,tol, pflag)
lambda_vec = list(dic_lambda.values())
terms_vec = list(dic_num.values())
err_vec = list(dic_error.values())
log_err_vec = np.log10(err_vec)
log_lambda_vec = np.log10(lambda_vec)
plt.subplot(1,2,1)
plt.scatter(log_lambda_vec, terms_vec)
plt.xlabel("Threshold (log_$\lambda$)")
plt.ylabel("Number of terms")
plt.subplot(1,2,2)
plt.scatter(terms_vec, log_err_vec)
plt.xlabel("Number of terms")
plt.ylabel("Error (log)")
plt.show()
| [
"yiruic@g.clemson.edu"
] | yiruic@g.clemson.edu |
f2b8c9a7622b4657969fb9800cd35901be8fe2e1 | e83df449e6956d5af8e4b98d535a9daacbbff477 | /main.py | 0215ec4d5e158a0c5cdccee9fcaa8569fd2549a5 | [] | no_license | LefterisJP/race_analyzer | 2f48edc34bb299f0d96e3a19a4f245b1b082f21d | 08a5041817e227969775a42656c2bce2030ed69f | refs/heads/master | 2020-03-28T22:40:01.078406 | 2018-09-18T07:47:53 | 2018-09-18T07:47:53 | 149,248,881 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 204 | py | import click
@click.group(invoke_without_command=True)
@click.pass_context
def main(ctx, threads, keyfile, input_file, respect_word_order, **kwargs):
pass
if __name__ == '__main__':
main()
| [
"lefteris@refu.co"
] | lefteris@refu.co |
2f6a455e356c43a3f644d394fdfcf5a6a01e4bfc | da97f5d59335859dfff09a5dad2d1819750c9bd8 | /phase1-text-modality-NetScale/DLmodel/deepANN/ANN.py | 167ba2627e0ba67b8f3fbb4cf55c297d8c11a5bc | [] | no_license | yindlib/DARPA_Phase1_SentimentAnalysis | 2b8cf44c19dad0ed88792c824e8938835473610f | 0f0d9e41cf2415e6e34b935e0af385862ec115e8 | refs/heads/master | 2020-02-26T14:26:13.726197 | 2014-01-07T09:08:57 | 2014-01-07T09:08:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 61,053 | py | import numpy, time, cPickle, gzip
import os
import sys
import theano
import theano.tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from Activations import *
from Noise import *
from Regularization import *
from Reconstruction_cost import *
from Logistic_regression import LogisticRegression
"""
CONVENTIONS:
* one_sided is True means that the range of values is non-negative.
* bounded is True means that the range of values is bounded to [-1, +1].
* depth = 1 means there is one encoding layer.
* update_type: 'global', 'local', or 'special'.
* For ModeSup, 'local' means update only the parameters of the
supervised layer (from the supervised features to the supervised
prediction).
* For ModeUnsup, 'local' means update only the parameters for the
depth_max encoding and decoding depth-1 paths.
* For ModeAux, 'local' means update only the parameters of the
auxiliary layer. In this way, it is similar to ModeSup. TODO:
Make 'local' for ModeAux have the same semantics as 'local'
for ModeUnsup. Or, look below for a better idea.
* 'global' means update all parameters from the input through
the final output, in terms of the cost (which could be a mixture
of reconstruction and/or supervised and/or auxiliary).
* 'special' is used only in ModeAux. It means update only the
parameters of the auxiliary layer, as well as the parameters
of the encoding layer just below it. It is similar to 'local'
for ModeUnsup.
TODO: Three types of update_types: 'global', 'lastlayer',
'lasttwolayers'. 'lasttwolayers' is not permitted for ModeUnsup.
'lastlayer' is not permitted for ModeAux, because the auxiliary
task is defined only to help train the actual model. (If we want
to use an auxiliary layer to test the features at some layer,
we should just define a ModeSup for the test task.)
* ModeAux should not be used to do unsupervised training. The reason
ModeAux is currently used is because ModeUnsup assume that the
encoder and decoder have identical activation functions, whereas
our top-level encoder is a rectifier and the top-level decoder
is a sigmoid. Instead, we should just adapt ModeUnsup so that the
encoder and decoder activations can be different (optionally), and
not use ModeAux for unsupervised training. To do so just confuses
the semantics.
"""
class DenseLayer(object):
""" Generalized Dense Layer class """
def __init__(self, rng, theano_rng, inp, n_inp, n_out, act = "tanh", noise = None,
wdreg = 'l2', spreg = 'l1', Winit = None, binit = None, maskinit = None,
upmaskbool = False, tag = ''):
""" This initialize a DenseLayer object:
***rng : numpy.random object
***theano_rng : theano shared random stream object
***inp : theano symbolic variable for the input of the layer (necessarly given)
***n_inp : nb of inputs
***n_out : nb of units
***act : activation [available in Activation.py]
***noise : noise [available in Noise.py]
***wdreg : weights decay regularization [available in Regularisation.py]
***spreg : sparsity of the code regularization [available in Regularisation.py]
***Winit : initial weights matrix (if None, randomly created)
***binit : initial bias vector (if None, 0s vector)
***maskinit : initial mask vector (if None: 1s vector; if 1: random -1/1s vector)
***tag : name of the layer
"""
self.inp = inp
# Random generator
self.rng = rng
self.theano_rng = theano_rng
## Number of inputs and outputs
self.n_inp = n_inp
self.n_out = n_out
# Activation
self.act = act
self.act_fn = eval(self.act+"_act")
# Noise
self.noise = noise
self.noise_fn = eval(self.noise+"_noise") if self.noise != None else None
# Weight decay
self.wdreg = wdreg
self.wdreg_fn = eval(self.wdreg)
# Sparsity
self.spreg = spreg
self.spreg_fn = eval(self.spreg)
# Units specification
self.one_sided = False if act in ['tanh','tanhnorm','softsign','arsinh','plc'] else True
self.maskinit = maskinit
if type(self.maskinit) != numpy.ndarray and self.maskinit == 1:
self.one_sided = False
if type(self.maskinit) == numpy.ndarray:
if sum(self.maskinit) != self.maskinit.shape[0]:
self.one_sided = False
self.bounded = False if act in ['rectifier','softplus','arsinh','pascalv'] else 1.
#special cases
if act == 'tanhnorm':
self.bounded = 1.759
self.tag = tag
#update mask for bbprop
self.upmaskbool = upmaskbool
#-----------------------------------------------------------------------------------
allocW = False # to track allocation of the weights
if Winit == None: # if no initial weights are given, do the random initialization
wbound = numpy.sqrt(6./(n_inp+n_out))
#@TO THINK: to have one different for specific activation:
#here only valid for anti-symmetric f(-x)=-f(x) and [x~0 -> f(x)=x] activations.
W_values = numpy.asarray( rng.uniform( low = -wbound, high = wbound, \
size = (n_inp, n_out)), dtype = theano.config.floatX)
self.W = theano.shared(value = W_values, name = 'W'+self.tag)
allocW = True
else:
self.W = Winit
allocb = False # to track allocation of the bias
if binit == None: # if no initial bias are given, do the 0 initialization
b_values = numpy.zeros((n_out,), dtype= theano.config.floatX)
self.b = theano.shared(value= b_values, name = 'b'+self.tag)
allocb = True
else:
self.b = binit
allocmask = False # to track allocation of the mask
if type(self.maskinit) != numpy.ndarray: # if no initial bias are given, do the 0 initialization
if self.maskinit == 1:
mask_values = numpy.asarray((rng.binomial(1,0.5,(n_out,))-0.5)*2, dtype= theano.config.floatX)
allocmask = 'random'
else: #None
mask_values = numpy.ones((n_out,), dtype= theano.config.floatX)
allocmask = 'ones'
self.mask = theano.shared(value= mask_values, name = 'mask'+self.tag)
else:
self.mask = self.maskinit
#-----------------------------------------------------------------------------------
self.createout(None)
# standardized attribute
self.params = [self.W, self.b] # gradient descent params
self.wd = self.wdreg_fn(self.W)
self.sp = self.spreg_fn(self.out)
if self.upmaskbool:
self.updatemaskinit()
# @TO DO: special update attibute (for bbprop, rectifier count, rescaling weigths..)
#-----------------------------------------------------------------------------------
# Print init
print >> sys.stderr, '\t\t\t**** DenseLayer.__init__ ****'
print >> sys.stderr, '\t\t\ttag = ', tag
print >> sys.stderr, '\t\t\tinp = ', inp
print >> sys.stderr, '\t\t\tn_inp = ', self.n_inp
print >> sys.stderr, '\t\t\tn_out = ', self.n_out
print >> sys.stderr, '\t\t\tact = ', self.act
print >> sys.stderr, '\t\t\tnoise = ', self.noise
print >> sys.stderr, '\t\t\tout = ', self.out
print >> sys.stderr, '\t\t\tparams (gradients) = ', self.params
print >> sys.stderr, '\t\t\twdreg (weigth decay) = ', self.wdreg
print >> sys.stderr, '\t\t\tspreg (sparsity) = ', self.spreg
print >> sys.stderr, '\t\t\tupmaskbool = ', self.upmaskbool
print >> sys.stderr, '\t\t\tmaskinit = ', self.maskinit
print >> sys.stderr, '\t\t\tallocW, allocb, allocmask = ', allocW, allocb, allocmask
# @TO DO: special update attibute (for bbprop, rectifier count, rescaling weigths..)
def createout(self, noise_lvl): #create output with a scalar noise parameter
self.noise_lvl = noise_lvl
if self.noise == None or self.noise_lvl == None or self.noise_lvl == 0.:
self.lin = T.dot(self.inp, self.W) + self.b
self.lin.name = 'lin'+self.tag
self.out = self.mask * self.act_fn(self.lin)
self.out.name = 'out'+self.tag
elif self.noise == 'special':
print >> sys.stderr, 'special noise'
self.lin = T.dot(self.inp, self.W) + self.b
self.lin.name = 'lin'+self.tag
self.out = self.mask * self.act_fn(self.noise_fn(self.theano_rng,self.lin,self.noise_lvl))
self.out.name = 'out'+self.tag
else:
self.lin = T.dot(self.noise_fn(self.theano_rng, self.inp, self.noise_lvl),\
self.W) + self.b
self.lin.name = 'lin'+self.tag
self.out = self.mask * self.act_fn(self.lin)
self.out.name = 'out'+self.tag
return self.out
def updatemaskinit(self): #create update mask (used for bbprop)
"""
This is not used. See the note above about bbprop by LeCun.
"""
self.W_upmask = theano.shared(value= numpy.ones((self.n_inp, self.n_out),\
dtype= theano.config.floatX), name = 'W_fact'+self.tag)
self.b_upmask = theano.shared(value= numpy.ones((self.n_out,),\
dtype= theano.config.floatX), name = 'b_fact'+self.tag)
self.upmask = [self.W_upmask, self.b_upmask]
def bbprop(self,outgrad): #symbolic bbprop declaration
"""
This is not used. See the note above about bbprop by LeCun.
"""
self.act_der = eval(self.act + '_der')
self.lin_bbprop = outgrad * self.act_der(self.lin) * self.act_der(self.lin)
self.dict_bbprop = {}
self.dict_bbprop.update({self.b_upmask:T.sum(self.lin_bbprop,0)})
self.dict_bbprop.update({self.W_upmask:T.dot(T.transpose(self.inp*self.inp),self.lin_bbprop)})
return T.dot(self.lin_bbprop,T.transpose(self.W * self.W)),self.dict_bbprop
def save(self,path):
"""
NOTE: This only saves the current parameters, for whatever Theano
graph we are currently working with.
"""
f = open(path+'W.pkl','w')
cPickle.dump(self.W.value,f,-1)
f.close()
print >> sys.stderr, self.W, 'saved in %s'%(path+'W.pkl')
f = open(path+'b.pkl','w')
cPickle.dump(self.b.value,f,-1)
f.close()
print >> sys.stderr, self.b, 'saved in %s'%(path+'b.pkl')
f = open(path+'mask.pkl','w')
cPickle.dump(self.mask.value,f,-1)
f.close()
print >> sys.stderr, self.mask, 'saved in %s'%(path+'mask.pkl')
def load(self,path):
"""
NOTE: This only loads the current parameters, for whatever Theano
graph we are currently working with.
"""
f = open(path+'W.pkl','r')
self.W.value = cPickle.load(f)
f.close()
print >> sys.stderr, self.W, 'loaded from %s'%(path+'W.pkl')
f = open(path+'b.pkl','r')
self.b.value = cPickle.load(f)
f.close()
print >> sys.stderr, self.b, 'loaded from %s'%(path+'b.pkl')
f = open(path+'mask.pkl','r')
self.mask.value = cPickle.load(f)
f.close()
print >> sys.stderr, self.mask, 'loaded from %s'%(path+'mask.pkl')
#def scaling_rectifierweigths(self):
#def moving_averageandvariances(self):
#def localcontrastnormalization(self):
#-----------------------------------------------------------------------------------
class SDAE(object):
"""
Generalized Denoising Autoencoder class
The class is flexible, insofar as it allows a variety of different
paths through which the reconstruction error can be computed (and
used for updates). Look at ModeUnsup for more information.
Denoising auto-encoder variables are stored throughout calls.
However, ModeSup will overwrite the previous supervised layer
(unless it is called with identical depth_max and depth_min as
the last ModeSup invokation, in which case the supervised layer is
not changed.)
You can, for example, call ModeUnsup then ModeSup then ModeUnsup,
and the last ModeUnsup will not touch the supervised layer.
"""
def __init__(self, rng, theano_rng, depth , one_sided_in, inp = None, n_inp = 1, n_hid = 1,
layertype = DenseLayer, act = "tanh" , noise = "binomial", tie = True, maskbool = None,
n_out = 1, out = None, outtype = LogisticRegression, regularization = False,
sparsity = False, wdreg = 'l2', spreg = 'l1', reconstruction_cost = 'cross_entropy', bbbool = None):
""" This initialize a SDAE (Stacked Denoising Auto-Encoder) object:
***rng : numpy.random object
***theano_rng : theano shared random stream object
***depth : Number of hidden layers
***one_sided_in: The input is one-sided or not.
***inp : theano symbolic variable for the input of the network
(if None: created)
***n_inp : nb of inputs
***n_hid : nb of units per layer (or a vector of length
depth if different sizes)
***layertype : Layerclass to be used (or a list if different)
***act : activation [available in Activation.py] (or a list if different)
***noise : noise [available in Noise.py] (or a list if different)
***tie : boolean, if true shared weights for encoder and
corresponding decoder (or a list if different tie value for
each layer).
***maskbool : if None 1s mask, if 1 random mask (-1 1)
(or a list if different)
***n_out : nb of outputs units for the supervised layer.
***out : theano symbolic variable for the output of the network (if None: created)
***outtype : outlayer class
***regularization : regularisation coefficient or false if not (or a list if different)
***spasity : sparsity coefficient or false if not (or a list if different)
***wdreg : weights decay regularization [available in Regularisation.py]
***spreg : sparsity of the code regularization [available in Regularisation.py]
***reconstruction_cost : cost of reconstruction (quadratic
or cross-entropy or scaled)
"""
self.one_sided_in = one_sided_in #very important for cross entropy reconstruction.
self.inp = inp if inp != None else T.matrix('inp')
self.out = out if out != None else T.ivector('out')
# Random generator
self.rng = rng
self.theano_rng = theano_rng
# Network size
self.depth = depth
self.n_inp = n_inp
self.n_hid = self.__listify(n_hid,self.depth)
self.n_out = n_out
# Layer specific
self.layertype = self.__listify(layertype,self.depth)
self.act = self.__listify(act,self.depth)
self.noise = self.__listify(noise,self.depth)
self.tie = self.__listify(tie,self.depth)
self.maskbool = self.__listify(maskbool,self.depth)
# @Warning: bbprop in the tie weights case not trivial and not implemented!!!!
for i in self.tie:
if bbbool == True:
assert i == False
self.outtype = outtype
self.regularization = self.__listify(regularization,self.depth+1) # +1 for supervised layer
self.sparsity = self.__listify(sparsity,self.depth)
self.reconstruction_cost = reconstruction_cost
self.reconstruction_cost_fn = eval(reconstruction_cost+'_cost')
self.wdreg = wdreg
self.spreg = spreg
self.bbbool = bbbool
#for aux target init:
self.aux = False
self.aux_active = False
self.auxdepth = None
self.auxlayertype = None
self.auxlayer = None
self.auxtarget = None
self.aux_scaling = None
self.aux_one_sided = None
self.auxregularization = None
self.auxn_out = None
self.auxact = None
self.aux_one_sided = None
self.auxwdreg = None
#hard coded list paramters for saving and loading
self.paramsinitkeys = ['depth','one_sided_in','n_inp','n_hid','layertype',\
'act','noise','tie','maskbool','n_out','outtype','regularization',\
'sparsity','wdreg','spreg','reconstruction_cost','bbbool']
self.paramscurrentkeys = ['mode','depth_min','depth_max','aux','noise_lvl',\
'update_type','lr','sup_scaling','unsup_scaling',\
'hessscal']
self.paramsauxkeys = ['auxdepth','auxn_out','aux_scaling','auxregularization','auxlayertype',\
'auxact','aux_one_sided','auxwdreg','auxwdreg']
#first init by default
self.ModeMixte(self.depth)
def __listify(self, x, length):
if type(x) is list:
assert len(x) == length
return x
else:
return [x]*length
def __redefinemodel(self,direction,depth_max,depth_min=0,noise_lvl=0.,update_type = 'global'):
""" This function redefine the Theano symbolic variables of the
SDAE or the supervised model (i.e the added noise level
and the last encoding layer until which to propagate)
TODO: Rename direction to "encoding", "supervised", "decoding"
***direction : 1 for encoding path, 0 for supervised layer, -1 for decoding path
***depth_max : last encoding layer (before decoding) or last input to supervised layer
***depth_min : layer at which you add noise in the input
therefore also the last decoding layer or first input to supervised layer
***noise_lvl : scalar from 0 to 1 specifying the amount of noise to add
***update_type : local (depth_max or outlayer if supervised),
global (from depth_min to depth_max or the whole network if supervised)
[only local for supervised with concatenated input]
"""
# Encoding and decoding declaration
if direction != 0:
allocbool = False # this is used for the first declaration
# different init for decoding and encoding:
if direction == 1: #encoding
# Inputs
tmp_n_inp = self.n_inp
tmp_inp = self.inp
# Specifics to encoding path
text = 'Encoding'
tag = 'enc'
if not hasattr(self,'layers'): #if first declaration
allocbool = True
self.layers = [None]*self.depth
tmp_layers = self.layers
# declaration loop iterator
itera = xrange(0,depth_max)
else:
# Inputs
tmp_n_inp = self.layers[depth_max-1].n_out #need an encoding path...
tmp_inp = self.layers[depth_max-1].out
# Specifics to decoding path
text = 'Decoding'
tag = 'dec'
if not hasattr(self,'layersdec'): #if first declaration
allocbool = True
self.layersdec = [None]*self.depth
tmp_layers = self.layersdec
# declaration loop iterator
itera = xrange(depth_max-1,depth_min-1,-1)
# Stacking layers
for i in itera:
if direction == 1:
tmp_n_out = self.n_hid[i]
else:
tmp_n_out = self.layers[i].n_inp
print >> sys.stderr, '\t\t---- ',text,' layer #%s ----'%(i+1)
if allocbool:
Wtmp = None
btmp = None
masktmp = self.maskbool[i]
else:
Wtmp = tmp_layers[i].W
btmp = tmp_layers[i].b
masktmp = tmp_layers[i].mask
if direction == -1 and self.tie[i]:
Wtmp = self.layers[i].W.T
if i-1 >=0 :
masktmp = self.layers[i-1].mask
else:
masktmp = None
tmp_layers[i] = self.layertype[i](self.rng, self.theano_rng,tmp_inp,tmp_n_inp,
tmp_n_out, self.act[i], noise = self.noise[i],
Winit = Wtmp, binit = btmp, maskinit = masktmp, wdreg = self.wdreg,
spreg =self.spreg, tag = tag + '%s'%(i+1), upmaskbool = self.bbbool)
# If noise layer in encoding path, add the noise
if direction == 1 and i==depth_min and self.noise[i]!='special':
print >> sys.stderr, 'depth',i,self.noise[i]
tmp_layers[i].createout(noise_lvl)
if len(self.noise)>i and direction == 1 and i==depth_min-1 and self.noise[i+1]=='special':
print >> sys.stderr, 'at layer',i,'change noise to special'
savenoise = tmp_layers[i].noise
tmp_layers[i].noise = 'special'
tmp_layers[i].noise_fn = eval(tmp_layers[i].noise+"_noise") if tmp_layers[i].noise != None else None
tmp_layers[i].createout(noise_lvl)
tmp_layers[i].noise = savenoise
tmp_layers[i].noise_fn = eval(tmp_layers[i].noise+"_noise") if tmp_layers[i].noise != None else None
# getting the right parameters for updates
#-----------------------------------------------------------------------------------
# Global update
if update_type == 'global' and i >= depth_min:
if direction == 1 or not(self.tie[i]):
self.params += tmp_layers[i].params
if self.regularization[i]:
self.wd += [self.regularization[i]*tmp_layers[i].wd]
else:
self.params += [tmp_layers[i].params[-1]]
if self.bbbool:
self.upmask += tmp_layers[i].upmask
if direction == 1 and self.sparsity[i]:
self.sp += [self.sparsity[i]*tmp_layers[i].sp]
if direction == -1 and i > depth_min and self.sparsity[i-1]:
self.sp += [self.sparsity[i-1]*tmp_layers[i].sp]
#@TO THINK: is this obvious?
#not the same code in encoding and decoding but do we want the
#same sparsity in the codes...?
#no need to do it for depth_min in decoding (target already sparse)
#-----------------------------------------------------------------------------------
# Local update
if (update_type == 'local' or update_type =='special') and i == depth_max-1 and self.mode != 'Sup' and\
(self.mode != 'Aux' or self.update_type == 'special'):
if direction == 1 or not(self.tie[i]):
self.params += tmp_layers[i].params
if self.regularization[i]:
self.wd += [self.regularization[i]*tmp_layers[i].wd]
if direction == 1 and self.sparsity[i]:
self.sp += [self.sparsity[i]*tmp_layers[i].sp]
if self.bbbool:
self.upmask += tmp_layers[i].upmask
#-----------------------------------------------------------------------------------
# New input for next iteration in the loop
tmp_inp = tmp_layers[i].out
tmp_n_inp = tmp_layers[i].n_out
# outlayer declaration
if direction == 0:
if depth_max == depth_min: #only one input at depth_max
tmp_inp = self.layers[depth_max-1].out
tmp_n_inp = self.n_hid[depth_max-1]
else: #concatenate layers from depth_min to depth_max
assert update_type == 'local' #only local update allowed
tmp_list = [1] #first arg of T.join()
tmp_n_inp = 0
if depth_min==-1:
tmp_list += [self.inp] #take the original input
depth_min = 0
tmp_n_inp += self.n_inp
tmp_list += [self.layers[j].out for j in xrange(depth_min,depth_max)]
#concatenate inputs
tmp_inp = T.join(*tmp_list)
tmp_n_inp += numpy.sum(self.n_hid[depth_min:depth_max])
print >> sys.stderr, '\t---- Output Layer ----'
Winit = None
binit = None
# If the previous graph with an outlayer and it has the
# same depth_max and depth_min (see ModeSup), then we store
# the weights of the previous outlayer.
if hasattr(self,'outlayer') and self.outlayerdepth == (depth_max,depth_min):
Winit = self.outlayer.W
binit = self.outlayer.b
self.outlayer = self.outtype(self.rng,tmp_inp, tmp_n_inp, self.n_out,self.wdreg,\
self.bbbool,Winit = Winit,binit = binit)
self.outlayerdepth = (depth_max,depth_min)
self.params += self.outlayer.params
if self.bbbool:
self.upmask += self.outlayer.upmask
if self.regularization[-1]:
self.wd += [self.regularization[-1]*self.outlayer.wd]
def __definecost(self):
""" This initialize the symbolic cost, grad and updates"""
if self.mode == 'Unsup' or self.mode == "Mixte":
if self.depth_min == 0:
in_sided = self.one_sided_in
in_bounded = 1.
else:
in_sided = self.layers[self.depth_min-1].one_sided
in_bounded = self.layers[self.depth_min-1].bounded
out_bounded = self.layersdec[self.depth_min].bounded
out_sided = self.layersdec[self.depth_min].one_sided
self.unsup_cost = self.reconstruction_cost_fn(self.layers[self.depth_min].inp,\
self.layersdec[self.depth_min].out, self.layersdec[self.depth_min].lin,\
in_sided,out_sided,in_bounded,out_bounded,self.layersdec[self.depth_min].act)
self.unsup_cost[0][0] = self.unsup_scaling * self.unsup_cost[0][0]
self.unsup_cost[1] = self.unsup_scaling * self.unsup_cost[1]
else:
self.unsup_cost = [[],[]]
wdaux = []
paramsaux = []
if self.aux and self.aux_active:
if (self.update_type != 'special' or self.depth+self.auxdepth == self.depth_max):
paramsaux += self.auxlayer.params
if self.auxregularization:
wdaux += [self.auxregularization*self.auxlayer.wd]
self.aux_cost = self.reconstruction_cost_fn( self.auxtarget, self.auxlayer.out,\
self.auxlayer.lin,self.aux_one_sided,self.auxlayer.one_sided,\
1.,self.auxlayer.bounded,self.auxlayer.act)
self.aux_cost[0][0] = self.aux_scaling * self.aux_cost[0][0]
self.aux_cost[1] = self.aux_scaling * self.aux_cost[1]
else:
self.aux_cost = [[],[]]
if self.mode == 'Sup':
self.cost = sum([self.sup_scaling * self.outlayer.cost(self.out)] +\
self.aux_cost[0] + self.wd + wdaux + self.sp)
if self.mode == 'Unsup':
self.cost = sum(self.unsup_cost[0] + self.aux_cost[0] + self.wd + wdaux + self.sp)
if self.mode == 'Mixte':
self.cost = sum(self.unsup_cost[0] + [self.sup_scaling * self.outlayer.cost(self.out)] +\
self.aux_cost[0] + self.wd + wdaux + self.sp)
if self.mode == 'Aux':
self.cost = sum(self.aux_cost[0] + self.wd + wdaux + self.sp)
self.grad = T.grad(self.cost,self.params+paramsaux)
self.updates = dict((p, p - self.lr * g) for p, g in zip(self.params+paramsaux, self.grad))
def __definebbprop(self):
"""
This is currently unused. It is the second-order method of Yann LeCun.
It is pretty slow and not all paths are well-tested.
"""
ParamHess = {}
bb_tmp = 0
if self.mode != 'Aux':
if self.mode == 'Unsup' or self.mode == "Mixte":
bb_tmp += self.unsup_cost[1]
for i in xrange(self.depth_min,self.depth_max,1):
if self.aux and i == self.depth - self.auxdepth:
bb_tmp2, hess_tmp2 = self.auxlayer.bbprop(self.aux_cost[1])
bb_tmp += bb_tmp2
ParamHess.update(hess_tmp2)
bb_tmp, hess_tmp = self.layersdec[i].bbprop(bb_tmp)
ParamHess.update(hess_tmp)
if self.mode == 'Sup' or self.mode == "Mixte":
bb_tmp2, hess_tmp2 = self.outlayer.bbprop()
bb_tmp += bb_tmp2
ParamHess.update(hess_tmp2)
if self.mode == 'Sup':
if self.update_type=='global':
itera = xrange(self.depth_max-1,-1,-1)
else:
itera = []
if self.mode == 'Mixte' or self.mode == 'Unsup':
itera = xrange(self.depth_max-1,self.depth_min-1,-1)
for i in itera:
if self.aux and i == self.depth + self.auxdepth - 1:
bb_tmp2, hess_tmp2 = self.auxlayer.bbprop(self.aux_cost[1])
bb_tmp += bb_tmp2
ParamHess.update(hess_tmp2)
bb_tmp, hess_tmp = self.layers[i].bbprop(bb_tmp)
ParamHess.update(hess_tmp)
#auxconnected to first layer?
if self.aux and self.depth + self.auxdepth == 0:
bb_tmp2, hess_tmp2 = self.auxlayer.bbprop(self.aux_cost[1])
ParamHess.update(hess_tmp2)
else:
assert self.aux_active
bb_tmp, hess_tmp = self.auxlayer.bbprop(self.aux_cost[1])
ParamHess.update(hess_tmp)
if self.update_type=='global':
if self.auxdepth>0:
for i in xrange(self.depth - self.auxdepth,self.depth_max,1):
bb_tmp, hess_tmp = self.layersdec[i].bbprop(bb_tmp)
ParamHess.update(hess_tmp)
for i in xrange(self.depth_max-1,-1,-1):
bb_tmp, hess_tmp = self.layers[i].bbprop(bb_tmp)
ParamHess.update(hess_tmp)
else:
for i in xrange(self.depth-1+self.auxdepth,-1,-1):
bb_tmp, hess_tmp = self.layers[i].bbprop(bb_tmp)
ParamHess.update(hess_tmp)
for p in ParamHess.keys():
ParamHess[p]= self.hessscal / (ParamHess[p] + self.hessscal)
paramsaux = []
upmaskaux = []
if self.aux and (self.update_type != 'special' or self.auxdepth == 0):
paramsaux += self.auxlayer.params
if self.bbbool:
upmaskaux += self.auxlayer.upmask
self.specialupdates.update(ParamHess)
self.updates = dict((p, p - self.lr * m * g) for p, m, g in \
zip(self.params+paramsaux, self.upmask+upmaskaux, self.grad))
def __monitorfunction(self):
inp1 = [self.inp]
inp2 = [self.inp]
if self.mode != 'Unsup':
inp2 += [self.out]
if self.aux:
inp2 += [self.auxtarget]
self.representation = [None] * (self.depth+1)
self.activation = [None] * (self.depth+1)
self.representationdec = [None] * self.depth
self.activationdec = [None] * self.depth
self.auxrepresentation = None
self.auxactivation = None
for i in range(self.depth_max):
self.representation[i] = theano.function(inp1,self.layers[i].out)
self.activation[i] = theano.function(inp1,self.layers[i].lin)
if self.mode != 'Sup':
for i in xrange(self.depth_max-1,self.depth_min-1,-1):
self.representationdec[i] = theano.function(inp1,self.layersdec[i].out)
self.activationdec[i] = theano.function(inp1,self.layersdec[i].lin)
if self.mode != 'Unsup':
self.representation[-1] = theano.function(inp1,self.outlayer.out)
self.activation[-1] = theano.function(inp1,self.outlayer.lin)
if self.aux:
self.auxrepresentation = theano.function(inp1,self.auxlayer.out)
self.auxactivation = theano.function(inp1,self.auxlayer.lin)
self.compute_cost = theano.function(inp2,self.cost)
self.compute_gradient = theano.function(inp2,self.grad)
if self.mode != 'Unsup':
self.error = theano.function(inp2,self.outlayer.errors(self.out))
def __checkauxactive(self):
if self.auxdepth>0:
if self.mode == 'Sup':
return False
else:
if (self.depth_max > self.depth - self.auxdepth) and (self.depth_min <= self.depth - self.auxdepth):
return True
else:
return False
else:
if (self.depth_max >= self.depth + self.auxdepth):
return True
else:
return False
def auxiliary(self, init, auxdepth, auxn_out, aux_scaling=1., auxregularization = False,
auxlayertype = DenseLayer, auxact = 'sigmoid', aux_one_sided = True,
auxwdreg = 'l2', Wtmp = None, btmp = None,afficheb = True, maskinit = None):
""" This creates an auxiliary target layer in the network.
It will overwrite the old self.auxlayer, unless you pass the
old Wtmp and btmp values. If you don't pass these values,
the weights and biases will be initialized.
***init : if 1 initialize the auxtarget, if 0 delete previous auxtarget
***auxdepth : When it is 0, put the auxlayer on the top of
the encoding path. -1 is one layer below the top. TODO:
Use consistent names for layer depth (like max_depth in
other functions)?
***auxn_out : The number of output units.
***auxlayer : a layer object already initialized with the good input given
***aux_one_sided : true if the auxtarget is one_sided
***auxregularization : weights decay regularisation value for the aux layer
***aux_scaling : scaling factor to equilibrate with unsup_cost
@TO THINK: should I divide by the number of output neurons to make them comparable?
"""
if init: #init side
self.aux = True
self.auxdepth = auxdepth
self.aux_active = self.__checkauxactive()
self.auxlayertype = auxlayertype
self.auxtarget = T.matrix('auxtarget')
self.aux_scaling = aux_scaling
self.aux_one_sided = aux_one_sided
self.auxregularization = auxregularization
self.auxn_out = auxn_out
self.auxact = auxact
self.aux_one_sided = aux_one_sided
self.auxwdreg = auxwdreg
if auxdepth <= 0:
tmp_inp = self.layers[auxdepth-1].out
tmp_n_inp = self.layers[auxdepth-1].n_out
else:
tmp_inp = self.layersdec[-auxdepth].out
tmp_n_inp = self.layersdec[-auxdepth].n_out
print >> sys.stderr, '\t---- Auxiliary Layer ----'
self.auxlayer = self.auxlayertype(self.rng, self.theano_rng,tmp_inp,tmp_n_inp,auxn_out,
auxact, noise = None, Winit = Wtmp, binit = btmp, wdreg = auxwdreg,
spreg = 'l1', tag = 'aux' + '%s'%(auxdepth),upmaskbool = self.bbbool,
maskinit=maskinit)
else: #delete side
assert self.mode != 'Aux'
self.aux = False
self.aux_active = False
self.auxdepth = None
self.auxlayertype = None
if self.auxlayer != None:
del self.auxlayer
self.auxlayer = None
self.auxtarget = None
self.aux_scaling = None
self.aux_one_sided = None
self.auxregularization = None
self.auxn_out = None
self.auxact = None
self.aux_one_sided = None
self.auxwdreg = None
#to redefine properly the function
self.__definecost()
#self.__monitorfunction()
if self.bbbool:
self.__definebbprop()
if afficheb:
self.afficher()
def trainfunctionbatch(self,data,datal=None,aux = None,batchsize = 10):
"""
Return the Theano training (update) function, as well as the
number of minibatches.
data = unlabelled training data.
datal = labels of training data.
We actually pass in data and datal, which are shared variables,
so they can be stored on the GPU upfront.
TODO: Rename to x and y, throughout?
For mode = "Sup" or "Mixte", we use the labels.
For auxiliary mode and "Unsup", we don't use the labels.
"""
# compute number of minibatches for training
if type(data) is list:
n_max = data[0].value.shape[0] / batchsize
else:
n_max = data.value.shape[0] / batchsize
givens = {}
index = T.lscalar() # index to a [mini]batch
if self.aux and self.aux_active:
if type(aux) is list:
givens.update({self.auxtarget:\
T.cast(aux[0][index*batchsize:(index+1)*batchsize]/aux[1]+aux[2],aux[3])})
else:
givens.update({self.auxtarget:aux[index*batchsize:(index+1)*batchsize]})
if self.mode == 'Sup' or self.mode == 'Mixte':
if type(datal) is list:
givens.update({self.out:\
T.cast(datal[0][index*batchsize:(index+1)*batchsize]/datal[1]+datal[2],datal[3])})
else:
givens.update({self.out:datal[index*batchsize:(index+1)*batchsize]})
if type(data) is list:
givens.update({self.inp:\
T.cast(data[0][index*batchsize:(index+1)*batchsize]/data[1]+data[2],data[3])})
else:
givens.update({self.inp:data[index*batchsize:(index+1)*batchsize]})
# allocate symbolic variables for the data
trainfunc = theano.function([index], self.cost, updates = self.updates, givens = givens)
return trainfunc, n_max
def errorfunction(self,data,datal,batchsize = 1000):
if type(data) is list:
n_max = data[0].value.shape[0] / batchsize
assert n_max*batchsize == data[0].value.shape[0]
else:
n_max = data.value.shape[0] / batchsize
assert n_max*batchsize == data.value.shape[0]
givens = {}
index = T.lscalar() # index to a [mini]batch
if self.mode != 'Unsup':
if type(data) is list:
givens.update({self.inp:\
T.cast(data[0][index*batchsize:(index+1)*batchsize]/data[1]+data[2],data[3])})
else:
givens.update({self.inp:data[index*batchsize:(index+1)*batchsize]})
if type(datal) is list:
givens.update({self.out:\
T.cast(datal[0][index*batchsize:(index+1)*batchsize]/datal[1]+datal[2],datal[3])})
else:
givens.update({self.out:datal[index*batchsize:(index+1)*batchsize]})
# allocate symbolic variables for the data
func = theano.function([index], self.outlayer.errors(self.out), givens = givens)
def func2():
error = 0
for i in range(n_max):
error += func(i)
return error / float(n_max)
return func2
else:
return False
def costfunction(self,data,datal=None,aux=None, batchsize = 1000):
if type(data) is list:
n_max = data[0].value.shape[0] / batchsize
assert n_max*batchsize == data[0].value.shape[0]
else:
n_max = data.value.shape[0] / batchsize
assert n_max*batchsize == data.value.shape[0]
givens = {}
index = T.lscalar() # index to a [mini]batch
if self.aux and self.aux_active:
if type(aux) is list:
givens.update({self.auxtarget:\
T.cast(aux[0][index*batchsize:(index+1)*batchsize]/aux[1]+aux[2],aux[3])})
else:
givens.update({self.auxtarget:aux[index*batchsize:(index+1)*batchsize]})
if self.mode == 'Sup' or self.mode == 'Mixte':
if type(datal) is list:
givens.update({self.out:\
T.cast(datal[0][index*batchsize:(index+1)*batchsize]/datal[1]+datal[2],datal[3])})
else:
givens.update({self.out:datal[index*batchsize:(index+1)*batchsize]})
if type(data) is list:
givens.update({self.inp:\
T.cast(data[0][index*batchsize:(index+1)*batchsize]/data[1]+data[2],data[3])})
else:
givens.update({self.inp:data[index*batchsize:(index+1)*batchsize]})
# allocate symbolic variables for the data
func = theano.function([index], self.cost, givens = givens)
def func2():
cost = 0
for i in range(n_max):
cost += func(i)
return cost / float(n_max)
return func2
def save(self,fname):
"""
NOTE: This only loads the current parameters, for whatever Theano
graph we are currently working with.
"""
#paramsinit = dict((i,self.__dict__[i]) for i in self.paramsinitkeys)
#paramscurrent = dict((i,self.__dict__[i]) for i in self.paramscurrentkeys)
#paramsaux = dict((i,self.__dict__[i]) for i in self.paramsauxkeys)
#f = open(fname+'/params.pkl','w')
#cPickle.dump(paramsinit,f,-1)
#cPickle.dump(paramscurrent,f,-1)
#cPickle.dump(paramsaux,f,-1)
#f.close()
#print >> sys.stderr, 'params.pkl saved in %s'%fname
for i in range(self.depth):
self.layers[i].save(fname+'/Layer'+str(i+1)+'_')
if not self.tie[i]:
self.layersdec[i].save(fname+'/Layerdec'+str(i+1)+'_')
if self.auxlayer != None:
self.auxlayer.save(fname+'/Layeraux_')
self.outlayer.save(fname+'/Layerout_')
print >> sys.stderr, 'saved in %s'%fname
def load(self,fname):
"""
NOTE: This only loads the current parameters, for whatever Theano
graph we are currently working with.
"""
#f = open(fname+'/params.pkl','r')
#paramsinit = cPickle.load(f)
#paramscurrent = cPickle.load(f)
#paramsaux = cPickle.load(f)
#f.close()
#print >> sys.stderr, 'params.pkl loaded in %s'%fname
#reload base model-----------------------
#tmp = False
#for i in self.paramsinitkeys:
# if self.__dict__[i] != paramsinit[i]:
# tmp = True
#if tmp:
# del self.layers
# del self.layersdec
# paramsinit.update({'inp' : self.inp, 'out' : self.out,\
# 'rng':self.rng,'theano_rng':self.theano_rng})
# self.__init__(**paramsinit)
#reload auxiliary layer------------------
#tmp = False
#for i in self.paramsauxkeys:
# if self.__dict__[i] != paramsaux[i]:
# tmp = True
#if tmp:
# self.auxiliary(1,**paramsaux)
#reloadmode-----------------------------
#tmp = False
#for i in self.paramscurrentkeys:
# if self.__dict__[i] != paramscurrent[i]:
# tmp = True
#if tmp:
# self.aux = paramscurrent.pop('aux')
# fdb = 1
# if fdb and paramscurrent['mode'] == 'Sup':
# fdb = 0
# paramscurrent.pop('mode')
# paramscurrent.pop('noise_lvl')
# paramscurrent.pop('unsup_scaling')
# self.ModeSup(**paramscurrent)
# if fdb and paramscurrent['mode'] == 'Unsup':
# fdb = 0
# paramscurrent.pop('mode')
# paramscurrent.pop('sup_scaling')
# self.ModeUnsup(**paramscurrent)
# if fdb and paramscurrent['mode'] == 'Mixte':
# fdb = 0
# paramscurrent.pop('mode')
# self.ModeMixte(**paramscurrent)
# if fdb and paramscurrent['mode'] == 'Aux':
# fdb = 0
# paramscurrent.pop('mode')
# paramscurrent.pop('noise_lvl')
# paramscurrent.pop('unsup_scaling')
# paramscurrent.pop('sup_scaling')
# paramscurrent.pop('depth_min')
# self.ModeAux(**paramscurrent)
for i in range(self.depth):
self.layers[i].load(fname+'/Layer'+str(i+1)+'_')
if not self.tie[i]:
self.layersdec[i].load(fname+'/Layerdec'+str(i+1)+'_')
if self.auxlayer != None:
self.auxlayer.load(fname+'/Layeraux_')
self.outlayer.load(fname+'/Layerout_')
print >> sys.stderr, 'loaded from %s'%fname
def ModeUnsup(self,depth_max,depth_min=0,noise_lvl=None,update_type = 'global',
lr = 0.1, unsup_scaling = 1., hessscal = 0.001):
"""
Redefine the symbolic variables in the [something] Theano graph
of this class. This is the Theano graph for performing training.
WARNING: After you call this function, you MUST call
trainfunctionbatch. Otherwise, you will have a stale Theano graph.
NOTE: The activation function for each decoding layer will
be identical to the activation function for the corresponding
encoding layer. This means that if we have a rectifier unit for
the encoder, we would also have a rectifier for the decoder. This
is undesirable. Hence, we use ModeAux instead for the rectifier
unit.
depth_max - The top level through which you are computing the
reconstruction. Cannot be higher than the depth of the overall
architecture.
depth_min - The first level through which you put the noise,
and also the target which you try to reconstruct.
update_type - 'global' or 'local'. 'local' means that you update
the parameters only of the top-most denoising AA. 'global' means
that you update the parameters of every layer, from depth_min
to depth_max back down to depth_min.
"""
self.mode = 'Unsup'
self.lr = lr
self.sup_scaling = None
self.unsup_scaling = unsup_scaling
self.hessscal = hessscal if self.bbbool else None
self.update_type = update_type
self.depth_max = depth_max
self.depth_min = depth_min
self.noise_lvl = noise_lvl
self.params = []
self.upmask = []
self.specialupdates = {}
self.wd = []
self.sp = []
self.__redefinemodel(1, depth_max,depth_min,noise_lvl,update_type)
self.__redefinemodel(-1, depth_max,depth_min,update_type=update_type)
if self.aux:
self.aux_active = self.__checkauxactive()
if self.aux_active:
self.auxiliary(1, auxdepth = self.auxdepth, auxn_out = self.auxn_out,
aux_scaling = self.aux_scaling, auxregularization = self.auxregularization,
auxlayertype = self.auxlayertype, auxact = self.auxact,
aux_one_sided = self.aux_one_sided,auxwdreg = self.auxwdreg,
Wtmp = self.auxlayer.W, btmp = self.auxlayer.b,afficheb = False)
self.__definecost()
if self.bbbool:
self.__definebbprop()
#self.__monitorfunction()
self.afficher()
def ModeSup(self,depth_max,depth_min=0,update_type = 'global',lr = 0.1,
sup_scaling = 1., hessscal = 0.001):
"""
Define the Theano symbolic variables for computing the supervised symbol.
***depth_max : The highest layer, where you are adding the
supervised layer. This might not necessarily be the top
layer, if we are interested in using a supervised signal at
lower layers.
***depth_min : All layers from this point up will contribute
their features to the logistic regression. If this is the
same as depth_max, then only the depth_max features are used
for classification.
***update_type : 'global' or 'local'. 'global' means update
all parameters from the input through depth_max and also the
supervised layer. 'local' means update only the supervised
layer.
NOTE: For each (depth_min, depth_max) tuple, this corresponds to
a new supervised layer. You will *lose* the previous
supervised layer that you constructed. (Unless that
supervised layer had the same depth_min and depth_max, in
which case we just keep the old one and don't change it. See
__redefine_model where it checks for outlayer and depth_max
and depth_min.)
NOTE: If depth_max != depth_min, i.e. you are concatenating
layers for supervised features, then you are only permitted
to do 'local' updates. The intuition is that we don't
want global updates the improve the lower layer supervised
classification then interfere with the creation of higher
level features and make it harder for higher-level features
to do supervised classification.
"""
self.mode = 'Sup'
self.lr = lr
self.sup_scaling = sup_scaling
self.unsup_scaling = None
self.hessscal = hessscal if self.bbbool else None
self.depth_max = depth_max
self.depth_min = depth_min
if depth_max != depth_min:
update_type = 'local'
self.update_type = update_type
self.noise_lvl = None
self.params = []
self.upmask = []
self.specialupdates = {}
self.wd = []
self.sp = []
self.__redefinemodel(1, depth_max,0,None,update_type)
self.__redefinemodel(0, depth_max,depth_min,update_type = update_type)
if self.aux:
self.aux_active = self.__checkauxactive()
if self.aux_active:
self.auxiliary(1, auxdepth = self.auxdepth, auxn_out = self.auxn_out,
aux_scaling = self.aux_scaling, auxregularization = self.auxregularization,
auxlayertype = self.auxlayertype, auxact = self.auxact,
aux_one_sided = self.aux_one_sided,auxwdreg = self.auxwdreg,
Wtmp = self.auxlayer.W, btmp = self.auxlayer.b,afficheb = False)
self.__definecost()
if self.bbbool:
self.__definebbprop()
#self.__monitorfunction()
self.afficher()
def ModeMixte(self, depth_max, depth_min=0, noise_lvl=None, update_type = 'global',
lr = 0.1, sup_scaling = 1., unsup_scaling = 1., hessscal = 0.001):
"""
A combination of ModeUnsup and ModeSup.
However, the logistic regression is defined only on the top encoding layer.
"""
# @to change when equilibrium optimizer won't cycle sup_scaling = 0.5, unsup_scaling =0.5
self.mode = 'Mixte'
self.lr = lr
self.sup_scaling = sup_scaling
self.unsup_scaling = unsup_scaling
self.hessscal = hessscal if self.bbbool else None
self.update_type = update_type
self.depth_max = depth_max
self.depth_min = depth_min
self.noise_lvl = noise_lvl
# always to do for model redefining
self.params = []
self.upmask = []
self.specialupdates = {}
self.wd = []
self.sp = []
self.__redefinemodel(1, depth_max,depth_min,noise_lvl,update_type)
self.__redefinemodel(0, depth_max,depth_max)
self.__redefinemodel(-1, depth_max,depth_min,update_type=update_type)
if self.aux:
self.aux_active = self.__checkauxactive()
if self.aux_active:
self.auxiliary(1, auxdepth = self.auxdepth, auxn_out = self.auxn_out,
aux_scaling = self.aux_scaling, auxregularization = self.auxregularization,
auxlayertype = self.auxlayertype, auxact = self.auxact,
aux_one_sided = self.aux_one_sided,auxwdreg = self.auxwdreg,
Wtmp = self.auxlayer.W, btmp = self.auxlayer.b,afficheb = False)
self.__definecost()
if self.bbbool:
self.__definebbprop()
#self.__monitorfunction()
self.afficher()
def ModeAux(self,depth_max,update_type = 'global', lr = 0.1, hessscal = 0.001, noise_lvl = None):
"""
Redefine Theano symbolic variables for the auxiliary layer.
The cost is defined only for the auxiliary layer.
"""
self.depth_max = depth_max
self.depth_min = 0
self.aux_active = self.__checkauxactive()
assert self.aux == True and self.aux_active == True
self.mode = 'Aux'
self.lr = lr
self.sup_scaling = None
self.unsup_scaling = None
self.aux_scaling = 1.
self.hessscal = hessscal if self.bbbool else None
self.depth_max = depth_max
self.update_type = update_type
self.noise_lvl = noise_lvl
self.params = []
self.upmask = []
self.specialupdates = {}
self.wd = []
self.sp = []
self.__redefinemodel(1, min(depth_max,self.depth + self.auxdepth),depth_max-1,noise_lvl,update_type)
if self.auxdepth>0:
self.__redefinemodel(-1, depth_max, self.depth - self.auxdepth,None,update_type)
self.auxiliary(1, auxdepth = self.auxdepth, auxn_out = self.auxn_out,
aux_scaling = self.aux_scaling, auxregularization = self.auxregularization,
auxlayertype = self.auxlayertype, auxact = self.auxact,
aux_one_sided = self.aux_one_sided,auxwdreg = self.auxwdreg,
Wtmp = self.auxlayer.W, btmp = self.auxlayer.b,afficheb = False)
self.__definecost()
if self.bbbool:
self.__definebbprop()
#self.__monitorfunction()
self.afficher()
def untie(self):
for i in range(self.depth):
if self.tie[i] == True:
self.tie[i] = False
self.layersdec[i].W = theano.shared(value = numpy.asarray(self.layers[i].W.value.T,\
dtype = theano.config.floatX),name = 'Wdec%s'%i)
print >> sys.stderr, 'layer %s untied, Warning, you need to redefine the mode'%i
def afficher(self):
paramsaux = []
wdaux = []
if self.aux and self.aux_active \
and (self.update_type != 'special' or self.depth+self.auxdepth == self.depth_max):
paramsaux += self.auxlayer.params
if self.auxregularization:
wdaux += [self.auxregularization*self.auxlayer.wd]
print >> sys.stderr, '\t**** SDAE ****'
print >> sys.stderr, '\tdepth = ', self.depth
print >> sys.stderr, '\tmode = ', self.mode
print >> sys.stderr, '\tdepth_min, depth_max, update_type = ', self.depth_min,',', \
self.depth_max,',', self.update_type
print >> sys.stderr, '\tinp, n_inp = ', self.inp ,',' , self.n_inp
print >> sys.stderr, '\tn_hid = ', self.n_hid
print >> sys.stderr, '\tlayertype = ', self.layertype
print >> sys.stderr, '\tact = ', self.act
print >> sys.stderr, '\tnoise, noise_lvl = ', self.noise,',', self.noise_lvl
print >> sys.stderr, '\ttie = ', self.tie
print >> sys.stderr, '\tmaskbool = ', self.maskbool
print >> sys.stderr, '\tn_out, outtype = ', self.n_out,',' , self.outtype
print >> sys.stderr, '\tlr = ', self.lr
print >> sys.stderr, '\tsup_scaling, unsup_scaling, aux_scaling = ', self.sup_scaling, \
self.unsup_scaling, self.aux_scaling
print >> sys.stderr, '\tregularization, wdreg = ', self.regularization,',', self.wdreg
print >> sys.stderr, '\tsparsity, spreg = ', self.sparsity,',', self.spreg
print >> sys.stderr, '\tparams, wd, sp = ', self.params+paramsaux,',', self.wd+wdaux, ',', self.sp
print >> sys.stderr, '\tbbbool, hessscal = ', self.bbbool,',', self.hessscal
print >> sys.stderr, '\taux, auxtarget, aux_one_sided, auxdepth, auxregularization = ', \
self.aux, ',', self.auxtarget, ',', self.aux_one_sided, ',', \
self.auxdepth, ',', self.auxregularization
print >> sys.stderr, '\tauxact, auxn_out, auxwdreg = ', \
self.auxact, ',', self.auxn_out, ',', self.auxwdreg
sys.stderr.flush()
if __name__ == '__main__':
import pylearn.datasets.MNIST
import copy
theano.config.floatX='float64'
dat = pylearn.datasets.MNIST.full()
test = theano.shared(value = numpy.asarray((dat.test.x),dtype = theano.config.floatX),name='test')
testl = T.cast(theano.shared(value = numpy.asarray(dat.test.y,dtype = theano.config.floatX),name='testl'),'int32')
valid = theano.shared(value = numpy.asarray((dat.valid.x),dtype = theano.config.floatX),name='valid')
validl = T.cast(theano.shared(value = numpy.asarray(dat.valid.y,dtype = theano.config.floatX),name='validl'),'int32')
train = theano.shared(value = numpy.asarray((dat.train.x),dtype = theano.config.floatX),name='train')
trainl = T.cast(theano.shared(value = numpy.asarray(dat.train.y,dtype = theano.config.floatX),name='trainl'),'int32')
del dat
a=SDAE(numpy.random,RandomStreams(),act='rectifier',depth=3,one_sided_in=True,n_hid=1000,\
regularization=False,sparsity=0.00001,spreg = 'l1_target(0.5)',\
reconstruction_cost='quadratic',n_inp=784,n_out=10,tie=False,maskbool=1)
def training(a,train,trainl,test,testl,maxi = 2,b=False):
g,n = a.trainfunctionbatch(data = train,datal=trainl,batchsize=10)
if b:
f = a.errorfunction(data=test,datal=testl)
else:
f = a.costfunction(data=test,datal=testl)
err = f()
epoch = 0
while epoch<=maxi:
for i in range(n):
print >> sys.stderr, g(i), 'epoch:', epoch, 'err:',err , i
epoch += 1
err = f()
neworder = numpy.random.permutation(train.value.shape[0])
train.value = train.value[neworder,:]
trainl.value = trainl.value[neworder]
#a.ModeUnsup(1,0,0.25,'global',lr=0.01)
#training(a,train,trainl,test,testl,maxi = 100)
#a.ModeUnsup(2,1,0.25,'global',lr=0.01)
#training(a,train,trainl,test,testl,maxi = 100)
#a.ModeUnsup(3,2,0.25,'global',lr=0.01)
#training(a,train,trainl,test,testl,maxi = 100)
a.ModeSup(3,3,'global',lr=0.1)
training(a,train,trainl,test,testl,maxi = 5000,b=True)
| [
"glorotxa@iro.umontreal.ca"
] | glorotxa@iro.umontreal.ca |
3dcd7b4a5b15205b98dc36ef6d1fd925d9be13ee | 4aec5f54bd7b2ab06ab2b3e05767798ea1678182 | /Final_analysis/monte_carlo.py | 93ad8dbb3e01bd23520b049d883acf60ab35b705 | [] | no_license | anirudh217sharma/final_project_2020Sp | 10f752173457cf6365b56d281b9c2876431cf83c | d7ac83ec078219902883f7dd8f8cf2fa597063df | refs/heads/master | 2022-08-16T19:48:23.181516 | 2020-05-22T01:19:43 | 2020-05-22T01:19:43 | 255,766,305 | 0 | 1 | null | 2020-04-15T01:00:05 | 2020-04-15T01:00:04 | null | UTF-8 | Python | false | false | 7,595 | py | import random
from typing import Dict, List, Any, Union
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
import math
import copy
def to_str(var): # https://stackoverflow.com/questions/24914735/convert-numpy-list-or-float-to-string-in-python
"""
:param var: input -decimal number
:return:
Converted integer
>>> to_str(52.09566843846285)
'52'
>>> to_str(29.537659592948213)
'29'
"""
return str(list(np.reshape(np.asarray(var), (1, np.size(var)))[0]))[1:-1].split('.')[0]
def distance(x1, y1, x2, y2):
"""
:param x1: First person's x coordinate
:param y1: First person's y coordinate
:param x2: Second person's x coordinate
:param y2: Second person's y coordinate
:param d: Distance under which a person will become infected
:return: A Boolean
>>> distance(1,1,2,2)
True
>>> distance(1,1,8,9)
False
"""
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
return abs(distance) <= 6
final_dict = {}
def death_recovery_calculator(final_dict):
"""
:param final_dict: Total infected population after two months
return: simulation_death_record - a dictionary containing the death information for various age groups
"""
final_dict['death_rate'] = []
final_dict['age_group'] = []
final_dict['count'] = []
for num in final_dict['age']:
if num <= 29:
final_dict['death_rate'].append(0.2)
final_dict['age_group'].append('less_then_29')
elif 30 <= num <= 39:
final_dict['death_rate'].append(0.4)
final_dict['age_group'].append('between 30 and 39')
elif 40 <= num <= 49:
final_dict['death_rate'].append(0.6)
final_dict['age_group'].append('between 40 and 49')
elif 50 <= num <= 59:
final_dict['death_rate'].append(1.4)
final_dict['age_group'].append('between 50 and 59')
elif 60 <= num <= 69:
final_dict['death_rate'].append(3.6)
final_dict['age_group'].append('between 60 and 69')
elif 70 <= num <= 79:
final_dict['death_rate'].append(8.0)
final_dict['age_group'].append('between 70 and 79')
else:
final_dict['death_rate'].append(15.0)
final_dict['age_group'].append('greater than 80')
final_dict['count'] = [1] * len(final_dict['age'])
infected_population = pd.DataFrame(final_dict)
infected_population['death_number'] = infected_population['death_rate'] / 100
simulation_death_record = dict(infected_population.groupby(['age_group']).sum()['death_number'])
return simulation_death_record
def no_social_distancing(infected_percentage, final_dict, test_set):
"""
:param infected_percentage: List to store precentage of infected people each day
:param final_dict: Dictionary to store information about infected people
:param test_set : Dictionary representing the population
:return: infected_percentage,final_dict
"""
a = 0
b = 1
c = 0
delta = 0
while a < 15:
for m in range(4):
counter = []
for i, num in enumerate(test_set['condition']):
if num == 'I':
for j, k in enumerate(test_set['xy']):
try:
if distance(k[0], k[1], test_set['xy'][i][0], test_set['xy'][i][1]) and i != j:
final_dict['age'].append(test_set['age'][j])
final_dict['condition'].append('I')
final_dict['xy'].append(k)
test_set['condition'][j] == 'I'
counter.append(j)
else:
continue
except:
continue
test_set['x'] = [random.randint(1, 150) for i in range(len(test_set['condition']))]
test_set['y'] = [random.randint(1, 150) for i in range(len(test_set['condition']))]
test_set['xy'] = list(zip(test_set['x'], test_set['y']))
del test_set['x']
del test_set['y']
b += 1
infected_percentage['number'].append(((len(counter) + delta) / 1000) * 100)
infected_percentage['day'].append(b)
# print(len(test_set['age']))
delta += len(counter)
# print(delta)
# print(len(counter))
try:
for thi in counter:
test_set['age'].pop(thi)
test_set['condition'].pop(thi)
test_set['xy'].pop(thi)
test_set['delta'].pop(thi)
except:
continue
# print(len(test_set['age']))
a += 1
return infected_percentage, final_dict
def social_distancing(infected_percentage_social_distancing, final_dict_sd, test_set_sd):
"""
:param infected_percentage: List to store precentage of infected people each day
:param final_dict: Dictionary to store information about infected people
:param test_set : Dictionary representing the population
:return: infected_percentage_social_distancing,final_dict_sd
"""
a = 0
b = 1
c = 0
delta = 0
while a < 15:
for m in range(4):
counter = []
for i, num in enumerate(test_set_sd['condition']):
if num == 'I':
for j, k in enumerate(test_set_sd['xy']):
try:
if distance(k[0], k[1], test_set_sd['xy'][i][0], test_set_sd['xy'][i][1]) and i != j:
final_dict_sd['age'].append(test_set_sd['age'][j])
final_dict_sd['condition'].append('I')
final_dict_sd['xy'].append(k)
test_set_sd['condition'][j] == 'I'
counter.append(j)
else:
continue
except:
continue
b += 1
infected_percentage_social_distancing['number'].append(((len(counter) + delta) / 1000) * 100)
infected_percentage_social_distancing['day'].append(b)
# print(len(test_set_sd['age']))
delta += len(counter)
# print(delta)
try:
for thi in counter:
test_set_sd['age'].pop(thi)
test_set_sd['condition'].pop(thi)
test_set_sd['xy'].pop(thi)
test_set_sd['delta'].pop(thi)
except:
continue
# print(len(test_set_sd['age']))
test_set_sd['x'] = [random.randint(1, 150) for i in range(len(test_set_sd['condition']))]
test_set_sd['y'] = [random.randint(1, 150) for i in range(len(test_set_sd['condition']))]
test_set_sd['xy'] = list(zip(test_set_sd['x'], test_set_sd['y']))
del test_set_sd['x']
del test_set_sd['y']
a += 1
# print(a)
return infected_percentage_social_distancing, final_dict_sd
if __name__ == "__main__":
import doctest
doctest.testmod()
| [
"noreply@github.com"
] | anirudh217sharma.noreply@github.com |
a3d7cbb516bade8830653b00d9a64990d27e9a98 | b8224f58c7c481f808f933b175b53dc0cf1fbcb8 | /tools/scan_log_dau.py | cbcf1b48c2d6ed98bb6fcd9c07141e82f9ec6395 | [] | no_license | waipbmtd/dwarf | 0ceebb1ef0265a88c66e508db8558fe523f4d5c9 | 9a31b4d57b50961bc3aab4bd7701fa9aad49bf97 | refs/heads/master | 2021-01-18T09:18:53.719434 | 2014-09-21T08:50:33 | 2014-09-21T08:50:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,118 | py | #!/usr/bin/env python
#coding: utf-8
#name: scan log
#by Camelsky 2012/02/19
import os
import re
import tornado
import time
import gzip
from bitarray import bitarray
from tornado.options import options, define
from datetime import date, datetime, timedelta
try:
import redis
except:
print("Need python module \'redis\' but not found!")
exit(1)
import dauconfig
import dwarf.dau
import dwarf.daux
import logging
import db_config
config = dauconfig
class redisPipeline:
conn = None
count = 0
def __init__(self, conf):
r = redis.Redis(host=conf['host'], port=conf['port'], db=conf['db'])
self.conn = r.pipeline()
def __del__(self):
self._save()
def _save(self):
self.conn.execute()
def setbit(self, reKey, offset, identfy=1):
self.conn.setbit(reKey, offset, identfy)
self.count += 1
if self.count & 0xFF == 0:
self._save()
def get_redis_client(pipe=False):
conf = db_config.redis_conf
try:
if pipe:
conn = redisPipeline(conf)
else:
conn = redis.Redis(**conf)
return conn
except Exception, e:
print "redis connection Error!", e
raise e
def markActiveUserid(date, userid, redis_cli):
# redis_cli = get_redis_client()
auRecord = dwarf.daux.AUrecord(redis_cli)
if auRecord.mapActiveUserid(date,userid):
print date, userid
def scanLogFile(date):
fconf = config.logfile_conf
filename = fconf['dir']+fconf['name_format'].format(date=date)
print('open log file:', filename)
if re.search('.gz$', filename):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'r')
uids = []
count = 0
while 1:
line = f.readline()
if line:
regmatch = re.search('from=[\'|"]([0-9]+)[\'|"]', line)
if regmatch:
uids.append(regmatch.group(1))
count += 1
if count & 0xFFFF == 0:
yield uids
uids = []
else:
yield uids
f.close()
break
def openLogFile(filename):
if re.search('.gz$', filename):
print('open log file:', filename)
f = gzip.open(filename, 'rb')
else:
print('open log file:', filename)
f = open(filename, 'r')
return f
def genMapbytes(barr, uid):
bLen = barr.length()
offset = int(uid)
if offset > 0 and offset <= config.MAX_BITMAP_LENGTH:
if bLen < offset:
barr += bitarray(1)*(offset-bLen)
barr[offset] = True
return barr
def doScan(from_date, to_date, port='9022'):
"""
扫瞄from_date 到 to_date 之间的request日志
将每日访问用户id映射入bitmap
"""
print from_date, to_date
days = (to_date-from_date).days+1
dateList = [from_date+timedelta(v) for v in range(days)]
redis_cli = get_redis_client(True)
auRecord = dwarf.daux.AUrecord(redis_cli)
for date in dateList:
sDate = date.strftime(config.DATE_FORMAT)
print 'scan', sDate
s = time.time()
for uids in scanLogFile(sDate):
[auRecord.mapActiveUserid(date,uid) for uid in set(uids)]
e = time.time()
print 'Elapsed:', e-s,'sec'
def run():
define("f", default=None)
define("t", default=None)
define("port", default='9022')
tornado.options.parse_command_line()
#计算扫瞄日志的时间范围
Today_date = date.today()
Yesterday_date = date.today()-timedelta(days=1)
sToday_date = Today_date.strftime(config.DATE_FORMAT)
sYesterday_date = Yesterday_date.strftime(config.DATE_FORMAT)
if not options.f :
options.f = sYesterday_date
if not options.t :
options.t = sYesterday_date
try:
from_date = datetime.strptime(options.f, config.DATE_FORMAT)
to_date = datetime.strptime(options.t, config.DATE_FORMAT)
except ValueError, e:
raise e
doScan(from_date, to_date)
if __name__ == '__main__':
run() | [
"camelsky@gmail.com"
] | camelsky@gmail.com |
bb2caed37e605c5250648871051bb3ede642a153 | 6dcff1b33a873a70a4a902861dbb5bc840a38c73 | /ncip.py | 6288e6aade969cd2eb4617eebbbb892f41ebd5ea | [] | no_license | aygumov-g/python-NumberCipher | 62017b9ec4feb49cbaf615f78e327b8377f4a9d3 | 3e3bff4f9282d6d6e504551cb75d7ede698a2f28 | refs/heads/main | 2023-07-03T03:07:19.491692 | 2021-08-07T17:39:04 | 2021-08-07T17:39:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 294 | py | from random import randint as ___
def _(_):
__ = {"_": [_, ""]}
_____ = 0
for _ in _:
____ = ___(1, 2)
if ____ == 1:
__["_"][1] += str(int(_) + 1)
__[f"{_____}_{_}"] = "+"
else:
__["_"][1] += str(int(_) - 1)
__[f"{_____}_{_}"] = "-"
_____ += 1
return __
| [
"noreply@github.com"
] | aygumov-g.noreply@github.com |
27b6bdd518263435054c9958b4f58b514197843e | dc7e8f371d82c2872735cb28ed6076d105d33b88 | /DICTIONARY-5.py | ae68af8f710e8a4358cbc22b4788709666aec950 | [] | no_license | Arf17BTEC004/myfiles | e98ec3ce35913edc6da36d2d0c036469910c2410 | 29af22ae8c881b647818235165d161258c6706ea | refs/heads/master | 2021-05-11T12:22:11.125542 | 2018-04-26T05:44:31 | 2018-04-26T05:44:31 | 117,656,669 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 77 | py | #DICTIONARY-5
D={1:200,2:400,"PI":3.1416}
z=D[2]
print(z)
V=D["PI"]
print(V)
| [
"noreply@github.com"
] | Arf17BTEC004.noreply@github.com |
2531b746cd58d19a2a200cd4e67130b29fd1ce89 | 574999525b737f173411948954edb787ae185b86 | /Unit 1.py | ae0d9bf7567e5af01570d24329405cbb10883a76 | [] | no_license | tarunapraja/TA-SKT | fb09cbdd75b9dfc83a92574a51dd17e1ecf8100b | e1b4582bf2a5d7ebc74e0d23527431c1b7d0ac72 | refs/heads/master | 2020-05-26T00:09:25.617233 | 2019-05-22T13:51:10 | 2019-05-22T13:51:10 | 188,047,898 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 669 | py | from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client
server = SimpleXMLRPCServer(("0.0.0.0", 5556))
def Emergency_Calls(namaLapor, alamatLapor) :
client_Pusat = xmlrpc.client.ServerProxy("http://127.0.0.1:5555")
notif = client_Pusat.laporan(1, namaLapor, alamatLapor)
if notif == "Laporan diterima":
return "Berita Tersampaikan"
else :
return "Berita Tidak terkirim"
def Notif(namaLapor, alamatLapor) :
print("Terdapat laporan kebakaran atas nama ",namaLapor," dengan alamat ",alamatLapor)
return 1
server.register_function(Emergency_Calls, "Emergency_Calls")
server.register_function(Notif, "Notif")
server.serve_forever() | [
"noreply@github.com"
] | tarunapraja.noreply@github.com |
b6c80e7c951bf771e35b6eed2c5e9bd931b4952d | 69fa3beeb1b35be0d1b16ee519e6ec0844a43b18 | /client/urls.py | 9cda64eed2944e3160ad2e163dd255da8fb1c340 | [] | no_license | lw347347/intex2final | 626869d0b4671a8b45fc3aa25093d9910a8f1a54 | ec2532eace9bf80abdf0565d8b5acb6c0994865c | refs/heads/master | 2022-12-10T02:53:36.318385 | 2020-04-10T01:51:50 | 2020-04-10T01:51:50 | 254,377,110 | 0 | 1 | null | 2022-12-08T04:01:07 | 2020-04-09T13:21:11 | JavaScript | UTF-8 | Python | false | false | 164 | py | from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path('', TemplateView.as_view(template_name='client/index.html')),
] | [
"lw347347@byu.edu"
] | lw347347@byu.edu |
c5f8396f5be58964491d8ccb9b3bb9a355d4c79c | 5d95b7bddb828407efdfd58f9cc25e9ae2d8f5b2 | /problem005.py | 3765c61254c58972773602c236397bce1dc2bea5 | [] | no_license | Carl-Aslund/project-euler | 3ec0ce9db1b91e3248c1f4eb4425a5f0de8ce975 | c36dc4e967707e141043f4a5cabd37ccafde49ce | refs/heads/master | 2021-09-13T07:41:34.359409 | 2018-04-26T17:29:09 | 2018-04-26T17:29:09 | 115,889,706 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 463 | py | def gcd(x, y):
"""Returns the greatest common denominator of two integers."""
if y == 0:
return x
else:
r = x % y
return gcd(y, r)
def superLcm(num):
"""Returns the least common multiple of all numbers from 1 to num."""
lcm = 1
for i in range(2, num+1):
if lcm%i == 0:
continue
else:
gcdNumI = gcd(lcm,i)
lcm = lcm*i//gcdNumI
return lcm
print(superLcm(20))
| [
"caslund@g.hmc.edu"
] | caslund@g.hmc.edu |
1f22d2db31666c1bd1fff6012090e64e0ed64f02 | 493869fbe452ad6524e9d1a4570a978f87a2c5c3 | /api/migrations/0004_auto_20190818_1125.py | 75b0dba2f29eb6268e8a86ec06019c41bc0decf4 | [] | no_license | NeKadgar/KIWIDO | 33491fa4fe78872ab9c3c76a4434ff6700ed687c | 3255c32406190e26b8804fe7524bb6b56e50cee7 | refs/heads/master | 2020-07-11T23:44:10.098551 | 2019-08-29T07:26:42 | 2019-08-29T07:26:42 | 204,668,228 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 524 | py | # Generated by Django 2.0.6 on 2019-08-18 08:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20190818_1124'),
]
operations = [
migrations.AlterField(
model_name='note',
name='done',
field=models.TextField(blank=True),
),
migrations.AlterField(
model_name='note',
name='editing',
field=models.TextField(blank=True),
),
]
| [
"37880360+NeKadgar@users.noreply.github.com"
] | 37880360+NeKadgar@users.noreply.github.com |
ec86aee2863caad73625cec5b38ecb008e726e79 | 462c56e7454c97e0541588b9be66a4e216ea20fd | /399.evaluate-division.py | a3cfbdefe5a676c0fd3cfbca9f067f3686c034cf | [] | no_license | LouisYLWang/leetcode_python | d5ac6289e33c5d027f248aa3e7dd66291354941c | 2ecaeed38178819480388b5742bc2ea12009ae16 | refs/heads/master | 2020-05-27T08:38:48.532000 | 2019-12-28T07:08:57 | 2019-12-28T07:08:57 | 188,549,256 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,199 | py | #
# @lc app=leetcode id=399 lang=python3
#
# [399] Evaluate Division
#
class Solution(object):
def calcEquation(self, equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
div_map = dict()
for [i,j], v in zip(equations, values):
if i in div_map:
div_map[i][j] = v
else: div_map[i] = {j:v}
if j in div_map:
div_map[j][i] = 1/v
else: div_map[j] = {i:1/v}
print(div_map)
def get_res(i, j, ans):
if i not in div_map or j not in div_map:
return -1.0
elif i == j:
return 1.0
else:
if j in div_map[i]:
return div_map[i][j]
else:
for k in div_map[i]:
# use visited to control repeating visit
visited.add(i)
if k not in visited:
temp = get_res(k, j, ans)
# do not mistakenly use if temp
if temp != -1:
return div_map[i][k] * temp
# notice: if not find anything, remember to return -1
return -1.0
# an alternative way of implementing get_res (more compact)
def get_res(i, j, ans):
if i not in div_map:
return -1.0
elif i == j:
return 1.0
for k in div_map[i]:
if j == k:
return div_map[i][j]
elif k not in visited:
visited.add(i)
temp = get_res(k, j, ans)
if temp != -1:
return div_map[i][k] * temp
return -1.0
res = list()
for query in queries:
visited = set()
res.append(get_res(query[0], query[1], 1))
return res
| [
"louis.yl.wang@outlook.com"
] | louis.yl.wang@outlook.com |
0f21630b7245ca179cf9e8e5fb6e5e94b4c702b8 | a6ade10bf4bca2bd8a86a614cdb8121501ceb1fe | /Homework 20.09.62_9.py | f6f6314d6f88355e065198eb75a361859a233e72 | [] | no_license | thitima20/Homework-20.09.62 | 1f6bdd20c5ee946f8b64b82e030d4ac4a1adc8f1 | 4f74e8b16de3dd9d01d14d2c484444bcb3e342ec | refs/heads/master | 2020-07-29T23:49:01.962490 | 2019-09-22T15:59:38 | 2019-09-22T15:59:38 | 210,006,272 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,021 | py | sum = 0.0
n = 0
#Define of variable กำหนดให้ sum เท่ากับ 0.0 กำหนดให้ n เท่ากับ 0
number = int(input("Enter number :"))
#input รับค่าตัวเลขเข้ามาทางแป้นพิมพ์
while number > -1:
#process ทำเงื่อนไข while โดยให้รับตัวเลขเข้ามาเรื่อยๆจนกระทั่งมีการรับตัวเลข -1 เข้ามาจึงหยุดรับตัวเลขแล้วนำตัวเลขทั้งหมดมาบวกกันแล้วหาค่าเฉลี่ย
sum = sum + number
n = n + 1
number = int(input("Enter number :"))
avg = sum / n
#output เมื่อทำขั้นตอน process แล้วได้คำตอบ output ออกมาให้แสดงออกทางหน้าจอด้วยคำสั่ง print
print("Avg =", avg) | [
"noreply@github.com"
] | thitima20.noreply@github.com |
928ddd4f81277a2748416b7bccc1aff34c828f94 | f36cfc095a978711e0b34781a6972a927558a542 | /Python practice/Numpy Dot and Cross (easy).py | bcfd3733b9ba79721ab123a0da9d475a5f0560a6 | [] | no_license | dmironov1993/hackerRank | 9ac2c83451fa4833f99969ef148b08918a4b2b6d | 6090e654254477eaea1840fa4b75a9a79a0548c2 | refs/heads/master | 2020-04-23T10:33:41.363235 | 2019-11-22T13:38:09 | 2019-11-22T13:38:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 152 | py | import numpy as np
n = int(input())
a,b = (np.array([input().strip().split() for _ in range(n)], dtype=np.int) for _ in range(2))
print (np.dot(a,b))
| [
"noreply@github.com"
] | dmironov1993.noreply@github.com |
3114c485da23751ff29c831da4c16036721032cc | f96a3e4c19672187184efd0fc67dec221aa6e2e7 | /utils.py | e7ddfc240efb1895d8f5d3baa4f59d4e394234f1 | [] | no_license | nowoodwar/nlp_final_project | 4b0c3da882d2d767b57dd55315543752b94b4391 | 341de88c49534bda6533f72e7a3eca8170f5d870 | refs/heads/master | 2022-06-24T07:44:13.730958 | 2020-05-09T03:42:03 | 2020-05-09T03:42:03 | 261,875,027 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,496 | py | import json
def f1_score(pred, answer):
pcnt = 0
for word in pred:
if word in answer:
pcnt += 1
rcnt = 0
for word in answer:
if word in pred:
rcnt += 1
precision = pcnt / len(pred)
recall = rcnt / len(answer)
# cover divide by zero exception
if precision + recall == 0.:
return 0.
# harmonic mean
f1 = (2*precision*recall)/(precision + recall)
return f1
def preprocess(file_path):
context_list = []
context_map = {}
question_list = []
answer_list = []
with open(file_path, "r", encoding='utf-8') as file:
reader = json.load(file)["data"]
ctx_i, qa_i = 0, 0
for data in reader:
for paragraph in data['paragraphs']:
context_list.append(paragraph['context'])
for qa in paragraph['qas']:
question_list.append(qa['question'])
answers = []
for answer in qa['answers']:
answers.append(answer['text'])
answer_list.append(answers)
context_map[str(qa_i)] = ctx_i
qa_i += 1
ctx_i += 1
return {
"context_list": context_list,
"context_map": context_map,
"question_list": question_list,
"answer_list": answer_list
} | [
"nathaniel.woodward1@gmail.com"
] | nathaniel.woodward1@gmail.com |
e5f2a3153a84e84c9df8be23e4b8958bcbd08513 | d88b6c430c293b9ad464de4f503b51da85be96cd | /python/第一周/user_login.py | da1d8bd1f633d2d87848e573f2e740267e413ea1 | [] | no_license | lww2020/linux | 346573bb48782da41ef14e92ef3afbbe039a71d5 | c8c799f6dad6bceaa5bdd6b4d980aaa26992305c | refs/heads/master | 2022-10-11T22:48:53.080419 | 2018-05-07T03:20:07 | 2018-05-07T03:20:07 | 119,628,170 | 0 | 1 | null | 2022-10-06T23:59:20 | 2018-01-31T03:15:37 | Python | UTF-8 | Python | false | false | 508 | py | # -*- coding:utf-8 -*-
# Author: davie
# 表达式if ... else
"""
场景一:用户登陆验证
1、提示用户输入用户名和密码
2、验证用户名和密码
如果错误,则输出用户名或密码错误
如果成功,则输出欢迎,xxx!
"""
import getpass
name = "davie"
pwd = "abc123"
_name = input("请输入用户名:")
_pwd = input("请输入密码:")
if _name == name and _pwd == pwd:
print("欢迎,{}".format(name),'!')
else:
print("用户名或密码错误!!!") | [
"13439017540@163.com"
] | 13439017540@163.com |
0872b9077d049b94233d0fb75c56b78c011dc985 | 4fa160afca22f6c98db6566012fb17f84905471a | /flask_stream.py | 19b905ff4f5f864762d07cbb9ac2b11227c55ce7 | [] | no_license | aish058/Twitter-streaming-master | 591c01c4f5425a733bad4131a57f018e2885596b | a97d6b8bd07a44e87b5d3a774c542e7b248388d1 | refs/heads/master | 2023-01-28T01:28:08.412549 | 2020-12-13T07:56:15 | 2020-12-13T07:56:15 | 321,012,748 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,881 | py |
# import necessary modules
from tweepy.streaming import StreamListener
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from tweepy import OAuthHandler , Stream , API
from sqlalchemy import Table,select,insert,create_engine,MetaData,cast,desc
from sqlalchemy import Column,String,Integer,Date
import json
import pyodbc
import urllib
import pandas as pd
import numpy as np
app = Flask(__name__)
api_flask = Api(app)
# Authentication Details
consumer_key = " "
consumer_secret = " "
access_token = " "
access_token_secret = " "
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = API(auth)
quoted = urllib.parse.quote_plus('DRIVER={ODBC Driver 13 for SQL Server};Server=<server name>;Database=<database>;UID=<username>;PWD=<password>;Port=1433;Trusted_connection=yes')
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted))
conn = engine.connect()
metadata = MetaData()
twitter = Table('Twitter_Data' , metadata ,
Column('Date',Date()),
Column('TweetId',String(50)),
Column('Tweet',String(5000)),
Column('AuthorId',String(50)),
Column('ScreenName',String(100)),
Column('Source',String(500)),
Column('RetweetCount',Integer()),
Column('FavoriteCount',Integer()),
Column('FollowerCount',Integer()),
Column('UserURL',String(500)),
Column('Language',String(50)),
extend_existing=True
)
tweet = {}
# A class to stream tweets and its metadata
class StdOutListener(StreamListener):
def __init__(self,api,count):
self.api = api
self.counter = count + 1
def on_status(self,data):
self.counter -= 1
if self.counter > 0 :
tweet = {'Date':data.created_at , 'TweetId':str(data.id) ,'Tweet':data.text,
'AuthorID':str(data.user.id),'ScreenName':data.user.screen_name,
'Source': data.source,'RetweetCount':data.retweet_count,
'FavoriteCount':data.favorite_count,'FollowerCount':data.user.followers_count,
'UserURL':data.user.url , 'Language' : data.user.lang}
metadata.create_all(engine)
stmt = insert(twitter)
conn.execute(stmt , tweet)
else :
return False
# A function to display query results
def show_result(result):
result = [{'Date': str(i[0]) , 'TweetId':i[1] ,'Tweet':i[2],
'AuthorID':i[3],'ScreenName':i[4],
'Source': i[5],'RetweetCount':i[6],
'FavoriteCount':i[7],'FollowerCount':i[8],
'UserURL':i[9] ,'Language' : i[10]} for i in result]
return jsonify(result)
# A class to stream and store tweets in a SQL database
class store_tweets(Resource):
def get(self,query,count):
streaming = StdOutListener(api,count)
stream = Stream(auth,streaming)
track = query.split('or')
stream.filter(track = track)
return {'Status' : 'Data inserted in database.' }
# Show table name
class table_name(Resource):
def get(self):
return {'The name of table containing twitter data is' : 'Twitter_Data'}
# Delete twitter table from database
class delete_table(Resource):
def get(self):
twitter = Table('Twitter_Data',metadata,autoload=True,autoload_with = engine)
twitter.drop(engine)
return {'Status' : 'The table of tweets was deleted.'}
# Check table size
class table_size(Resource):
def get(self):
try:
stmt = 'SELECT COUNT(*) FROM Twitter_Data'
result = conn.execute(stmt).scalar()
return {'Size of Twitter data table': result}
except:
return {'Size of Twitter data table': 0}
# Display column names
class column_names(Resource):
def get(self):
column_names = "Date, TweetId, Tweet, AuthorID, ScreenName, Source, RetweetCount, FavoriteCount, FollowerCount, UserURL, Language"
return {'Columns' : column_names}
# Display all the data inside the table
class show_table_data(Resource):
def get(self):
stmt = 'SELECT * FROM Twitter_Data'
result = conn.execute(stmt).fetchall()
result = show_result(result)
return result
# A query to filter integer columns
class filter_int_columns(Resource):
def get(self,column,operator,num):
twitter = Table('Twitter_Data',metadata,autoload=True,autoload_with = engine)
if column in ['FavoriteCount','RetweetCount','FollowerCount']:
stmt = select([twitter])
if operator == '=':
stmt = stmt.where(twitter.columns[column] == num)
elif operator == '<':
stmt = stmt.where(twitter.columns[column] < num)
elif operator == '>':
stmt = stmt.where(twitter.columns[column] > num)
else:
return 'Operator should be either one of the following : < , > , ='
result = conn.execute(stmt).fetchall()
if len(result) > 0:
result = show_result(result)
return result
else:
return {'status' : 'No results found for the given filter.'}
else:
return {'status':'The input column should be an integer type column, i.e. one of : FavoriteCount, RetweetCount, FollowerCount'}
# A query to filter string columns
class filter_string_columns(Resource):
def get(self,column,operator,text):
twitter = Table('Twitter_Data',metadata,autoload=True,autoload_with = engine)
if column in ['TweetdId','Tweet','AuthorId','ScreenName','Source','UserURL','Language']:
stmt = select([twitter])
if operator == 'starts':
stmt = stmt.where(twitter.columns[column].startswith(text))
elif operator == 'ends':
stmt = stmt.where(twitter.columns[column].endswith(text))
elif operator == '=':
text = text.encode('utf-8')
stmt = stmt.where(twitter.columns[column] == text)
elif operator == 'contains':
pattern = '%'+text+'%'
stmt = stmt.where(twitter.columns[column].like(pattern))
else:
return "Operator should be either one of the following : 'starts' , 'ends' , '=' , 'contains'"
result = conn.execute(stmt).fetchall()
if len(result) > 0:
result = show_result(result)
return result
else:
return {'status' : 'No results found for the given filter.'}
else:
return {'status':'The input column should be a string type column, i.e. one of : TweetdId, Tweet, AuthorId, ScreenName, Source, UserURL'}
# Sorting columns
class sort(Resource):
def get(self,column,order):
twitter = Table('Twitter_Data',metadata,autoload=True,autoload_with = engine)
stmt = select([twitter])
if order == 'asc':
stmt = stmt.order_by(twitter.columns[column])
elif order == 'desc':
stmt = stmt.order_by(desc(twitter.columns[column]))
else:
return {'Status' : "Order should be one of 'asc' or 'desc' "}
result = conn.execute(stmt).fetchall()
if len(result) > 0:
result = show_result(result)
return result
else:
return {'Status' : 'No results found.'}
# Display tweets in specified range of dates
class date_range(Resource):
def get(self,from_date,to_date):
twitter = Table('Twitter_Data',metadata,autoload=True,autoload_with = engine)
stmt = select([twitter])
stmt = stmt.where(cast(twitter.columns.Date,String).between(from_date,to_date))
result = conn.execute(stmt).fetchall()
if len(result) > 0:
result = show_result(result)
return result
else:
return {'status' : 'No results found for the given range.'}
# Implement your own custom query
class custom_query(Resource):
def get(self,query):
result = conn.execute(query).fetchall()
if len(result) > 0:
result = show_result(result)
return result
else:
return {'status' : 'No results found for the given query.'}
# Export the twitter table data into a csv file
class export_to_csv(Resource):
def get(self,path):
stmt = 'SELECT * FROM Twitter_Data'
result = conn.execute(stmt).fetchall()
if len(result) > 0:
result = [{'Date':i[0] , 'TweetId':i[1] ,'Tweet':i[2].encode('utf-8'),
'AuthorID':i[3],'ScreenName':i[4].encode('utf-8'),
'Source': i[5].encode('utf-8'),'RetweetCount':i[6],
'FavoriteCount':i[7],'FollowerCount':i[8],
'UserURL':i[9] ,'Language' : i[10]} for i in result ]
df = pd.DataFrame(np.zeros((len(result),10)))
df.columns = ['Date', 'TweetId', 'Tweet', 'AuthorID', 'ScreenName', 'Source', 'RetweetCount', 'FavoriteCount', 'FollowerCount', 'UserURL']
for i in range(len(result)):
for j in df.columns:
df[j][i] = result[i][j]
path = path.split('-')
file = path[0] + ':/'
l = len(path)
for i in range(1,l-1):
file = file + path[i] + '/'
file = file + path[-1]
df.to_csv(file , header = True , index = False)
return {'Status' : 'The dataframe was successfully exported to a csv file.'}
# adding resources for all the classes in the REST API
api_flask.add_resource(delete_table , '/delete_table')
api_flask.add_resource(table_size , '/table_size')
api_flask.add_resource(table_name , '/table_name')
api_flask.add_resource(column_names , '/column_names')
api_flask.add_resource(store_tweets, '/store_tweets/<string:query>/<int:count>')
api_flask.add_resource(show_table_data, '/show_data')
api_flask.add_resource(filter_int_columns, '/filter_int/<string:column>/<string:operator>/<int:num>')
api_flask.add_resource(filter_string_columns, '/filter_string/<string:column>/<string:operator>/<string:text>')
api_flask.add_resource(sort, '/sort/<string:column>/<string:order>')
api_flask.add_resource(date_range, '/date_range/<string:from_date>/<string:to_date>')
api_flask.add_resource(custom_query,'/custom/<string:query>')
api_flask.add_resource(export_to_csv,'/export_csv/<string:path>')
if __name__ == '__main__':
app.run(host='0.0.0.0')
| [
"aishwaryanamballa@gmail.com"
] | aishwaryanamballa@gmail.com |
a7b8a5f71a4ce1617079c294f79021a5b598397a | a1519a7542babb21cc702a2548db05b4292b1524 | /models/base_model.py | ef5ab4045e5b23dc999367b4997c4cff56e6ec4a | [] | no_license | fabbrimatteo/VHA | d01ee2f2366a9d97d033e15084c1b875add5a05b | 95da5679f29937544ef6128d6dcd4f2a4a01dac7 | refs/heads/master | 2022-11-07T00:31:13.097395 | 2020-06-23T13:30:40 | 2020-06-23T13:30:40 | 273,720,548 | 10 | 3 | null | null | null | null | UTF-8 | Python | false | false | 1,058 | py | # -*- coding: utf-8 -*-
# ---------------------
from typing import *
import torch
from path import Path
from torch import nn
class BaseModel(nn.Module):
def __init__(self):
super().__init__()
@property
def n_param(self):
# type: (BaseModel) -> int
"""
:return: number of parameters
"""
return sum(p.numel() for p in self.parameters() if p.requires_grad)
@property
def is_cuda(self):
# type: () -> bool
"""
:return: `True` if the model is on Cuda; `False` otherwise
"""
return next(self.parameters()).is_cuda
def save_w(self, path):
# type: (Union[str, Path]) -> None
"""
save model weights in the specified path
"""
torch.save(self.state_dict(), path)
def load_w(self, path):
# type: (Union[str, Path]) -> None
"""
load model weights from the specified path
"""
self.load_state_dict(torch.load(path))
def requires_grad(self, flag):
# type: (bool) -> None
"""
:param flag: True if the model requires gradient, False otherwise
"""
for p in self.parameters():
p.requires_grad = flag
| [
"matteo.fabbri@unimore.it"
] | matteo.fabbri@unimore.it |
b27180e2c627edbd66d6a659a550743b4923a753 | 3e0bdaaabc8bd4837c37716ff45c703847601de6 | /show/views.py | 068afd583e58279f831a88508c2eb483e52ad95e | [] | no_license | komakao/junior | 69f042ab01e4f204587e2da755648d499a1e920c | 956127a1d0e5ed6fa2ae76a165c877ab1abb85e6 | refs/heads/master | 2018-11-02T06:00:22.831088 | 2018-08-27T03:20:11 | 2018-08-27T03:20:11 | 117,407,637 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 34,786 | py | # -*- coding: utf-8 -*-
from __future__ import division
from django.shortcuts import render
from show.models import ShowGroup, ShowReview, Round, ShowFile
from django.core.exceptions import ObjectDoesNotExist
from student.models import Enroll
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from show.forms import GroupForm, ShowForm, ReviewForm, ImageUploadForm, GroupShowSizeForm
from teacher.models import Classroom
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from django.http import HttpResponseRedirect
from django.utils import timezone
from django.db.models import Sum
from account.models import Profile, PointHistory, Log
from django.contrib.auth.models import User
from account.avatar import *
from django.core.exceptions import ObjectDoesNotExist
from collections import OrderedDict
from django.http import JsonResponse
from django.http import HttpResponse
import math
import cStringIO as StringIO
from PIL import Image,ImageDraw,ImageFont
from binascii import a2b_base64
import os
import StringIO
import zipfile
import xlsxwriter
from datetime import datetime
from django.utils.timezone import localtime
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from uuid import uuid4
from wsgiref.util import FileWrapper
from operator import itemgetter
def is_teacher(user, classroom_id):
return user.groups.filter(name='teacher').exists() and Classroom.objects.filter(teacher_id=user.id, id=classroom_id).exists()
# 判斷是否開啟事件記錄
def is_event_open(request):
enrolls = Enroll.objects.filter(student_id=request.user.id)
for enroll in enrolls:
classroom = Classroom.objects.get(id=enroll.classroom_id)
if classroom.event_open:
return True
return False
# 所有組別
def group(request, round_id):
show = Round.objects.get(id=round_id)
classroom_id = show.classroom_id
classroom = Classroom.objects.get(id=classroom_id)
student_groups = []
group_show_open = Classroom.objects.get(id=classroom_id).group_show_open
groups = ShowGroup.objects.filter(round_id=round_id)
try:
student_group = Enroll.objects.get(student_id=request.user.id, classroom_id=classroom_id).group_show
except ObjectDoesNotExist :
student_group = []
for group in groups:
enrolls = Enroll.objects.filter(classroom_id=classroom_id, group_show=group.id)
student_groups.append([group, enrolls, classroom.group_show_size-len(enrolls)])
#找出尚未分組的學生
def getKey(custom):
return custom.seat
enrolls = Enroll.objects.filter(classroom_id=classroom_id)
nogroup = []
for enroll in enrolls:
if enroll.group_show == 0 :
nogroup.append(enroll)
nogroup = sorted(nogroup, key=getKey)
# 記錄系統事件
if is_event_open(request) :
log = Log(user_id=request.user.id, event=u'查看創意秀組別<'+classroom.name+'>')
log.save()
return render_to_response('show/group.html', {'round_id':round_id, 'nogroup': nogroup, 'group_show_open':group_show_open, 'teacher':is_teacher(request.user, classroom_id), 'student_groups':student_groups, 'classroom_id':classroom_id, 'student_group':student_group}, context_instance=RequestContext(request))
# 新增組別
def group_add(request, round_id):
show = Round.objects.get(id=round_id)
classroom_id = show.classroom_id
classroom_name = Classroom.objects.get(id=classroom_id).name
if request.method == 'POST':
form = GroupForm(request.POST)
if form.is_valid():
group = ShowGroup(name=form.cleaned_data['name'],round_id=int(round_id))
group.save()
enrolls = Enroll.objects.filter(classroom_id=classroom_id)
for enroll in enrolls :
review = ShowReview(show_id=group.id, student_id=enroll.student_id)
review.save()
# 記錄系統事件
if is_event_open(request) :
log = Log(user_id=request.user.id, event=u'新增創意秀組別<'+group.name+'><'+classroom_name+'>')
log.save()
return redirect('/show/group/'+round_id)
else:
form = GroupForm()
return render_to_response('show/group_add.html', {'form':form}, context_instance=RequestContext(request))
# 新增創意秀
def round_add(request, classroom_id):
round = Round(classroom_id=classroom_id)
round.save()
return redirect('/show/group/'+str(round.id))
# 設定組別人數
def group_size(request, round_id):
show = Round.objects.get(id=round_id)
classroom_id = show.classroom_id
if request.method == 'POST':
form = GroupShowSizeForm(request.POST)
if form.is_valid():
classroom = Classroom.objects.get(id=classroom_id)
classroom.group_show_size = form.cleaned_data['group_show_size']
classroom.save()
# 記錄系統事
if is_event_open(request) :
log = Log(user_id=request.user.id, event=u'設定創意秀組別人數<'+classroom.name+'><'+str(form.cleaned_data['group_show_size'])+'>')
log.save()
return redirect('/show/group/'+str(classroom_id))
else:
classroom = Classroom.objects.get(id=classroom_id)
form = GroupShowSizeForm(instance=classroom)
return render_to_response('show/group_size.html', {'form':form}, context_instance=RequestContext(request))
# 加入組別
def group_enroll(request, round_id, group_id):
show = Round.objects.get(id=round_id)
classroom_id = show.classroom_id
classroom_name = Classroom.objects.get(id=classroom_id).name
group_name = ShowGroup.objects.get(id=group_id).name
enroll = Enroll.objects.filter(student_id=request.user.id, classroom_id=classroom_id)
enroll.update(group_show=group_id)
# 記錄系統事件
if is_event_open(request) :
log = Log(user_id=request.user.id, event=u'加入創意秀組別<'+group_name+'><'+classroom_name+'>')
log.save()
return redirect('/show/group/'+round_id)
# 刪除組別
def group_delete(request, group_id, round_id):
round = Round.objects.get(id=round_id)
classroom_name = Classroom.objects.get(id=round.classroom_id).name
group_name = ShowGroup(id=group_id).name
group = ShowGroup.objects.get(id=group_id)
# 記錄系統事件
if is_event_open(request) :
log = Log(user_id=request.user.id, event=u'刪除創意秀組別<'+group_name+'><'+classroom_name+'>')
log.save()
group.delete()
return redirect('/show/group/'+round_id)
# 開放選組
def group_open(request, round_id, action):
show = Round.objects.get(id=round_id)
classroom_id = show.classroom_id
classroom = Classroom.objects.get(id=classroom_id)
if action == "1":
classroom.group_show_open=True
classroom.save()
# 記錄系統事件
if is_event_open(request) :
log = Log(user_id=request.user.id, event=u'開放創意秀選組<'+classroom.name+'>')
log.save()
else :
classroom.group_show_open=False
classroom.save()
# 記錄系統事件
if is_event_open(request) :
log = Log(user_id=request.user.id, event=u'關閉創意秀選組<'+classroom.name+'>')
log.save()
return redirect('/show/group/'+round_id)
# 上傳創意秀
class ShowUpdateView(UpdateView):
#model = ShowGroup
#fields = ['name', 'title','number']
form_class = ShowForm
#template_name_suffix = '_update_form'
#success_url = "/show/group/2"
def get(self, request, **kwargs):
self.object = ShowGroup.objects.get(id=self.kwargs['group_show'])
members = Enroll.objects.filter(group_show=self.kwargs['group_show'])
form_class = self.get_form_class()
form = self.get_form(form_class)
context = self.get_context_data(object=self.object, form=form, members=members)
return self.render_to_response(context)
def get_object(self, queryset=None):
obj = ShowGroup.objects.get(id=self.kwargs['group_show'])
return obj
def form_valid(self, form):
obj = form.save(commit=False)
showfiles = []
try:
filepath = self.request.FILES['file']
except :
filepath = False
# 限制小組成員才能上傳
members = Enroll.objects.filter(group_show=self.kwargs['group_show'])
is_member = False
for member in members :
if self.request.user.id == member.student_id:
is_member = True
if is_member :
if filepath :
myfile = self.request.FILES['file']
fs = FileSystemStorage()
filename = "static/show/"+self.kwargs['group_show']+"/"+uuid4().hex+".sb2"
fs.save(filename, myfile)
obj.file = filename
#save file
showfile = ShowFile(show_id=self.kwargs['group_show'], filename=filename)
showfile.save()
#save object
obj.publish = timezone.now()
obj.done = True
obj.save()
if obj.done == False:
for member in members:
# credit
update_avatar(member.student_id, 4, 3)
# History
history = PointHistory(user_id=member.student_id, kind=4, message=u'3分--繳交創意秀<'+obj.title+'>', url='/show/detail/'+str(obj.id))
history.save()
# 記錄系統事件
if is_event_open(self.request) :
log = Log(user_id=self.request.user.id, event=u'上傳創意秀<'+obj.name+'>')
log.save()
return redirect('/show/group/'+self.kwargs['round_id'])
else :
return redirect('homepage')
# 評分
class ReviewUpdateView(UpdateView):
model = ShowReview
form_class = ReviewForm
template_name_suffix = '_review'
def get(self, request, **kwargs):
show = ShowGroup.objects.get(id=self.kwargs['show_id'])
try:
self.object = ShowReview.objects.get(show_id=self.kwargs['show_id'], student_id=self.request.user.id)
except ObjectDoesNotExist:
self.object = ShowReview(show_id=self.kwargs['show_id'], student_id=self.request.user.id)
self.object.save()
reviews = ShowReview.objects.filter(show_id=self.kwargs['show_id'], done=True)
score1 = reviews.aggregate(Sum('score1')).values()[0]
score2 = reviews.aggregate(Sum('score2')).values()[0]
score3 = reviews.aggregate(Sum('score3')).values()[0]
score = [self.object.score1, self.object.score2,self.object.score3]
if reviews.count() > 0 :
score1 = score1 / reviews.count()
score2 = score2 / reviews.count()
score3 = score3 / reviews.count()
scores = [math.ceil(score1*10)/10, math.ceil(score2*10)/10, math.ceil(score3*10)/10, reviews.count()]
else :
scores = [0,0,0,0]
members = Enroll.objects.filter(group_show=self.kwargs['show_id'])
form_class = self.get_form_class()
form = self.get_form(form_class)
showfiles = ShowFile.objects.filter(show_id=self.kwargs['show_id']).order_by("-id")
round = Round.objects.get(id=self.kwargs['round_id'])
teacher = is_teacher(self.request.user, round.classroom_id)
context = self.get_context_data(teacher=teacher, showfiles=showfiles, show=show, form=form, members=members, review=self.object, scores=scores, score=score, reviews=reviews)
return self.render_to_response(context)
def get_object(self, queryset=None):
try :
obj = ShowReview.objects.get(show_id=self.kwargs['show_id'], student_id=self.request.user.id)
except ObjectDoesNotExist:
obj = ShowReview(show_id=self.kwargs['show_id'], student_id=self.request.user.id)
obj.save()
return obj
def form_valid(self, form):
show = ShowGroup.objects.get(id=self.kwargs['show_id'])
#save object
obj = form.save(commit=False)
if obj.done == False:
round_id = ShowGroup.objects.get(id=self.kwargs['show_id']).round_id
classroom_id = Round.objects.get(id=round_id).classroom_id
member = Enroll.objects.get(classroom_id=classroom_id, student_id=self.request.user.id)
# credit
update_avatar(member.student, 4, 1)
# History
show = ShowGroup.objects.get(id=self.kwargs['show_id'])
history = PointHistory(user_id=member.student_id, kind=4, message=u'1分--評分創意秀<'+show.title+'>', url='/show/detail/'+str(show.id))
history.save()
obj.publish = timezone.now()
obj.done = True
obj.save()
# 記錄系統事件
if is_event_open(self.request) :
log = Log(user_id=self.request.user.id, event=u'評分創意秀<'+show.name+'>')
log.save()
return redirect('/show/detail/'+self.kwargs['round_id']+'/'+self.kwargs['show_id'])
# 所有同學的評分
class ReviewListView(ListView):
context_object_name = 'reviews'
template_name = 'show/reviewlist.html'
def get_queryset(self):
show = ShowGroup.objects.get(id=self.kwargs['show_id'])
# 記錄系統事件
if is_event_open(self.request) :
log = Log(user_id=self.request.user.id, event=u'查看創意秀所有評分<'+show.name+'>')
log.save()
return ShowReview.objects.filter(show_id=self.kwargs['show_id'], done=True).order_by("-publish")
def get_context_data(self, **kwargs):
ctx = super(ReviewListView, self).get_context_data(**kwargs)
try :
review = ShowReview.objects.get(show_id=self.kwargs['show_id'], student_id=self.request.user.id)
except ObjectDoesNotExist:
review = ShowReview(show_id=self.kwargs['show_id'], student_id=self.request.user.id)
review.save()
show = ShowGroup.objects.get(id=self.kwargs['show_id'])
members = Enroll.objects.filter(group_show=self.kwargs['show_id'])
reviews = ShowReview.objects.filter(show_id=self.kwargs['show_id'], done=True)
score1 = reviews.aggregate(Sum('score1')).values()[0]
score2 = reviews.aggregate(Sum('score2')).values()[0]
score3 = reviews.aggregate(Sum('score3')).values()[0]
score = [review.score1, review.score2, review.score3]
if reviews.count() > 0 :
score1 = score1 / reviews.count()
score2 = score2 / reviews.count()
score3 = score3 / reviews.count()
scores = [math.ceil(score1*10)/10, math.ceil(score2*10)/10, math.ceil(score3*10)/10, score1+score2+score3, reviews.count()]
else :
scores = [0,0,0,0]
ctx['scores'] = scores
ctx['show'] = show
ctx['members'] = members
round = Round.objects.get(id=show.round_id)
ctx['teacher'] = is_teacher(self.request.user, round.classroom_id)
return ctx
# 排行榜
class RankListView(ListView):
context_object_name = 'lists'
template_name = 'show/ranklist.html'
def get_queryset(self):
def getKey(custom):
return custom[2]
lists = []
show = Round.objects.get(id=self.kwargs['round_id'])
classroom_id = show.classroom_id
shows = ShowGroup.objects.filter(round_id=self.kwargs['round_id'])
for show in shows :
students = Enroll.objects.filter(group_show=show.id)
reviews = ShowReview.objects.filter(show_id=show.id, done=True)
if reviews.count() > 0 :
score = reviews.aggregate(Sum('score'+self.kwargs['rank_id'])).values()[0]/reviews.count()
else :
score = 0
lists.append([show, students, score, reviews.count(), self.kwargs['rank_id'], self.kwargs['round_id']])
lists= sorted(lists, key=getKey, reverse=True)
# 記錄系統事件
if is_event_open(self.request) :
log = Log(user_id=self.request.user.id, event=u'查看創意秀排行榜<'+self.kwargs['rank_id']+'>')
log.save()
return lists
def show_download(request, show_id, showfile_id):
showfile = ShowFile.objects.get(id=showfile_id)
show = ShowGroup.objects.get(id=show_id)
members = Enroll.objects.filter(group_show=show_id)
username = ""
for member in members:
username = username + member.student.first_name + "_"
filename = show_id + "_" + username + "_" + show.title + ".sb2"
download = settings.BASE_DIR + "/" + showfile.filename
wrapper = FileWrapper(file( download, "r" ))
response = HttpResponse(wrapper, content_type = 'application/force-download')
#response = HttpResponse(content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename={0}'.format(filename.encode('utf8'))
# It's usually a good idea to set the 'Content-Length' header too.
# You can also set any other required headers: Cache-Control, etc.
return response
#return render_to_response('student/download.html', {'download':download})
# 教師查看創意秀評分情況
class TeacherListView(ListView):
context_object_name = 'lists'
template_name = 'show/teacherlist.html'
def get_context_data(self, **kwargs):
context = super(TeacherListView, self).get_context_data(**kwargs)
context['round_id'] = self.kwargs['round_id']
return context
def get_queryset(self):
lists = {}
counter = 0
round = Round.objects.get(id=self.kwargs['round_id'])
classroom_id = round.classroom_id
enrolls = Enroll.objects.filter(classroom_id=classroom_id).order_by('seat')
classroom_name = Classroom.objects.get(id=classroom_id).name
for enroll in enrolls:
lists[enroll.id] = []
shows = ShowGroup.objects.filter(round_id=round.id)
if not shows.exists():
lists[enroll.id].append([enroll])
else :
for show in shows:
members = Enroll.objects.filter(group_show=show.id)
try:
review = ShowReview.objects.get(show_id=show.id, student_id=enroll.student_id)
except ObjectDoesNotExist:
review = ShowReview(show_id=show.id)
lists[enroll.id].append([enroll, review, show, members])
lists = OrderedDict(sorted(lists.items(), key=lambda x: x[1][0][0].seat))
# 記錄系統事件
if is_event_open(self.request) :
log = Log(user_id=self.request.user.id, event=u'查看創意秀評分狀況<'+classroom_name+'>')
log.save()
return lists
# 教師查看創意秀評分情況
class ScoreListView(ListView):
context_object_name = 'lists'
template_name = 'show/scorelist.html'
def get_queryset(self):
lists = {}
counter = 0
show = Round.objects.get(id=self.kwargs['round_id'])
classroom_id = show.classroom_id
enrolls = Enroll.objects.filter(classroom_id=classroom_id).order_by('seat')
classroom_name = Classroom.objects.get(id=classroom_id).name
shows = ShowGroup.objects.filter(round_id=show.id)
for showa in shows:
members = Enroll.objects.filter(group_show=showa.id)
reviews = ShowReview.objects.filter(show_id=showa.id, done=True)
score1 = reviews.aggregate(Sum('score1')).values()[0]
score2 = reviews.aggregate(Sum('score2')).values()[0]
score3 = reviews.aggregate(Sum('score3')).values()[0]
if reviews.count() > 0 :
score1 = score1 / reviews.count()
score2 = score2 / reviews.count()
score3 = score3 / reviews.count()
scores = [math.ceil(score1*10)/10, math.ceil(score2*10)/10, math.ceil(score3*10)/10, score1+score2+score3, reviews.count()]
else :
scores = [0,0,0,0]
lists[showa.id] = [showa, scores, members, self.kwargs['round_id']]
# 記錄系統事件
if is_event_open(self.request) :
log = Log(user_id=self.request.user.id, event=u'查看創意秀平均分數<'+classroom_name+'>')
log.save()
lists = OrderedDict(sorted(lists.items(), key=lambda x: x[1][1][3], reverse=True))
#lists = OrderedDict(sorted(lists.items(), key=itemgetter(1)))
return lists
# 藝廊
class GalleryListView(ListView):
context_object_name = 'lists'
paginate_by = 10
template_name = 'show/gallerylist.html'
def get_queryset(self):
# 記錄系統事件
if self.request.user.id > 0 :
log = Log(user_id=self.request.user.id, event=u'查看藝廊')
else :
log = Log(user_id=0,event=u'查看藝廊')
if is_event_open(self.request) :
log.save()
return ShowGroup.objects.filter(open=True).order_by('-publish')
# 查看藝郎某項目
def GalleryDetail(request, show_id):
show = ShowGroup.objects.get(id=show_id)
reviews = ShowReview.objects.filter(show_id=show_id, done=True)
score1 = reviews.aggregate(Sum('score1')).values()[0]
score2 = reviews.aggregate(Sum('score2')).values()[0]
score3 = reviews.aggregate(Sum('score3')).values()[0]
if reviews.count() > 0 :
score1 = score1 / reviews.count()
score2 = score2 / reviews.count()
score3 = score3 / reviews.count()
scores = [math.ceil(score1*10)/10, math.ceil(score2*10)/10, math.ceil(score3*10)/10, reviews.count()]
else :
scores = [0,0,0,0]
members = Enroll.objects.filter(group_show=show_id)
#context = self.get_context_data(show=show, form=form, members=members, review=self.object, scores=scores, score=score, reviews=reviews)
# 記錄系統事件
if request.user.id > 0 :
log = Log(user_id=request.user.id, event=u'查看藝廊<'+show.name+'>')
else :
log = Log(user_id=0, event=u'查看藝廊<'+show.name+'>')
log.save()
classroom_id = Round.objects.get(id=show.round_id).classroom_id
showfiles = ShowFile.objects.filter(show_id=show.id)
return render(request, 'show/gallerydetail.html', {'show': show, 'showfiles':showfiles, 'members':members, 'scores':scores, 'reviews':reviews, 'teacher':is_teacher(request.user, classroom_id)})
# 將創意秀開放到藝廊
def make(request):
show_id = request.POST.get('showid')
action = request.POST.get('action')
if show_id and action :
try :
show = ShowGroup.objects.get(id=show_id)
if action == 'open':
show.open = True
# 記錄系統事件
if is_event_open(request) :
log = Log(user_id=request.user.id, event=u'藝廊上架<'+show.name+'>')
log.save()
else:
show.open = False
# 記錄系統事件
if is_event_open(request) :
log = Log(user_id=request.user.id, event=u'藝廊下架<'+show.name+'>')
log.save()
show.save()
except ObjectDoesNotExist :
pass
return JsonResponse({'status':'ok'}, safe=False)
else:
return JsonResponse({'status':'ko'}, safe=False)
# 上傳 Dr Scratch 分析圖
def upload_pic(request, show_id):
m = []
if request.method == 'POST':
'''
form = ImageUploadForm(request.POST, request.FILES)
if form.is_valid():
try:
m = ShowGroup.objects.get(id=show_id)
m.picture = form.cleaned_data['image']
image_field = form.cleaned_data.get('image')
image_file = StringIO.StringIO(image_field.read())
image = Image.open(image_file)
image = image.resize((800, 600), Image.ANTIALIAS)
image_file = StringIO.StringIO()
image.save(image_file, 'JPEG', quality=90)
image_field.file = image_file
m.save()
except ObjectDoesNotExist:
pass
classroom_id = Enroll.objects.filter(student_id=request.user.id).order_by('-id')[0].classroom.id
# 記錄系統事件
log = Log(user_id=request.user.id, event='上傳Dr Scratch分析圖成功')
log.save()
return redirect('/show/detail/'+show_id)
'''
try:
dataURI = request.POST.get("screenshot")
head, data = dataURI.split(',', 1)
mime, b64 = head.split(';', 1)
mtype, fext = mime.split('/', 1)
binary_data = a2b_base64(data)
directory = 'static/show/' + show_id
image_file = "static/show/{id}/{filename}.{ext}".format(id=show_id, filename='Dr-Scratch', ext=fext)
if not os.path.exists(directory):
os.makedirs(directory)
with open(image_file, 'wb') as fd:
fd.write(binary_data)
fd.close()
m = ShowGroup.objects.get(id=show_id)
m.picture = image_file
m.save()
except ObjectDoesNotExist:
pass
classroom_id = Enroll.objects.filter(student_id=request.user.id).order_by('-id')[0].classroom.id
# 記錄系統事件
if is_event_open(request) :
log = Log(user_id=request.user.id, event='上傳Dr Scratch分析圖成功')
log.save()
round_id = ShowGroup.objects.get(id=show_id).round_id
return redirect('/show/detail/'+str(round_id)+'/'+show_id+'/#drscratch')
else :
try:
m = ShowGroup.objects.get(id=show_id)
except ObjectDoesNotExist:
pass
form = ImageUploadForm()
return render_to_response('show/drscratch.html', {'form':form, 'show': m}, context_instance=RequestContext(request))
def excel(request, round_id):
output = StringIO.StringIO()
workbook = xlsxwriter.Workbook(output)
shows = ShowGroup.objects.filter(round_id=round_id)
worksheet = workbook.add_worksheet(u"分組")
c = 0
for show in shows:
worksheet.write(c, 0, show.name)
worksheet.write(c, 1, show.title)
#worksheet.write(c, 2, "https://scratch.mit.edu/projects/"+show.number)
number = 3
members = Enroll.objects.filter(group_show=show.id)
for member in members:
worksheet.write(c, number, "("+str(member.seat)+")"+member.student.first_name)
number = number + 1
c = c + 1
for show in shows :
worksheet = workbook.add_worksheet(show.name)
worksheet.write(0,0, u"組員")
number = 1
members = Enroll.objects.filter(group_show=show.id)
for member in members:
worksheet.write(0, number, "("+str(member.seat)+")"+member.student.first_name)
number = number + 1
worksheet.write(1,0, u"作品名稱")
worksheet.write(1,1, show.title)
worksheet.write(2,0, u"上傳時間")
worksheet.write(2,1, str(localtime(show.publish)))
#worksheet.write(3,1, "https://scratch.mit.edu/projects/"+str(show.number))
worksheet.write(3,0, u"評分者")
worksheet.write(3,1, u"美工設計")
worksheet.write(3,2, u"程式難度")
worksheet.write(3,3, u"創意表現")
worksheet.write(3,4, u"評語")
worksheet.write(3,5, u"時間")
showreviews = ShowReview.objects.filter(show_id=show.id)
score1 = showreviews.aggregate(Sum('score1')).values()[0]
score2 = showreviews.aggregate(Sum('score2')).values()[0]
score3 = showreviews.aggregate(Sum('score3')).values()[0]
if showreviews.count() > 0 :
score1 = score1 / showreviews.count()
score2 = score2 / showreviews.count()
score3 = score3 / showreviews.count()
scores = [math.ceil(score1*10)/10, math.ceil(score2*10)/10, math.ceil(score3*10)/10, showreviews.count()]
else :
scores = [0,0,0,0]
worksheet.write(4,0, u"平均("+str(scores[3])+u"人)")
worksheet.write(4,1, scores[0])
worksheet.write(4,2, scores[1])
worksheet.write(4,3, scores[2])
index = 5
reviews = []
classroom_id = Round.objects.get(id=round_id).classroom_id
for showreview in showreviews:
enroll = Enroll.objects.get(classroom_id=classroom_id, student_id=showreview.student_id)
reviews.append([showreview, enroll])
def getKey(custom):
return custom[1].seat
reviews = sorted(reviews, key=getKey)
for review in reviews:
worksheet.write(index,0, "("+str(review[1].seat)+")"+review[1].student.first_name)
worksheet.write(index,1, review[0].score1)
worksheet.write(index,2, review[0].score2)
worksheet.write(index,3, review[0].score3)
worksheet.write(index,4, review[0].comment)
worksheet.write(index,5, str(localtime(review[0].publish)))
index = index + 1
worksheet.insert_image(index+1,0, 'static/show/'+str(show.id)+'/Dr-Scratch.png')
workbook.close()
# xlsx_data contains the Excel file
#response = HttpResponse(content_type='application/vnd.ms-excel')
#response['Content-Disposition'] = 'attachment; filename=Show'+str(datetime.now().date())+'.xlsx'
xlsx_data = output.getvalue()
#response.write(xlsx_data)
xls_file = "static/show/content.xlsx"
directory = 'static/show/'
if not os.path.exists(directory):
os.makedirs(directory)
with open(xls_file, 'wb') as fd:
fd.write(xlsx_data)
fd.close()
#return output
def classroom(request, classroom_id):
rounds = Round.objects.filter(classroom_id=classroom_id)
classroom = Classroom.objects.get(id=classroom_id)
return render(request, 'show/classroom.html', {'classroom':classroom, 'rounds': rounds})
def commentall(request, round_id):
round = Round.objects.get(id=round_id)
classroom = Classroom.objects.get(id=round.classroom_id)
enrolls = Enroll.objects.filter(classroom_id=round.classroom_id)
return render(request, 'show/commentall.html', {'classroom':classroom, 'round':round, 'enrolls': enrolls})
def comment(request, round_id, user_id):
classroom_id = Round.objects.get(id=round_id).classroom_id
classroom = Classroom.objects.get(id=classroom_id)
reviews = ShowReview.objects.filter(student_id=user_id)
user = User.objects.get(id=user_id)
lists = []
for review in reviews:
shows = ShowGroup.objects.filter(id=review.show_id)
for show in shows:
if review.comment != "":
lists.append([show, review, round_id])
return render(request, 'show/comment.html', {'user':user, 'classroom':classroom, 'lists': lists})
def zip(request, round_id):
# Files (local path) to put in the .zip
# FIXME: Change this (get paths from DB etc)
#filenames = [settings.BASE_DIR + "/static/certificate/sample1.jpg", settings.BASE_DIR + "/static/certificate/sample2.jpg"]
# Folder name in ZIP archive which contains the above files
# E.g [thearchive.zip]/somefiles/file2.txt
# FIXME: Set this to something better
round = Round.objects.get(id=round_id)
classroom = Classroom.objects.get(id=round.classroom_id)
zip_subdir = u"創意秀_" + classroom.name + u"班_" + round_id
zip_filename = "%s.zip" % zip_subdir
# Open StringIO to grab in-memory ZIP contents
s = StringIO.StringIO()
# The zip compressor
zf = zipfile.ZipFile(s, "w")
excelfile = excel(request, round_id)
filename = "content.xlsx"
zip_path = os.path.join(zip_subdir, filename)
fdir = settings.BASE_DIR + "/static/show/"
fname = "content.xlsx"
fpath = fdir + fname
zf.write(fpath, zip_path)
shows = ShowGroup.objects.filter(round_id=round_id)
for show in shows:
try:
showfiles = ShowFile.objects.filter(show_id=show.id).order_by("-id")
# Calculate path for file in zip
#fdir , fname = os.path.split(fpath)
if showfiles.exists():
fdir = settings.BASE_DIR + "/"
fname = showfiles[0].filename
fpath = fdir + fname
enrolls = Enroll.objects.filter(group_show=show.id)
members = ""
for enroll in enrolls:
members += enroll.student.first_name+"_"
filename = show.name + "_" + members + show.title + ".sb2"
zip_path = os.path.join(zip_subdir, filename)
# Add file, at correct path
zf.write(fpath, zip_path)
except ObjectDoesNotExist:
pass
# Must close zip for all contents to be written
zf.close()
# Grab ZIP file from in-memory, make response with correct MIME-type
resp = HttpResponse(s.getvalue(), content_type = "application/x-zip-compressed")
# ..and correct content-disposition
resp['Content-Disposition'] = 'attachment; filename={0}'.format(zip_filename.encode('utf8'))
return resp | [
"t005@mail.nksh.tp.edu.tw"
] | t005@mail.nksh.tp.edu.tw |
4cbb7136f4df01db845e675c4c192d0096913692 | 2145fc1a9b769cbf20dc2b14ea6ad1108533c69c | /src/EnginePDI2.py | edecf14b475bd387b40327f1f33daa2c9f971eee | [] | no_license | ErunamoJAZZ/Visor-Unal | c2b65810cebaded73496f12f6fe08b19f2bc4ffa | 8a2762063f883c3d2feac23d0c0846449599e6ad | refs/heads/master | 2020-05-20T06:51:05.966276 | 2011-05-25T21:11:18 | 2011-05-25T21:11:18 | 1,402,875 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,642 | py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
Created on 1/05/2011
@author: Carlos Daniel Sanchez Ramirez <ErunamoJAZZ>
@web: https://github.com/ErunamoJAZZ/Visor-Unal
'''
import wx, ImageChops, EngineGlobal
from EngineGlobal import ImgActual
#--Filtros 2
def invertir(event):
img_out= ImageChops.invert( ImgActual.img_gray )
ImgActual.padre.mostrarFiltro( EngineGlobal.pilToBitmap( img_out ) )
def init_umbral_bin(event):
global def_umbral
dlg = wx.TextEntryDialog(None, u'Introduzca el valor máximo del umbral (El otro lo puede saignar dinamicamente)',
u'Umbral Binario', '')
if dlg.ShowModal() == wx.ID_OK:
try:
dato = int(dlg.GetValue() )
if 0 > dato > 255: raise ValueError
def_umbral = lambda i, val_um1, val_um2=dato: 0 if val_um1 < i < val_um2 else 255
ImgActual.padre.mostrarFiltro( EngineGlobal.pilToBitmap( ImgActual.img_gray ), True )
except ValueError:
print(u'>> Error, introduzca un número, y Válido')
def init_umbral(event):
global def_umbral
def_umbral = lambda i, val_um: 0 if i < val_um else 255
ImgActual.padre.mostrarFiltro( EngineGlobal.pilToBitmap( ImgActual.img_gray ), True )
def umbral(valor_umbral ):
'''
recibe un valor para el umbral, y devuelve el bitmap correspondiente.
'''
img_out=ImgActual.img_gray.point(lambda i: def_umbral(i, valor_umbral) )
return EngineGlobal.pilToBitmap( img_out )
def suma(event):
dlg = wx.TextEntryDialog(None,u"Introduzca el valor a SUMAR o RESTAR [-14, por ejemplo]:",'Suma','')
if dlg.ShowModal() == wx.ID_OK:
try:
dato = int(dlg.GetValue() )
if dato > 255: raise ValueError
img_out = ImgActual.img_gray.point(lambda i: i + dato )
ImgActual.padre.mostrarFiltro( EngineGlobal.pilToBitmap( img_out ), img_out )
except ValueError:
print(u'>> Error, introduzca un número, y Válido')
def multipli(event):
dlg = wx.TextEntryDialog(None, u"Introduzca el valor a Multiplicar [2, ó 0.5 para dividir por 2]:",
u'Multiplicación', '')
if dlg.ShowModal() == wx.ID_OK:
try:
dato = float(dlg.GetValue() )
if dato > 255: raise ValueError
img_out=ImgActual.img_gray.point(lambda i: int(i * dato ) )
ImgActual.padre.mostrarFiltro( EngineGlobal.pilToBitmap( img_out ), img_out )
except ValueError:
print(u'>> Error, introduzca un número, y Válido')
| [
"anonimato1990@gmail.com"
] | anonimato1990@gmail.com |
c76c365d2833d030743e5acd1e237a6437a9dc21 | 4c05b18026076bd3652561344950f82875d60715 | /commands/wallet.py | b3d9e9badf6b34f3209aa25f727632c9cef28034 | [] | no_license | hoomji/Cryptomon | 7a6a44d8c3f6bdff589e541ddb0d671fd133cc05 | 92d4ea1bd94f97b91bd036f8cb4af1232c8969d8 | refs/heads/main | 2023-04-22T00:45:09.986460 | 2021-05-16T22:38:40 | 2021-05-16T22:38:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 601 | py |
async def wallet(message, numGraphicCards, numDogecoin, numEthereum, numBitcoin):
await message.channel.send('You have **' + str(numGraphicCards) + '** graphic cards <:graphic_card:843320481905377320>. \n\
You have **' + str(numDogecoin) + '** dogecoin <:dogecoin:843319595086905374>. \n\
You have **' + str(numEthereum) + '** ethereum <:ethereum:843319807046189057>. \n\
You have **' + str(numBitcoin) + '** bitcoin <:bitcoin:843319546165198858>.')
# THE ':cryptoName:longnumber' AND ':graphic_card:longnumber' IS FOR MY OWN SERVER CUSTOM EMOJI, SO JUST REPLACE IT WITH YOUR OWN CUSTOM EMOJI | [
"chris.lpher15@gmail.com"
] | chris.lpher15@gmail.com |
0e466f4ac716661f529c7dba7cacc70a9e2d454b | 5b9b2ec5fb3142609882a3320c6e64c6b912395c | /LeetCode/mostWaterContainer.py | b38ef468717fd38297251aa67b4e445ea5621a0e | [] | no_license | anildhaker/DailyCodingChallenge | 459ba7ba968f4394fb633d6ba8b749c1e4cb7fb0 | f1cfc52f156436dc7c0a6c43fa939cefac5cee36 | refs/heads/master | 2020-04-20T18:58:33.133225 | 2020-01-11T14:50:52 | 2020-01-11T14:50:52 | 169,036,874 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 642 | py | # Given n non-negative integers a1, a2, ..., an , where each represents a point at
# coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line
# i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a
# container, such that the container contains the most water.
def maxArea(self, height: List[int]) -> int:
i = 0
j = len(height)-1
area = 0
while i < j :
area = max(area,(j-i)*min(height[i],height[j]))
if height[i] < height[j]:
i += 1
else:
j -= 1
return area | [
"anildhaker777@gmail.com"
] | anildhaker777@gmail.com |
c2f2895427ec8379e4299bb6ab2aeb011ad52e6c | c3d6dda3406eb8b5794afcfde0fcd8f61d763a21 | /algorithm/12-maxNum_number.py | 482dda9f673141854231e29f48532084dfa83104 | [] | no_license | xixijiushui/Python_algorithm | e3dd35ecb364e65e592ecfa322e444b7c371a8bc | 5789545fec82a2edc7f6a94aa55387eb736fca42 | refs/heads/master | 2020-04-02T08:21:46.995180 | 2018-10-23T02:24:18 | 2018-10-23T02:24:18 | 154,241,793 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,644 | py | def printMaxOfnDigits(n):
'''
用字符串形式打印,防止大数
:param n:
:return:
'''
if n <= 0:
return
number = ['0'] * n
while not Increment(number):
PrintNumber(number)
def Increment(number):
# 从后往前遍历,首次+1,如果大于==10且不是第0位,则将本身做0处理,将上一位+1
# 如果第0位的值为10,则达到最大值
isOverflow = False
nTakeOver = 0
nLength = len(number)
for i in range(nLength - 1, -1, -1):
nSum = int(number[i]) + nTakeOver
if i == nLength - 1:
nSum += 1
if nSum >= 10:
if i == 0:
isOverflow = True
else:
nSum -= 10
nTakeOver = 1
number[i] = str(nSum)
else:
number[i] = str(nSum)
break
return isOverflow
def PrintNumber(number):
isBeginning = True
nLength = len(number)
for i in range(nLength):
if isBeginning and number[i] != '0':
isBeginning = False
if not isBeginning:
print(number[i], end='')
print()
# printMaxOfnDigits(3)
def Print1ToMaxOfNDigits(n):
if n <= 0:
return
number = ['0'] * n
for i in range(10):
number[0] = str(i)
Print1ToMaxOfNDigitsRecursively(number, n, 0)
def Print1ToMaxOfNDigitsRecursively(number, length, index):
if index == length - 1:
PrintNumber(number)
return
for i in range(10):
number[index + 1] = str(i)
Print1ToMaxOfNDigitsRecursively(number, length, index + 1)
Print1ToMaxOfNDigits(3) | [
"291940740@qq.com"
] | 291940740@qq.com |
d6ac249c0aeae1eca0533c3a797777ba69484826 | f99776ce9262682c3bf87c08576227545d456cba | /Principal.py | ef18a74c78fb04b196dc75325aea7d5b3514d4c3 | [] | no_license | alanperez43/EJER-integrador-unidad-2 | 6de3f23cb413e54a6ff0ab59fcd2289ad277a84e | b75acb30648f0912fcca5c32dcc6c70d0ecf687b | refs/heads/main | 2023-04-16T10:08:02.646738 | 2021-04-30T04:34:45 | 2021-04-30T04:34:45 | 363,026,619 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 459 | py | from Manejador_Integrante import Manejador_Integrante
from Manejadores_Proyecto import Manejador_Proyecto
if __name__ == "__main__":
ManejProyecto = Manejador_Proyecto()
ManejIntegrante = Manejador_Integrante()
ManejProyecto.Cargar_Archivo("proyectos.csv")
ManejIntegrante.Cargar_Archivo_Integrante("integrantesProyecto.csv")
ManejProyecto.Calcular_Puntos(ManejIntegrante)
"""SIN TERMINAR, No supe hacer el ultimo punto :(""" | [
"noreply@github.com"
] | alanperez43.noreply@github.com |
d6a3a4e4d4fb2734344f08d15a075ff36ef8792f | ec9e14cebaf5d00b73f2c25b00acab2885dbd706 | /models/keras_train.py | 1a74f92a00d93ee2e4ab623dc2e6abbd42491c1f | [
"Apache-2.0"
] | permissive | loopdigga96/quora-kaggle | d1af1e6697ab3161fae9c1028681a0ac3b4ccfba | 04883ea7052e342fd6b3ecdf8d1061f2de71fe55 | refs/heads/master | 2021-06-18T01:54:41.045297 | 2017-04-12T19:25:35 | 2017-04-12T19:25:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,028 | py |
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Input, Flatten, Dropout
from keras.layers import Conv1D, MaxPooling1D, Embedding
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss
from nltk.corpus import stopwords
import gensim, logging
import json
MAX_NUM_WORDS = 125
# In[15]:
def submit(y_pred, test, filename):
sub = pd.DataFrame()
sub = pd.DataFrame()
sub['test_id'] = test['test_id']
sub['is_duplicate'] = y_test
sub.to_csv(filename, index=False)
def save_sparse_csr(filename,array):
np.savez(filename,data = array.data ,indices=array.indices,
indptr =array.indptr, shape=array.shape )
def load_sparse_csr(filename):
loader = np.load(filename)
return csr_matrix(( loader['data'], loader['indices'], loader['indptr']),
shape = loader['shape'])
def correct_dataset(dataset):
dataset.loc[(dataset['question1'] == dataset['question2']), 'is_duplicate'] = 1
return dataset
def process_dataset(dataset, correct_dataset=False):
dataset['question1'].fillna(' ', inplace=True)
dataset['question2'].fillna(' ', inplace=True)
#delete punctuation
dataset['question1'] = dataset['question1'].str.replace('[^\w\s]','')
dataset['question2'] = dataset['question2'].str.replace('[^\w\s]','')
#lower questions
dataset['question1'] = dataset['question1'].str.lower()
dataset['question2'] = dataset['question2'].str.lower()
#union questions
dataset['union'] = pd.Series(dataset['question1']).str.cat(dataset['question2'], sep=' ')
if correct_dataset:
return correct_dataset(dataset)
else:
return dataset
def split_and_rem_stop_words(line):
cachedStopWords = stopwords.words("english")
return [word for word in line.split() if word not in cachedStopWords]
def create_word_to_vec(sentences, embedding_path, verbose=0, save=1, **params_for_w2v):
if verbose:
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
model = gensim.models.Word2Vec(sentences, **params_for_w2v)
if save:
model.save(embedding_path)
return model
def create_embeddings(sentences, embeddings_path='embeddings/embedding.npz',
verbose=0, **params):
"""
Generate embeddings from a batch of text
:param embeddings_path: where to save the embeddings
:param vocab_path: where to save the word-index map
"""
if verbose:
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
model = gensim.models.Word2Vec(sentences, **params)
weights = model.wv.syn0
np.save(open(embeddings_path, 'wb'), weights)
def load_vocab(vocab_path):
"""
Load word -> index and index -> word mappings
:param vocab_path: where the word-index map is saved
:return: word2idx, idx2word
"""
with open(vocab_path, 'r') as f:
data = json.loads(f.read())
word2idx = data
idx2word = dict([(v, k) for k, v in data.items()])
return word2idx, idx2word
def get_word2vec_embedding_layer(embeddings_path):
"""
Generate an embedding layer word2vec embeddings
:param embeddings_path: where the embeddings are saved (as a numpy file)
:return: the generated embedding layer
"""
weights = np.load(open(embeddings_path, 'rb'))
layer = Embedding(input_dim=weights.shape[0], output_dim=weights.shape[1], weights=[weights],
trainable=False)
return layer
# In[4]:
print 'Loading train'
import os.path
if os.path.isfile('dataframes/train.h5'):
train = pd.read_pickle('dataframes/train.h5')
else:
train = pd.read_csv('../datasets/train.csv')
train = process_dataset(train)
train['union_splitted'] = train['union'].apply(lambda sentence: split_and_rem_stop_words(sentence))
train.to_pickle('dataframes/train.h5')
# In[10]:
max_num_words = train['union_splitted'].map(len).max()
len_x = len(train['union_splitted'])
print 'Tokenizing'
tokenizer = Tokenizer(nb_words=MAX_NUM_WORDS, split=' ')
tokenizer.fit_on_texts(train['union'])
sequences = tokenizer.texts_to_sequences(train['union'])
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
X_train = pad_sequences(sequences, maxlen=MAX_NUM_WORDS)
y_train = train.is_duplicate.tolist()
print('Shape of data tensor:', X_train.shape)
# In[12]:
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.10)
# In[16]:
if not os.path.isfile('../embeddings/embedding.npz'):
print 'Training embeddings'
create_embeddings(sentences=train['union_splitted'], embeddings_path='../embeddings/embedding.npz', verbose=1)
print 'Loading embeddings'
weights = np.load(open('../embeddings/embedding.npz', 'rb'))
# In[13]:
embedding_layer = Embedding(input_dim=weights.shape[0], output_dim=100, weights=[weights],
input_length=max_num_words, trainable=False)
# # embedding_layer = get_word2vec_embedding_layer('embeddings/embedding.npz')
model = Sequential()
model.add(embedding_layer)
model.add(Conv1D(16, 3, activation='relu'))
# model.add(MaxPooling1D(5))
model.add(Conv1D(32, 4, activation='relu'))
model.add(MaxPooling1D(2))
model.add(Conv1D(64, 5, activation='relu'))
model.add(MaxPooling1D(4))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
# model.add(Dropout(0.5))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=128, nb_epoch=6, validation_data=(X_val, y_val))
model.save('keras_models/new_model_6_1dropout_epochs.h5')
# In[ ]:
| [
"tretyak.1996@gmail.com"
] | tretyak.1996@gmail.com |
2abe2ec9dd5f8ad8d9bbdf25bbb40f3f4c1d8867 | be8027be5e57b51b9d26beab1e895707c0d8cc57 | /assignment1/svm.py | f8ff5e5497930675a87e14bc0bf41f3c5e021db0 | [] | no_license | akashanand93/cs231n | 7f13625ef15cfc5e278506bc69fb8dd9ac52b2f2 | 2868b96d852c518d04dc4db98dbacc78ab98c4e8 | refs/heads/master | 2020-03-19T06:21:28.796248 | 2018-06-05T06:02:02 | 2018-06-05T06:02:02 | 136,012,255 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,042 | py | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 24 09:47:37 2017
@author: akash.a
"""
# Run some setup code for this notebook.
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
from __future__ import print_function
# This is a bit of magic to make matplotlib figures appear inline in the
# notebook rather than in a new window.
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
%load_ext autoreload
%autoreload 2
####################################################################################
# Load the raw CIFAR-10 data.
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# As a sanity check, we print out the size of the training and test data.
print('Training data shape: ', X_train.shape)
print('Training labels shape: ', y_train.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
####################################################################################
# Visualize some examples from the dataset.
# We show a few examples of training images from each class.
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
num_classes = len(classes)
samples_per_class = 7
for y, cls in enumerate(classes):
idxs = np.flatnonzero(y_train == y)
idxs = np.random.choice(idxs, samples_per_class, replace=False)
for i, idx in enumerate(idxs):
plt_idx = i * num_classes + y + 1
plt.subplot(samples_per_class, num_classes, plt_idx)
plt.imshow(X_train[idx].astype('uint8'))
plt.axis('off')
if i == 0:
plt.title(cls)
plt.show()
####################################################################################
# Split the data into train, val, and test sets. In addition we will
# create a small development set as a subset of the training data;
# we can use this for development so our code runs faster.
num_training = 49000
num_validation = 1000
num_test = 1000
num_dev = 500
# Our validation set will be num_validation points from the original
# training set.
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val = y_train[mask]
# Our training set will be the first num_train points from the original
# training set.
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]
# We will also make a development set, which is a small subset of
# the training set.
mask = np.random.choice(num_training, num_dev, replace=False)
X_dev = X_train[mask]
y_dev = y_train[mask]
# We use the first num_test points of the original test set as our
# test set.
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
print('Train data shape: ', X_train.shape)
print('Train labels shape: ', y_train.shape)
print('Validation data shape: ', X_val.shape)
print('Validation labels shape: ', y_val.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
###################################################################################
# Preprocessing: reshape the image data into rows
X_train = np.reshape(X_train, (X_train.shape[0], -1))
X_val = np.reshape(X_val, (X_val.shape[0], -1))
X_test = np.reshape(X_test, (X_test.shape[0], -1))
X_dev = np.reshape(X_dev, (X_dev.shape[0], -1))
# As a sanity check, print out the shapes of the data
print('Training data shape: ', X_train.shape)
print('Validation data shape: ', X_val.shape)
print('Test data shape: ', X_test.shape)
print('dev data shape: ', X_dev.shape)
###################################################################################
# Preprocessing: subtract the mean image
# first: compute the image mean based on the training data
mean_image = np.mean(X_train, axis=0)
print(mean_image[:10]) # print a few of the elements
plt.figure(figsize=(4,4))
plt.imshow(mean_image.reshape((32,32,3)).astype('uint8')) # visualize the mean image
plt.show()
###################################################################################
# second: subtract the mean image from train and test data
X_train -= mean_image
X_val -= mean_image
X_test -= mean_image
X_dev -= mean_image
###################################################################################
# third: append the bias dimension of ones (i.e. bias trick) so that our SVM
# only has to worry about optimizing a single weight matrix W.
X_train = np.hstack([X_train, np.ones((X_train.shape[0], 1))])
X_val = np.hstack([X_val, np.ones((X_val.shape[0], 1))])
X_test = np.hstack([X_test, np.ones((X_test.shape[0], 1))])
X_dev = np.hstack([X_dev, np.ones((X_dev.shape[0], 1))])
print(X_train.shape, X_val.shape, X_test.shape, X_dev.shape)
###################################################################################
# Evaluate the naive implementation of the loss we provided for you:
from cs231n.classifiers.linear_svm import svm_loss_naive
import time
# generate a random SVM weight matrix of small numbers
W = np.random.randn(3073, 10) * 0.0001
loss, grad = svm_loss_naive(W, X_dev, y_dev, 0.000005)
print('loss: %f' % (loss, ))
###################################################################################
# Once you've implemented the gradient, recompute it with the code below
# and gradient check it with the function we provided for you
# Compute the loss and its gradient at W.
loss, grad = svm_loss_naive(W, X_dev, y_dev, 0.0)
# Numerically compute the gradient along several randomly chosen dimensions, and
# compare them with your analytically computed gradient. The numbers should match
# almost exactly along all dimensions.
from cs231n.gradient_check import grad_check_sparse
f = lambda w: svm_loss_naive(w, X_dev, y_dev, 0.0)[0]
grad_numerical = grad_check_sparse(f, W, grad)
# do the gradient check once again with regularization turned on
# you didn't forget the regularization gradient did you?
loss, grad = svm_loss_naive(W, X_dev, y_dev, 5e1)
f = lambda w: svm_loss_naive(w, X_dev, y_dev, 5e1)[0]
grad_numerical = grad_check_sparse(f, W, grad)
###################################################################################
# Next implement the function svm_loss_vectorized; for now only compute the loss;
# we will implement the gradient in a moment.
tic = time.time()
loss_naive, grad_naive = svm_loss_naive(W, X_dev, y_dev, 0.000005)
toc = time.time()
print('Naive loss: %e computed in %fs' % (loss_naive, toc - tic))
from cs231n.classifiers.linear_svm import svm_loss_vectorized
tic = time.time()
loss_vectorized, _ = svm_loss_vectorized(W, X_dev, y_dev, 0.000005)
toc = time.time()
print('Vectorized loss: %e computed in %fs' % (loss_vectorized, toc - tic))
# The losses should match but your vectorized implementation should be much faster.
print('difference: %f' % (loss_naive - loss_vectorized))
###################################################################################
# Complete the implementation of svm_loss_vectorized, and compute the gradient
# of the loss function in a vectorized way.
# The naive implementation and the vectorized implementation should match, but
# the vectorized version should still be much faster.
tic = time.time()
_, grad_naive = svm_loss_naive(W, X_dev, y_dev, 0.000005)
toc = time.time()
print('Naive loss and gradient: computed in %fs' % (toc - tic))
tic = time.time()
_, grad_vectorized = svm_loss_vectorized(W, X_dev, y_dev, 0.000005)
toc = time.time()
print('Vectorized loss and gradient: computed in %fs' % (toc - tic))
# The loss is a single number, so it is easy to compare the values computed
# by the two implementations. The gradient on the other hand is a matrix, so
# we use the Frobenius norm to compare them.
difference = np.linalg.norm(grad_naive - grad_vectorized, ord='fro')
print('difference: %f' % difference)
###################################################################################
# In the file linear_classifier.py, implement SGD in the function
# LinearClassifier.train() and then run it with the code below.
from cs231n.classifiers import LinearSVM
svm = LinearSVM()
tic = time.time()
loss_hist = svm.train(X_train, y_train, learning_rate=1e-7, reg=2.5e4,
num_iters=1500, verbose=True)
toc = time.time()
print('That took %fs' % (toc - tic))
###################################################################################
# A useful debugging strategy is to plot the loss as a function of
# iteration number:
plt.plot(loss_hist)
plt.xlabel('Iteration number')
plt.ylabel('Loss value')
plt.show()
###################################################################################
# Write the LinearSVM.predict function and evaluate the performance on both the
# training and validation set
y_train_pred = svm.predict(X_train)
print('training accuracy: %f' % (np.mean(y_train == y_train_pred), ))
y_val_pred = svm.predict(X_val)
print('validation accuracy: %f' % (np.mean(y_val == y_val_pred), ))
###################################################################################
# Use the validation set to tune hyperparameters (regularization strength and
# learning rate). You should experiment with different ranges for the learning
# rates and regularization strengths; if you are careful you should be able to
# get a classification accuracy of about 0.4 on the validation set.
learning_rates = [1.5e-7, 1e-7, 0.5e-7]
regularization_strengths = [1.5e4, 2.5e4, 3.5e4]
# results is dictionary mapping tuples of the form
# (learning_rate, regularization_strength) to tuples of the form
# (training_accuracy, validation_accuracy). The accuracy is simply the fraction
# of data points that are correctly classified.
results = {}
best_val = -1 # The highest validation accuracy that we have seen so far.
best_svm = None # The LinearSVM object that achieved the highest validation rate.
################################################################################
# TODO:
for learning_rate in learning_rates:
for regularization_strength in regularization_strengths:
svm = LinearSVM()
loss_hist = svm.train(X_train, y_train, learning_rate=learning_rate,
reg=regularization_strength, num_iters=1000,
verbose=False)
y_train_pred = svm.predict(X_train)
y_val_pred = svm.predict(X_val)
train_acc = np.mean(y_train == y_train_pred)
val_acc = np.mean(y_val == y_val_pred)
results[(learning_rate, regularization_strength)] = (train_acc, val_acc)
if best_val < val_acc:
best_val = val_acc
best_svm = svm
print('Regularization strength: %e , Learning rate : %e, Val accuracy: %f' % (regularization_strength, learning_rate, val_acc))
# Print out results.
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print('lr %e reg %e train accuracy: %f val accuracy: %f' % (
lr, reg, train_accuracy, val_accuracy))
print('best validation accuracy achieved during cross-validation: %f' % best_val)
###################################################################################
# Visualize the cross-validation results
import math
x_scatter = [math.log10(x[0]) for x in results]
y_scatter = [math.log10(x[1]) for x in results]
# plot training accuracy
marker_size = 100
colors = [results[x][0] for x in results]
plt.subplot(2, 1, 1)
plt.scatter(x_scatter, y_scatter, marker_size, c=colors)
plt.colorbar()
plt.xlabel('log learning rate')
plt.ylabel('log regularization strength')
plt.title('CIFAR-10 training accuracy')
# plot validation accuracy
colors = [results[x][1] for x in results] # default size of markers is 20
plt.subplot(2, 1, 2)
plt.scatter(x_scatter, y_scatter, marker_size, c=colors)
plt.colorbar()
plt.xlabel('log learning rate')
plt.ylabel('log regularization strength')
plt.title('CIFAR-10 validation accuracy')
plt.show()
##################################################################################
# Evaluate the best svm on test set
y_test_pred = best_svm.predict(X_test)
test_accuracy = np.mean(y_test == y_test_pred)
print('linear SVM on raw pixels final test set accuracy: %f' % test_accuracy)
##################################################################################
# Visualize the learned weights for each class.
# Depending on your choice of learning rate and regularization strength, these may
# or may not be nice to look at.
w = best_svm.W[:-1,:] # strip out the bias
w = w.reshape(32, 32, 3, 10)
w_min, w_max = np.min(w), np.max(w)
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
for i in range(10):
plt.subplot(2, 5, i + 1)
# Rescale the weights to be between 0 and 255
wimg = 255.0 * (w[:, :, :, i].squeeze() - w_min) / (w_max - w_min)
plt.imshow(wimg.astype('uint8'))
plt.axis('off')
plt.title(classes[i])
| [
"akashanand.iitd@gmail.com"
] | akashanand.iitd@gmail.com |
b8a549c3b7c45307883c792948da9e84bc74ed7d | 2180f68982790f7e1c1e201b314f9bb3a3a8bb00 | /hw4/saliency_map.py | 3e873aee799357a028f3515f2bcf9f05cf07d665 | [] | no_license | jimmycsie/Artificial_Intelligence | bee8eae316b105832c6677d118967f7728b371b9 | 476d3c50d85db27127a149a2d88f7d0c03927752 | refs/heads/master | 2022-03-28T00:47:40.359850 | 2019-12-23T04:35:41 | 2019-12-23T04:35:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,559 | py | import sys, os
import csv
import numpy as np
from keras.models import load_model
import keras.backend as K
import matplotlib.pyplot as plt
import matplotlib
model = load_model('CNN.h5')
input_path = sys.argv[1] # "train.csv"
directory = sys.argv[2] # "picture/"
isget = [0]*7
sample_data = []
class_data = []
with open(file = input_path, mode = 'r', encoding = "GB18030") as csvfile:
rows = csv.reader(csvfile)
count = 0
for row in rows:
temp = []
if(count<23000):
count += 1
continue
if(isget[int(row[0])] == False):
isget[int(row[0])] = True
class_data.append(int(row[0]))
row = row[1].split(' ')
for i in range(len(row)):
row[i] = float(row[i])
sample_data.append(row)
csvfile.close()
sample_data = np.array(sample_data, dtype = float)
sample_data = np.reshape(sample_data, (7, 48, 48, 1))
target = np.zeros([7, 7], dtype = float)
for i in range(7):
target[i][class_data[i]] = 1
def compile_saliency_function(model):
inp = model.input
outp = model.output
saliency = K.gradients(K.categorical_crossentropy(target,outp), inp)[0]
return K.function([inp], [saliency])
sal = compile_saliency_function(model)([sample_data])
sal = np.reshape(sal[0], (7, 48, 48))
sample_data = np.reshape(sample_data, (7, 48, 48))
sal = np.abs(sal)
for i in range(7):
sal[i] = (sal[i] - np.mean(sal[i])) / (np.std(sal[i]) + 1e-30)
sal *= 0.1
sal = np.clip(sal, 0, 1)
for index in range(7):
#img = plt.imshow(sample_data[index])
#img.set_cmap('gray')
name = './' + directory +'original_' + str(class_data[index]) + '.jpg'
#plt.savefig(name)
plt.imsave(name, sample_data[index], cmap="gray")
#plt.clf()
heatmap = sal[index]
thres = 0.001
mask = sample_data[index]
mask[np.where(heatmap <= thres)] = np.mean(mask)
#plt.figure()
#plt.imshow(heatmap, cmap=plt.cm.jet)
#plt.colorbar()
#plt.tight_layout()
#fig = plt.gcf()
name = './' + directory + 'fig1_' + str(class_data[index]) + '.jpg' # saliency_map
#plt.savefig(name)
plt.imsave(name, heatmap, cmap=plt.cm.jet)
#plt.clf()
#plt.figure()
#plt.imshow(mask, cmap='gray')
#plt.colorbar()
#plt.tight_layout()
#fig = plt.gcf()
name = './' + directory + 'mask_original_' + str(class_data[index]) + '.jpg'
#plt.savefig(name)
#plt.imsave(name, mask)
plt.imsave(name, mask, cmap="gray")
#plt.clf()
#plt.show()
| [
"b06705057@ntu.edu.tw"
] | b06705057@ntu.edu.tw |
44ddb595fa8ac21513ee748b7c62de7f6f8ba96b | 94d5ef47d3244950a0308c754e0aa55dca6f2a0e | /migrations/versions/553c32c42187_removed_item_id_column_item_.py | 70b909a8c7a6a5a1625fc039afbe238d715c6a25 | [] | no_license | MUMT-IT/mis2018 | 9cbc7191cdc1bcd7e0c2de1e0586d8bd7b26002e | 69fabc0b16abfeba44173caa93d4f63fa79033fd | refs/heads/master | 2023-08-31T16:00:51.717449 | 2023-08-31T11:30:13 | 2023-08-31T11:30:13 | 115,810,883 | 5 | 5 | null | 2023-09-14T10:08:35 | 2017-12-30T17:06:00 | HTML | UTF-8 | Python | false | false | 1,832 | py | """removed item id column, item relationship, quantity, unit, note and status return procurement in ProcurementBorrowDetail model
Revision ID: 553c32c42187
Revises: 68a7bfa29b3a
Create Date: 2023-02-24 11:41:24.833000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '553c32c42187'
down_revision = '68a7bfa29b3a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'procurement_borrow_details_item_id_fkey', 'procurement_borrow_details', type_='foreignkey')
op.drop_column('procurement_borrow_details', 'item_id')
op.drop_column('procurement_borrow_details', 'note')
op.drop_column('procurement_borrow_details', 'status_return_procurement')
op.drop_column('procurement_borrow_details', 'unit')
op.drop_column('procurement_borrow_details', 'quantity')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('procurement_borrow_details', sa.Column('quantity', sa.INTEGER(), autoincrement=False, nullable=True))
op.add_column('procurement_borrow_details', sa.Column('unit', sa.VARCHAR(), autoincrement=False, nullable=True))
op.add_column('procurement_borrow_details', sa.Column('status_return_procurement', sa.VARCHAR(), autoincrement=False, nullable=True))
op.add_column('procurement_borrow_details', sa.Column('note', sa.TEXT(), autoincrement=False, nullable=True))
op.add_column('procurement_borrow_details', sa.Column('item_id', sa.INTEGER(), autoincrement=False, nullable=True))
op.create_foreign_key(u'procurement_borrow_details_item_id_fkey', 'procurement_borrow_details', 'procurement_details', ['item_id'], ['id'])
# ### end Alembic commands ###
| [
"91609845+AIMTYADA@users.noreply.github.com"
] | 91609845+AIMTYADA@users.noreply.github.com |
c9698f69a352b6a3843b8b47da144c699952fec5 | b6df7cda5c23cda304fcc0af1450ac3c27a224c1 | /data/codes/bluquar_cube.py | c9bc60edb49769e4a1e2ad2a9460bddc02746812 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | vieira-rafael/py-search | 88ee167fa1949414cc4f3c98d33f8ecec1ce756d | b8c6dccc58d72af35e4d4631f21178296f610b8a | refs/heads/master | 2021-01-21T04:59:36.220510 | 2016-06-20T01:45:34 | 2016-06-20T01:45:34 | 54,433,313 | 2 | 4 | null | null | null | null | UTF-8 | Python | false | false | 43,257 | py | # cube.py# Chris Barker# CMU S13 15-112 Term Project
from Tkinter import *from geometry import *import heapqimport copyimport randomimport solutionsimport mathfrom math import sin, cos, pi
class Struct(object): pass
def loadObject(path, index): with open(path) as file: try: data = file.read() except Exception as e: print 'Error reading data!', e return eval(data)[index]
def drawChevron(canvas, cx, cy, r): coords = (cx - 0.3 * r, cy - 0.5 * r, cx - 0.2 * r, cy - 0.5 * r, cx + 0.3 * r, cy, cx - 0.2 * r, cy + 0.5 * r, cx - 0.3 * r, cy + 0.5 * r, cx - 0.3 * r, cy + 0.4 * r, cx + 0.2 * r, cy, cx - 0.3 * r, cy - 0.4 * r) canvas.create_polygon(*coords, fill='white', state='disabled')
def brief(L): s = '' for e in L: s += str(e[0]) return s
def reversal(move): if type(move) == tuple: move = move[0] if type(move) == str: if "'" in move: move = move[0] else: move = move + "'" return move
def darken(color): if color[0] != '#': if color == 'white': color = '#ffffff' elif color == 'orange': color = '#ffa500' elif color == 'red': color = '#ff0000' elif color == 'blue': color = '#0000ff' elif color == 'green': color = '#00ff00' elif color == 'yellow': color = '#ffff00' else: return color return darken(color) else: red = int(color[1:3], 16) green = int(color[3:5], 16) blue = int(color[5:7], 16) red /= 2 green /= 2 blue /= 2 return '#%02x%02x%02x' % (red, green, blue)
class CenterPiece(object): def __init__(self, vec, parent): self.vec = vec self.parent = parent def callback(self, e): self.parent.addMoves([self.vec], self.PLAYING)
class Cube(object): directions = { I_HAT : 'green', -I_HAT : 'blue', J_HAT : 'red', -J_HAT : 'orange', K_HAT : 'yellow', -K_HAT : 'white'}
helpStrings = { 'general': 'Welcome to Cubr!\nHover over a button below to view help for it.\n\n\The Rubik\'s Cube, invented in 1974 by Erno Rubik, is one of the most popular toys of all time.\n\It consists of six independently rotating faces, each with nine colored stickers.\n\The goal is to arrange the cube so that each face contains only one color.\n\In 1981 David Singmaster published his popular three-layer solution method, which is used in this program.\n\With practice, most people could solve the cube in under a minute. Since then, speedcubing has taken off and the current record is held by \n\Mats Valk, who solved the cube in 5.55 seconds. In 2010, Tomas Rokicki proved that any Rubik\'s cube can be solved in 20 face rotations or less.\n\n\This program will interactively guide you through the three-layer solution algorithm.\n\At each step of the solution, you will be given information describing the step you are completing.\n\You may either work with a randomly generated Rubik\'s Cube, or use your webcam to input the current configuration of your own cube!\n\n\Many people think of solving the cube as moving the 54 stickers into place. However, it is much more helpful to think about it as\n\moving 20 "blocks" (12 edges, 8 corners) into place. The centers of each face always stay in the same orientation relative to each other,\n\and the stickers on each block always stay in place relative to each other.\n\Solving the first layer means getting four edges and four corners in place so that one face is all the same color.\n\This is intuitive for many people, but by being conscious of the algorithms you use, you can improve your time and consistency.\n\The second layer of blocks requires only one algorithm, and involves moving only four edge pieces into place.\n\The third and final layer is the most complicated, and requires separate algorithms for orienting (getting the stickers facing the right way)\n\and for permuting (getting the individual blocks into place). With enough practice, you can be an expert cube solver!\n\',
'pause': 'During a guided solution, press this button to pause your progress.', 'play': 'During a guided solution, press this button to resume solving the cube.', 'reverse': 'During a guided solution, press this button to reverse the moves made so far.', 'back': 'Press this button to step one move backward.', 'step': 'Press this button to step one move forward.', 'speedUp': 'Press this button to increase the rotation speed during a guided solution.', 'slowDown': 'Press this button to decrease the rotation speed during a guided solution.', 'fromCamera': 'Press this button to start the camera and input the configuration of your Rubik\'s cube.\n\Tip: When inputting your cube through the camera, tilt the cube up or down to reduce glare from the screen.\n\More tips: If the program misrecognizes a color, press the spacebar anyway to record the colors. Then, click on the misrecognized\n\color and select the correct color from the list of colors that will pop up. Make sure you copy the movement of the virtual cube when it\n\rotates to the next face so that your cube will be interpreted accurately.', 'guide': 'guides through solution', 'guideFast': 'guides through solution more quickly', 'reset': 'resets the cube to a solved state', 'shuffle': 'shuffles the cube', 'solve': 'solves the cube', 'info': 'reopen this screen', 'stats': 'shows statistics' }
faceColors = { }
@classmethod def setFaceColors(cls): cls.faceColors = {} for z in xrange(3): for y in xrange(3): for x in xrange(3): pieceId = z * 9 + y * 3 + x + 1 cls.faceColors[pieceId] = [ ] (X, Y, Z) = (x - 1, y - 1, z - 1) pos = Vector(X,Y,Z) for vec in [Vector(0,0,1), Vector(0,1,0), Vector(1,0,0)]: for direction in cls.directions: if direction // vec: if direction ** pos > 0: cls.faceColors[pieceId].append(cls.directions[direction]) def __init__(self, canvas, controlPane, app, mode='solved'): Cube.setFaceColors()
self.state = CubeState(mode) self.faces = { } self.size = 3 self.center = Vector(0,0,0) self.app = app
(self.PAUSED, self.PLAYING, self.REVERSING, self.STEP, self.BACK) = (1,2,3,4,5) self.status = self.PAUSED
(self.INGAME, self.SHOWINGINFO, self.SHOWINGSTATS) = range(3) self.helpState = self.SHOWINGINFO self.statString = '' self.helpIndex = 'general'
self.shuffling = False
self.delay = 100 self.direction = (0, 0) self.after = 0 self.debug = False self.message = "" self.sol = '' self.shuffleLen = 200
self.moveList = [ ] self.moveIndex = -1
self.controlPane = controlPane self.timeBetweenRotations = 0 self.timeUntilNextRotation = 0
self.rotating = False self.rotationAxis = False self.rotationDirection = False self.rotationCount = 0 self.maxRot = 5 self.rotationQueue = [ ] self.rotatingValues = [ ] self.sensitivity = 0.04 # click and drag
self.showingPB = False self.pbMin = 0 self.pbVal = 0 self.pbMax = 0
self.paused = False
self.configureControls(controlPane)
self.configureWindow(canvas) self.showInWindow()
@property def maxRot(self): return self.maxRotationCount @maxRot.setter def maxRot(self, value): self.maxRotationCount = value self.rotationDTheta = math.pi / (2. * self.maxRotationCount) @maxRot.deleter def maxRot(self): pass def configureControls(self, pane):
pane.delete(ALL)
width = int(pane.cget('width')) height = int(pane.cget('height'))
r = 24
# # PAUSE # (cx, cy) = (width/2, height/2) pauseButton = pane.create_oval(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(pauseButton, '<Button-1>', self.pause) pane.create_rectangle(cx - (r * 0.35), cy - (r * 0.5), cx - (r * 0.10), cy + (r * 0.5), fill='#ffffff', state='disabled') pane.create_rectangle(cx + (r * 0.35), cy - (r * 0.5), cx + (r * 0.10), cy + (r * 0.5), fill='#ffffff', state='disabled')
pane.tag_bind(pauseButton, '<Enter>', lambda e: self.assignHelp('pause')) pane.tag_bind(pauseButton, '<Leave>', lambda e: self.assignHelp('general'))
# # PLAY # (cx, cy) = (width/2 + r*2.4, height/2) playButton = pane.create_oval(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(playButton, '<Button-1>', self.play) pane.create_polygon(cx - r * 0.35, cy - r * 0.5, cx + r * 0.55, cy, cx - r * 0.35, cy + r * 0.5, fill='#ffffff', state='disabled') pane.tag_bind(playButton, '<Enter>', lambda e: self.assignHelp('play')) pane.tag_bind(playButton, '<Leave>', lambda e: self.assignHelp('general'))
# # REVERSE # (cx, cy) = (width/2 - r*2.4, height/2) reverseButton = pane.create_oval(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(reverseButton, '<Button-1>', self.reverse) pane.create_polygon(cx + r * 0.35, cy - r * 0.5, cx - r * 0.55, cy, cx + r * 0.35, cy + r * 0.5, fill='#ffffff', state='disabled') pane.tag_bind(reverseButton, '<Enter>', lambda e: self.assignHelp('reverse')) pane.tag_bind(reverseButton, '<Leave>', lambda e: self.assignHelp('general'))
# # SPEED UP # (cx, cy) = (width/2 + r * 10.0, height/2) speedUpButton = pane.create_rectangle(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(speedUpButton, '<Button-1>', self.speedUp) drawChevron(pane, cx, cy, r) drawChevron(pane, cx - 0.3 * r, cy, r * 0.8) drawChevron(pane, cx + 0.3 * r, cy, r * 1.2) pane.tag_bind(speedUpButton, '<Enter>', lambda e: self.assignHelp('speedUp')) pane.tag_bind(speedUpButton, '<Leave>', lambda e: self.assignHelp('general'))
# # SLOW DOWN # (cx, cy) = (width/2 + r * 7.5, height/2) slowDownButton = pane.create_rectangle(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(slowDownButton, '<Button-1>', self.slowDown) drawChevron(pane, cx - 0.3 * r, cy, r * 0.8) drawChevron(pane, cx, cy, r) pane.tag_bind(slowDownButton, '<Enter>', lambda e: self.assignHelp('slowDown')) pane.tag_bind(slowDownButton, '<Leave>', lambda e: self.assignHelp('general'))
# # SHUFFLE # (cx, cy) = (r * 1.5, height/2) shuffleButton = pane.create_oval(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(shuffleButton, '<Button-1>', self.shuffle) coords = (cx - 0.6 * r, cy - 0.4 * r, cx - 0.6 * r, cy - 0.2 * r, cx - 0.2 * r, cy - 0.2 * r, cx + 0.2 * r, cy + 0.4 * r, cx + 0.6 * r, cy + 0.4 * r, cx + 0.6 * r, cy + 0.6 * r, cx + 0.8 * r, cy + 0.3 * r, cx + 0.6 * r, cy - 0.0 * r, cx + 0.6 * r, cy + 0.2 * r, cx + 0.2 * r, cy + 0.2 * r, cx - 0.2 * r, cy - 0.4 * r, cx - 0.4 * r, cy - 0.4 * r)
pane.create_polygon(*coords, outline='#ffffff', fill='#0000ff', state='disabled')
coords = (cx - 0.6 * r, cy + 0.4 * r, cx - 0.6 * r, cy + 0.2 * r, cx - 0.2 * r, cy + 0.2 * r, cx + 0.2 * r, cy - 0.4 * r, cx + 0.6 * r, cy - 0.4 * r, cx + 0.6 * r, cy - 0.6 * r, cx + 0.8 * r, cy - 0.3 * r, cx + 0.6 * r, cy - 0.0 * r, cx + 0.6 * r, cy - 0.2 * r, cx + 0.2 * r, cy - 0.2 * r, cx - 0.2 * r, cy + 0.4 * r, cx - 0.4 * r, cy + 0.4 * r)
pane.create_polygon(*coords, outline='#ffffff', fill='#0000ff', state='disabled') pane.tag_bind(shuffleButton, '<Enter>', lambda e: self.assignHelp('shuffle')) pane.tag_bind(shuffleButton, '<Leave>', lambda e: self.assignHelp('general'))
# # SOLVE # (cx, cy) = (r * 4.0, height/2) solveButton = pane.create_oval(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(solveButton, '<Button-1>', self.solve) pane.create_text(cx, cy, text='Solve', fill='white', state='disabled') pane.tag_bind(solveButton, '<Enter>', lambda e: self.assignHelp('solve')) pane.tag_bind(solveButton, '<Leave>', lambda e: self.assignHelp('general'))
# # RESET # (cx, cy) = (r * 6.5, height/2) resetButton = pane.create_oval(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(resetButton, '<Button-1>', self.reset)
pane.create_text(cx, cy, text='Reset', fill='white', state='disabled') pane.tag_bind(resetButton, '<Enter>', lambda e: self.assignHelp('reset')) pane.tag_bind(resetButton, '<Leave>', lambda e: self.assignHelp('general'))
# # FROM CAMERA # (cx, cy) = (r * 9.0, height/2) fromcamButton = pane.create_oval(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(fromcamButton, '<Button-1>', self.fromCamera)
pane.create_text(cx, cy-12, text='From', fill='white', state='disabled') pane.create_text(cx, cy, text='Camera', fill='white', state='disabled') pane.tag_bind(fromcamButton, '<Enter>', lambda e: self.assignHelp('fromCamera')) pane.tag_bind(fromcamButton, '<Leave>', lambda e: self.assignHelp('general')) # # GUIDE # (cx, cy) = (r * 12.5, height/2) guideButton = pane.create_rectangle(cx - 2*r, cy - r, cx + 2*r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(guideButton, '<Button-1>', self.guideThrough)
pane.create_text(cx, cy-12, text='Guide Through', fill='white', state='disabled') pane.create_text(cx, cy, text='Solution', fill='white', state='disabled') pane.tag_bind(guideButton, '<Enter>', lambda e: self.assignHelp('guide')) pane.tag_bind(guideButton, '<Leave>', lambda e: self.assignHelp('general'))
# # GUIDE FASTER # (cx, cy) = (r * 17.5, height/2) guideFastButton = pane.create_rectangle(cx - 2.5*r, cy - r, cx + 2.5*r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(guideFastButton, '<Button-1>', self.guideFastThrough)
pane.create_text(cx, cy-12, text='Guide Through', fill='white', state='disabled') pane.create_text(cx, cy, text='Solution (Faster)', fill='white', state='disabled') pane.tag_bind(guideFastButton, '<Enter>', lambda e: self.assignHelp('guideFast')) pane.tag_bind(guideFastButton, '<Leave>', lambda e: self.assignHelp('general'))
# # BACK # r = 14 (cx, cy) = (width/2 - r*7.5, height/2) backButton = pane.create_oval(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(backButton, '<Button-1>', self.back) pane.create_polygon(cx + r * 0.35, cy - r * 0.5, cx - r * 0.55, cy, cx + r * 0.35, cy + r * 0.5, fill='#ffffff', state='disabled') pane.tag_bind(backButton, '<Enter>', lambda e: self.assignHelp('back')) pane.tag_bind(backButton, '<Leave>', lambda e: self.assignHelp('general'))
# # FORWARD # (cx, cy) = (width/2 + r*7.5, height/2) stepButton = pane.create_oval(cx - r, cy - r, cx + r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(stepButton, '<Button-1>', self.step) pane.create_polygon(cx - r * 0.35, cy - r * 0.5, cx + r * 0.55, cy, cx - r * 0.35, cy + r * 0.5, fill='#ffffff', state='disabled') pane.tag_bind(stepButton, '<Enter>', lambda e: self.assignHelp('step')) pane.tag_bind(stepButton, '<Leave>', lambda e: self.assignHelp('general'))
# # INFO # (cx, cy) = (width - r * 3.5, height/2) helpButton = pane.create_rectangle(cx - 2*r, cy - r, cx + 2*r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(helpButton, '<Button-1>', lambda e: self.assignHelpState(self.SHOWINGINFO))
pane.create_text(cx, cy, text='Help', fill='white', state='disabled') pane.tag_bind(helpButton, '<Enter>', lambda e: self.assignHelp('info')) pane.tag_bind(helpButton, '<Leave>', lambda e: self.assignHelp('general'))
# # STATS # (cx, cy) = (width - r * 8.0, height/2) statsButton = pane.create_rectangle(cx - 2*r, cy - r, cx + 2*r, cy + r, fill='#0088ff', activefill='#00ffff', outline='#ffffff', width=1, activewidth=3) pane.tag_bind(statsButton, '<Button-1>', self.showStats)
pane.create_text(cx, cy, text='Stats', fill='white', state='disabled') pane.tag_bind(statsButton, '<Enter>', lambda e: self.assignHelp('stats')) pane.tag_bind(statsButton, '<Leave>', lambda e: self.assignHelp('general'))
def configureWindow(self, canvas): if canvas == None: self.root = Tk() (self.width, self.height) = (450, 450) self.canvas = Canvas(self.root, width=self.width, height=self.height, background='#333333') self.needsLoop = True else: self.root = canvas._root() self.canvas = canvas (self.width, self.height) = (int(canvas.cget('width')), int(canvas.cget('height'))) self.needsLoop = False
self.dim = {'width': self.width, 'height': self.height} def speedUp(self, e): self.maxRot = max(1, self.maxRot - 1) def slowDown(self, e): self.maxRot += 1
def timer(self): needsRedraw = self.move() or (not self.status == self.PAUSED)
if self.rotating: self.rotationCount -= 1 if self.rotationCount <= 0: self.rotating = False self.rotatingValues = [ ] self.state.rotate(self.rotationItem) del self.rotationItem needsRedraw = True
if self.timeUntilNextRotation > 0: self.timeUntilNextRotation -= 1
if (not self.rotating) and (self.timeUntilNextRotation <= 0): if (self.status == self.PLAYING) or (self.status == self.STEP): if self.moveIndex >= (len(self.moveList) - 1): self.status = self.PAUSED self.updateMessage('') self.shuffling = False else: self.moveIndex += 1 needsRedraw = self.makeMove(self.moveList[self.moveIndex], animate = not self.shuffling, render = not self.shuffling or (self.moveIndex % 20 == 0))
if (self.status == self.REVERSING) or (self.status == self.BACK): if self.moveIndex < 0: self.status = self.PAUSED else: needsRedraw = self.makeMove(reversal(self.moveList[self.moveIndex])) self.moveIndex -= 1
if (self.status == self.STEP) or (self.status == self.BACK): self.status = self.PAUSED self.timeUntilNextRotation = self.timeBetweenRotations
if needsRedraw: try: self.redraw() except: self.updateMessage('Could not read cube.') self.state.setSolved() self.redraw()
def updateMessage(self, msg): self.message = msg
def updateSol(self, msg): self.sol = msg
def showInWindow(self): self.canvas.pack() self.camera = Camera(Vector(4,-6.5,-7), Vector(0,0,0), pi/5, self.dim) self.amt = self.camera.sensitivity * self.camera.pos.dist(self.camera.origin) self.redraw() if self.needsLoop: root.mainloop() def cleanup(self): for pg in self.faces.values(): self.canvas.itemconfig(pg, state='hidden')
def move(self): self.amt = self.camera.sensitivity * self.camera.pos.dist(self.camera.origin) redraw = False if self.direction != (0, 0): self.camera.rotate(self.direction) redraw = True if self.app.resized: self.app.dragVal = (0,0) self.app.resized = False redraw = True elif self.app.dragVal != (0,0): self.camera.rotate((-self.sensitivity * self.app.dragVal[0], -self.sensitivity * self.app.dragVal[1])) redraw = True self.app.dragVal = (self.app.dragVal[0] * 0.7, self.app.dragVal[1] * 0.7) if self.app.dragVal[0] < 0.01 and self.app.dragVal[1] < 0.01: self.app.dragVal = (0,0) return redraw
@staticmethod def corners(center, direction, *args): if len(args) == 0: if direction // Vector(0,1,0): # parallel norm1 = Vector(1, 0, 0) else: norm1 = Vector(0,1,0) norm2 = 2 * direction * norm1 else: (norm1, norm2) = args
corners = [ ] for coef1 in xrange(-1, 2, 2): for coef2 in xrange(coef1, -2 * coef1, -2*coef1): corner = center + (0.5 * norm1 * coef1 + 0.5 * norm2 * coef2) corners.append(corner) return corners
def pieceOffset(self, x, y, z): z -= 1 y -= 1 x -= 1 return Vector(x,y,z) def redraw(self): self.canvas.delete(ALL)
# Top message self.canvas.create_text(self.camera.width/2, 40, text=self.message, fill='white', font='Arial 24 bold')
# Bottom message sol = self.sol lineWidth = 100 margin = 15 y = self.camera.height - margin - 20 while len(sol) > 0: self.canvas.create_text(self.camera.width/2, y, text=sol[-lineWidth:], fill='white', font='Courier 12') y -= margin sol = sol[:-lineWidth]
# Progress bar if self.showingPB: w = (self.width * (self.moveIndex - self.pbMin + 1) / (max(1, self.pbMax - self.pbMin))) self.canvas.create_rectangle(0, self.height-20, w, self.height, fill='#00ff66')
toDraw = [ ]
for z in xrange(self.size): for y in xrange(self.size): for x in xrange(self.size): try: (pieceID, rotationKey) = self.state.state[z][y][x] except: pieceID = 1 rotationKey = 210
pieceCenter = self.center + self.pieceOffset(x, y, z) outDirections = [d for d in Cube.directions if d**pieceCenter > 0] sod = [ ] #sorted out directions for od in outDirections: if od // CubeState.keys[rotationKey / 100]: sod.append(od) for od in outDirections: if od // CubeState.keys[(rotationKey / 10) % 10]: sod.append(od) for od in outDirections: if od // CubeState.keys[rotationKey % 10]: sod.append(od)
pieceRotation = Vector(0,0,0) theta = 0.
if pieceID in self.rotatingValues: oldCenter = pieceCenter pieceOffset = pieceCenter - (pieceCenter > self.rotationAxis) pieceRotation = self.rotationAxis * pieceOffset theta = self.rotationDTheta * (self.maxRot - self.rotationCount)
if self.rotationDirection: theta *= -1
pieceCenter = (pieceCenter > self.rotationAxis) pieceCenter = pieceCenter + cos(theta) * pieceOffset pieceCenter = pieceCenter + sin(theta) * pieceRotation
faceColors = Cube.faceColors[pieceID] for direc, color in zip(sod, faceColors): axes = () faceCenter = pieceCenter + (direc / 2)
if pieceID in self.rotatingValues: if direc // self.rotationAxis: faceCenter = pieceCenter + (direc / 2) if self.rotationAxis // Vector(0,1,0): axis0temp = Vector(1,0,0) else: axis0temp = Vector(0,1,0) axis1temp = direc * axis0temp axis0 = axis0temp * cos(theta) + axis1temp * sin(theta) axis1 = axis0 * direc axes = (axis0, axis1) else: perp = -1 * (direc * self.rotationAxis) perp = perp ^ (direc.mag) faceCenter = pieceCenter + (sin(theta) * (perp / 2) + cos(theta) * (direc / 2)) axis0 = self.rotationAxis axis1 = (faceCenter - pieceCenter) * self.rotationAxis * 2 axes = (axis0, axis1) visible = (faceCenter - pieceCenter) ** (faceCenter - self.camera.pos) < 0 corners = self.corners(faceCenter, pieceCenter - faceCenter, *axes) corners = [corner.flatten(self.camera) for corner in corners] state = 'disabled' # if visible else 'hidden' outline = '#888888' if visible else 'gray' if not visible: color = 'gray' a = 0 if visible else 1000 spec = (corners, color, state, outline) toDraw.append(((pieceCenter-self.camera.pos).mag + a, spec)) #a = self.canvas.create_polygon(corners, fill=color, # width=2, state=state, outline='#888888' # #,activewidth=4, activefill=darken(color) # ) if self.debug: self.canvas.create_text(faceCenter.flatten(self.camera), text=str(pieceID))
#if pieceCenter.mag() == 1: # b = CenterPiece(pieceCenter, self) # self.canvas.tag_bind(a, '<Button-1>', b.callback)
""" newCorners = () for corner in corners: newCorners += corner.flatten(self.camera) if visible: self.canvas.create_polygon(self.faces[(pieceID,color)], newCorners) #self.canvas.itemconfig(self.faces[(pieceID,color)], state=state) """
toDraw.sort(lambda a,b: cmp(b,a)) for polygon in toDraw: spec = polygon[1] (corners, color, state, outline) = spec self.canvas.create_polygon(corners, fill=color, width=2, state=state, outline=outline)
self.drawHelp()
def gatherStats(self): self.statString = 'Unable to fetch solution logs.' stats = None try: with open('solutionLogs.txt') as file: stats = eval(file.read()) except: return if stats is not None: self.statString = ''
stats = [s.split(';') for s in stats]
moves = [stat[-1] for stat in stats] # Gets last element moves = [mv[6:] for mv in moves] # Remove "Moves:" moves = [int(mv) for mv in moves] if len(moves) == 0: self.statString += "No solutions generated yet." return self.statString += "%d solution%s logged.\n" % (len(moves), '' if len(moves)==1 else 's') avgMoves = sum(moves)/len(moves) self.statString += "Average number of 90 degree face rotations per solution: %d\n" % (avgMoves)
times = [stat[-2] for stat in stats] # gets 2nd to last element times = [tm[6:-4] for tm in times] # removes "Time: " ... " sec" times = [float(tm) for tm in times] avgTime = sum(times)/(max(1, len(times))) self.statString += "Average time needed to generate a solution: %0.4f seconds" % (avgTime)
def resetStats(self): try: with open('solutionLogs.txt', 'r+') as file: file.seek(0) # beginning file.truncate() file.writelines(['[]']) except: return
def showStats(self, *args): self.gatherStats() self.helpState = self.SHOWINGSTATS
def drawHelp(self): ## MAGIC NUMBERS EVERYWHERE if self.helpState == self.SHOWINGINFO: canvas = self.canvas canvas.create_rectangle(100, 100, self.width-100, self.height-100, fill='#888888', outline='#ccccff', width=4) canvas.create_rectangle(110, 110, 140, 140, fill='#880000', activefill='#aa0000') canvas.create_text(125, 125, text='X', fill='black', state='disabled')
canvas.create_rectangle(self.width/2-50, self.height-140, self.width/2+50, self.height-110, fill='#008800', activefill='#00aa00') canvas.create_text(self.width/2, self.height-125, text='Start', fill='black', state='disabled')
canvas.create_text(self.width/2, 130, text="Welcome to Cubr!", font='Arial 25 bold')
canvas.create_text(self.width/2, self.height/2, text=self.helpStrings[self.helpIndex])
elif self.helpState == self.SHOWINGSTATS: canvas = self.canvas canvas.create_rectangle(100, 100, self.width-100, self.height-100, fill='#888888', outline='#ccccff', width=4) canvas.create_rectangle(110, 110, 140, 140, fill='#880000', activefill='#aa0000') canvas.create_text(125, 125, text='X', fill='black', state='disabled')
canvas.create_rectangle(self.width/2-50, self.height-140, self.width/2+50, self.height-110, fill='#008800', activefill='#00aa00') canvas.create_text(self.width/2, self.height-125, text='Back', fill='black', state='disabled')
canvas.create_rectangle(147, self.height-130, 178, self.height-115, fill='#aaffaa', activefill='#ffffff') canvas.create_text(250, self.height-130, text="These statistics are generated dynamically.\nClick here to reset your data logs.", state='disabled')
canvas.create_text(self.width/2, self.height/2, text=self.statString, font='Arial 24 bold')
def click(self, event): if self.helpState == self.SHOWINGINFO or self.helpState == self.SHOWINGSTATS: if 110 < event.x < 140 and 110 < event.y < 140: self.helpState = self.INGAME self.redraw() elif self.width/2-50 < event.x < self.width/2+50 and \ self.height-140 < event.y < self.height-110: self.helpState = self.INGAME self.redraw() if self.helpState == self.SHOWINGSTATS: if 147 < event.x < 178 and self.height-130 < event.y < self.height-115: self.resetStats() self.showStats() self.redraw()
def assignHelp(self, key): self.helpIndex = key self.redraw()
def assignHelpState(self, state): self.helpState = state self.redraw()
def setConfig(self, config): try: self.state = CubeState('barebones')
if self.debug: print self.state
# Modify the state to include [(color, direction), (color, direction), ...] # And then parse pieceId and orientationKey out of that
def faceToAxis(face): if self.debug: print face center = face[1][1] axis = [vec for vec in Cube.directions if Cube.directions[vec].lower() == center.lower()][0] return axis
def setAxes(normal, known, dirString): dirString = dirString.lower() if dirString == 'up': up = known elif dirString == 'down': up = known * -1 elif dirString == 'left': up = (normal * known) elif dirString == 'right': up = (known * normal)
down = up * -1 left = (up * normal) right = left * -1
return (up, down, left, right)
timesTouched = [[[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0]]]
for faceInfo in config: axis = faceToAxis(faceInfo.currentFace) prevAxis = nextAxis = None if faceInfo.prevFace: prevAxis = faceToAxis(faceInfo.prevFace) if faceInfo.nextFace: nextAxis = faceToAxis(faceInfo.nextFace) prevTurn = faceInfo.prevTurn nextTurn = faceInfo.nextTurn
if self.debug: print 'axis:', axis, Cube.directions[axis] print 'prevAxis:', prevAxis, if prevAxis: print Cube.directions[prevAxis] print 'nextAxis:', nextAxis, if nextAxis: print Cube.directions[nextAxis] print 'prevTurn:', prevTurn print 'nextTurn:', nextTurn
if prevTurn: (up, down, left, right) = setAxes(axis, prevAxis, prevTurn) elif nextTurn: (up, down, left, right) = setAxes(axis, nextAxis * -1, nextTurn)
if self.debug: print 'up:', up, Cube.directions[up] print 'down:', down, Cube.directions[down] print 'left:', left, Cube.directions[left] print 'right:', right, Cube.directions[right]
for row in xrange(3): for col in xrange(3): pos = axis pos = pos + (down * (row - 1)) pos = pos + (right * (col - 1))
(x, y, z) = pos.components (x, y, z) = (int(x+1), int(y+1), int(z+1)) if self.debug: print 'x,y,z', x, y, z, print 'pos=', pos
timesTouched[z][y][x] += 1
cell = self.state.state[z][y][x] if type(cell) == list: cell.append((faceInfo.currentFace[row][col], axis))
if self.debug: print 'state=', self.state print 'times', timesTouched
# Cast each [ ] list to a ( ) tuple # [(color,dir),(color,dir),(color,dir)] ----> (pieceId, orientationKey)
reverseZ = -1 if self.camera.view ** Vector(0,0,1) < 0 else 1 reverseY = -1 if self.camera.view ** Vector(0,1,0) < 0 else 1 reverseX = -1 if self.camera.view ** Vector(1,0,0) < 0 else 1
zRange = range(3)[::reverseZ] yRange = range(3)[::reverseY] xRange = range(3)[::reverseX]
for z in zRange: for y in yRange: for x in xRange: cell = self.state.state[z][y][x] if type(cell) == list: pieceId = -1 colors = set() for i in cell: colors.add(i[0]) for key in Cube.faceColors: if set(Cube.faceColors[key]) == colors: pieceId = key break if pieceId >= 0: desiredColorOrder = Cube.faceColors[pieceId] currentOrder = [ ] ori = 0 notAdded = set([0,1,2])
cell.sort(lambda a,b: cmp(desiredColorOrder.index(a[0]), desiredColorOrder.index(b[0])))
for i in cell: ori *= 10 if i[1] // Vector(0,0,1): ori += 2 notAdded.discard(2) elif i[1] // Vector(0,1,0): ori += 1 notAdded.discard(1) elif i[1] // Vector(1,0,0): ori += 0 notAdded.discard(0)
while len(notAdded) > 0: ori *= 10 ori += notAdded.pop()
orientationKey = ori
else: raise ValueError('Invalid Cube')
if pieceId in (5, 11, 13, 14, 15, 17, 23): raise ValueError('Invalid Cube') # Center piece
desired = Cube.faceColors[CubeState.solvedState[z][y][x][0]]
if self.debug: print 'The piece with colors %s is at the position of %s' % (colors, desired) print 'setting (%d,%d,%d) to (%s, %s)' % (z,y,x,pieceId,orientationKey)
self.state.state[z][y][x] = (pieceId, orientationKey) except: self.updateMessage('Unable to read camera input.') self.state.setSolved() self.redraw() if self.debug: print 'final state=', self.state self.redraw() def addMoves(self, moves, status=-1): self.moveList[self.moveIndex+1:] = [ ] self.moveList.extend(moves) if status != -1: self.status = status
def rotate(self, axis): self.showingPB = False self.addMoves([axis], self.PLAYING)
def makeMove(self, move, render=True, animate=True): if type(move) == tuple: self.updateMessage(move[1]) axis = move[0] else: axis = move
self.rotationItem = self.state.rotationInfo(axis)
if animate: self.rotating = True
self.rotationAxis = self.rotationItem.rotationAxis self.rotatingValues = self.rotationItem.rotatingValues self.rotationDirection = self.rotationItem.rotationDirection self.rotationCount = self.maxRot
else: self.rotating = False self.state.rotate(self.rotationItem) while (self.moveIndex + 1) % 20 != 0: if self.moveIndex == len(self.moveList) - 1: self.updateMessage('') break self.moveIndex += 1 move = self.moveList[self.moveIndex] if type(move) == tuple: self.updateMessage(move[1]) axis = move[0] else: axis = move self.rotationItem = self.state.rotationInfo(axis) self.state.rotate(self.rotationItem)
return render
def pause(self, e): self.status = self.PAUSED def play(self, e): self.status = self.PLAYING def step(self, e): self.timeUntilNextRotation self.status = self.STEP def back(self, e): self.timeUntilNextRotation = 0 self.status = self.BACK def reverse(self, e): self.status = self.REVERSING def fromCamera(self, e): if not self.app.inCam: self.app.fromCamera() def reset(self, e): self.moveList = [ ] self.moveIndex = 0 self.shuffling = False self.showingPB = False self.state.setSolved() self.redraw()
def solve(self, *args): try: solution = self.getSolution() except Exception as e: import traceback, sys txt = 'Error finding solution. Make sure your cube is configured legally and was input accurately.' print 'error:', e traceback.print_exc(file=sys.stdout) self.updateMessage(txt) self.redraw() else: if not self.showingPB: self.addMoves(solution, self.PLAYING) self.showingPB = True self.pbMin = len(self.moveList) - len(solution) self.pbMax = len(self.moveList) self.updateSol('With F as Red and U as Yellow: Solution: '+brief(solution)) self.maxRot = 5 self.timeBetweenRotations = 0 self.timeUntilNextRotation = 0
def guideThrough(self, *args): if not self.showingPB: self.solve() self.maxRot = 20 self.timeBetweenRotations = 35 self.timeUntilNextRotation = 15
def guideFastThrough(self, *args): if not self.showingPB: self.solve() self.maxRot = 13 self.timeBetweenRotations = 18 self.timeUntilNextRotation = 5
def shuffle(self, *args): self.showingPB = False n = self.shuffleLen delay = 5 moves = ["U", "L", "D", "R", "F", "B", "U'", "L'", "D'", "R'", "F'", "B'" ] moveList = [(random.choice(moves), "Shuffling step %d of %d" % (i+1,n)) for i in xrange(n)] self.addMoves(moveList, self.PLAYING) self.shuffling = True self.status = self.PLAYING
def getSolution(self, method='beginner'): if method == 'beginner': solution = solutions.beginner3Layer(self.state.copy()) return solution
class CubeState(object): """Container for a 3D list representing the cube's state.Non-graphical; meant for algorithmic purposes."""
# Each element is in the form (pieceID, orientationKey) # Orientation Keys: # CORNERS # 2 == Z # 1 == Y # 0 == X # orientationKey = [first priority][second priority][third priority] # 210 = ZYX # 021 = XZY # etc.
solvedState = [[[ ( 1, 210), ( 2, 210), ( 3, 210) ], [ ( 4, 210), ( 5, 210), ( 6, 210) ], [ ( 7, 210), ( 8, 210), ( 9, 210) ]],
[[ (10, 210), (11, 210), (12, 210) ], [ (13, 210), (14, 210), (15, 210) ], [ (16, 210), (17, 210), (18, 210) ]],
[[ (19, 210), (20, 210), (21, 210) ], [ (22, 210), (23, 210), (24, 210) ], [ (25, 210), (26, 210), (27, 210) ]]]
barebones = [[[ [], [], [] ], [ [], ( 5, 210), [] ], [ [], [], [] ]],
[[ [], (11, 210), [] ], [ (13, 210), (14, 210), (15, 210) ], [ [], (17, 210), [] ]],
[[ [], [], [] ], [ [], ( 23, 210), [] ], [ [], [], [] ]]] keys = { 2: Vector(0,0,1), 1: Vector(0,1,0), 0: Vector(1,0,0)} perpendiculars = { Vector(0,0,1): [0, 1], Vector(0,1,0): [0, 2], Vector(1,0,0): [1, 2]}
movementCodes = solutions.MOVE_CODES movementKeys = { "U": Vector(0,0,1), "D": Vector(0,0,-1), "L": Vector(-1,0,0), "R": Vector(1,0,0), "F": Vector(0,1,0), "B": Vector(0,-1,0) }
def __init__(self, state='solved'): self.state = state self.size = 3 if self.state == 'solved': self.setSolved() elif self.state == 'barebones': self.setBare() def __str__(self): s = '' for z in xrange(self.size): for y in xrange(self.size): for x in xrange(self.size): item = str(self.state[z][y][x]) s += item s += '\n' s += '\n' return s
def condense(self): s = 'State:' for z in xrange(self.size): for y in xrange(self.size): for x in xrange(self.size): item = self.state[z][y][x] item2 = str(item[0]) + "'" + str(item[1]) s += item2 s += ',' s += ',' s += ',' return s
@classmethod def getPerps(cls, p): for key in cls.perpendiculars: if key // p: return cls.perpendiculars[key]
@staticmethod def kthDigit(num, k): num /= (10**k) return num % 10
@staticmethod def swapDigits(num, i, j): ithDigit = CubeState.kthDigit(num, i) num -= ithDigit * int(10**i) jthDigit = CubeState.kthDigit(num, j) num -= jthDigit * int(10**j) num += ithDigit * int(10**j) num += jthDigit * int(10**i) return num
def rotationInfo(self, axis): isNeg = False if type(axis) == str and "'" in axis: isNeg = True axis = axis[0]
if type(axis) == str: axis = CubeState.movementKeys[axis]
rotationIndcs = [ ] for x in xrange(self.size): for y in xrange(self.size): for z in xrange(self.size): pos = Vector(x-1,y-1,z-1) if pos**axis > 0 and pos == axis: rotationIndcs.append((x,y,z))
oldValues = { } for i in rotationIndcs: oldValues[i] = self.state[i[2]][i[1]][i[0]]
rot = Struct() rot.rotationAxis = axis rot.rotatingValues =[val[0] for val in oldValues.values()] rot.rotationDirection = isNeg rot.oldValues = oldValues rot.rotationIndcs = rotationIndcs return rot
def rotate(self, r):
# Vector axis of rotation
axis = r.rotationAxis isNeg = r.rotationDirection rotationIndcs = r.rotationIndcs oldValues = r.oldValues
for idx in rotationIndcs: pos = Vector(idx[0]-1, idx[1]-1, idx[2]-1) posn = pos - (pos > axis) newn = axis * posn if isNeg: newn = newn * -1. new = newn + (pos > axis)
# Alter the rotationkey (oldId, oldKey) = oldValues[idx] perps = CubeState.getPerps(axis) toSwap = [ ] for perp in perps: for i in xrange(self.size): if CubeState.kthDigit(oldKey, i) == perp: toSwap.append(i) newKey = CubeState.swapDigits(oldKey, *toSwap) newValue = (oldId, newKey)
newi = (int(new.x+1), int(new.y+1), int(new.z+1)) self.state[newi[2]][newi[1]][newi[0]] = newValue
def copy(self): return CubeState(copy.deepcopy(self.state))
def setBare(self): self.state = copy.deepcopy(CubeState.barebones)
def setSolved(self): self.state = copy.deepcopy(CubeState.solvedState) | [
"thaisnviana@gmail.com"
] | thaisnviana@gmail.com |
54d11543ee75f0af1f4f83889eae2efd752b0fbd | ba6c64c6f8d348a86c16395aaa5f8fadc6cf4386 | /python/lab4/exercice3.py | 3315c352898877e66c2fcb152bf9491422c2eacb | [] | no_license | AmalM7/DataScienceAcademy | 875f00b1909a3b9ba76e178852db7aa6e851e220 | aa3719465f9582436f511ce56ad94cdf59354dca | refs/heads/master | 2020-03-30T19:21:32.129618 | 2018-10-07T19:59:39 | 2018-10-07T19:59:39 | 151,538,683 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 274 | py | import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
x=np.linspace(0, 10*np.pi, 100)
y=np.cos(x)
y2=np.exp(-x/10)*np.cos(x)
plt.plot(x,y, 'r', x, y2, 'g')
plt.title('Cos function and cos with exponentiel')
plt.xlabel('x')
plt.ylabel('y & y2')
plt.show()
| [
"noreply@github.com"
] | AmalM7.noreply@github.com |
404a81bab69f0ff9408a716756755d82973ea033 | c0f72a4c87794df5c4c239ddfc0392f7b9295d3f | /top/api/rest/TopatsTaskDeleteRequest.py | 162b86495235cb30dd4a04ecdb6d98d9891e873b | [
"MIT"
] | permissive | chenluzhong150394/taobao-top-python3_version | c37ec2093726212b49a84598becd183b9104bd99 | 61b262c46e48504754a9427986595bce0ae0e373 | refs/heads/master | 2020-11-27T16:28:46.526318 | 2020-06-29T14:32:16 | 2020-06-29T14:32:16 | 229,528,970 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 301 | py | '''
Created by auto_sdk on 2013-06-03 16:32:57
'''
from top.api.base import RestApi
class TopatsTaskDeleteRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.task_id = None
def getapiname(self):
return 'taobao.topats.task.delete'
| [
"18438128833@163.com"
] | 18438128833@163.com |
f901db4af23a8c26750f616948c92326dd175944 | 4cdf4e243891c0aa0b99dd5ee84f09a7ed6dd8c8 | /python/decorator/6.py | 9daaa357949d9124d267fde893e0bbd950f06d36 | [
"MIT"
] | permissive | gozeon/code-collections | 464986c7765df5dca980ac5146b847416b750998 | 13f07176a6c7b6ac13586228cec4c1e2ed32cae4 | refs/heads/master | 2023-08-17T18:53:24.189958 | 2023-08-10T04:52:47 | 2023-08-10T04:52:47 | 99,432,793 | 1 | 0 | NOASSERTION | 2020-07-17T09:25:44 | 2017-08-05T15:56:53 | JavaScript | UTF-8 | Python | false | false | 310 | py | import logging
def user_logging(func):
def wrapper(*args, **kwargs):
logging.warn("%s is running" % func.__name__)
return func(*args, **kwargs)
return wrapper
@user_logging
def foo(name, age=None, height=None):
print('i am %s, age %s, height %s' % (name, age, height))
foo('haha', 12, 40)
| [
"goze.qiu@gmail.com"
] | goze.qiu@gmail.com |
72c6ba22b595645497c1256efaee42a15556634f | e27be3e6be1d68c1c4899c09d46dd15a10270ddd | /trainingData.py | 20102dc3fcd2068ed8e7718a230190cfd8b85c64 | [] | no_license | mewturn/capstone8_p16 | 3e79c160b5e74054da22f085db83553e8c09b821 | 5dd54d9275e8d1f146db8020cf52300e33c36107 | refs/heads/master | 2021-06-21T07:49:40.123947 | 2017-07-12T04:16:52 | 2017-07-12T04:16:52 | 92,831,856 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,106 | py | ## Milton Li 2017
## Capstone 8 - Project 16: Bio-waste Disposal
## Singapore University of Technology and Design
## Uses simple linear regression to determine if a pixel is green or non-green
from PIL import Image
import sys
import numpy as np
from time import sleep
from math import exp
# Requires imageAnalysis.py
from imageAnalysis import getPixelData
## totalimages: number of total images
## type: type of image -> "green" or "notgreen"
def run(totalimages, type=None):
## Output to be returned at the end
output = []
count = 0
## Gets the pixel data from the image
for i in range(1, totalimages+1):
image = type + str(i) + ".jpg"
pixels = getPixelData(image)
print("Processing image...")
## Adds it to the array of green output
for pixel in pixels:
if pixel in output:
continue
output.append(pixel)
print("Complete!")
return output
def train(trainingdata, weights, ground_truth, testingdata, test_ground_truth):
## Learning rate and the expected change to last (w(t+1) - w(t))
lr = 0.005
eps = 1e-6
## Initialize a temporary variable to check if the expected stepsize is reached
change = 1
## Sets the iteration count and the maximum iterations allowed
iteration = 0
maxitr = 10000
## Normalise the datasets w.r.t to maximum RGB value of 255
trainingdata = np.divide(trainingdata, 255.0)
testingdata = np.divide(testingdata, 255.0)
## N: the size of training data
N = len(trainingdata)
## Keep changing weights until the required step size (eps)
while change > eps:
## Initialise error and update term
error = 0
update = 0
## Keeps track of iteration number and allows us to know that the program has not hung
iteration += 1
## Modify the weights according to the classifications
for i in range(N):
## Predict f(x)
predict = activation(trainingdata[i], weights)
## Compute error for the particular x in the training data
error += (computeError(ground_truth[i], predict)) / N
## Compute gradient for the particular x in the training data w.r.t. w
update += (computeGradient(ground_truth[i], predict, trainingdata[i])) / N
## Update weights
weights -= lr * update
## Calculate norm(w(t+1) - w(t))
change = np.linalg.norm(lr * update)
## Intervals to checkpoint
if iteration % 200 == 0:
print("Iteration #", iteration, "Error:", error, "Weight:", weights)
## Check validation error with some set of testing data
#print("Validation error:", test(testingdata, weights, test_ground_truth))
## End when the expected step size is achieved (eps) or when the maximum iteration is reached
if iteration > maxitr:
print("Maximum iteration reached. Error:", error)
break
print("Algorithm terminated. Optimal weights were found with error:", error)
print("Last change", change)
return weights
def test(testingdata, weights, ground_truth):
## Initialise error
error = 0
N = len(testingdata)
for i in range(N):
predict = activation(testingdata[i], weights)
error += computeError(ground_truth[i], predict)
return error
## Activation function used to predict y from w and x
def activation(parameters, weights):
return np.dot(parameters, weights)
## We use quadratic loss function (f(x) - y)^2 with the normalisation_term being the total number of points sampled
def computeError(actual, predict):
return (actual - predict) ** 2
## We compute gradient of the error function w.r.t. w: (np.dot(w,x) - y) times x
def computeGradient(actual, predict, parameters):
return -2 * (actual - predict) * parameters
## Generates a list of ground truths comprising 1 (green) or -1 (not green)
def groundTruth(ones, negs):
truth = [1] * ones
false = [-1] * negs
return truth + false
if __name__ == "__main__":
## __images: number of images in the training set
## __output: Output list to write into, without duplicate RGB values
greenimages = 5 ## Currently up to 5
otherimages = 5 ## Currently up to 5
greenoutput = run(greenimages, "green")
otheroutput = run(otherimages, "notgreen")
## Training data set formed by merging the two lists
trainingset = np.asarray(greenoutput + otheroutput)
## Adds a weight bias term 1 to the front of each x vector
trainingset = np.insert(trainingset, 0, 1, axis=1)
## Ground truths
groundtruths = groundTruth(len(greenoutput), len(otheroutput))
# WEIGHT TRAINING
## Initialise weights to be [w(0), w(1), w(2), w(3)] = [0, 0, 0, 0]
w = np.zeros(4)
''' WEIGHTS AT DIFFERENT ITERATION NUMBERS (INTERVALS OF 2000)
## ITR 2000 -> Error: 0.29987, Weights: [0.027571, 0.10667, 1.7119, -0.15630]
## ITR 4000 -> Error: 0.24196, Weights: [0.043756, -0.34832, 2.1669, -0.55597]
## ITR 6000 -> Error: 0.21088, Weights: [0.057828, -0.70851, 2.5007, -0.81439]
## ITR 8000 -> Error: 0.19369, Weights: [0.070381, -0.99738, 2.74890, -0.97368]
## ITR 10000 -> Error: 0.18378, Weights: [0.081832, -1.2328, 2.9351, -1.0643]
'''
## WEIGHT TESTING
testingoutput = getPixelData("test_green.jpg")
## Creates an array of testing data and adds a weight bias term 1 to the front of each x vector
testingset = np.asarray(testingoutput)
testingset = np.insert(testingset, 0, 1, axis=1)
## Ground truths of test data
testgroundtruths = groundTruth(len(testingoutput), 0)
## Commence training
w = train(trainingset, w, groundtruths, testingset, testgroundtruths)
| [
"pathonice@hotmail.com"
] | pathonice@hotmail.com |
2bd22c0de567d1dbd8801755524271b751d1729a | 0fdf1ff89ca55a6b1f3f67d1c1ff5590cc6c0826 | /views.py | 96968b35baee7bba15ea70debb38f5e6a4ddd28e | [] | no_license | geminsky/simple-Student-management-system | 3b296463cf78623f2006f781915bb292c2d600b0 | 7e67fed588650ba1df01c40684eca8688d1556cd | refs/heads/master | 2020-03-24T17:38:42.578379 | 2018-08-28T06:09:51 | 2018-08-28T06:09:51 | 142,866,238 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 8,517 | py | from django.views import generic
from . import models
from . import forms
from django import urls
from django.urls import reverse_lazy
from django.shortcuts import get_object_or_404,redirect
from django.http import HttpResponseRedirect,HttpResponse
from django import http
from django.core.urlresolvers import reverse
from django.shortcuts import render
class Dashboard(generic.TemplateView):
template_name = 'loggedin.html'
class StandardDisplay(generic.TemplateView):
template_name = 'standard.html'
def get_context_data(self, **kwargs):
context=super(StandardDisplay,self).get_context_data(**kwargs)
context['datas']=models.Standard.objects.all()
return context
class DivisionDisplay(generic.TemplateView):
template_name = 'div.html'
def get_context_data(self, **kwargs):
context=super(DivisionDisplay,self).get_context_data(**kwargs)
context['divs']=models.Division.objects.all().order_by('division')
return context
class StandardAdd(generic.TemplateView):
template_name = 'addform.html'
def get_context_data(self, **kwargs):
context = super(StandardAdd, self).get_context_data(**kwargs)
context['form']=forms.StdForm
return context
def post(self,request,*args,**kwargs):
form=forms.StdForm(request.POST)
if form.is_valid():
form.save()
return http.HttpResponseRedirect(urls.reverse('newapp:standard_list'))
class AddDivision(generic.TemplateView):
template_name='add_div_form.html'
def get_context_data(self, **kwargs):
context = super(AddDivision,self).get_context_data()
context['formdiv']=forms.DivForm
return context
def post(self,request,*args,**kwargs):
formdiv=forms.DivForm(request.POST)
if formdiv.is_valid():
formdiv.save()
return http.HttpResponseRedirect(urls.reverse('newapp:div_list'))
class AddClass(generic.TemplateView):
template_name = 'add_class_form.html'
def get_context_data(self, **kwargs):
context= super(AddClass, self).get_context_data()
context['formclass']=forms.ClassForm
return context
def post(self,request,*args,**kwargs):
formclass=forms.ClassForm(request.POST)
if formclass.is_valid():
formclass.save()
return HttpResponseRedirect(urls.reverse('newapp:class_list'))
class ClassView(generic.TemplateView):
template_name = 'class_list.html'
def get_context_data(self, **kwargs):
context = super(ClassView, self).get_context_data(**kwargs)
context['classes'] = models.Classes.objects.all().order_by('classes')
return context
class AddStudent(generic.TemplateView):
template_name = 'addstudent.html'
def get_context_data(self, **kwargs):
context= super(AddStudent, self).get_context_data()
context['addstud']=forms.StudentForm
return context
def post(self,request,*args,**kwargs):
addstud=forms.StudentForm(request.POST)
if addstud.is_valid():
addstud.save()
return HttpResponseRedirect(urls.reverse('newapp:add_student'))
else:
return HttpResponse("form is not validated")
class StudentList(generic.TemplateView):
template_name = 'class_list.html'
def get_context_data(self, **kwargs):
context = super(StudentList, self).get_context_data(**kwargs)
context['student'] = models.Classes.objects.all()
return context
class StudentView(generic.TemplateView):
template_name = 'student_detail_list.html'
def get_context_data(self, **kwargs):
context = super(StudentView, self).get_context_data(**kwargs)
context['studs'] = models.Student.objects.all().order_by('classes')
return context
class ClassDetails(generic.TemplateView):
template_name = 'class_details.html'
def get_context_data(self, **kwargs):
context=super(ClassDetails,self).get_context_data(**kwargs)
context['clas']=models.Student.objects.filter(classes_id=self.kwargs.get('pk')).order_by('name')
context['tot']=models.Student.objects.filter(classes_id=self.kwargs.get('pk')).count()
context['girls']=models.Student.objects.filter(classes_id=self.kwargs.get('pk')).filter(gender='female').count()
context['boys']=models.Student.objects.filter(classes_id=self.kwargs.get('pk')).filter(gender='male').count()
print(context)
return context
class StudentDetails(generic.TemplateView):
template_name = 'student_detail.html'
def get_context_data(self, **kwargs):
context=super(StudentDetails,self).get_context_data(**kwargs)
context['stud']=models.Student.objects.filter(id=self.kwargs.get('pk'))
return context
def DeleteStudent(request, pk):
j = get_object_or_404(models.Student, id=pk)
j.delete()
return redirect('newapp:student_details')
class EditStudent(generic.UpdateView):
model = models.Student
form_class = forms.StudentForm
template_name = 'edit_student.html'
def get_success_url(self):
return reverse('newapp:student_details')
class AddFee(generic.TemplateView):
template_name = 'add_fee_form.html'
def get_context_data(self, **kwargs):
context = super(AddFee, self).get_context_data()
context['formfee'] = forms.FeeForm
return context
def post(self, request, *args, **kwargs):
formfee = forms.FeeForm(request.POST)
if formfee.is_valid():
formfee.save()
return HttpResponseRedirect(urls.reverse('newapp:class_list'))
class FeeList(generic.TemplateView):
template_name = 'fee_list.html'
def get_context_data(self, **kwargs):
context=super(FeeList,self).get_context_data(**kwargs)
context['clas']=models.Fee.objects.filter(classes_id=self.kwargs.get('pk'))
return context
class PayFees(generic.TemplateView):
template_name = 'pay_fees.html'
model = models.FeeDetails
def get_context_data(self, **kwargs):
context = super(PayFees,self).get_context_data(**kwargs)
context['form'] = forms.PayForm(classes_id=self.kwargs.get('pk'))
return context
def post(self, request,pk):
#fee=get_object_or_404(models.FeeDetails,classes_id=pk)
if request.method=="POST":
print(request.POST)
ids = models.Fee.objects.filter(classes_id=self.kwargs.get('pk'))
i=list(ids)
length=len(i)
for j in i:
f = models.FeeDetails.objects.create(name_id=request.POST.get('name'),fee_type_id=j.id, fee_amt=request.POST.get(j.fee_type),classes_id=request.POST.get('classes'))
f.save()
return HttpResponseRedirect(reverse('newapp:class_list'))
class FeeDisplay(generic.TemplateView):
template_name = 'fee_display.html'
def get_context_data(self, **kwargs):
context=super(FeeDisplay,self).get_context_data(**kwargs)
context['clas']=models.FeeDetails.objects.filter(classes_id=self.kwargs.get('pk')).distinct()
return context
# class AddFee(generic.TemplateView):
# template_name = 'add_fee_form.html'
# def get_context_data(self, **kwargs):
# context= super(AddFee, self).get_context_data()
# context['formfee']=forms.FeeForm
# return context
#
# def post(self,request,*args,**kwargs):
# formfee=forms.FeeForm(request.POST)
# if formfee.is_valid():
# formfee.save()
# return HttpResponseRedirect(urls.reverse('newapp:fee_list'))
#
# class FeeList(generic.TemplateView):
# template_name = 'fee_list.html'
# def get_context_data(self, **kwargs):
# context = super(FeeList, self).get_context_data(**kwargs)
# context['fees'] = models.Fees.objects.all()
# return context
#
#
# class PayFee(generic.UpdateView):
#
# model = models.Student
# form_class = forms.PayForm
# template_name = 'payform.html'
#
#
# def get_success_url(self):
# return reverse('newapp:student_details')
#
#
# def Search(request):
# query = request.GET.get('q')
# if query:
# # There was a query entered.
# results = models.Student.objects.filter(name=query)
# else:
# # If no query was entered, simply return all objects
# results = models.Student.objects.all()
# return render(request, 'loggedin.html', {'results': results})
| [
"noreply@github.com"
] | geminsky.noreply@github.com |
edde83793cbbb6f5ecd213edbf7171025f7c5995 | f603b0edb36f3578b99c49aea68c09acb222b5e2 | /exercicios/Curso_Udemy_Python/sec3_aula58.py | 6506bd25d840427c70745b94680fc8c9fb54c13b | [
"MIT"
] | permissive | igobarros/maratona-data-science-brasil | 260d8160a356dfdf5876cfef03a0aacc7f20340e | cc07476579134a2764f00d229d415657555dcdd1 | refs/heads/master | 2021-10-09T23:33:25.278361 | 2019-01-04T15:08:43 | 2019-01-04T15:08:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 292 | py |
class MyList(list):
def append(self, *args):
self.extend(args)
m = MyList()
m.append(0)
m.append(1,2,3,4,5,6)
print(m)
class MyList1(list):
def sort(self):
return 'eae vey? ta afim de ordenar?'
l = [4,1,78,34,4,9]
'''l.sort()
print(l)'''
lista = MyList1()
print(lista.sort())
| [
"igorestacioceut@gmail.com"
] | igorestacioceut@gmail.com |
d601062928f2c0c729a3a3eebf2c8f75763a9cb1 | 24a82d0870568d483d2662dbe10cca64e4fa1d5c | /cpo/tests/test_monitor.py | 17475aac2147164de76ccb9e3e2673767983d954 | [
"MIT"
] | permissive | worc3131/CPO | f62ad7e5ff8fd160f0343f4e7ad33e7a12e84e14 | de738f18188566327c407bd34f0683d827b5d5d5 | refs/heads/master | 2023-01-29T17:23:09.747953 | 2020-12-11T12:00:55 | 2020-12-11T12:00:55 | 312,937,633 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 59 | py |
from cpo import *
def test_monitor_init():
Monitor()
| [
"web.gwh@gmail.com"
] | web.gwh@gmail.com |
62e2d967a282ac5680b4914b1029424289056226 | b13a2f7fd32446e2f6ba9a0c0fffd11a413de07e | /models.py | 66f4050e234222e63fbd79163e8257df39c57dde | [] | no_license | zeehjr/peewee-example | 2c009e5734c6ba4cb155301530ee0493a7254d15 | c1f42247a94085e613b9033098f110c1dab3c363 | refs/heads/master | 2023-03-21T13:27:10.757741 | 2021-03-20T02:58:19 | 2021-03-20T02:58:19 | 349,611,738 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 329 | py | from peewee import *
db = PostgresqlDatabase('hello', user='postgres',
password='postgres', host='localhost', port=5455)
class Person(Model):
name = CharField()
birthday = DateField()
address = CharField()
class Meta:
database = db # This model uses the "people.db" database.
| [
"zeehtecnologia@gmail.com"
] | zeehtecnologia@gmail.com |
873a1fe78becceec2ced01f6cd9255e19f8656f0 | 7044b8b5fbc27b9fe92e342b22bbc5948d4635a9 | /busan.py | 24e1ba5f97b4330aeddf3c43600f2efcc58add20 | [] | no_license | dannykbsoul/Train-To-Busan-Text | effcf375bade97a426c126ecc5721df61af069e5 | e2e7650d98e30f8758ce2265b0e01063c13c83a4 | refs/heads/master | 2021-09-08T10:54:46.953212 | 2018-03-09T10:36:34 | 2018-03-09T10:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,838 | py | import os,sys
import jieba, codecs, math
import jieba.posseg as pseg
names = {} #姓名字典
relationships = {} #关系字典
lineNames = [] #每段内人物关系
jieba.load_userdict("dict.txt") #加载字典
with codecs.open("busan.txt","r","utf8") as f:
for line in f.readlines():#读取文件所有东西,每行作为列表的一个元素
poss = pseg.cut(line)#分词并返回该词词性
lineNames.append([])#为新读入的一段添加人物名称列表
for w in poss:
if w.flag != "nr" or len(w.word)<2:
continue
#当分词长度小于2或该词词性不为nr时认为该词不为人名
lineNames[-1].append(w.word)
#为当段的环境增加一个人物
if names.get(w.word) is None:
names[w.word] = 0
relationships[w.word] = {}
names[w.word]+=1
#该人物出现次数加1
for name, times in names.items():
print(name, times)
print(relationships)
print(lineNames)
for line in lineNames:
for name1 in line:
for name2 in line:
if name1 == name2:
continue
if relationships[name1].get(name2) is None:
relationships[name1][name2]= 1
else:
relationships[name1][name2] = relationships[name1][name2]+1
print(relationships)
with codecs.open("busan_node.txt", "w", "gbk") as f:
f.write("Id Label Weight\r\n")
for name, times in names.items():
f.write(name + " " +name+" "+str(times)+"\r\n")
with codecs.open("busan_edge.txt","w","gbk") as f:
f.write("Source Target Weight\r\n")
for name, edges in relationships.items():
for v, w in edges.items():
if w>3:
f.write(name+" "+v+" "+str(w)+"\r\n")
| [
"noreply@github.com"
] | dannykbsoul.noreply@github.com |
de91906e8d58d1f166cf343956e0f9b9d933f43d | 8678ab710d9b898d62ac46e189317fb8b19e57a8 | /models/attentive.py | 71c0e84c0ea325cb55dfa3294e4af3b1bf9de926 | [] | no_license | bdura/attentive-eligibility | 7efbd84912d3f62a43ea47f54a34d4b2a5290ebe | 42b23d35516b93ea0134a579f97107e0dba6def4 | refs/heads/master | 2020-04-30T23:17:22.194066 | 2019-09-03T22:50:23 | 2019-09-03T22:50:23 | 177,140,255 | 0 | 1 | null | 2019-08-23T21:20:36 | 2019-03-22T12:56:33 | Jupyter Notebook | UTF-8 | Python | false | false | 1,514 | py | from torch import nn
import math
import torch
class Attentive(nn.Module):
def __init__(self, input_dim, hidden_dimensions=(64, 64, 64, 64), memory_size=256, memory_dimension=32, key_dimension=16, output_dim=2):
super(Attentive, self).__init__()
self.memory = nn.Parameter(torch.randn(memory_size, memory_dimension))
dims = [input_dim] + list(hidden_dimensions)
self.mlp = nn.Sequential(*[
nn.Sequential(
nn.Linear(d1, d2),
nn.ReLU()
)
for d1, d2 in zip(dims[:-1], dims[1:])
])
self.memory2key = nn.Linear(memory_dimension, key_dimension)
self.hidden2query = nn.Linear(hidden_dimensions[-1], key_dimension)
self.softmax = nn.Softmax(dim=2)
self.d = key_dimension
self.hidden2value = nn.Linear(hidden_dimensions[-1], memory_dimension)
self.output_layer = nn.Linear(memory_dimension, output_dim)
def forward(self, x):
h = self.mlp(x)
x = self.hidden2value(h)
q = self.hidden2query(h)
k = self.memory2key(self.memory)
if len(q.size()) == 2:
q = q.unsqueeze(0)
k = k.unsqueeze(0)
v = self.memory.unsqueeze(0)
else:
v = self.memory
z = torch.bmm(q, k.transpose(1, 2)) / math.sqrt(self.d)
s = torch.bmm(self.softmax(z), v)
s = s.squeeze(0)
x = x + s.detach()
x = self.output_layer(x)
return x
| [
"basile.dura@polytechnique.edu"
] | basile.dura@polytechnique.edu |
57b0f2d60e3bfda979abf47e6ea2d40de7d2e825 | a8d4602b1416d4f14c256b41fd004d605d57b6ed | /python/license_manage.py | 1a64aecee37422513f9e8d9f8a4e62c610be68d1 | [] | no_license | barnesry/junos-scripts | bc83486af8c50d27c4e16c5e47223053c3bc4626 | b698d3f318dede7e2366d2e5d9e9ae1aea749fa6 | refs/heads/master | 2023-02-05T10:18:43.452464 | 2023-02-01T17:43:36 | 2023-02-01T17:44:37 | 47,650,581 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,245 | py | #! /usr/bin/python
# Retreive arbitrary information from remote devices using NETCONF RPC calls
import sys
import argparse
from jnpr.junos.utils.config import Config
from jnpr.junos.exception import *
from jnpr.junos import Device
from pprint import pprint as pp
from lxml import etree
def getArguments():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--target", dest="target", help="ip_address to connect to", required=True)
parser.add_argument("-u", "--user", dest="user", help="username to connect", required=True)
parser.add_argument("-p", "--password", dest="password", help="password to connect", required=True)
parser.add_argument("-c", "--command", dest="rpcCommand", help="rpc request to send to target in quotes", required=True)
return parser.parse_args()
#pp(args.target)
def connectDevice(dev):
print("Attempting to open a connection to {0}...".format(dev.hostname)),
try:
dev.open()
print "Success!"
except Exception as err:
print "Cannot connect to device:", err
def lockConfig(dev):
print "Locking the configuration...",
try:
dev.cu.lock()
print "Success!"
except LockError:
print "Error: Unable to lock configuration"
dev.close()
def unlockConfig(dev):
print "Unlocking the configuration...",
try:
dev.cu.unlock()
print "Success!"
except UnlockError:
print "Error: Unable to unlock configuration"
dev.close()
def loadConfig(dev, configfile):
print "Loading configuration changes...",
try:
dev.cu.load(path=configfile, merge=True)
print "Success!"
except ValueError as err:
print "Uh Oh, something went wrong.", err.message
except Exception as err:
if err.cmd.find('.//ok') is None:
rpc_msg = err.rsp.findtext('.//error-message')
print "Unable to load configuration changes: ", rpc_msg
# since we failed to apply the config we need to unlock it
unlockConfig(dev)
def main():
usage = "Usage: %prog -t <target_IP> -u <username> -p <password>"
# get our args from the commandline
args = getArguments()
# construct our Device object
dev = Device(user=args.user, host=args.target, password=args.password)
# Open a connection
connectDevice(dev)
# Bind Config instance to Device instance
# dev.bind( cu=Config )
# Lock the configuration
# lockConfig(dev)
# Check our diffs
#print "Displaying Diffs..."
#dev.cu.pdiff()
#invoke the RPC equivalent to "show version"
sw = dev.rpc.get_software_information()
print(etree.tostring(sw))
# get interface info
#interfaces = dev.rpc.get_interface_information(terse=True)
# get license info
license = dev.rpc.get_license_summary_information()
licese_key = dev.rpc.get_license_key_information()
print(etree.tostring(license))
print(etree.tostring(licese_key))
# will save a rescue config, but complain about it
# result = dev.cli(command="request system configuration rescue save")
# unlock the config
# unlockConfig(dev)
# executes only if not called as a module
if __name__ == "__main__":
main()
| [
"barnesry@gmail.com"
] | barnesry@gmail.com |
ec46ebcaaa624f2ac7abf272df486a27cd2075fe | b25055503a8f0de13b4f7aece4f6cf1ba5c9d3ab | /tests/fixtures.py | 03ad2db59c5325385cda821694184a7a51d8a6c9 | [
"MIT"
] | permissive | mkturkcan/autobahn-sync | a340eb9f32c331a9b4331f0a1701e18ef78e3d9e | 2663520c032912c0769647de8fc5e47d9234cf07 | refs/heads/master | 2020-03-19T12:41:23.387271 | 2018-06-12T16:54:30 | 2018-06-12T16:54:30 | 136,533,456 | 0 | 0 | null | 2018-06-07T21:34:46 | 2018-06-07T21:34:46 | null | UTF-8 | Python | false | false | 1,294 | py | from os import path
from time import sleep
import subprocess
import pytest
from autobahn_sync import AutobahnSync, ConnectionRefusedError
CROSSBAR_CONF_DIR = path.abspath(path.dirname(__file__)) + '/.crossbar'
START_CROSSBAR = not pytest.config.getoption("--no-router")
@pytest.fixture(scope="module")
def crossbar(request):
if START_CROSSBAR:
# Start a wamp router
subprocess.Popen(["crossbar", "start", "--cbdir", CROSSBAR_CONF_DIR])
started = False
for _ in range(20):
sleep(0.5)
# Try to engage a wamp connection with crossbar to make sure it is started
try:
test_app = AutobahnSync()
test_app.run()
# test_app.session.disconnect() # TODO: fix me
except ConnectionRefusedError:
continue
else:
started = True
break
if not started:
raise RuntimeError("Couldn't connect to crossbar router")
def finalizer():
p = subprocess.Popen(["crossbar", "stop", "--cbdir", CROSSBAR_CONF_DIR])
p.wait()
if START_CROSSBAR:
request.addfinalizer(finalizer)
@pytest.fixture
def wamp(crossbar):
wamp = AutobahnSync()
wamp.run()
return wamp
@pytest.fixture
def wamp2(crossbar):
return wamp(crossbar)
| [
"emmanuel.leblond@gmail.com"
] | emmanuel.leblond@gmail.com |
975f89e11fb627f2f539de6588f134c33750d365 | bdc86421fea4d5cc7b15dea0911460d487803d52 | /NB/NB_data.py | 261c59c9c44837c69f4e1144b28acff13f9922d5 | [] | no_license | cherria96/BEST | a28506e16f2a2f2935078d0ffda93ed09dd9c539 | 8bd98dcb9f581c1169f36e7015b01f0844a9d22e | refs/heads/main | 2023-07-05T09:39:27.434773 | 2021-08-26T13:46:53 | 2021-08-26T13:46:53 | 315,267,655 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,683 | py | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 17:19:08 2020
@author: sujin
"""
import pandas as pd
#import data
filename = 'NB_data.xlsx'
data = pd.read_excel(filename, index_col = 0, na_values= ['',' - ',0])
data = data.T
data.dropna(how = 'all', inplace=True)
data = data.fillna(0)
#feautres, labels
labels = data[['substrate']]
features = data.drop('substrate', axis = 1)
#encoding
from sklearn.preprocessing import StandardScaler
#train test data split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(features,labels, test_size = 0.2)
#Standard Scaler
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
#NB model
from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
#validation & evaluation
from sklearn.model_selection import cross_val_score, cross_val_predict
print("\n**cross validation score**\n", cross_val_score(clf, X_train, y_train, cv = 3, scoring = 'accuracy'))
from sklearn.metrics import plot_confusion_matrix, classification_report
y_train_pred = cross_val_predict(clf, X_train, y_train, cv = 3)
report = classification_report(y_train, y_train_pred)
print("\n**classification report**\n", report)
report_test = classification_report(y_test, y_pred)
print("\n**classification report**\n", report_test)
import matplotlib.pyplot as plt
plt.figure(1)
plot_confusion_matrix(clf, X_train, y_train)
plt.title("train data")
plt.figure(2)
plot_confusion_matrix(clf, X_test, y_test)
plt.title("test data")
plt.show()
plt.clf()
| [
"sujineeda@postech.ac.kr"
] | sujineeda@postech.ac.kr |
80a876d02aa0d4d1c1a901b0311bd3e3900c7ef4 | 7623386df02a52145b174700621fa70973e81d0e | /shakecastaebm/validation/generate.py | 7925da9b8f3a495b9c6fce24a65e5ca2affc39d0 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain-disclaimer"
] | permissive | dslosky-usgs/shakecast-aebm | f641f6a3bac3d466fb4e0f02b4913e0b63fa5ecb | bec1ad970989a7121096123f0b3a84c20ed0a0cc | refs/heads/master | 2021-06-24T07:02:27.539492 | 2018-08-08T20:51:08 | 2018-08-08T20:51:08 | 144,181,944 | 0 | 0 | null | 2018-08-09T17:09:24 | 2018-08-09T17:09:24 | null | UTF-8 | Python | false | false | 1,409 | py | import os
import sys
from . import shakecast
from . import workbook
from . import damping
from . import demand
if __name__ == '__main__':
pp_fig, capacity_fig, acc_diff_fig, disp_diff_fig = workbook.run()
cap_fig, haz_fig, dsf_fig, dem_fig, sc_pp_fig, impact_fig = shakecast.run()
damp1, damp2 = damping.run()
demand1, demand2 = demand.run()
if len(sys.argv) > 1:
path = sys.argv[1]
else:
path = '.'
if not os.path.exists(path):
os.makedirs(path)
# save workbook validation figures
pp_fig.savefig(os.path.join(path, 'perf_point1'))
capacity_fig.savefig(os.path.join(path, 'capacity_comp'))
acc_diff_fig.savefig(os.path.join(path, 'acc_diff'))
disp_diff_fig.savefig(os.path.join(path, 'disp_diff'))
# save shakecast figures
cap_fig.savefig(os.path.join(path, 'sc_capacity'))
haz_fig.savefig(os.path.join(path, 'sc_hazard'))
dsf_fig.savefig(os.path.join(path, 'sc_dsf'))
dem_fig.savefig(os.path.join(path, 'sc_demand'))
sc_pp_fig.savefig(os.path.join(path, 'perf_point2'))
impact_fig.savefig(os.path.join(path, 'impact_fig'))
# save damping figures
damp1.savefig(os.path.join(path, 'damping_beta'))
damp2.savefig(os.path.join(path, 'damping_dsf'))
# save demand figures
demand1.savefig(os.path.join(path, 'hazard_expansion'))
demand2.savefig(os.path.join(path, 'damped_demand'))
| [
"dslosky@usgs.gov"
] | dslosky@usgs.gov |
0d4f77554fb7d7a5b92a8ebcc2b46aeb23fd76a5 | ad6350f06a14f07ebcbe1b187cb0bb7cb2b69ea3 | /tts/utils/alphabet.py | cb5a0c370cf07cab2048ad1a747f2d5821c0649d | [
"MIT"
] | permissive | isadrtdinov/tacotron | 77b87d67ad6623371adf1fdddc22f97d1a77250f | 994716c0f731735b0edde57b920549b83bdd89ca | refs/heads/main | 2023-01-20T01:18:05.122722 | 2020-11-27T18:26:16 | 2020-11-27T18:26:16 | 313,932,561 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 634 | py | import torch
class Alphabet(object):
def __init__(self, tokens=''):
self.index_to_token = {}
self.index_to_token.update({i: tokens[i] for i in range(len(tokens))})
self.token_to_index = {token: index
for index, token in self.index_to_token.items()}
def string_to_indices(self, string):
return torch.tensor([self.token_to_index[token] for token in string \
if token in self.token_to_index], dtype=torch.long)
def indices_to_string(self, indices):
return ''.join(self.index_to_token[index.item()] for index in indices)
| [
"ildussadrtdinov@MacBook-Pro-Ildus.local"
] | ildussadrtdinov@MacBook-Pro-Ildus.local |
4322ca67ffbdb44eb6b884bb802c4659eef90fc4 | e9333f51cf76e94b68cce9d0daf5da545ced54a7 | /HAR/lib/python3.7/site-packages/kivy_ios/recipes/flask/__init__.py | 0a559ccbc6ab96a59245dabc675c722b938fdee4 | [] | no_license | locnguyen14/HAR-data-collection | a5be42ebb261bedb3b62dd3b736b7b3c5da27467 | 681ccd94208f624fe224fa7e944c9437ee8d31ca | refs/heads/master | 2022-11-14T03:47:44.158681 | 2020-06-01T20:05:55 | 2020-06-01T20:05:55 | 268,619,084 | 0 | 1 | null | 2022-11-02T05:33:39 | 2020-06-01T19:57:10 | C | UTF-8 | Python | false | false | 999 | py | # pure-python package, this can be removed when we'll support any python package
from kivy_ios.toolchain import PythonRecipe, shprint
from os.path import join
import sh
import os
class FlaskRecipe(PythonRecipe):
version = "master"
url = "https://github.com/mitsuhiko/flask/archive/{version}.zip"
depends = ["python", "jinja2", "werkzeug", "itsdangerous", "click"]
def install(self):
arch = list(self.filtered_archs)[0]
build_dir = self.get_build_dir(arch.arch)
os.chdir(build_dir)
hostpython = sh.Command(self.ctx.hostpython)
build_env = arch.get_env()
dest_dir = join(self.ctx.dist_dir, "root", "python")
build_env['PYTHONPATH'] = join(dest_dir, 'lib', 'python3.7', 'site-packages')
cmd = sh.Command("sed")
shprint(cmd, "-i", "", "s/setuptools/distutils.core/g", "./setup.py", _env=build_env)
shprint(hostpython, "setup.py", "install", "--prefix", dest_dir, _env=build_env)
recipe = FlaskRecipe()
| [
"ndxloc1995@gmail.com"
] | ndxloc1995@gmail.com |
220dfaaeafb0194a281d372055511fb51b1ca888 | f7f2e8af3e9b19840396ab5da36bfa161cf03484 | /setup.py | 3466011a2a76c26eb5542750376251fd57f946c5 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | Nevinoven/bcwallet | 2a4713f24505978f681d6d398300c144834bfbf0 | afaef09b3c3ac87de765cd9a915f98c046084b21 | refs/heads/master | 2021-01-15T23:50:56.911620 | 2015-12-08T18:29:22 | 2015-12-08T18:29:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 692 | py | # https://youtu.be/kNke39OZ2k0?t=65
from setuptools import setup
setup(
name='bcwallet',
version='1.2.3',
description='Simple BIP32 HD cryptocurrecy command line wallet',
author='Michael Flaxman',
author_email='mflaxman+blockcypher@gmail.com',
url='https://github.com/blockcypher/bcwallet/',
py_modules=['bcwallet'],
install_requires=[
'clint==0.4.1',
'blockcypher==1.0.53',
'bitmerchant==0.1.8',
'tzlocal==1.2',
],
entry_points='''
[console_scripts]
bcwallet=bcwallet:invoke_cli
''',
packages=['bcwallet'],
)
| [
"mflaxman@gmail.com"
] | mflaxman@gmail.com |
0f89fce50eea8c4c073a162371547050cac89eab | e672b8a57d5224116e70e81cb1ad1ed56e62de0c | /Human/decoration.py | 90d7d968ff9836043b63250e334a81084229f36d | [] | no_license | ShiShuyang/LineMe-1 | a13616fd10bdec2c63e6d6fa648f23fc4d1dfb61 | 5eb4de329d0bf588edf8ad1684a4ec5fa529fecf | refs/heads/master | 2021-01-22T21:00:34.273257 | 2016-05-16T08:04:17 | 2016-05-16T08:04:17 | 58,914,351 | 0 | 0 | null | 2016-05-16T08:00:20 | 2016-05-16T08:00:19 | null | UTF-8 | Python | false | false | 110 | py | #!/usr/bin/env python
# coding: utf-8
# created by hevlhayt@foxmail.com
# Date: 2016/4/14
# Time: 20:23
#
| [
"hevlhayt@foxmail.com"
] | hevlhayt@foxmail.com |
08b920065a55018808faf3d41b34e60eed62fb80 | 53cf1ca9d6bd615280515ab0deacb43cd0521758 | /app/main.py | 1af0d5da3b9b7a8d77891096a247f001b2852c5d | [] | no_license | BaptPicxDev/gitlab-ci_cd-tuto | 33f3d7dcb3d5ab0c51d804681d00880790f5d81a | b1ce6ca85b15eca7115ba52345e026e6e9781216 | refs/heads/main | 2023-01-05T13:34:14.016749 | 2020-11-05T20:35:14 | 2020-11-05T20:35:14 | 310,262,805 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 658 | py | # -*- coding: utf-8 -*-
#############################################
# author : Baptiste PICARD #
# date : 05/11/2020 #
# last modif : 05/11/2020 #
# contact : dev.baptpicxdev@gmail.com #
# #
# overview : Main code. #
#############################################
## Imports
import math
import datetime
## Librairies
## Functions
def get_pi() :
return math.pi
## Main script
if __name__ == '__main__':
start_time = datetime.datetime.now()
print("Starting the script.")
print(get_pi())
print("End of the script. It takes : {} secs.".format((datetime.datetime.now()-start_time).seconds)) | [
"picard.baptiste@laposte.net"
] | picard.baptiste@laposte.net |
164272c7c197a50b02def627df3852104c8d4b26 | 656341483ae8abe8792942d26556fdd4ff5ca7a9 | /Case/AS/Http/DocPolicyMgnt/test_AddPolicyPwdStrength201.py | ce8cafe542826cd32d85e60e6ce32d22c57ae029 | [] | no_license | GWenPeng/Apitest_framework | b57ded9be4ec896d4ba8e02e9135bc7c73d90034 | ab922c82c2454a3397ddbf4cd0771067734e1111 | refs/heads/master | 2022-11-26T05:54:47.168062 | 2020-08-06T01:45:12 | 2020-08-06T01:45:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,886 | py | import pytest
import allure
import sys
sys.path.append("../../../../")
from Common.readjson import JsonRead
from DB_connect.mysqlconnect import DB_connect
from Common.http_request import Http_client
@pytest.mark.ASP_344
@pytest.mark.high
@allure.severity('blocker') # 优先级
@allure.feature("文档域策略管控")
class Test_AddPolicy_PwdStrengthCheck201(object):
@allure.testcase("ID5318,用例名:新增策略配置--密码强度,配置成功--返回201")
# 每条用例执行完成后执行,清除环境
@pytest.fixture(scope="function")
def teardown(self):
pass
yield
db = DB_connect()
db.delete("delete from t_policy_tpls")
@pytest.mark.parametrize("jsondata,checkpoint", argvalues=JsonRead(
"AS\\Http\\DocPolicyMgnt\\testdata\\test_AddPolicyPwdStrength201.json").dict_value_join())
def test_AddPolicy_PwdStrengthCheck201(self, jsondata,checkpoint,teardown):
# 新增策略
add_client = Http_client()
add_client.post(url="/api/document-domain-management/v1/policy-tpl",
jsondata=jsondata,
header="{\"Content-Type\":\"application/json\"}")
# 接口响应状态断言
assert add_client.status_code == checkpoint['status_code']
# 获取t_policy_tpls表中策略id
db = DB_connect()
query_result = db.select_one("select f_id from t_policy_tpls")
# sql查询结果为元组,获取元组第一个值,即策略id
global policyid
policyid = query_result[0]
# 拼接location预期值
location = "/api/document-domain-management/v1/policy-tpl/" + policyid
assert location == add_client.respheaders['Location']
assert add_client.elapsed <= 20.0
if __name__ == '__main__':
pytest.main(['-q', '-v', 'test_AddPolicyPwdStrength201.py'])
| [
"gu.wenpeng@eisoo.com"
] | gu.wenpeng@eisoo.com |
fe2626a09fd3ab4d98545f44ebb333024eed4d3a | 97d78f39d39abcc54b1e71dea5338783fd1e27d6 | /userapp/forms.py | 02034118009fdcca7f83ad469c869c320e7b0c7c | [] | no_license | AmitMhamunkar/FoodMarket | 00242cd373fe98d65f32e4eacb996848c737a0be | 449528ae1070296b32d3e914a7b9b9c1d9882ddc | refs/heads/master | 2022-09-18T14:17:06.206568 | 2020-06-02T08:26:19 | 2020-06-02T08:26:19 | 268,738,764 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 201 | py | from django import forms
from userapp.models import UserModel
class Userform(forms.ModelForm):
password=forms.CharField(widget=forms.PasswordInput)
class Meta:
model=UserModel
fields='__all__'
| [
"amitmhamunkar100@gmail.com"
] | amitmhamunkar100@gmail.com |
acaaee529a13bf693918e730895d0eb890816e9a | 11eaf88a3303188f9a50008510a2f662258ecef9 | /simplegrid/tests/test_pyproj.py | 8247c0d8fb4d05a1814bf771ce0b690e048edad5 | [] | no_license | turpinhill/simplegrid | 0694c274348c5d4705db68555809c1f05674a70a | afc3ede79839086821e107eb66e62e44ad245f2c | refs/heads/master | 2022-11-12T21:14:47.125304 | 2019-11-23T01:21:00 | 2019-11-23T01:21:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,236 | py |
import numpy as np
import numpy.testing as nptest
import pyproj
import unittest
class TestPyproj(unittest.TestCase):
def test_pyproj_1(self):
"""pyproj.Geod.inv and .npts validation test: N-S segment distance sums.
"""
# does the segment distance sum equal the total endpoint distance?:
lon1,lat1,lon2,lat2 = 0.,0.,0.,1.
npts = 10
geod = pyproj.Geod(ellps='sphere')
allpts = np.concatenate((
np.array([[lon1,lat1]]),
np.array(geod.npts(lon1,lat1,lon2,lat2,npts)),
np.array([[lon2,lat2]])))
_,_,segdist = geod.inv( allpts[0:-1,0], allpts[0:-1,1], allpts[1:,0],
allpts[1:,1])
_,_,totdist = geod.inv(lon1,lat1,lon2,lat2)
nptest.assert_almost_equal(np.sum(segdist),totdist)
def test_pyproj_2(self):
"""pyproj.Geod.inv and .npts validation test: SW-NE segment distance sums.
"""
# does the segment distance sum equal the total endpoint distance?:
lon1,lat1,lon2,lat2 = 0.,0.,1.,1.
npts = 10
geod = pyproj.Geod(ellps='sphere')
allpts = np.concatenate((
np.array([[lon1,lat1]]),
np.array(geod.npts(lon1,lat1,lon2,lat2,npts)),
np.array([[lon2,lat2]])))
_,_,segdist = geod.inv( allpts[0:-1,0], allpts[0:-1,1], allpts[1:,0],
allpts[1:,1])
_,_,totdist = geod.inv(lon1,lat1,lon2,lat2)
nptest.assert_almost_equal(np.sum(segdist),totdist)
def test_pyproj_3(self):
"""pyproj.Geod.inv and .npts validation test: E-W segment distance sums.
"""
# does the segment distance sum equal the total endpoint distance?:
lon1,lat1,lon2,lat2 = 0.,0.,1.,0.
npts = 10
geod = pyproj.Geod(ellps='sphere')
allpts = np.concatenate((
np.array([[lon1,lat1]]),
np.array(geod.npts(lon1,lat1,lon2,lat2,npts)),
np.array([[lon2,lat2]])))
_,_,segdist = geod.inv( allpts[0:-1,0], allpts[0:-1,1], allpts[1:,0],
allpts[1:,1])
_,_,totdist = geod.inv(lon1,lat1,lon2,lat2)
nptest.assert_almost_equal(np.sum(segdist),totdist)
if __name__=='__main__':
unittest.main()
| [
"greg.moore@jpl.nasa.gov"
] | greg.moore@jpl.nasa.gov |
2677fc45376627ea6983a6097ff047b14fddf0d9 | eacd7d7e22c7f71435e1b2ce13d6c8c44eea1ca9 | /api/hpcpm/api/resources/endpoints/RuleTypes.py | 88a217bb2981da3c50f0718128abda5d95894863 | [
"MIT"
] | permissive | tomix86/hpcpm | d5af235571adcc03930a6161b950c98a1e2d2c81 | 9fa8341249deb8c5689d0f3743f9b76d46b2dd69 | refs/heads/master | 2021-03-16T10:12:44.751779 | 2017-09-07T18:13:39 | 2017-09-07T18:13:39 | 73,505,604 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 544 | py | from flask_restful import Resource
from flask_restful_swagger import swagger
from hpcpm.api.helpers.constants import AVAILABLE_RULE_TYPES
class RuleTypes(Resource):
@swagger.operation(
notes='This endpoint is used for returning available power management rule types',
nickname='/rule_types',
parameters=[],
responseMessages=[
{
'code': 200,
'message': 'Rule types found'
}
]
)
def get(self):
return AVAILABLE_RULE_TYPES, 200
| [
"bartekmp@outlook.com"
] | bartekmp@outlook.com |
effe7dc25476101643ced680af1b5b329b9d4308 | de27e6d143f40d5948244597b861d522a9a272f6 | /fjord/heartbeat/migrations/0009_answer_country.py | f824482bc7c9c38b3c33cf27d7df7e8ff5aaac97 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | mozilla/fjord | 7f31af6dd80869ca856f8a02ff10e72c81685368 | 0fcb81e6a5edaf42c00c64faf001fc43b24e11c0 | refs/heads/master | 2023-07-03T18:20:01.651759 | 2017-01-10T20:12:33 | 2017-01-10T20:12:33 | 5,197,539 | 18 | 22 | null | 2016-08-22T14:56:11 | 2012-07-26T21:25:00 | Python | UTF-8 | Python | false | false | 519 | py | # -*- coding: utf-8 -*-
"""
Add country to heartbeat Answer table.
"""
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('heartbeat', '0008_auto_20150305_1442'),
]
operations = [
migrations.AddField(
model_name='answer',
name='country',
field=models.CharField(default='', max_length=4, null=True, blank=True),
preserve_default=True,
),
]
| [
"willkg@mozilla.com"
] | willkg@mozilla.com |
ba62cc4936adb4692e0e0453711d19b420bee0ed | e03bce53de6f88c0e09f56e4fe11c36af0f1161f | /tests/functional/cfngin/hooks/test_awslambda/test_runner.py | d790a94e4e9319a5152fbf92403ed18fa28eec90 | [
"Apache-2.0"
] | permissive | onicagroup/runway | 20c31df9cbc1a1ffc5c9aa468ce5cf7d6ac7899f | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | refs/heads/master | 2023-08-30T22:35:54.113981 | 2023-08-29T14:13:35 | 2023-08-29T14:13:35 | 122,529,924 | 156 | 79 | Apache-2.0 | 2023-09-13T13:43:50 | 2018-02-22T20:12:55 | Python | UTF-8 | Python | false | false | 10,335 | py | """Test AWS Lambda hook."""
# pylint: disable=no-self-argument
# pylint: disable=redefined-outer-name,unexpected-keyword-arg,unused-argument
from __future__ import annotations
import json
import shutil
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Generator, Optional
import boto3
import pytest
from pydantic import root_validator
from runway._cli import cli
from runway.compat import cached_property
from runway.utils import BaseModel
if TYPE_CHECKING:
from click.testing import CliRunner, Result
from mypy_boto3_cloudformation.client import CloudFormationClient
from mypy_boto3_cloudformation.type_defs import StackTypeDef
from mypy_boto3_lambda.client import LambdaClient
from sample_app.src.type_defs import LambdaResponse
from runway.context import RunwayContext
AWS_REGION = "us-east-1"
LOCAL_PYTHON_RUNTIME = f"python{sys.version_info.major}.{sys.version_info.minor}"
STACK_PREFIX = "test-awslambda"
CURRENT_DIR = Path(__file__).parent
SRC_DIR = CURRENT_DIR / "sample_app" / "src"
DOCKER_MYSQL_DIR = SRC_DIR / "docker_mysql"
DOCKER_XMLSEC_DIR = SRC_DIR / "docker_xmlsec"
ENV_VARS = {
"CI": "1",
"LOCAL_PYTHON_RUNTIME": LOCAL_PYTHON_RUNTIME,
"PIPENV_VENV_IN_PROJECT": "1",
"PIPENV_VERBOSITY": "-1",
"POETRY_VIRTUALENVS_IN_PROJECT": "true",
"PYXMLSEC_STATIC_DEPS": "1",
}
pytestmark = pytest.mark.skipif(
not shutil.which("mysql_config"),
reason="mysql_config CLI from mysql OS package must be installed and in PATH",
)
class AwslambdaStackOutputs(BaseModel):
"""Outputs of a Stack used for testing the awslambda hook."""
CodeImageUri: Optional[str] = None
CodeS3Bucket: str
CodeS3Key: str
CodeS3ObjectVersion: Optional[str] = None
CodeZipFile: Optional[str] = None
LambdaFunction: str
LambdaFunctionArn: str
LambdaRole: str
LayerContentS3Bucket: Optional[str] = None
LayerContentS3Key: Optional[str] = None
LayerContentS3ObjectVersion: Optional[str] = None
LayerVersion: Optional[str] = None
Runtime: str
@root_validator(allow_reuse=True, pre=True)
def _convert_null_to_none(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Convert ``null`` to ``NoneType``."""
def _handle_null(v: Any) -> Any:
if v == "null":
return None
return v
return {k: _handle_null(v) for k, v in values.items()}
class AwslambdaTester:
"""Class to simplify testing the awslambda hook's results."""
def __init__(self, session: boto3.Session, stack_name: str) -> None:
"""Instantiate class."""
self._session = session
self.stack_name = stack_name
@cached_property
def cfn_client(self) -> CloudFormationClient:
"""AWS CloudFormation client."""
return self._session.client("cloudformation")
@cached_property
def client(self) -> LambdaClient:
"""AWS Lambda client."""
return self._session.client("lambda")
@cached_property
def outputs(self) -> AwslambdaStackOutputs:
"""Stack outputs."""
return AwslambdaStackOutputs.parse_obj(
{
output["OutputKey"]: output["OutputValue"]
for output in self.stack.get("Outputs", [])
if "OutputKey" in output and "OutputValue" in output
}
)
@cached_property
def stack(self) -> StackTypeDef:
"""AWS Lambda Function CloudFormation Stack data."""
stacks = self.cfn_client.describe_stacks(StackName=self.stack_name)["Stacks"]
if not stacks:
raise ValueError(
f"Stack {self.stack_name} not found in region {self._session.region_name}"
)
return stacks[0]
def invoke(self, *, payload: Optional[str] = None) -> LambdaResponse:
"""Invoke the Lambda Function."""
response = self.client.invoke(
FunctionName=self.outputs.LambdaFunction,
InvocationType="RequestResponse",
**{"Payload": payload} if payload else {},
)
if "Payload" in response:
return json.load(response["Payload"])
raise ValueError("Lambda Function did not return a payload")
def assert_runtime(tester: AwslambdaTester, runtime: str) -> None:
"""Assert that the deployment package is using the expected runtime."""
assert tester.outputs.Runtime == runtime
def assert_uploaded(tester: AwslambdaTester, deploy_result: Result) -> None:
"""Assert that the deployment package was uploaded."""
uri = f"s3://{tester.outputs.CodeS3Bucket}/{tester.outputs.CodeS3Key}"
assert f"uploading deployment package {uri}..." in deploy_result.stdout, "\n".join(
line for line in deploy_result.stdout.split("\n") if uri in line
)
@pytest.fixture(scope="module")
def deploy_result(cli_runner: CliRunner) -> Generator[Result, None, None]:
"""Execute `runway deploy` with `runway destroy` as a cleanup step."""
yield cli_runner.invoke(cli, ["deploy"], env=ENV_VARS)
assert cli_runner.invoke(cli, ["destroy"], env=ENV_VARS).exit_code == 0
shutil.rmtree(CURRENT_DIR / ".runway", ignore_errors=True)
shutil.rmtree(CURRENT_DIR / "sample_app" / ".runway", ignore_errors=True)
# remove .venv/ & *.lock from source code directories - more important for local testing
(DOCKER_MYSQL_DIR / "Pipfile.lock").unlink(missing_ok=True)
(DOCKER_XMLSEC_DIR / "poetry.lock").unlink(missing_ok=True)
for subdir in [DOCKER_MYSQL_DIR, DOCKER_XMLSEC_DIR]:
shutil.rmtree(subdir / ".venv", ignore_errors=True)
@pytest.mark.order("first")
def test_deploy_exit_code(deploy_result: Result) -> None:
"""Test deploy exit code."""
assert deploy_result.exit_code == 0, deploy_result.output
def test_deploy_log_messages(deploy_result: Result) -> None:
"""Test deploy log messages."""
build_skipped = [
line for line in deploy_result.stdout.split("\n") if "build skipped" in line
]
assert not build_skipped, "\n".join(build_skipped)
def test_docker(
deploy_result: Result, namespace: str, runway_context: RunwayContext
) -> None:
"""Test function built with Docker."""
tester = AwslambdaTester(
runway_context.get_session(region=AWS_REGION),
f"{namespace}-{STACK_PREFIX}-docker",
)
assert_runtime(tester, "python3.9")
assert_uploaded(tester, deploy_result)
response = tester.invoke()
response_str = json.dumps(response, indent=4, sort_keys=True)
assert response["code"] == 200, response_str
assert response["data"]["requests"]
assert "index.py" in response["data"]["dir_contents"]
assert "urllib3/__init__.py" in response["data"]["dir_contents"]
assert "requests/__init__.py" in response["data"]["dir_contents"]
assert "charset_normalizer/__init__.py" in response["data"]["dir_contents"]
assert "certifi/__init__.py" in response["data"]["dir_contents"]
def test_local(
deploy_result: Result, namespace: str, runway_context: RunwayContext
) -> None:
"""Test function built with local python."""
tester = AwslambdaTester(
runway_context.get_session(region=AWS_REGION),
f"{namespace}-{STACK_PREFIX}-local",
)
assert_runtime(tester, LOCAL_PYTHON_RUNTIME)
assert_uploaded(tester, deploy_result)
response = tester.invoke()
assert response["code"] == 200
assert response["data"]["dir_contents"] == ["index.py"]
def test_mysql(
deploy_result: Result, namespace: str, runway_context: RunwayContext
) -> None:
"""Test function built from Dockerfile for mysql."""
tester = AwslambdaTester(
runway_context.get_session(region=AWS_REGION),
f"{namespace}-{STACK_PREFIX}-mysql",
)
assert_runtime(tester, "python3.9")
assert_uploaded(tester, deploy_result)
response = tester.invoke()
response_str = json.dumps(response, indent=4, sort_keys=True)
assert response["code"] == 200, response_str
assert len(response["data"]["mysqlclient"]) >= 10
assert "Pipfile" not in response["data"]["dir_contents"]
def test_xmlsec(
deploy_result: Result, namespace: str, runway_context: RunwayContext
) -> None:
"""Test function built from Dockerfile for xmlsec."""
tester = AwslambdaTester(
runway_context.get_session(region=AWS_REGION),
f"{namespace}-{STACK_PREFIX}-xmlsec",
)
assert_runtime(tester, "python3.9")
assert_uploaded(tester, deploy_result)
response = tester.invoke()
response_str = json.dumps(response, indent=4, sort_keys=True)
assert response["code"] == 200, response_str
assert "etree" in response["data"]["lxml"]
assert "KeysManager" in response["data"]["xmlsec"]
assert ".gitignore" not in response["data"]["dir_contents"]
assert "poetry.lock" not in response["data"]["dir_contents"]
def test_xmlsec_layer(
deploy_result: Result, namespace: str, runway_context: RunwayContext
) -> None:
"""Test layer built from Dockerfile for xmlsec."""
tester = AwslambdaTester(
runway_context.get_session(region=AWS_REGION),
f"{namespace}-{STACK_PREFIX}-xmlsec-layer",
)
assert_runtime(tester, "python3.9")
assert_uploaded(tester, deploy_result)
response = tester.invoke()
response_str = json.dumps(response, indent=4, sort_keys=True)
assert response["code"] == 200, response_str
assert "etree" in response["data"]["lxml"]
assert "KeysManager" in response["data"]["xmlsec"]
assert response["data"]["dir_contents"] == ["index.py"]
def test_plan(cli_runner: CliRunner, deploy_result: Result) -> None:
"""Test ``runway plan`` - this was not possible with old hook.
deploy_result required so cleanup does not start before this runs.
"""
# remove *.lock files to prevent change in source hash
(DOCKER_MYSQL_DIR / "Pipfile.lock").unlink(missing_ok=True)
(DOCKER_XMLSEC_DIR / "poetry.lock").unlink(missing_ok=True)
plan_results = cli_runner.invoke(cli, ["plan"], env=ENV_VARS)
assert plan_results.exit_code == 0, plan_results.output
matches = [
line for line in plan_results.stdout.split("\n") if line.endswith(":no changes")
]
a_list = [4, 5]
# count needs to be updated if number of test stacks change
assert len(matches) in a_list, "\n".join(matches)
| [
"noreply@github.com"
] | onicagroup.noreply@github.com |
7ba46c749dc56f61686678a649ead7e766863166 | a38889c0446f17cce43817b24925e3969a202509 | /jtop/gui/pinfo.py | 3e984bfced78256455f04f0183ace49f967667ed | [
"MIT"
] | permissive | sherief/jetson_stats | 46a4c108e27471a558f9b72dac2e0067dbd49767 | f8c669f5023820847d9c3ae4c8a6d3db13fec55f | refs/heads/master | 2020-06-22T04:41:17.759004 | 2019-07-15T17:51:00 | 2019-07-15T17:51:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,010 | py | # -*- coding: UTF-8 -*-
# Copyright (C) 2019, Raffaello Bonghi <raffaello@rnext.it>
# All rights reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import curses
from datetime import timedelta
# Page class definition
from .jtopgui import Page
# Graphics elements
from .jtopguilib import plot_name_info
# Menu GUI pages
from .jtopguimenu import strfdelta
class INFO(Page):
def __init__(self, stdscr, jetson, refresh):
super(INFO, self).__init__("INFO", stdscr, jetson, refresh)
def draw(self, key):
"""
Write all environment variables
"""
# Screen size
height, width = self.stdscr.getmaxyx()
# Position information
posx = 2
start_pos = 2
spacing = 20
# Up time
uptime_string = strfdelta(timedelta(seconds=self.jetson.uptime), "{days} days {hours}:{minutes}:{seconds}")
plot_name_info(self.stdscr, start_pos, posx, "- Up Time", uptime_string)
start_pos += 1
# Loop build information
idx = 0
# Board info
self.stdscr.addstr(start_pos + idx, posx, "- Board:", curses.A_BOLD)
for name, info in self.jetson.board["board"].items():
self.stdscr.addstr(start_pos + idx + 1, posx + 2, "* " + name + ":")
self.stdscr.addstr(start_pos + idx + 1, posx + spacing, info, curses.A_BOLD)
idx += 1
# Libraries info
self.stdscr.addstr(start_pos + idx + 1, posx, "- Libraries:", curses.A_BOLD)
idx += 1
for name, info in self.jetson.board["libraries"].items():
self.stdscr.addstr(start_pos + idx + 1, posx + 2, "* " + name + ":")
self.stdscr.addstr(start_pos + idx + 1, posx + spacing, info, curses.A_BOLD)
idx += 1
# IP address and Hostname
if self.jetson.local_interfaces:
plot_name_info(self.stdscr, start_pos + idx + 1, posx, "- Hostname", self.jetson.local_interfaces["hostname"])
self.stdscr.addstr(start_pos + idx + 2, posx, "- Interfaces", curses.A_BOLD)
idx += 3
for name, ip in self.jetson.local_interfaces["interfaces"].items():
self.stdscr.addstr(start_pos + idx, posx + 2, "* " + name + ":")
self.stdscr.addstr(start_pos + idx, posx + spacing, ip, curses.A_BOLD)
idx += 1
# Author information
plot_name_info(self.stdscr, start_pos, width - 30, "Author", "Raffaello Bonghi")
plot_name_info(self.stdscr, start_pos + 1, width - 30, "e-mail", "raffaello@rnext.it")
| [
"raffaello@rnext.it"
] | raffaello@rnext.it |
e83053677b773cf8fb2f40cc45a95b9496c8904b | 98e3f47c7730e5aa1546fc5a3ae1aa5d34bd55fd | /functions/sendmessage.py | 614e0281d234840b37df681d4387821d57eb59ce | [] | no_license | Philip-Nunoo/smsrequest | b68ac3748f2e216c9887004786624dea53ea8f20 | ed3e6e56675015a51adae087e32d5353b5c5bc60 | refs/heads/master | 2020-05-18T06:50:47.086437 | 2013-02-02T17:17:55 | 2013-02-02T17:17:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,963 | py | #from requestPortal.models import Message#, Hospital, Patient, MessageLog
import datetime
key = "22ccfebddfe274033b29"
url = "http://bulk.mnotification.com/smsapi"
def sendMessage():
messages_object = Message.objects.filter(start_at_date = datetime.date.today())
if (messages_object):
for message in messages_object:
if message.active:
message_content = message.message_content;
phone_number = message.receipient_name.telephone_number
sender_id = message.receipient_name.hospital_id
get_data = {
'key': key,
'to': phone_number,
'msg': message_content,
'sender_id': sender_id
}
print "Sending message: " + message_content
print "To: " + phone_number
#requests.get(url, params = get_data) # This line sends the message to mnotify
'''
creating a log of message that was sent
'''
patient = Patient.objects.get(id = message.receipient_name.id)
message_log = MessageLog.objects.create( message = message, patient = patient)
if message.message_frequency == "daily":
#message.start_at_date = message.start_at_date + datetime.timedelta(days=1)
#print "Daily messages"
pass
if message.message_frequency == "weekly":
#message.start_at_date = message.start_at_date + datetime.timedelta(days=7)
#print "Weekly Message"
pass
if message.message_frequency == "monthly":
#message.start_at_date = message.start_at_date + datetime.timedelta(days=30)
#print "Monthly Message"
pass
if message.message_frequency == "specify":
#print "Specific date set"
pass
#if message.start_at_date > message.end_at_date: # if message exceeds ending date active = False
# message.active = False
#else:
# print "no message to send today"
def sendMessageNow(message, receipient_id):
#save message content
message_content = message
#get the number of the receipient from the id
patient = Patient.objects.get(id = receipient_id)
phone_number = patient.telephone_number
#get the hospital the receipient is registered to from the receipient_id variable
sender_id = patient.hospital_id.hospital_name
#store the message in the message variable
get_data = {
'key': key,
'to': phone_number,
'msg': message_content,
'sender_id': sender_id
}
##requests.get(url, params = get_data)
print "message sent to user"
| [
"philip@Trek.(none)"
] | philip@Trek.(none) |
211af288fcd6aac7b3e766454a3c3c59daa490d5 | 13c9f25290bf455bb131e1a24467375e46001cef | /Alpha/input.py | 4fb7cce0b9073334c1e0e2ffbf07edddaa67cd62 | [] | no_license | JonesRobM/LoDiS_CC | 74ff1db563c7a3ee8f4bedefaddbce20a31c01e5 | b3900d3745121928254a0b2acbc92b1a7d9fa3f5 | refs/heads/master | 2020-12-10T18:10:49.171456 | 2020-03-10T11:42:55 | 2020-03-10T11:42:55 | 233,669,401 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,233 | py | import Process
import pickle
Supported=[
'rdf', 'cna', 'adj', 'pdf', 'pdfhomo', 'agcn', 'nn',
'SimTime', 'EPot', 'ETot', 'EKin', 'EDelta', 'MeanETot', 'Temp'
]
System = {
'base_dir' : 'TestTraj/',
'movie_file_name' : 'movie.xyz',
'energy_file_name' : 'energy.out',
'Homo' : ['Au', 'Pd'], 'HomoQuants' : [ 'HoPDF', 'HoRDF', 'CoM', 'HoAdj' ],
'Hetero' : True, 'HeteroQuants' : [ 'HePDF', 'HeRDF', 'HeAdj' ],
'Start' : 0, 'End' : 1000, 'Step' : 1, 'Skip' : 50, 'UniformPDF' : False, 'Band' : 0.05,
'HCStats' : True,
'SimTime': True, 'EPot': True, 'ETot' : True,
'EKin' : True, 'EDelta' : True, 'MeanETot' : True, 'Temp' : True
}
Quantities = {
'euc' : None, 'rdf' : None, 'pos' : None, 'cna' : None,
'adj' : None, 'pdf' : None, 'agcn' : None, 'nn' : None, 'CoM' : None,
'SimTime': None, 'EPot': None, 'ETot' : None,
'EKin' : None, 'EDelta' : None, 'MeanETot' : None, 'Temp' : None
}
TestMetadata = Process.Process(System, Quantities)
with open('TestTraj/MetadataSample.csv', "wb") as f:
pickle.dump(TestMetadata,f, pickle.HIGHEST_PROTOCOL)
| [
"noreply@github.com"
] | JonesRobM.noreply@github.com |
43fbed3229e50ebf22a3382519bb2c96007bb077 | 2d0c223226caefeca891162f04fa47a9cc4ce039 | /fabfile/__init__.py | deacab26bb21ba770797a0362a55441bb1c7afa6 | [
"MIT"
] | permissive | Halleck45/stage1 | 1ed195aa6ad9dada19ead838a20cee4ee4528357 | ddd443719a160364bde1cb6f5d0ff20c2e4aebca | refs/heads/master | 2021-01-17T22:31:13.680057 | 2014-08-09T14:11:14 | 2014-08-09T14:11:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,776 | py | from fabric.api import *
from time import sleep
import deploy
import service
# env.hosts = ['batcave.stage1.io', 'alpha.stage1.io', 'alom.fr']
env.roledefs = {
'web': ['batcave.stage1.io'],
'help': ['batcave.stage1.io'],
'blog': ['batcave.stage1.io'],
'router': ['alpha.stage1.io'],
'build': [
'alom.fr',
'alpha.stage1.io'
],
}
# env.host_string = 'stage1.io'
env.user = 'root'
env.project_path = '/var/www/stage1'
env.upstart_path = '/etc/init'
env.remote_dump_path = '/root/dump'
env.local_dump_path = '~/dump'
# env.use_ssh_config = True
env.rsync_exclude_from = './app/Resources/rsync-exclude.txt'
env.processes_prefix = 'stage1'
env.processes = [
'consumer-build',
'consumer-kill',
'consumer-project-import',
'consumer-docker-output',
'websockets',
'aldis',
'hipache',
]
env.log_files = [
'/var/log/nginx/*.log',
'/var/log/stage1/*.log',
'%s/app/logs/*.log' % env.project_path,
'/var/log/syslog',
'/var/log/php5-fpm.log',
'/var/log/mysql/error.log',
]
# @task
# def backup():
# run('mkdir -p %s' % env.remote_dump_path);
# run('mysqldump -u root symfony | gzip > %s/stage1.sql.gz' % env.remote_dump_path)
# run('cp /var/lib/redis/dump.rdb %s/dump.rdb' % env.remote_dump_path)
# local('rsync --verbose --rsh=ssh --progress -crDpLt --force --delete %(user)s@%(host)s:%(remote)s/* %(local)s' % {
# 'user': env.user,
# 'host': env.host_string,
# 'remote': env.remote_dump_path,
# 'local': env.local_dump_path
# })
# @task
# def inject():
# if not local('test -d %s' % env.local_dump_path).succeeded:
# info('nothing to inject')
# exit
# local('mysqladmin -u root -f drop symfony')
# local('mysqladmin -u root create symfony')
# local('gunzip -c %s/stage1.sql.gz | mysql -u root symfony' % env.local_dump_path)
# local('sudo service redis-server stop')
# local('sudo cp %s/dump.rdb /var/lib/redis/dump.rdb' % env.local_dump_path)
# local('sudo service redis-server start')
# hipache_init_redis_local()
# local('sudo restart %s-hipache' % env.processes_prefix)
# local('sudo restart %s-websockets' % env.processes_prefix)
# @task
# def restore():
# if not local('test -d %s' % env.local_dump_path).succeeded:
# info('nothing to restore')
# exit
# local('rsync --verbose --rsh=ssh --progress -crDpLt --force --delete %(local)s/* %(user)s@%(host)s:%(remote)s' % {
# 'user': env.user,
# 'host': env.host_string,
# 'remote': env.remote_dump_path,
# 'local': env.local_dump_path
# })
# run('mysqladmin -u root -f drop symfony')
# run('mysqladmin -u root create symfony')
# run('gunzip -c %s/stage1.sql.gz | mysql -u root symfony' % env.remote_dump_path)
# run('service redis-server stop')
# run('cp %s/dump.rdb /var/lib/redis/dump.rdb' % env.remote_dump_path)
# run('service redis-server start')
# run('restart %s-hipache' % env.processes_prefix)
# run('restart %s-websockets' % env.processes_prefix)
# @task
# def upstart_export():
# local('sudo foreman export upstart /etc/init -u root -a stage1')
# @task
# def upstart_deploy():
# local('sudo rm -rf /tmp/init/*')
# local('sudo foreman export upstart /tmp/init -u root -a stage1')
# local('sudo find /tmp/init -type f -exec sed -e \'s!/vagrant!%s!\' -e \'s! export PORT=.*;!!\' -i "{}" \;' % env.project_path)
# local('rsync --verbose --rsh=ssh --progress -crDpLt --force --delete /tmp/init/* %(user)s@%(host)s:%(remote)s' % {
# 'user': env.user,
# 'host': env.host_string,
# 'remote': env.upstart_path
# })
# @task
# def rm_cache():
# sudo('rm -rf %s/app/cache/*' % env.project_path)
# @task
# def llog():
# local('sudo tail -f %s' % ' '.join(env.log_files))
# @task
# def log():
# sudo('tail -f %s' % ' '.join(env.log_files))
# @task
# def log_build():
# sudo('tail -f /tmp/log/consumer-build.*.log')
# @task
# def prepare_assets():
# info('preparing assets')
# local('app/console assetic:dump --env=prod --no-debug')
# @task
# def provision():
# # with settings(warn_only=True):
# # if run('test -f /etc/apt/sources.list.d/dotdeb.list').succeeded:
# # info('already provisioned, skipping')
# # return
# info('provisioning %s' % env.host_string)
# with cd('/tmp'):
# put('packer/support/config/apt/dotdeb.list', 'apt-dotdeb.list')
# put('packer/support/config/apt/docker.list', 'apt-docker.list')
# put('packer/support/config/apt/rabbitmq.list', 'apt-rabbitmq.list')
# put('packer/support/config/apt/sources.list', 'apt-sources.list')
# put('packer/support/config/nginx/prod/default', 'nginx-default')
# put('packer/support/config/php/prod.ini', 'php-php.ini')
# put('packer/support/config/grub/default', 'grub-default')
# put('packer/support/config/docker/default', 'docker-default')
# put('packer/support/scripts/stage1.sh', 'stage1.sh')
# put('packer/support/scripts/prod.sh', 'prod.sh')
# with settings(warn_only=True):
# if run('test -d /usr/lib/vmware-tools').succeeded:
# put('packer/support/config/rabbitmq/vm.config', 'rabbitmq-rabbitmq.config')
# sudo('bash /tmp/stage1.sh')
# sudo('bash /tmp/prod.sh')
# # reboot()
# @task
# def check_connection():
# run('echo "OK"')
# @task
# def redis_list_frontends():
# run('redis-cli keys frontend:\\*')
# @task
# def redis_list_auths():
# run('redis-cli keys auth:\\*')
# @task
# def redis_flushall():
# info('flushing redis')
# run('redis-cli FLUSHALL')
# @task
# def hipache_init_redis():
# info('initializing redis for hipache')
# run('redis-cli DEL frontend:%s' % env.host_string)
# run('redis-cli RPUSH frontend:%s stage1 http://127.0.0.1:8080/' % env.host_string)
# run('redis-cli DEL frontend:help.%s' % env.host_string)
# run('redis-cli RPUSH frontend:help.%s help http://127.0.0.1:8080/' % env.host_string)
# @task
# def hipache_init_redis_local():
# local('redis-cli DEL frontend:stage1.dev')
# local('redis-cli RPUSH frontend:stage1.dev stage1 http://127.0.0.1:8080/')
# local('redis-cli DEL frontend:help.stage1.dev')
# local('redis-cli RPUSH frontend:help.stage1.dev help http://127.0.0.1:8080/')
# @task
# def fix_permissions():
# with settings(warn_only=True):
# if run('test -d %s/app/cache' % env.project_path).succeeded:
# info('fixing cache and logs permissions')
# www_user = run('ps aux | grep -E \'nginx\' | grep -v root | head -1 | cut -d\ -f1')
# sudo('setfacl -R -m u:%(www_user)s:rwX -m u:$(whoami):rwX %(project_path)s/app/cache %(project_path)s/app/logs' % { 'www_user': www_user, 'project_path': env.project_path })
# sudo('setfacl -dR -m u:%(www_user)s:rwX -m u:$(whoami):rwX %(project_path)s/app/cache %(project_path)s/app/logs' % { 'www_user': www_user, 'project_path': env.project_path })
# @task
# def needs_cold_deploy():
# with settings(warn_only=True):
# return run('test -d %s' % env.project_path).failed
# @task
# def prepare():
# with settings(warn_only=True):
# if run('test -d %s' % env.project_path).succeeded:
# info('already prepared, skipping')
# return
# info('preparing host')
# sudo('mkdir %s' % env.project_path)
# sudo('chown -R www-data:www-data %s' % env.project_path)
# @task
# def reset_database():
# processes_stop()
# with cd(env.project_path):
# run('app/console --env=prod doctrine:database:drop --force')
# run('app/console --env=prod doctrine:database:create')
# run('app/console --env=prod doctrine:schema:update --force')
# processes_start()
# docker_clean()
# @task
# def create_database():
# run('%s/app/console --env=prod doctrine:database:create' % env.project_path)
# @task
# def init_parameters():
# run('cp %s/app/config/parameters.yml.dist %s/app/config/parameters.yml' % (env.project_path, env.project_path))
# run('cp %s/app/config/github.yml.dist %s/app/config/github.yml' % (env.project_path, env.project_path))
# @task
# def docker_update():
# docker_build()
# @task
# def docker_build():
# info('building docker')
# sudo('docker build -t stage1 %s/docker/stage1' % env.project_path)
# sudo('docker build -t php %s/docker/php' % env.project_path)
# sudo('docker build -t symfony2 %s/docker/symfony2' % env.project_path)
# @task
# def docker_clean():
# info('cleaning docker')
# sudo('%s/bin/docker/clean.sh' % env.project_path)
# @task
# def deploy():
# if needs_cold_deploy():
# info('first time deploy')
# cold_deploy()
# else:
# hot_deploy()
# @task
# def cold_deploy():
# prepare()
# branch = git_branch()
# info('deploying branch "%s"' % branch)
# prepare_deploy(branch)
# tag_release()
# reset_environment()
# prepare_assets()
# processes_stop()
# rsync()
# fix_permissions()
# with cd(env.project_path):
# docker_build()
# init_parameters()
# info('clearing remote cache')
# run('php app/console cache:clear --env=prod --no-debug')
# run('chmod -R 0777 app/cache app/logs')
# create_database()
# info('running database migrations')
# run('php app/console doctrine:schema:update --env=prod --no-debug --force')
# # services_restart()
# processes_start()
# run('chown -R www-data:www-data %s' % env.project_path)
# run('chmod -R 0777 %s/app/cache %s/app/logs' % (env.project_path, env.project_path))
# @task
# def hot_deploy():
# branch = git_branch()
# info('deploying branch "%s"' % branch)
# prepare_deploy(branch)
# tag_release()
# reset_environment()
# prepare_assets()
# # processes_stop()
# rsync()
# with cd(env.project_path):
# info('clearing remote cache')
# run('php app/console cache:clear --env=prod --no-debug')
# run('chmod -R 0777 app/cache app/logs')
# info('running database migrations')
# run('php app/console doctrine:schema:update --env=prod --no-debug --force')
# # services_restart()
# # processes_start()
# run('chown -R www-data:www-data %s' % env.project_path)
# run('chmod -R 0777 %s/app/cache %s/app/logs' % (env.project_path, env.project_path))
# def info(string):
# print(green('---> %s' % string))
# def warning(string):
# print(yellow('---> %s' % string))
# def error(string):
# abord(red('---> %s' %string))
# @task
# def is_release_tagged():
# return len(local('git tag --contains HEAD', capture=True)) > 0
# @task
# def git_branch():
# return local('git symbolic-ref -q HEAD | sed -e \'s,^refs/heads/,,\'', capture=True)
# @task
# def builder_restart():
# info('restarting builder')
# with settings(warn_only=True):
# sudo('restart %s-consumer-build' % env.processes_prefix)
# @task
# def processes_stop():
# info('stopping processes')
# with settings(warn_only=True):
# for process in env.processes:
# sudo('stop %s-%s' % (env.processes_prefix, process))
# @task
# def processes_start():
# info('starting processes')
# with settings(warn_only=True):
# for process in env.processes:
# sudo('start %s-%s' % (env.processes_prefix, process))
# @task
# def processes_restart():
# info('restarting processes')
# with settings(warn_only=True):
# for process in env.processes:
# sudo('restart %s-%s' % (env.processes_prefix, process))
# @task
# def services_restart():
# sudo('/etc/init.d/nginx restart')
# sudo('/etc/init.d/php5-fpm restart')
# sudo('/etc/init.d/rabbitmq-server restart')
# @runs_once
# @task
# def prepare_deploy(ref='HEAD'):
# info('checking that the repository is clean')
# with settings(warn_only=True):
# if (1 == local('git diff --quiet --ignore-submodules -- %s' % ref).return_code):
# error('Your repository is not in a clean state.')
# # local('git fetch --quiet origin refs/heads/%(ref)s:refs/remotes/origin/%(ref)s' % {'ref': ref})
# if (1 == local('git diff --quiet --ignore-submodules -- remotes/origin/%s' % ref)):
# error('Please merge origin before deploying')
# @task
# def diff():
# last_tag = local('git describe --tags $(git rev-list --tags --max-count=1)', capture=True)
# local('git log --pretty=oneline --color %s..' % last_tag)
# @runs_once
# @task
# def tag_release():
# if is_release_tagged():
# info('release is already tagged, skipping')
# return
# tag = local('git describe --tags $(git rev-list --tags --max-count=1) | sed \'s/v//\' | awk -F . \'{ printf "v%d.%d.%d", $1, $2, $3 + 1 }\'', capture=True)
# local('git tag %s' % tag)
# info('tagged version %s' % tag)
# local('git push origin --tags')
# @runs_once
# @task
# def reset_environment():
# info('resetting local environment')
# local('php app/console cache:clear --env=prod --no-debug --no-warmup')
# # local('php app/console cache:clear --env=dev --no-debug --no-warmup')
# local('composer dump-autoload --optimize')
# @task
# def rsync():
# info('rsyncing to remote')
# c = "rsync --verbose --rsh=ssh --exclude-from=%(exclude_from)s --progress -crDpLt --force --delete ./ %(user)s@%(host)s:%(remote)s" % {
# 'exclude_from': env.rsync_exclude_from,
# 'user': env.user,
# 'host': env.host_string,
# 'remote': env.project_path
# }
# local(c)
| [
"grosfrais@gmail.com"
] | grosfrais@gmail.com |
309e77246c235fefa9e1854661928a6a02ab1d49 | fd0f1daa3a9ae9a8db894988f90767fdd9a97dde | /usbtest.py | 442087709a35cddc2eb732a8e6730daa7a846c40 | [] | no_license | handelxh/python | 28ea57e1fa5bd35e5d91148eb7cff71ce5e9680d | 3183fca68b686c794cf857d04af2c2345fb9f802 | refs/heads/master | 2016-09-05T12:39:35.462516 | 2014-09-09T02:00:35 | 2014-09-09T02:00:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 689 | py | import usb.core
import usb.util
# find our device
dev = usb.core.find(idVendor=0x040d, idProduct=0x340a)
# # was it found?
# if dev is None:
# raise ValueError('Device not found')
# # set the active configuration. With no arguments, the first
# # configuration will be the active one
# dev.set_configuration()
# # get an endpoint instance
# cfg = dev.get_active_configuration()
# intf = cfg[(0,0)]
# ep = usb.util.find_descriptor(
# intf,
# # match the first OUT endpoint
# custom_match = \
# lambda e: \
# usb.util.endpoint_direction(e.bEndpointAddress) == \
# usb.util.ENDPOINT_OUT)
# assert ep is not None
# # write the data
# ep.write('test') | [
"handelxh@163.com"
] | handelxh@163.com |
4a2670d464ccb643b28efd7bb90b6c5de24f027a | 3c037200d101bdfc3774d7ef05800fa0029f0b56 | /segmentation/Models/block.py | 2882928c195599965d5440da490f676a484d3d45 | [] | no_license | wzjialang/Semi-InstruSeg | 81a679cad4fb9a91a820d4b43f63efba02775cd5 | 5a2156eb1d5239d90ed2485a3bbc882db104d866 | refs/heads/master | 2023-03-15T20:47:07.682356 | 2020-10-09T04:28:48 | 2020-10-09T04:28:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,473 | py | import torch
import torch.nn as nn
from torch.nn.modules.loss import _Loss
class SoftDiceLoss(_Loss):
def __init__(self, size_average=None, reduce=None, reduction='mean'):
super(SoftDiceLoss, self).__init__(size_average, reduce, reduction)
def forward(self, y_pred, y_gt):
numerator = torch.sum(y_pred*y_gt)
denominator = torch.sum(y_pred*y_pred + y_gt*y_gt)
return numerator/denominator
class First3D(nn.Module):
def __init__(self, in_channels, middle_channels, out_channels, dropout=False):
super(First3D, self).__init__()
layers = [
nn.Conv3d(in_channels, middle_channels, kernel_size=3, padding=1),
nn.BatchNorm3d(middle_channels),
nn.ReLU(inplace=True),
nn.Conv3d(middle_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm3d(out_channels),
nn.ReLU(inplace=True)
]
if dropout:
assert 0 <= dropout <= 1, 'dropout must be between 0 and 1'
layers.append(nn.Dropout3d(p=dropout))
self.first = nn.Sequential(*layers)
def forward(self, x):
return self.first(x)
class Encoder3D(nn.Module):
def __init__(
self, in_channels, middle_channels, out_channels,
dropout=False, downsample_kernel=2
):
super(Encoder3D, self).__init__()
layers = [
nn.MaxPool3d(kernel_size=downsample_kernel),
nn.Conv3d(in_channels, middle_channels, kernel_size=3, padding=1),
nn.BatchNorm3d(middle_channels),
nn.ReLU(inplace=True),
nn.Conv3d(middle_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm3d(out_channels),
nn.ReLU(inplace=True)
]
if dropout:
assert 0 <= dropout <= 1, 'dropout must be between 0 and 1'
layers.append(nn.Dropout3d(p=dropout))
self.encoder = nn.Sequential(*layers)
def forward(self, x):
return self.encoder(x)
class Center3D(nn.Module):
def __init__(self, in_channels, middle_channels, out_channels, deconv_channels, dropout=False):
super(Center3D, self).__init__()
layers = [
nn.MaxPool3d(kernel_size=2),
nn.Conv3d(in_channels, middle_channels, kernel_size=3, padding=1),
nn.BatchNorm3d(middle_channels),
nn.ReLU(inplace=True),
nn.Conv3d(middle_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm3d(out_channels),
nn.ReLU(inplace=True),
nn.ConvTranspose3d(out_channels, deconv_channels, kernel_size=2, stride=2)
]
if dropout:
assert 0 <= dropout <= 1, 'dropout must be between 0 and 1'
layers.append(nn.Dropout3d(p=dropout))
self.center = nn.Sequential(*layers)
def forward(self, x):
return self.center(x)
class Decoder3D(nn.Module):
def __init__(self, in_channels, middle_channels, out_channels, deconv_channels, dropout=False):
super(Decoder3D, self).__init__()
layers = [
nn.Conv3d(in_channels, middle_channels, kernel_size=3, padding=1),
nn.BatchNorm3d(middle_channels),
nn.ReLU(inplace=True),
nn.Conv3d(middle_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm3d(out_channels),
nn.ReLU(inplace=True),
nn.ConvTranspose3d(out_channels, deconv_channels, kernel_size=2, stride=2)
]
if dropout:
assert 0 <= dropout <= 1, 'dropout must be between 0 and 1'
layers.append(nn.Dropout3d(p=dropout))
self.decoder = nn.Sequential(*layers)
def forward(self, x):
return self.decoder(x)
class Last3D(nn.Module):
def __init__(self, in_channels, middle_channels, out_channels, softmax=False):
super(Last3D, self).__init__()
layers = [
nn.Conv3d(in_channels, middle_channels, kernel_size=3, padding=1),
nn.BatchNorm3d(middle_channels),
nn.ReLU(inplace=True),
nn.Conv3d(middle_channels, middle_channels, kernel_size=3, padding=1),
nn.BatchNorm3d(middle_channels),
nn.ReLU(inplace=True),
nn.Conv3d(middle_channels, out_channels, kernel_size=1),
nn.Softmax(dim=1)
]
self.first = nn.Sequential(*layers)
def forward(self, x):
return self.first(x) | [
"zixuzhao1218@gmail.com"
] | zixuzhao1218@gmail.com |
78018c0b4ab40290bfbc391b78e67bacb8a8651c | 8aced53327d2345d34fe64d76798a69593a3bc16 | /RandomPasswordGenerator.py | a536efe7f3d3380089b0d6f99ff2db1388a047fd | [] | no_license | joo7998/Python_NumberGenerator | 4b5c37b9e2358e6d10df50a57daa0f925a36fe85 | 0150fc6cb84ba60695adf50c66036af1a418b07f | refs/heads/main | 2023-08-07T04:49:29.839145 | 2021-09-21T09:02:01 | 2021-09-21T09:02:01 | 408,752,074 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 823 | py | # 8 characters
# 2 upper, 2 lower, 2 numbers, 2 special letters
import random
# list = [1, 2, 5]
# random.shuffle(list)
# print(list)
def shuffle(string):
tempList = list(string)
random.shuffle(tempList)
return ''.join(tempList)
# print(random.randint(3, 9))
# chr : returns a str representing a character whose unicode is an integer
upper1 = chr(random.randint(65, 90))
upper2 = chr(random.randint(65, 90))
lower1 = chr(random.randint(97, 122))
lower2 = chr(random.randint(97, 122))
number1 = chr(random.randint(48, 57))
number2 = chr(random.randint(48, 57))
special1 = chr(random.randint(33, 47))
special2 = chr(random.randint(33, 47))
password = upper1 + upper2 + lower1 + lower2 + number1 + number2 + special1 + special2
password = shuffle(password)
print(password)
| [
"noreply@github.com"
] | joo7998.noreply@github.com |
be6b292a523be3b7f2b1249bf1015b6cfcb24ed6 | 90af4fb4c23ea4ca72d0d47223abbde14662e550 | /Stark_account/mixins.py | e7839e35d6e98c7190ba7fc522b172181f9f45a7 | [] | no_license | saeedrezaghazanfari/stark_panel | 3ce0232d87da460dfcc1ec3e97e4b07f73d3b3d2 | 15a7466bfc51a30edae8c3fee6a42b28f52d8f41 | refs/heads/main | 2023-05-08T22:35:38.931495 | 2021-06-06T08:14:02 | 2021-06-06T08:14:02 | 372,149,739 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 404 | py | from django.contrib.auth.decorators import login_required, user_passes_test
# Decorators
# is_authenticated permission decorator
def authenticated_required_decorator(function=None, login_url=None):
actual_decorator = user_passes_test(
lambda u: not u.is_authenticated,
login_url=login_url,
)
if function:
return actual_decorator(function)
return actual_decorator | [
"saeedreza.gh.1397@gmail.com"
] | saeedreza.gh.1397@gmail.com |
f6c28f792622e40fc67e2dfa9adebe9065bbe208 | 2da329f2893d97e40ed09ea07c8ce93c918afd8a | /Term 1/4. Introduction to TensorFlow/MINST_Training2/datasetMemoryTest.py | b67999322ede2773a3d04e4e6bbf99fc7ae4daa7 | [] | no_license | Abdilaziz/Self-Driving-NanoDegree | 4271726d30a830dbd9cf95c15346aecedac39771 | 2623fece4943181e32c6b814502dea0ffadbbfad | refs/heads/master | 2021-01-19T11:38:00.899885 | 2018-08-12T16:49:37 | 2018-08-12T16:49:37 | 82,256,055 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 651 | py | from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)
# Import MNIST data
mnist = input_data.read_data_sets('/datasets/ud730/mnist', one_hot=True)
# The features are already scaled and the data is shuffled
train_features = mnist.train.images
test_features = mnist.test.images
train_labels = mnist.train.labels.astype(np.float32)
test_labels = mnist.test.labels.astype(np.float32)
# Weights & bias
weights = tf.Variable(tf.random_normal([n_input, n_classes]))
bias = tf.Variable(tf.random_normal([n_classes]))
| [
"azizib2nd@gmail.com"
] | azizib2nd@gmail.com |
ed877d70208fb995c60c520bc27eebcce3ebbcba | dd6b960deef0c0f9c49403258020a641b3cafc69 | /rug/cli.py | c9754906f4b9210355912115ab6ec741a3f3dbb7 | [] | no_license | cou929/rug | 10506833bcda35c701bffe5acb935bcd2bb6cefb | 6b280c1572bd4c943f987257b2146f664f7d82a9 | refs/heads/master | 2021-01-22T06:58:46.766103 | 2020-04-08T15:43:07 | 2020-04-08T15:43:07 | 7,295,820 | 0 | 0 | null | 2012-12-25T09:22:58 | 2012-12-23T14:47:40 | Python | UTF-8 | Python | false | false | 2,367 | py | # -*- coding: utf-8 -*-
"""
rug.cli
CLI interface.
"""
import os
import sys
import optparse
from .articles import Articles
from .articles import ArticlesWithMeta
from .view import IndivisualPage, ArchivePage, AboutPage, RSS
def dispatch():
"""
Dispatcher.
Read stdin and command line options, then call property method.
"""
usage = 'usage: %prog -a ARTICLE_PATH -t TEMPLATE_PATH -o OUTPUT_PATH'
parser = optparse.OptionParser(usage=usage)
parser.add_option("-a", "--articles", action="store", dest="article_path",
type="string", help="path to articles dir (required)",
)
parser.add_option("-t", "--templete", action="store", dest="template_path",
type="string", help="path to templates dir (required)",
)
parser.add_option("-o", "--output", action="store", dest="output_path",
type="string", help="path to output dir (required)",
)
parser.add_option("-n", "--norss", action="store_true",
dest="norss", default=False,
help="don't publish new rss feed"
)
(options, args) = parser.parse_args()
if (not options.article_path or
not options.template_path or
not options.output_path):
parser.print_usage()
sys.exit(1)
run(options.article_path,
options.template_path,
options.output_path,
options.norss)
sys.exit()
def run(article_path, template_path, output_path, norss):
articles = ArticlesWithMeta(article_path).get()
templates = {
'layout': os.path.join(template_path, 'layout.mustache')
}
indivisual_page = IndivisualPage(articles,
templates,
output_path)
indivisual_page.publish()
templates['content'] = os.path.join(
template_path, 'include', 'archive.mustache')
archive_pate = ArchivePage(articles, templates, output_path)
archive_pate.publish()
templates['content'] = os.path.join(
template_path, 'include', 'about.html')
about_pate = AboutPage([], templates, output_path)
about_pate.publish()
if not norss:
rss = RSS(articles, templates, output_path)
rss.publish()
| [
"cou929@gmail.com"
] | cou929@gmail.com |
c14edfee003af5a818b5ccbf447009ef28f6ca1f | a9785114ec98aca4b1a4230f7a400acadb9d7c7d | /loadpkl.py | 5924df8b7e374990e44f95cea1312e2498441002 | [] | no_license | prakharg05/Clustering-KMeans-and-Agglomerative | e44face5142f9f102916a13d7d6b48112fb4e239 | d1d2dc55efc2da772909a9699ea5d8aac8eb4188 | refs/heads/master | 2020-05-04T04:03:40.491017 | 2019-04-01T22:46:01 | 2019-04-01T22:46:01 | 178,958,170 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 128 | py | import pickle
scores=pickle.load(open("./scores.pkl","rb"))
c=0
for i in scores:
print(i,scores[i])
c+=1
if c==35:
break | [
"noreply@github.com"
] | prakharg05.noreply@github.com |
8fc0c61edc7dbd406d57b6c6026f8b0e6517aa08 | 0175db4235469cc197570e1fc1761af3d502950e | /code/env/gridworld.py | d229829c7f54d61e17db4780f9de8740735b1b8f | [] | no_license | dpstart/rl | defe9fff962b669ab9b02002b4896f367a19c03a | 514ff69ba14bf5f99cb548430fa563954ceaabfb | refs/heads/master | 2020-04-11T20:47:58.450673 | 2019-08-24T17:47:27 | 2019-08-24T17:47:27 | 162,083,097 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,594 | py | # Code borrowed from https://github.com/dennybritz/reinforcement-learning/blob/master/lib/envs/gridworld.py
import numpy as np
import sys
from gym.envs.toy_text import discrete
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
class GridworldEnv(discrete.DiscreteEnv):
"""
Grid World environment from Sutton's Reinforcement Learning book chapter 4.
You are an agent on an MxN grid and your goal is to reach the terminal
state at the top left or the bottom right corner.
For example, a 4x4 grid looks as follows:
T o o o
o x o o
o o o o
o o o T
x is your position and T are the two terminal states.
You can take actions in each direction (UP=0, RIGHT=1, DOWN=2, LEFT=3).
Actions going off the edge leave you in your current state.
You receive a reward of -1 at each step until you reach a terminal state.
"""
metadata = {'render.modes': ['human', 'ansi']}
def __init__(self, shape=[4,4]):
if not isinstance(shape, (list, tuple)) or not len(shape) == 2:
raise ValueError('shape argument must be a list/tuple of length 2')
self.shape = shape
nS = np.prod(shape)
nA = 4
MAX_Y = shape[0]
MAX_X = shape[1]
P = {}
grid = np.arange(nS).reshape(shape)
it = np.nditer(grid, flags=['multi_index'])
while not it.finished:
s = it.iterindex
y, x = it.multi_index
P[s] = {a : [] for a in range(nA)}
is_done = lambda s: s == 0 or s == (nS - 1)
reward = 0.0 if is_done(s) else -1.0
# We're stuck in a terminal state
if is_done(s):
P[s][UP] = [(1.0, s, reward, True)]
P[s][RIGHT] = [(1.0, s, reward, True)]
P[s][DOWN] = [(1.0, s, reward, True)]
P[s][LEFT] = [(1.0, s, reward, True)]
# Not a terminal state
else:
ns_up = s if y == 0 else s - MAX_X
ns_right = s if x == (MAX_X - 1) else s + 1
ns_down = s if y == (MAX_Y - 1) else s + MAX_X
ns_left = s if x == 0 else s - 1
P[s][UP] = [(1.0, ns_up, reward, is_done(ns_up))]
P[s][RIGHT] = [(1.0, ns_right, reward, is_done(ns_right))]
P[s][DOWN] = [(1.0, ns_down, reward, is_done(ns_down))]
P[s][LEFT] = [(1.0, ns_left, reward, is_done(ns_left))]
it.iternext()
# Initial state distribution is uniform
isd = np.ones(nS) / nS
# We expose the model of the environment for educational purposes
# This should not be used in any model-free learning algorithm
self.P = P
super(GridworldEnv, self).__init__(nS, nA, P, isd)
def _render(self, mode='human', close=False):
if close:
return
outfile = StringIO() if mode == 'ansi' else sys.stdout
grid = np.arange(self.nS).reshape(self.shape)
it = np.nditer(grid, flags=['multi_index'])
while not it.finished:
s = it.iterindex
y, x = it.multi_index
if self.s == s:
output = " x "
elif s == 0 or s == self.nS - 1:
output = " T "
else:
output = " o "
if x == 0:
output = output.lstrip()
if x == self.shape[1] - 1:
output = output.rstrip()
outfile.write(output)
if x == self.shape[1] - 1:
outfile.write("\n")
it.iternext()
| [
"danielepaliotta96@gmail.com"
] | danielepaliotta96@gmail.com |
06ae81a4388c1262eae3644a03ca0ab1b791684a | 1a7456d2ca5d2e2db23b2e8dce7a9616a1efbab5 | /NN_for_dispatch/test_pytorch_nn_sigmoid_wsu_transfer_base.py | 5c54b1d9858be6c607f768a9f87c33e3bfe93cf0 | [] | no_license | nadiavp/NeuralNetwork | 093505e0fe4d68730632444372d09f799d410dc4 | 65be7a1e6e8a7296178b40e8ca35a55ae06b097e | refs/heads/master | 2020-03-25T19:15:36.763961 | 2019-11-12T20:42:27 | 2019-11-12T20:42:27 | 144,073,729 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 16,109 | py | #pytorch tests
import numpy as np
import xlrd
import torch
def train_nn_sigmoid(layers=4):
dtype = torch.float
#device = torch.device("cpu")
device = torch.device("cuda:0")
load_e = []
load_h = []
load_c = []
t_db = []
irrad = []
wb = xlrd.open_workbook('c:/Users/Nadia Panossian/Documents/GitHub/EAGERS_wsu/GUI/Optimization/Results/wsu_campus_2009_2012.xlsx')
sheet = wb.sheet_by_index(0)
n_disps = 365*24
inputs= torch.zeros(n_disps,16)#, device=device, dtype=dtype)
e_dem_max = [3787.993,6311.181,4533.527,378.7993]#sheet.cell_value(1,7)
h_dem_max = [7570.097,12612.55,9060.006,757.0097]#sheet.cell_value(1,8)
c_dem_max = [8345.065,13903.73,9987.5,834.5065]#sheet.cell_value(1,9)
cost_max = 0.07#sheet.cell_value(1,12)
for row in range(1,n_disps):
inputs[row-1,0] = sheet.cell_value(row,0)*38480/117415.7/e_dem_max[2]#E_dem_0
inputs[row-1,1] = sheet.cell_value(row,0)*38480/117415.7/e_dem_max[2]#E_dem_1
inputs[row-1,2] = sheet.cell_value(row,0)*32152/117415.7/e_dem_max[0]#E_dem_2
inputs[row-1,3] = sheet.cell_value(row,0)*53568.5/117415.7/e_dem_max[1]#E_dem_3
inputs[row-1,4] = sheet.cell_value(row,0)*3215.2/117415.7/e_dem_max[3]#E_dem_4
inputs[row-1,5] = sheet.cell_value(row,0)*38480/117415.7/e_dem_max[2]#E_dem_5
inputs[row-1,6] = sheet.cell_value(row,0)*3215.2/117415.7/e_dem_max[3]#E_dem_6
inputs[row-1,7] = sheet.cell_value(row,1)*32152/117415.7/h_dem_max[0]#H_dem_2
inputs[row-1,8] = sheet.cell_value(row,1)*53568.5/117415.7/h_dem_max[1]#H_dem_3
inputs[row-1,9] = sheet.cell_value(row,1)*38480/117415.7/h_dem_max[2]#H_dem_4
inputs[row-1,10] = sheet.cell_value(row,1)*3215.2/117415.7/h_dem_max[3]#H_dem_5
inputs[row-1,11] = sheet.cell_value(row,2)*32152/117415.7/c_dem_max[0]#C_dem_2
inputs[row-1,12] = sheet.cell_value(row,2)*53568.5/117415.7/c_dem_max[1]#C_dem_3
inputs[row-1,13] = sheet.cell_value(row,2)*38480/117415.7/c_dem_max[2]#C_dem_4
inputs[row-1,14] = sheet.cell_value(row,2)*3215.2/117415.7/c_dem_max[3]#C_dem_5
inputs[row-1,15] = 1#sheet.cell_value(row,4)/cost_max #utility electric cost
# inputs[row-2,0] = sheet.cell_value(row,1)#E_dem
# inputs[row-2,1] = sheet.cell_value(row,2)#H_dem
# inputs[row-2,2] = sheet.cell_value(row,3)#C_dem
# inputs[row-2,3] = sheet.cell_value(row,4)/cost_max #utility electric cost
#inputs[row-2,3] = sheet.cell_value(row,4)/sheet.cell_value(1,10)#Temp_db_C
#inputs[row-2,4] = sheet.cell_value(row,5)/sheet.cell_value(1,11)#Direct_normal_irradiance
# load_e.append(row)
# load_h.append(row[1])
# load_c.append(row[2])
# t_db.append(row[3])
# irrad.append(row[4])
# inputs.append(row)
#inputs[:,1] = (inputs[:,1]-min(inputs[:,1]))/h_dem_max
#inputs[:,2] = (inputs[:,2]-min(inputs[:,2]))/c_dem_max
# inputs[:,1] = inputs[:,1]/h_dem_max
# inputs[:,2] = inputs[:,2]/c_dem_max
print('inputs read')
wb = xlrd.open_workbook('c:/Users/Nadia Panossian/Documents/GitHub/EAGERS_wsu/GUI/Optimization/Results/wsu_cqp.xlsx')
sheet = wb.sheet_by_index(0)
disp = torch.zeros(n_disps,23)#, device=device, dtype=dtype)
for row in range(1,n_disps):
r = row-1
# inputs[r,0] -=sheet.cell_value(row,1)
disp[r,0] = sheet.cell_value(row,3)/2500#GT1
disp[r,1] = sheet.cell_value(row,15)/2187.5#GT2
disp[r,2] = sheet.cell_value(row,24)/1375#GT3
disp[r,3] = sheet.cell_value(row,25)/1375#GT4
disp[r,4] = sheet.cell_value(row,6)/20000#boiler1
disp[r,5] = sheet.cell_value(row,17)/20000#boiler2
disp[r,6] = sheet.cell_value(row,18)/20000#boiler3
disp[r,7] = sheet.cell_value(row,19)/20000#boiler4
disp[r,8] = sheet.cell_value(row,20)/20000#boiler5
disp[r,9] = sheet.cell_value(row,4)/(7.279884675000000e+03)#carrier1
disp[r,10] = sheet.cell_value(row,7)/(5.268245045000001e+03)#york1
disp[r,11] = sheet.cell_value(row,8)/(5.268245045000001e+03)#york3
disp[r,12] = sheet.cell_value(row,9)/(5.275278750000000e+03)#carrier7
disp[r,13] = sheet.cell_value(row,10)/(5.275278750000000e+03)#carrier8
disp[r,14] = sheet.cell_value(row,11)/(4.853256450000000e+03)#carrier2
disp[r,15] = sheet.cell_value(row,12)/(4.853256450000000e+03)#carrier3
disp[r,16] = sheet.cell_value(row,13)/(1.758426250000000e+03)#carrier4
disp[r,17] = sheet.cell_value(row,14)/(1.415462794200000e+03)#trane
disp[r,18] = sheet.cell_value(row,5)/2000000#cold water tank
disp[r,19] = 0.05#.9/1.1#sheet.cell_value(row,11)#voltage0#GT1 reactive
disp[r,20] = 0.05#1.1/1.1#sheet.cell_value(row,12)#voltage1# GT2 reactive
disp[r,21] = 0.05#.9/1.1#sheet.cell_value(row,13)#voltage2# GT3 reactive
disp[r,22] = 0.05#.9/1.1#sheet.cell_value(row,13)#voltage3# GT4 reactive
#disp[r,23] = .9/1.1#sheet.cell_value(row,14)#voltage4
#disp[r,24] = .9/1.1#sheet.cell_value(row,15)#voltage5
#disp[r,25] = .9/1.1#voltage6
# disp[r,0] = sheet.cell_value(row,2)/7000#GT1
# disp[r,1] = sheet.cell_value(row,3)/5000#GT2
# disp[r,2] = sheet.cell_value(row,4)/2000#FC1
# disp[r,3] = sheet.cell_value(row,5)/2000#FC2
# disp[r,4] = sheet.cell_value(row,6)/500#sGT
# disp[r,5] = sheet.cell_value(row,7)/1500#Diesel
# disp[r,6] = sheet.cell_value(row,8)/20000#Heater
# disp[r,7] = sheet.cell_value(row,9)/10000#chiller1
# disp[r,8] = sheet.cell_value(row,10)/10000#chiller2
# disp[r,9] = sheet.cell_value(row,11)/7500#small Chiller1
# disp[r,10] = sheet.cell_value(row,12)/7500#small Chiller2
# disp[r,11] = sheet.cell_value(row,13)/30000#battery
# disp[r,12] = sheet.cell_value(row,14)/75000#hot water tank
# disp[r,13] = sheet.cell_value(row,15)/200000#cold water tank
renew_gen = sheet.cell_value(row+1, 21) + sheet.cell_value(row+1,22)#sheet.cell_value(row+1,12) #solar generation
inputs[row-2,6] = inputs[row-2,6]-max(renew_gen,0)/e_dem_max[3]
# inputs[:,0] = inputs[:,0]/e_dem_max#inputs[:,0] = (inputs[:,0]-min(inputs[:,0]))/max(inputs[:,0])
#inputs[1:,4:] = disp[:-1,:]
inputs = inputs[1:,:]
disp = disp[1:,:]
print('outputs read')
#shuffle and separate training from testing
shuffled = [inputs,disp]
shuffled = torch.randperm(len(inputs[:,0]))
split_line = int(np.floor(len(inputs[:,0])/10))
inputs = inputs[shuffled,:]
disp = disp[shuffled,:]
inputs_train = inputs[:-split_line,:]
inputs_test = inputs[-split_line:, :]
disp_train = disp[:-split_line, :]
disp_test = disp[-split_line:, :]
disp = disp_train
inputs = inputs_train
#batch size, input dimension hidden dimension, output dimension
N, D_in, H, D_out = len(inputs[:,0]), len(inputs[0,:]), int(np.ceil(len(inputs[0,:])+len(disp[0,:])/2)), len(disp[0,:])
H2 = int(np.round(H*1.2))
H3 = int(np.round(H*0.8))
H4 = H2
x = inputs
y = disp
if layers == 1:
model = torch.nn.Sequential(
torch.nn.Sigmoid(D_in, D_out)
)
elif layers == 2:
model = torch.nn.Sequential(
torch.nn.Sigmoid(),
torch.nn.ReLU(),
torch.nn.Linear(D_in, D_out)
)
elif layers == 3:
model = torch.nn.Sequential(
torch.nn.Sigmoid(),
torch.nn.ReLU(),
torch.nn.Linear(D_in, H),
torch.nn.ReLU(),
torch.nn.Linear(H, D_out)
)
elif layers == 4:
model = torch.nn.Sequential(
torch.nn.Sigmoid(),
torch.nn.ReLU(),
torch.nn.Linear(D_in, H),
torch.nn.ReLU(),
torch.nn.Linear(H, H),
torch.nn.ReLU(),
torch.nn.Linear(H, D_out)
)
elif layers == 5:
model = torch.nn.Sequential(
torch.nn.Sigmoid(),
torch.nn.ReLU(),
torch.nn.Linear(D_in, H),
torch.nn.ReLU(),
torch.nn.Linear(H, H2),
torch.nn.ReLU(),
torch.nn.Linear(H2, H),
torch.nn.ReLU(),
torch.nn.Linear(H, D_out)
)
elif layers == 6:
model = torch.nn.Sequential(
torch.nn.Sigmoid(),
torch.nn.ReLU(),
torch.nn.Linear(D_in, H),
torch.nn.ReLU(),
torch.nn.Linear(H, H2),
torch.nn.ReLU(),
torch.nn.Linear(H2, H3),
torch.nn.ReLU(),
torch.nn.Linear(H3, H),
torch.nn.ReLU(),
torch.nn.Linear(H, D_out)
)
else: #layers = 7
model = torch.nn.Sequential(
torch.nn.Sigmoid(),
torch.nn.ReLU(),
torch.nn.Linear(D_in, H),
torch.nn.ReLU(),
torch.nn.Linear(H, H2),
torch.nn.ReLU(),
torch.nn.Linear(H2, H3),
torch.nn.ReLU(),
torch.nn.Linear(H3, H2),
torch.nn.ReLU(),
torch.nn.Linear(H2, H),
torch.nn.ReLU(),
torch.nn.Linear(H, D_out)
)
loss_fn = torch.nn.MSELoss(reduction='sum')
n_iters = 50000
loss_rate = np.zeros(n_iters)
learning_rate = 1e-6
for t in range(n_iters):
y_pred = model(x)
loss = loss_fn(y_pred, y)
print(t, loss.item())
loss_rate[t] = loss.item()
model.zero_grad()
loss.backward()
with torch.no_grad():
for param in model.parameters():
param -= learning_rate *param.grad
y_pred_np = y_pred.detach().numpy()
y_np = y.detach().numpy()
acc = sum((y_pred_np-y_np)**2)/len(y[:,0])
#a = 0
#test
y_pred = model(inputs_test)
y_pred_test = y_pred.detach().numpy()
y_test = disp_test.detach().numpy()
acc_test = sum((y_pred_test-y_test)**2)/len(y_test[:,0])
#b=0
# input_scale_factors = np.array([e_dem_max, h_dem_max, c_dem_max, cost_max])
# output_scale_factors = np.array([7000, 5000, 2000, 2000, 500, 1500, 20000, 10000, 10000, 7500, 7500, 30000, 75000, 200000])
input_scale_factors = np.array([e_dem_max[2], e_dem_max[2], e_dem_max[0], e_dem_max[1], e_dem_max[3], e_dem_max[2], e_dem_max[3],\
h_dem_max[0], h_dem_max[1], h_dem_max[2], h_dem_max[3], c_dem_max[0], c_dem_max[1], c_dem_max[2], c_dem_max[3], cost_max])
output_scale_factors = np.array([2500, 2187.5, 1375, 1375, 20000, 20000, 20000, 20000, 20000,\
7.279884675000000e+03, 5.268245045000001e+03, 5.268245045000001e+03, 5.275278750000000e+03, 5.275278750000000e+03, 4.853256450000000e+03,\
4.853256450000000e+03, 1.758426250000000e+03, 1.758426250000000e+03, 2000000, 2500, 2187.5, 1375, 1375])
print('nn trained, beginning transfer learning')
##################### next train on the conic solutions
wb = xlrd.open_workbook('c:/Users/Nadia Panossian/Documents/GitHub/EAGERS_wsu/GUI/Optimization/Results/conic_analysis_01.xlsx')
sheet = wb.sheet_by_index(1)
n_disps = int(round(100))
inputs= torch.zeros(n_disps,16)#, device=device, dtype=dtype)
e_dem_max = [3787.993,6311.181,4533.527,378.7993]#sheet.cell_value(1,7)
h_dem_max = [7570.097,12612.55,9060.006,757.0097]#sheet.cell_value(1,8)
c_dem_max = [8345.065,13903.73,9987.5,834.5065]#sheet.cell_value(1,9)
cost_max = 0.07#sheet.cell_value(1,12)
for row in range(n_disps):
r = (row*24)+1
inputs[row,0] = sheet.cell_value(r,111)*38480/117415.7/e_dem_max[2]#E_dem_0
inputs[row,1] = sheet.cell_value(r,111)*38480/117415.7/e_dem_max[2]#E_dem_1
inputs[row,2] = sheet.cell_value(r,111)*32152/117415.7/e_dem_max[0]#E_dem_2
inputs[row,3] = sheet.cell_value(r,111)*53568.5/117415.7/e_dem_max[1]#E_dem_3
inputs[row,4] = sheet.cell_value(r,111)*3215.2/117415.7/e_dem_max[3]#E_dem_4
inputs[row,5] = sheet.cell_value(r,111)*38480/117415.7/e_dem_max[2]#E_dem_5
inputs[row,6] = (sheet.cell_value(r,111)-sheet.cell_value(r,110))*3215.2/117415.7/e_dem_max[3]#E_dem_6
inputs[row,7] = sheet.cell_value(r,112)*32152/117415.7/h_dem_max[0]#H_dem_2
inputs[row,8] = sheet.cell_value(r,112)*53568.5/117415.7/h_dem_max[1]#H_dem_3
inputs[row,9] = sheet.cell_value(r,112)*38480/117415.7/h_dem_max[2]#H_dem_4
inputs[row,10] = sheet.cell_value(r,112)*3215.2/117415.7/h_dem_max[3]#H_dem_5
inputs[row,11] = sheet.cell_value(r,113)*32152/117415.7/c_dem_max[0]#C_dem_2
inputs[row,12] = sheet.cell_value(r,113)*53568.5/117415.7/c_dem_max[1]#C_dem_3
inputs[row,13] = sheet.cell_value(r,113)*38480/117415.7/c_dem_max[2]#C_dem_4
inputs[row,14] = sheet.cell_value(r,113)*3215.2/117415.7/c_dem_max[3]#C_dem_5
inputs[row,15] = 1#sheet.cell_value(r,116)/cost_max #utility electric cost
print('conic inputs read')
wb = xlrd.open_workbook('c:/Users/Nadia Panossian/Documents/GitHub/EAGERS_wsu/GUI/Optimization/Results/conic_analysis_mod3.xlsx')
sheet = wb.sheet_by_index(1)
disp = torch.zeros(n_disps,23)#, device=device, dtype=dtype)
for r in range(n_disps):
row = r*24+1
# inputs[r,0] -=sheet.cell_value(row,1)
disp[r,0] = sheet.cell_value(row,40)/2500#GT1
disp[r,1] = sheet.cell_value(row,41)/2187.5#GT2
disp[r,2] = sheet.cell_value(row,42)/1375#GT3
disp[r,3] = sheet.cell_value(row,43)/1375#GT4
disp[r,4] = sheet.cell_value(row,57)/20000#boiler1
disp[r,5] = sheet.cell_value(row,58)/20000#boiler2
disp[r,6] = sheet.cell_value(row,59)/20000#boiler3
disp[r,7] = sheet.cell_value(row,60)/20000#boiler4
disp[r,8] = sheet.cell_value(row,61)/20000#boiler5
disp[r,9] = sheet.cell_value(row,67)/(7.279884675000000e+03)#carrier1
disp[r,10] = sheet.cell_value(row,68)/(5.268245045000001e+03)#york1
disp[r,11] = sheet.cell_value(row,69)/(5.268245045000001e+03)#york3
disp[r,12] = sheet.cell_value(row,70)/(5.275278750000000e+03)#carrier7
disp[r,13] = sheet.cell_value(row,71)/(5.275278750000000e+03)#carrier8
disp[r,14] = sheet.cell_value(row,72)/(4.853256450000000e+03)#carrier2
disp[r,15] = sheet.cell_value(row,73)/(4.853256450000000e+03)#carrier3
disp[r,16] = sheet.cell_value(row,74)/(1.758426250000000e+03)#carrier4
disp[r,17] = sheet.cell_value(row,75)/(1.415462794200000e+03)#trane
disp[r,18] = sheet.cell_value(row,96)/2000000#cold water tank
disp[r,0] = sheet.cell_value(row,44)/2500#GT1 reactive
disp[r,1] = sheet.cell_value(row,45)/2187.5#GT2 reactive
disp[r,2] = sheet.cell_value(row,46)/1375#GT3 reactive
disp[r,3] = sheet.cell_value(row,47)/1375#GT4 reactive
#shuffle and separate training from testing
shuffled = [inputs,disp]
shuffled = torch.randperm(len(inputs[:,0]))
split_line = int(np.floor(len(inputs[:,0])/10))
inputs = inputs[shuffled,:]
disp = disp[shuffled,:]
inputs_train = inputs[:-split_line,:]
inputs_test = inputs[-split_line:, :]
disp_train = disp[:-split_line, :]
disp_test = disp[-split_line:, :]
disp = disp_train
inputs = inputs_train
y = disp
x = inputs
# transfer learned nn to conic problem
n_iters = int(round(n_iters/10))
for t in range(n_iters):
y_pred = model(x)
loss = loss_fn(y_pred, y)
print(t, loss.item())
loss_rate[t] = loss.item()
model.zero_grad()
loss.backward()
with torch.no_grad():
for param in model.parameters():
param -= learning_rate *param.grad
y_pred_np = y_pred.detach().numpy()
y_np = y.detach().numpy()
acc = sum((y_pred_np-y_np)**2)/len(y[:,0])
#test
y_pred = model(inputs_test)
y_pred_test = y_pred.detach().numpy()
y_test = disp_test.detach().numpy()
acc_test = sum((y_pred_test-y_test)**2)/len(y_test[:,0])
return model, acc, acc_test, input_scale_factors, output_scale_factors, loss_rate
def fire_nn(model, scaled_inputs):
y_pred = model(scaled_inputs)
return y_pred
| [
"nadia.panossian@wsu.edu"
] | nadia.panossian@wsu.edu |
2ca452bcbb76a5940af2d37e15ccbd301ac908f9 | 46af8b5c7d1790ee9ddef636c7428eb5f23de5e5 | /project/settings_local.py | d8b4e8f42916c8b50165d0ad17e924372de258a3 | [] | no_license | praekelt/speed-demo | f1370628ca9241ec5cb86ea76f6c615c1138fa9e | 782c9d7263bed59a7d2ab9dc5d169a7a348a277e | refs/heads/master | 2020-12-07T15:24:26.979572 | 2017-06-28T14:03:50 | 2017-06-28T14:03:50 | 95,519,936 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,601 | py | import os
import raven
# Declare or redeclare variables here
FOOFOO = 1
# You should redefine the CACHE setting here
# Configure raven. Set "dsn" to None for your development environment. It must
# be None - anything else causes problems.
RAVEN_CONFIG = {
"dsn": None
# "dsn": "https://<key>:<secret>@sentry.io/<project>",
}
# Uncomment if you are doing performance profiling with Django Debug Toolbar
DEBUG_TOOLBAR_PANELS = [
#"ddt_request_history.panels.request_history.RequestHistoryPanel",
"debug_toolbar.panels.versions.VersionsPanel",
"debug_toolbar.panels.timer.TimerPanel",
"debug_toolbar.panels.settings.SettingsPanel",
"debug_toolbar.panels.headers.HeadersPanel",
"debug_toolbar.panels.request.RequestPanel",
"debug_toolbar.panels.sql.SQLPanel",
"debug_toolbar.panels.staticfiles.StaticFilesPanel",
"debug_toolbar.panels.templates.TemplatesPanel",
"debug_toolbar.panels.cache.CachePanel",
"debug_toolbar.panels.signals.SignalsPanel",
"debug_toolbar.panels.logging.LoggingPanel",
"debug_toolbar.panels.redirects.RedirectsPanel",
]
INTERNAL_IPS = ["127.0.0.1", "172.30.45.146"]
RESULTS_CACHE_SIZE = 20000
# If you need to access an existing variable your code must be in configure
def configure(**kwargs):
# Uncomment if you are doing performance profiling with Django Debug Toolbar
return {
"INSTALLED_APPS": kwargs["INSTALLED_APPS"] + ["debug_toolbar"],
"MIDDLEWARE_CLASSES": (
"debug_toolbar.middleware.DebugToolbarMiddleware",
) + kwargs["MIDDLEWARE_CLASSES"]
}
return {}
| [
"hedleyroos@gmail.com"
] | hedleyroos@gmail.com |
3d8c9a6b8c16826dd47e2fa709ff4143b281e99e | 0bf234b5f9cda7085b98b92cf4f927f458cb82b7 | /hw/hw1/venv/bin/easy_install-3.6 | 42a154fbc5a777ac0700bf611b3898d20dc64dc9 | [] | no_license | zackmcnulty/CSE_446-Machine_Learning | 9a37ee60178d9237d502f270ecf0b8657e1ec700 | 8711ca0ffdd8e7df9d97b4b5db69bd66ac7cccf0 | refs/heads/master | 2020-05-03T20:03:08.531707 | 2019-06-13T20:13:22 | 2019-06-13T20:13:22 | 178,795,215 | 9 | 1 | null | null | null | null | UTF-8 | Python | false | false | 276 | 6 | #!/Users/zackmcnulty/Desktop/CSE/446/hw/hw1/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from setuptools.command.easy_install import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"zmcnulty@uw.edu"
] | zmcnulty@uw.edu |
a33352b695bd70175bb97b31eba91e1d62473697 | e15cbbde358b96ed0f7d2e0bf7e5e9d640251a6c | /frontend/urls.py | 1c6bdf4b0b38fb3a171572693a9c06274f5118bd | [] | no_license | jmrcastillo/djangoRest-javascript | 5fb5f7548217b6464325e2a95fe9d4c7d493243f | dfd2f45ab054a38d540c83506a6221ab023d1d27 | refs/heads/master | 2021-07-18T09:01:45.783743 | 2020-03-08T12:10:27 | 2020-03-08T12:10:27 | 245,807,881 | 0 | 0 | null | 2021-04-08T19:48:18 | 2020-03-08T12:11:38 | JavaScript | UTF-8 | Python | false | false | 249 | py | from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.list, name="list"),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| [
"jm.cass20@gmail.com"
] | jm.cass20@gmail.com |
d08e6121ee2290536a5b41e02083249be2e73fcf | 2ea17b7b5fe875821f05f2d148220cfe7082120f | /migrations/versions/59c170d304e0_.py | 5c39be4beaf508e801753d04c3316590d69575ae | [] | no_license | xilixjd/python_react_blog_back_end | b1c76759654847717846671906d9bd1a758cd8f7 | 6b88e8f9340d35988c948e7c9ca1dff74dcf75d6 | refs/heads/master | 2020-05-20T18:50:13.941816 | 2017-08-08T13:48:49 | 2017-08-08T13:48:49 | 88,735,190 | 19 | 1 | null | null | null | null | UTF-8 | Python | false | false | 662 | py | """empty message
Revision ID: 59c170d304e0
Revises: 390b63a723a6
Create Date: 2017-07-03 22:18:00.342518
"""
# revision identifiers, used by Alembic.
revision = '59c170d304e0'
down_revision = '390b63a723a6'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('chess', sa.Column('chess_board', mysql.LONGTEXT(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('chess', 'chess_board')
# ### end Alembic commands ###
| [
"349729220@qq.com"
] | 349729220@qq.com |
5afcc623ca168965aeb91214b9bcd6e332511aa8 | 455376ee634c6106cfbf9c82a24fc86522a94f5b | /models/BaseModelMail.py | d18fd7ffc21a2fae35a7fa7743e06dab1ea671ae | [] | no_license | dodancs/FIIT-BP-Canaries-Server | fc681f93f298473a7d3c4b8f403bb58dba8bf16f | dc3e48a6e40f210be7f82ef3b3dc01217855e6b7 | refs/heads/master | 2022-06-13T11:35:53.010541 | 2020-05-06T22:30:45 | 2020-05-06T22:30:45 | 214,129,860 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 708 | py | import peewee
import json
# Open configuration file
try:
with open('config.json', encoding='utf8') as config_file:
Config = json.load(config_file)
except:
print('Unable to open config.json!')
print('If you haven\'t created a configuration file, please use the example configuration file as a guide.')
print('Otherwise, make sure the file permissions are set correctly.')
exit(1)
db = peewee.MySQLDatabase(
Config['mail']['db_db'], host=Config['mail']['db_host'], port=Config['mail']['db_port'], user=Config['mail']['db_user'], passwd=Config['mail']['db_password'], charset=Config['mail']['db_charset'])
class BaseModel(peewee.Model):
class Meta:
database = db
| [
"dodancs@moow.info"
] | dodancs@moow.info |
a8eba0feb28aa882253f2324f18c0b5b36f77d7b | 2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae | /python/python_17350.py | 11db4fbe2ed5ba01f7114c7b6e2db2b35d8b6762 | [] | no_license | AK-1121/code_extraction | cc812b6832b112e3ffcc2bb7eb4237fd85c88c01 | 5297a4a3aab3bb37efa24a89636935da04a1f8b6 | refs/heads/master | 2020-05-23T08:04:11.789141 | 2015-10-22T19:19:40 | 2015-10-22T19:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 64 | py | # Django Foreign Key QuerySet (join)
user_obj.student_set.all()
| [
"ubuntu@ip-172-31-7-228.us-west-2.compute.internal"
] | ubuntu@ip-172-31-7-228.us-west-2.compute.internal |
11c103e803f402c7cd6758bf438339493c44d684 | 5ed389c1f3fc175aa73478fc3dcba4101520b80b | /python/spoonacular/com/spoonacular/client/model/inline_object.py | c1d9417abc5018f9a5ae89fa133d67f82de5c73f | [
"MIT"
] | permissive | jvenlin/spoonacular-api-clients | fae17091722085017cae5d84215d3b4af09082aa | 63f955ceb2c356fefdd48ec634deb3c3e16a6ae7 | refs/heads/master | 2023-08-04T01:51:19.615572 | 2021-10-03T13:30:26 | 2021-10-03T13:30:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,531 | py | # coding: utf-8
"""
spoonacular API
The spoonacular Nutrition, Recipe, and Food API allows you to access over 380,000 recipes, thousands of ingredients, 800,000 food products, and 100,000 menu items. Our food ontology and semantic recipe search engine makes it possible to search for recipes using natural language queries, such as \"gluten free brownies without sugar\" or \"low fat vegan cupcakes.\" You can automatically calculate the nutritional information for any recipe, analyze recipe costs, visualize ingredient lists, find recipes for what's in your fridge, find recipes based on special diets, nutritional requirements, or favorite ingredients, classify recipes into types and cuisines, convert ingredient amounts, or even compute an entire meal plan. With our powerful API, you can create many kinds of food and especially nutrition apps. Special diets/dietary requirements currently available include: vegan, vegetarian, pescetarian, gluten free, grain free, dairy free, high protein, whole 30, low sodium, low carb, Paleo, ketogenic, FODMAP, and Primal. # noqa: E501
The version of the OpenAPI document: 1.0
Contact: mail@spoonacular.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class InlineObject(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'title': 'str',
'upc': 'str',
'plu_code': 'str'
}
attribute_map = {
'title': 'title',
'upc': 'upc',
'plu_code': 'plu_code'
}
def __init__(self, title=None, upc=None, plu_code=None): # noqa: E501
"""InlineObject - a model defined in OpenAPI""" # noqa: E501
self._title = None
self._upc = None
self._plu_code = None
self.discriminator = None
self.title = title
self.upc = upc
self.plu_code = plu_code
@property
def title(self):
"""Gets the title of this InlineObject. # noqa: E501
:return: The title of this InlineObject. # noqa: E501
:rtype: str
"""
return self._title
@title.setter
def title(self, title):
"""Sets the title of this InlineObject.
:param title: The title of this InlineObject. # noqa: E501
:type: str
"""
if title is None:
raise ValueError("Invalid value for `title`, must not be `None`") # noqa: E501
if title is not None and len(title) < 1:
raise ValueError("Invalid value for `title`, length must be greater than or equal to `1`") # noqa: E501
self._title = title
@property
def upc(self):
"""Gets the upc of this InlineObject. # noqa: E501
:return: The upc of this InlineObject. # noqa: E501
:rtype: str
"""
return self._upc
@upc.setter
def upc(self, upc):
"""Sets the upc of this InlineObject.
:param upc: The upc of this InlineObject. # noqa: E501
:type: str
"""
if upc is None:
raise ValueError("Invalid value for `upc`, must not be `None`") # noqa: E501
self._upc = upc
@property
def plu_code(self):
"""Gets the plu_code of this InlineObject. # noqa: E501
:return: The plu_code of this InlineObject. # noqa: E501
:rtype: str
"""
return self._plu_code
@plu_code.setter
def plu_code(self, plu_code):
"""Sets the plu_code of this InlineObject.
:param plu_code: The plu_code of this InlineObject. # noqa: E501
:type: str
"""
if plu_code is None:
raise ValueError("Invalid value for `plu_code`, must not be `None`") # noqa: E501
self._plu_code = plu_code
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, InlineObject):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"davidurbansky@gmail.com"
] | davidurbansky@gmail.com |
2c30b5d149a45a1477fe25339ee8bfd87a8fa508 | 64552be25cf60634cb83ceff4d56087f7a148ba5 | /smtpbin/__main__.py | b15cbfac39caf41d06138322fa1fe9193d483a84 | [] | no_license | DisruptiveLabs/smtpbin | ccd348de8dcb8befe760cbfa1604d7394183dbed | 35acb3a56c05929f1a38349cd019cf3d20297b41 | refs/heads/master | 2021-03-16T10:13:09.405366 | 2016-09-09T23:27:17 | 2016-09-09T23:27:17 | 58,577,044 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,127 | py | import argparse
import asyncore
import os
import uuid
from smtpbin.backend import DataBase
from .http.server import HTTPServer
from .smtp.server import SMTPServer
from .websocket.server import WebSocketServer
LISTEN_ADDR = os.environ.get('LISTEN_ADDR', '0.0.0.0')
HTTP_PORT = int(os.environ.get('HTTP_PORT', '8000'))
WEBSOCKET_PORT = int(os.environ.get('WEBSOCKET_PORT', '8080'))
SMTP_PORT = int(os.environ.get('SMTP_PORT', '25000'))
map = {}
def run_servers(database, listen, http_port, smtp_port, websocket_port):
map['http'] = HTTPServer((listen, http_port), database)
map['smtp'] = SMTPServer((listen, smtp_port), database)
map['websocket'] = WebSocketServer((listen, websocket_port), database)
try:
asyncore.loop(timeout=5)
except KeyboardInterrupt:
pass
def print_connection_information(name, apikey):
print("""Connection information as follows:
SMTP Address: {LISTEN_ADDR}:{SMTP_PORT}
SMTP Username: {name}
SMTP Password: {apikey}
""".format(LISTEN_ADDR=LISTEN_ADDR, SMTP_PORT=SMTP_PORT, name=name, apikey=apikey))
def create_inbox(database, name):
apikey = uuid.uuid4().hex
database.create_inbox(name, apikey)
database.commit()
print_connection_information(name, apikey)
def reset_apikey(database, name):
apikey = uuid.uuid4().hex
if not database.set_inbox_apikey(name, apikey):
raise ValueError("No inbox found named {}".format(name))
database.commit()
print_connection_information(name, apikey)
parser = argparse.ArgumentParser()
parser.add_argument("--database", "-d", help="Path to store the sqlite database", default="smtpbin.db")
subparsers = parser.add_subparsers(help="Available Commands", dest="action")
run_parser = subparsers.add_parser('run', help='Run the server')
run_parser.add_argument("--listen", default=LISTEN_ADDR, type=str, help="Address to listen on")
run_parser.add_argument("--http-port", default=HTTP_PORT, type=int, help="Port for the HTTP Server")
run_parser.add_argument("--websocket-port", default=WEBSOCKET_PORT, type=int, help="Port for the Websocket Server")
run_parser.add_argument("--smtp-port", default=SMTP_PORT, type=int, help="Port for the SMTP Server")
create_inbox_parser = subparsers.add_parser('create_inbox', help="Create a new inbox")
create_inbox_parser.add_argument("name", help="Inbox name, also the username for SMTP")
reset_apikey_parser = subparsers.add_parser('reset_apikey', help="Reset an inbox's apikey")
reset_apikey_parser.add_argument("name", help="Inbox name, also the username for SMTP")
def main():
args = parser.parse_args()
if not args.action:
return parser.print_help()
database = DataBase(args.database)
if args.action == 'run':
return run_servers(database, args.listen, args.http_port, args.smtp_port, args.websocket_port)
elif args.action == 'create_inbox':
return create_inbox(database, args.name)
elif args.action == 'reset_apikey':
return reset_apikey(database, args.name)
else:
return parser.print_help()
if __name__ == '__main__':
main()
| [
"franklyn@tackitt.net"
] | franklyn@tackitt.net |
031c982fa9742c2d217e2ad4b5d9d71fa579951d | 6a7664887d6732ee44838b8cade9e675b8675f40 | /dialog.py | edead5baf1dbc6a58d9feedf0f20af14bc83657c | [] | no_license | nhatuan84/smarthome | 5a0cb6cc36bd4cf27bc7dee5120905d02981ca87 | 9a06a4bc389fef615d159912e4533447d05e4f55 | refs/heads/master | 2020-02-26T13:47:02.557395 | 2016-07-17T03:32:01 | 2016-07-17T03:32:01 | 59,874,296 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 700 | py | from Tkinter import *
#Note: if want to get return value by ref, use list as a param
class Dialog:
topic = None
ret = None
def __init__(self, parent, topic):
top = self.top = Toplevel(parent)
top.title('input value')
self.topic = topic
Label(top, text=self.topic).pack()
self.e = Entry(top, width=40)
self.e.pack(padx=5)
ok = Button(top, text="OK", command=self.ok)
ok.pack(padx=5, pady=5, side = LEFT)
cancel = Button(top, text="Cancel", command=self.cancel)
cancel.pack(padx=5, pady=5, side = LEFT)
def ok(self):
self.ret = self.e.get()
self.top.destroy()
def getVal(self):
return self.ret
def cancel(self):
self.top.destroy() | [
"noreply@github.com"
] | nhatuan84.noreply@github.com |
1d703d536cd58634814e73b82cb85c2077e52b3c | eeb84d194bc580ba13c3a909d443a8e59122041f | /serverdata/setup_server.py | ccc14011b35c8728290c6d24e72f15135ff9e35f | [
"Apache-2.0"
] | permissive | MelanX/Caelum | 15133fdcf8c3224bd6a3892dd27eae34436da573 | 5d4297889f50b31ba822857cb4c2c582949c10e1 | refs/heads/master | 2023-03-16T13:50:35.189704 | 2021-03-11T17:43:33 | 2021-03-11T17:43:33 | 346,451,201 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,288 | py | #!/usr/bin/env python3
import json
import os
import subprocess
import urllib.parse
from urllib.request import Request, urlopen
def downloadMods():
mods = []
with open('server.txt') as file:
for entry in file.read().split('\n'):
if not entry.strip() == '':
mods.append([x.strip() for x in entry.split('/')])
print('Install Forge')
mcv = mods[0][0]
mlv = mods[0][1]
request = Request(
f'https://files.minecraftforge.net/maven/net/minecraftforge/forge/{mcv}-{mlv}/forge-{mcv}-{mlv}-installer.jar'
)
response = urlopen(request)
with open('installer.jar', mode='wb') as file:
file.write(response.read())
subprocess.check_call(['java', '-jar', 'installer.jar', '--installServer'])
try:
os.remove('installer.jar')
os.remove('installer.jar.log')
except FileNotFoundError:
pass
try:
os.rename(f'forge-{mcv}-{mlv}.jar', 'forge.jar')
os.rename(f'minecraft_server.{mcv}.jar', 'minecraft.jar')
os.rename(f'{mcv}.json', 'minecraft.json')
print('Pretty minecraft.json')
with open('minecraft.json') as file:
minecraft_json = json.loads(file.read())
os.remove('minecraft.json')
with open('minecraft.json', mode='w') as file:
file.write(json.dumps(minecraft_json, indent=4))
except FileNotFoundError:
print('Failed to rename forge installer output. Forge seems to have changed their installer.')
print('Download Mods')
if not os.path.isdir('mods'):
os.makedirs('mods')
for mod in mods[1:]:
projectID = mod[0]
fileID = mod[1]
download_url = f'https://addons-ecs.forgesvc.net/api/v2/addon/{projectID}/file/{fileID}/download-url'
request1 = Request(download_url)
response1 = urlopen(request1)
file_url = response1.read().decode('utf-8')
request2 = Request(urllib.parse.quote(file_url))
response2 = urlopen(request2)
print('Downloading mod %s...' % file_url[file_url.rfind('/') + 1:])
with open('mods' + os.path.sep + file_url[file_url.rfind('/') + 1:],
mode='wb') as target:
target.write(response2.read())
if __name__ == '__main__':
downloadMods()
| [
"info@melanx.de"
] | info@melanx.de |
606be63b920885b73c92569ba3f6c110cf29c23a | 377bf89b212a75076ed533c9e030d029170eb885 | /devel/lib/python2.7/dist-packages/rezwan_pack/msg/_MyEvent.py | 99ab9c4ce921bc735ebd1e622703327fea425734 | [] | no_license | rezwanshubh/rez2-robtech | b6552d84ed9066f708dd8f58530bb18daeef97b2 | 1bcf5a9192c5b6332e215bafcbe4db95f7a6750f | refs/heads/master | 2021-01-20T14:47:16.569917 | 2017-05-11T18:48:51 | 2017-05-11T18:48:51 | 90,658,845 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,695 | py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from rezwan_pack/MyEvent.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class MyEvent(genpy.Message):
_md5sum = "2a533572c34f024512abad75ea2a34b4"
_type = "rezwan_pack/MyEvent"
_has_header = False #flag to mark the presence of a Header object
_full_text = """int8 direction_x
int8 direction_y
int8 wheel_rotation
bool btn_right
bool btn_left
bool btn_middle
"""
__slots__ = ['direction_x','direction_y','wheel_rotation','btn_right','btn_left','btn_middle']
_slot_types = ['int8','int8','int8','bool','bool','bool']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
direction_x,direction_y,wheel_rotation,btn_right,btn_left,btn_middle
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(MyEvent, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.direction_x is None:
self.direction_x = 0
if self.direction_y is None:
self.direction_y = 0
if self.wheel_rotation is None:
self.wheel_rotation = 0
if self.btn_right is None:
self.btn_right = False
if self.btn_left is None:
self.btn_left = False
if self.btn_middle is None:
self.btn_middle = False
else:
self.direction_x = 0
self.direction_y = 0
self.wheel_rotation = 0
self.btn_right = False
self.btn_left = False
self.btn_middle = False
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self
buff.write(_struct_3b3B.pack(_x.direction_x, _x.direction_y, _x.wheel_rotation, _x.btn_right, _x.btn_left, _x.btn_middle))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
_x = self
start = end
end += 6
(_x.direction_x, _x.direction_y, _x.wheel_rotation, _x.btn_right, _x.btn_left, _x.btn_middle,) = _struct_3b3B.unpack(str[start:end])
self.btn_right = bool(self.btn_right)
self.btn_left = bool(self.btn_left)
self.btn_middle = bool(self.btn_middle)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self
buff.write(_struct_3b3B.pack(_x.direction_x, _x.direction_y, _x.wheel_rotation, _x.btn_right, _x.btn_left, _x.btn_middle))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
_x = self
start = end
end += 6
(_x.direction_x, _x.direction_y, _x.wheel_rotation, _x.btn_right, _x.btn_left, _x.btn_middle,) = _struct_3b3B.unpack(str[start:end])
self.btn_right = bool(self.btn_right)
self.btn_left = bool(self.btn_left)
self.btn_middle = bool(self.btn_middle)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
_struct_3b3B = struct.Struct("<3b3B")
| [
"shubhbd@yahoo.com"
] | shubhbd@yahoo.com |
da7e60c923a0bead04c9bceed2b393379957799a | 82f38e3435630e9c0339ce68bd0086a16fea02c4 | /dex-net/src/dexnet/abstractstatic.py | daf799245459081374006f482e775d2cf0390b23 | [
"MIT"
] | permissive | peter0749/PointNetGPD | a9d2ad8d38ac6caf63879931a6c0f62c92b885d4 | 5e2be543057657f1faaef87e80074d392823e5df | refs/heads/master | 2020-09-24T14:40:48.139495 | 2020-05-28T13:13:42 | 2020-05-28T13:13:42 | 225,783,045 | 0 | 0 | MIT | 2019-12-04T05:01:25 | 2019-12-04T05:01:24 | null | UTF-8 | Python | false | false | 1,692 | py | # -*- coding: utf-8 -*-
"""
Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
Permission to use, copy, modify, and distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
hereby granted, provided that the above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology
Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-
7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF
THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
"""
# Abstact static methods
# Source: https://stackoverflow.com/questions/4474395/staticmethod-and-abc-abstractmethod-will-it-blend
class abstractstatic(staticmethod):
__slots__ = ()
def __init__(self, function):
super(abstractstatic, self).__init__(function)
function.__isabstractmethod__ = True
__isabstractmethod__ = True
| [
"lianghongzhuo@126.com"
] | lianghongzhuo@126.com |
48424c58d4841f72a346c4d91fa4d737bc3caba8 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2648/60678/289889.py | 2502a253d156988e60af2cf0b3448f5e525988df | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 354 | py | stringM = input()
stringS = input()
if stringM == 'whatthemomooofun' and stringS == 'moo':
print('whatthefun', end="")
if stringM == 'whatthemomooofun' and stringS == 'o':
print('whatthemmfun', end="")
if stringM == 'whatthemmfunwhatthemomooofun' and stringS == 'o':
print('whatthemmfun', end="")
else:
print(stringM)
print(stringS) | [
"1069583789@qq.com"
] | 1069583789@qq.com |
896013857c56f8a33fba33190c2ac0b1ae04c62d | 4ba091b217faddd0ee053c6f5f49547a3fc2713d | /DBT/tools/show_offset.py | ae16f7d6025aa3c0500ec96cc2e189e806b92946 | [
"Apache-2.0"
] | permissive | Catchen98/SOT-Projects | 98cb90058c288596dbf516004777553e176a5250 | 352f43cd7d615fbdb08246fad9aefee03beca9e3 | refs/heads/master | 2022-12-19T00:56:43.095395 | 2020-09-17T13:30:23 | 2020-09-17T13:30:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,935 | py | # -*- coding: utf-8 -*-
#@Author: Lidong Yu
#@Date: 2019-12-11 16:41:28
#@Last Modified by: Lidong Yu
#@Last Modified time: 2019-12-11 16:41:28
import matplotlib.pyplot as plt
import numpy as np
import cv2
import mmcv
import matplotlib
def kernel_inv_map(vis_attr, target_point, map_h, map_w):
#-1,0,1
pos_shift = [vis_attr['dilation'] * 0 - vis_attr['pad'],
vis_attr['dilation'] * 1 - vis_attr['pad'],
vis_attr['dilation'] * 2 - vis_attr['pad']]
source_point = []
for idx in range(vis_attr['filter_size']**2):
# -1,0,1 -1,-1,-1
# -1,0,1 0, 0, 0
# -1,0,1 1, 1, 1
#grid,y,x
cur_source_point = np.array([target_point[0] + pos_shift[idx // 3],
target_point[1] + pos_shift[idx % 3]])
if cur_source_point[0] < 0 or cur_source_point[1] < 0 \
or cur_source_point[0] > map_h - 1 or cur_source_point[1] > map_w - 1:
continue
source_point.append(cur_source_point.astype('f'))
return source_point
def offset_inv_map(source_points, offset):
for idx, _ in enumerate(source_points):
source_points[idx][0] += offset[2*idx]
source_points[idx][1] += offset[2*idx + 1]
# print(np.min(offset),np.max(offset))
return source_points
def get_bottom_position(vis_attr, top_points, all_offset):
map_h = all_offset[0].shape[2]
map_w = all_offset[0].shape[3]
for level in range(vis_attr['plot_level']):
source_points = []
for idx, cur_top_point in enumerate(top_points):
cur_top_point = np.round(cur_top_point)
if cur_top_point[0] < 0 or cur_top_point[1] < 0 \
or cur_top_point[0] > map_h-1 or cur_top_point[1] > map_w-1:
continue
cur_source_point = kernel_inv_map(vis_attr, cur_top_point, map_h, map_w)
cur_offset = np.squeeze(all_offset[level][:, :, int(cur_top_point[0]), int(cur_top_point[1])])
#print(all_offset[level][:, :, int(cur_top_point[0]), int(cur_top_point[1])])
# print(cur_offset.shape)
cur_source_point = offset_inv_map(cur_source_point, cur_offset)
source_points = source_points + cur_source_point
# print(cur_source_point)
top_points = source_points
return source_points
def plot_according_to_point(vis_attr, im, source_points, map_h, map_w, color=[255,0,0]):
plot_area = vis_attr['plot_area']
for idx, cur_source_point in enumerate(source_points):
# print(im.shape[0] / map_h)
y = np.round((cur_source_point[0] + 0.5) * im.shape[0] / map_h).astype('i')
x = np.round((cur_source_point[1] + 0.5) * im.shape[1] / map_w).astype('i')
if x < 0 or y < 0 or x > im.shape[1]-1 or y > im.shape[0]-1:
continue
y = min(y, im.shape[0] - vis_attr['plot_area'] - 1)
x = min(x, im.shape[1] - vis_attr['plot_area'] - 1)
y = max(y, vis_attr['plot_area'])
x = max(x, vis_attr['plot_area'])
im[y-plot_area:y+plot_area+1, x-plot_area:x+plot_area+1, :] = np.tile(
np.reshape(color, (1, 1, 3)), (2*plot_area+1, 2*plot_area+1, 1)
)
return im
def show_dconv_offset(im, all_offset, step=[2, 2], filter_size=3,
dilation=1, pad=1, plot_area=1, plot_level=4,stride=8):
vis_attr = {'filter_size': filter_size, 'dilation': dilation, 'pad': pad,
'plot_area': plot_area, 'plot_level': plot_level,'stride':stride}
map_h = all_offset[0].shape[2]
map_w = all_offset[0].shape[3]
step_h = step[0]
step_w = step[1]
start_h = np.round(step_h / 2).astype(np.int)
start_h=15*2
start_w = np.round(step_w / 2).astype(np.int)
start_w=20*2
plt.figure(figsize=(15, 5))
for im_h in range(start_h, map_h, step_h):
for im_w in range(start_w, map_w, step_w):
target_point = np.array([im_h, im_w]).astype(np.int)
source_y = np.round(target_point[0] * im.shape[0] / map_h).astype(np.int)
source_x = np.round(target_point[1] * im.shape[1] / map_w).astype(np.int)
if source_y < plot_area or source_x < plot_area \
or source_y >= im.shape[0] - plot_area or source_x >= im.shape[1] - plot_area:
print('out of image')
continue
cur_im = np.copy(im)
source_points = get_bottom_position(vis_attr, [target_point], all_offset)
cur_im = plot_according_to_point(vis_attr, cur_im, source_points, map_h, map_w)
cur_im[source_y-3:source_y+3+1, source_x-3:source_x+3+1, :] = \
np.tile(np.reshape([0, 255, 0], (1, 1, 3)), (2*3+1, 2*3+1, 1))
print('showing',im_h,im_w)
plt.axis("off")
plt.imshow(cur_im)
plt.show(block=False)
plt.pause(0.01)
plt.clf()
if __name__=='__main__':
img=matplotlib.image.imread('/home/ld/RepPoints/offset/000100.png')
# height, width = img.shape[:2]
# size=(int(width/8),int(height/8))
# img=cv2.resize(img,size)
offset156=np.load('/home/ld/RepPoints/offset/resnetl20.npy')
offset78=np.load('/home/ld/RepPoints/offset/resnetl21.npy')
offset39=np.load('/home/ld/RepPoints/offset/resnetl22.npy')
offset20=np.load('/home/ld/RepPoints/offset/resnetl23.npy')
print(offset156.shape)
# offset10=np.load('/home/ld/RepPoints/offset/init10.npy')
show_dconv_offset(img,[offset20,offset39,offset78,offset156])
# show_dconv_offset(im, [res5c_offset, res5b_offset, res5a_offset])
# #detach the init grad
# pts_out_refine = pts_out_refine + pts_out_init.detach()
# if dcn_offset.shape[-1]==156:
# np.save('/home/ld/RepPoints/offset/init.npy',dcn_offset.data.cpu().numpy())
# np.save('/home/ld/RepPoints/offset/refine.npy',pts_out_refine.data.cpu().numpy()) | [
"janey9503@126.com"
] | janey9503@126.com |
7a273b69ade85c025a308827da97ee147e75a0af | b26f62e1ae52df9e34c4ce27dc0f617416518e23 | /12-python-level-one/Part9_Functions_Exercises.py | fa8e0bc6622df3e7cfeea4082a548c026b1c314e | [] | no_license | Rutrle/udemy-django | 2ba5b39f69fc526c27d074818ff372c91f3b879b | 53502d8d87f9da907771bc044538844cf18f6895 | refs/heads/master | 2023-04-17T13:05:20.539842 | 2021-05-03T23:25:51 | 2021-05-03T23:25:51 | 339,551,118 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,332 | py | #####################################
#### PART 9: FUNCTION EXERCISES #####
#####################################
# Complete the tasks below by writing functions! Keep in mind, these can be
# really tough, its all about breaking the problem down into smaller, logical
# steps. If you get stuck, don't feel bad about having to peek to the solutions!
#####################
## -- PROBLEM 1 -- ##
#####################
# Given a list of integers, return True if the sequence of numbers 1, 2, 3
# appears in the list somewhere.
# For example:
# arrayCheck([1, 1, 2, 3, 1]) → True
# arrayCheck([1, 1, 2, 4, 1]) → False
# arrayCheck([1, 1, 2, 1, 2, 3]) → True
def arrayCheck_simple(nums):
return (1 in nums) and (2 in nums) and (3 in nums)
# CODE GOES HERE
def arrayCheck(nums):
for num in range(len(nums)-2):
if (nums[num]) == 1 and (nums[num+1]) == 2 and (nums[num+2]) == 3:
return True
return False
#####################
## -- PROBLEM 2 -- ##
#####################
# Given a string, return a new string made of every other character starting
# with the first, so "Hello" yields "Hlo".
# For example:
# stringBits('Hello') → 'Hlo'
# stringBits('Hi') → 'H'
# stringBits('Heeololeo') → 'Hello'
def stringBits(str_v):
return_str = ""
for i in range(0, len(str_v), 2):
return_str = return_str+str_v[i]
return return_str
print(stringBits('Heeololeo'))
print(stringBits('Hi'))
print(stringBits('Hello'))
#####################
## -- PROBLEM 3 -- ##
#####################
# Given two strings, return True if either of the strings appears at the very end
# of the other string, ignoring upper/lower case differences (in other words, the
# computation should not be "case sensitive").
#
# Note: s.lower() returns the lowercase version of a string.
#
# Examples:
#
# end_other('Hiabc', 'abc') → True
# end_other('AbC', 'HiaBc') → True
# end_other('abc', 'abXabc') → True
def end_other(a, b):
a = a.lower()
b = b.lower()
if len(a) < len(b):
a, b = b, a
for i in range(len(b)):
if a[-(len(b)-i)] != b[i]:
return False
return True
print(end_other('Hiabc', 'abc'), end_other(
'AbC', 'HiaBc'), end_other('abc', 'abXabc'))
#####################
## -- PROBLEM 4 -- ##
#####################
# Given a string, return a string where for every char in the original,
# there are two chars.
# doubleChar('The') → 'TThhee'
# doubleChar('AAbb') → 'AAAAbbbb'
# doubleChar('Hi-There') → 'HHii--TThheerree'
def doubleChar(old_str):
new_str = ""
for letter in old_str:
new_str = new_str+letter*2
return new_str
# CODE GOES HERE
print(doubleChar('The'), doubleChar('AAbb'), doubleChar('Hi-There'))
#####################
## -- PROBLEM 5 -- ##
#####################
# Read this problem statement carefully!
# Given 3 int values, a b c, return their sum. However, if any of the values is a
# teen -- in the range 13-19 inclusive -- then that value counts as 0, except 15
# and 16 do not count as a teens. Write a separate helper "def fix_teen(n):"that
# takes in an int value and returns that value fixed for the teen rule.
#
# In this way, you avoid repeating the teen code 3 times (i.e. "decomposition").
# Define the helper below and at the same indent level as the main no_teen_sum().
# Again, you will have two functions for this problem!
#
# Examples:
#
# no_teen_sum(1, 2, 3) → 6
# no_teen_sum(2, 13, 1) → 3
# no_teen_sum(2, 1, 14) → 3
def no_teen_sum(a, b, c):
return fix_teen(a)+fix_teen(b)+fix_teen(c)
def fix_teen(n):
teens = (list(range(13, 20)))
exceptions = [15, 16]
if n in teens and n not in exceptions:
return 0
else:
return n
print(no_teen_sum(1, 2, 3))
print(no_teen_sum(2, 13, 1))
print(no_teen_sum(2, 1, 14))
print(no_teen_sum(2, 1, 15))
#####################
## -- PROBLEM 6 -- ##
#####################
# Return the number of even integers in the given array.
#
# Examples:
#
# count_evens([2, 1, 2, 3, 4]) → 3
# count_evens([2, 2, 0]) → 3
# count_evens([1, 3, 5]) → 0
def count_evens(nums):
count = 0
for item in nums:
if item % 2 == 0:
count = count+1
return count
print(count_evens([2, 1, 2, 3, 4]),
count_evens([2, 2, 0]),
count_evens([1, 3, 5]))
| [
"rutrle@seznam.cz"
] | rutrle@seznam.cz |
00d0463174ebb9bd3d0a46757234bdd844e44449 | 531ffe58ab1c63ed5922a4eaada71addca7ea8b6 | /WGAN_PINNs_Burgers/custom_layers/__init__.py | 0fa09705de299cd847287435a7b46704e8b1d1b9 | [] | no_license | yihang-gao/WGAN_PINNs | 7d68b3ae4c5d36e61d2a7da16d197c0c794c913b | 0ec4cfc061f7deb713d492655dc39deb08912daa | refs/heads/main | 2023-08-14T14:57:35.897867 | 2021-10-04T05:13:41 | 2021-10-04T05:13:41 | 391,309,696 | 7 | 1 | null | null | null | null | UTF-8 | Python | false | false | 57 | py | from .bjorck_orthonormalize import bjorck_orthonormalize
| [
"noreply@github.com"
] | yihang-gao.noreply@github.com |
dbb75131e72c5c93512d4f11ded1c62172e744c7 | 0cd81e84ac066391f943a32c1a007aba4e670c0d | /subroutines/plot_gnomad_v_exome.py | 901ff43363e5215d29e37482d7aeedafacc71bc6 | [] | no_license | sarah-n-wright/UKBB-Exome-QC | d02036ac1e6f497a1fb49b5f458effcd86e11aad | 98b83b07b7c0d37f5a2ec7f1abd80fb395e3f794 | refs/heads/main | 2023-06-20T19:32:02.598126 | 2021-07-19T23:44:13 | 2021-07-19T23:44:13 | 387,558,077 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 486 | py | import sys
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
outdir=str(sys.argv[1])
df = pd.read_csv(outdir+"/combined_data.txt", sep="\s+", header=None)
df.columns = ["CHR", "Gene", "UKBB", "gnomAD"]
plt.figure()
fig=sns.jointplot(y="gnomAD", x="UKBB", data=df, s=1, xlim=(-40, 3000), ylim=(-40, 3000), marginal_kws=dict(bins=list(range(0,31000,100))))
#plt.savefig("~/Data/Transfer/combo_NOQC.png")
plt.savefig(outdir+"/gnomad_v_ukbb.png")
print("Done.")
| [
"sarahwright474@gmail.com"
] | sarahwright474@gmail.com |
ba28e5188ef6f71a5dc3327b881ed6dea86b8314 | 8a21df340880276501cca60eae84d65d0b1ed807 | /c2cwsgiutils_test_print.py | 75bed059229586a039a58fc5bf80b06aaabc449f | [
"BSD-2-Clause-Views"
] | permissive | arnaud-morvan/c2cwsgiutils | 038f73cd6e3de0b0d88c89c12b1ae50f45a6bed6 | aa06b77b247bd8969b88225ee3ea109886aefeac | refs/heads/master | 2020-06-17T05:08:24.800772 | 2019-07-08T07:45:02 | 2019-07-08T07:45:02 | 195,807,504 | 0 | 0 | NOASSERTION | 2019-07-08T12:28:19 | 2019-07-08T12:28:19 | null | UTF-8 | Python | false | false | 1,603 | py | #!/usr/bin/env python3
"""
Test a MapfishPrint server.
"""
import c2cwsgiutils.setup_process # noqa # pylint: disable=unused-import
import argparse
import logging
import pprint
from c2cwsgiutils.acceptance.print import PrintConnection
LOG = logging.getLogger("c2cwsgiutils_test_print")
def _parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", required=True, help="The base URL of the print, including the '/print'")
parser.add_argument("--app", default=None, help="The app name")
parser.add_argument("--referer", default=None, help="The referer (defaults to --url)")
parser.add_argument("--verbose", default=False, action="store_true", help="Enable debug output")
return parser.parse_args()
def main():
args = _parse_args()
if not args.verbose:
logging.root.setLevel(logging.INFO)
p = PrintConnection(base_url=args.url, origin=args.referer if args.referer else args.url)
p.wait_ready(app=args.app)
if args.app is None:
for app in p.get_apps():
if app != 'default':
print("\n\n" + app + "=================")
test_app(p, app)
else:
test_app(p, args.app)
def test_app(p, app):
capabilities = p.get_capabilities(app)
LOG.debug("Capabilities:\n%s", pprint.pformat(capabilities))
examples = p.get_example_requests(app)
for name, request in examples.items():
print("\n" + name + "-----------------")
pdf = p.get_pdf(app, request)
size = len(pdf.content)
print("Size=" + str(size))
main()
| [
"patrick.valsecchi@camptocamp.com"
] | patrick.valsecchi@camptocamp.com |
0639d1ea3232f1ae2b4fe762575e6f81ce7ef187 | 567bf02488f07d4783d59f8064c980acc0d012b9 | /three_room/dash/migrations/0001_initial.py | c7f19f4f181b0b37ff88bfee5dc76965e114e345 | [
"MIT"
] | permissive | mfrasquet/IBM_Hackathon | 37516e25a8bd5203ddc73460a1286e8eadd6662c | a84710bfc5c4f7079b960d722050e8fd954660c1 | refs/heads/master | 2020-04-07T14:54:37.666167 | 2018-11-23T00:58:07 | 2018-11-23T00:58:07 | 158,465,794 | 0 | 1 | MIT | 2018-11-22T16:48:05 | 2018-11-20T23:51:03 | Python | UTF-8 | Python | false | false | 1,102 | py | # Generated by Django 2.0.5 on 2018-11-20 21:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Contract',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('contractDate', models.DateField(auto_now_add=True)),
('tempMAX', models.FloatField(default=80)),
('tempMIN', models.FloatField(default=0)),
('hrMAX', models.FloatField(default=0)),
('hrMIN', models.FloatField(default=0)),
('accMAX', models.FloatField(default=0)),
('accMIN', models.FloatField(default=0)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"mfrasquetherraiz@gmail.com"
] | mfrasquetherraiz@gmail.com |
1762d5eb405a9283b28d8b9064e2eee1d484595e | 89ad7ee7bc30b57a0f66ec37ee525cac35b68677 | /bundle-workflow/src/manifests/build_manifest.py | 3962bcc25e9607e41cff231a7d07bb868065c7f4 | [
"Apache-2.0"
] | permissive | nknize/opensearch-build | 6760c1140a6706f994aaf208d4461fe2ab07f16b | 68e19a4c1c1005475ac070d583cdf0859f7807e0 | refs/heads/main | 2023-07-31T20:19:21.131817 | 2021-09-13T21:13:53 | 2021-09-13T21:13:53 | 406,205,917 | 0 | 0 | Apache-2.0 | 2021-09-14T03:05:13 | 2021-09-14T03:05:12 | null | UTF-8 | Python | false | false | 2,633 | py | # SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
from manifests.manifest import Manifest
"""
A BuildManifest is an immutable view of the outputs from a build step
The manifest contains information about the product that was built (in the `build` section),
and the components that made up the build in the `components` section.
The format for schema version 1.0 is:
schema-version: "1.0"
build:
name: string
version: string
architecture: x64 or arm64
components:
- name: string
repository: URL of git repository
ref: git ref that was built (sha, branch, or tag)
commit_id: The actual git commit ID that was built (i.e. the resolved "ref")
artifacts:
maven:
- maven/relative/path/to/artifact
- ...
plugins:
- plugins/relative/path/to/artifact
- ...
libs:
- libs/relative/path/to/artifact
- ...
- ...
"""
class BuildManifest(Manifest):
def __init__(self, data):
super().__init__(data)
self.build = self.Build(data["build"])
self.components = list(
map(lambda entry: self.Component(entry), data["components"])
)
def __to_dict__(self):
return {
"schema-version": "1.0",
"build": self.build.__to_dict__(),
"components": list(
map(lambda component: component.__to_dict__(), self.components)
),
}
class Build:
def __init__(self, data):
self.name = data["name"]
self.version = data["version"]
self.architecture = data["architecture"]
self.id = data["id"]
def __to_dict__(self):
return {
"name": self.name,
"version": self.version,
"architecture": self.architecture,
"id": self.id,
}
class Component:
def __init__(self, data):
self.name = data["name"]
self.repository = data["repository"]
self.ref = data["ref"]
self.commit_id = data["commit_id"]
self.artifacts = data["artifacts"]
self.version = data["version"]
def __to_dict__(self):
return {
"name": self.name,
"repository": self.repository,
"ref": self.ref,
"commit_id": self.commit_id,
"artifacts": self.artifacts,
"version": self.version,
}
| [
"noreply@github.com"
] | nknize.noreply@github.com |
010a26f7bfb1b1f3463bd00b8d0ae188891fe3be | a717fc6da91824ead3198b84b1c565d5ff7efa23 | /farm/picker/migrations/0001_initial.py | 24026428043e1410120f8bb419464508c869760c | [] | no_license | IvankaCaron/projekt3 | 4a2e7a91ec2207b241f99858e0764abb1579b9a3 | 159e3f66313fe694b752c03e3864e27a2e75883d | refs/heads/master | 2021-09-05T02:39:30.698936 | 2018-01-23T17:55:15 | 2018-01-23T17:55:15 | 116,667,238 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 613 | py | # Generated by Django 2.0 on 2017-12-12 10:44
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Spot',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=20)),
('location', django.contrib.gis.db.models.fields.PointField(srid=4326)),
],
),
]
| [
"ivanka.caron@gmail.com"
] | ivanka.caron@gmail.com |
1b42f5efa62b619564371bcfd3bdcddf49e465b4 | 5b86f575e6e858cbcc098422fa9cb8db85e46e17 | /ihu/main/forms.py | 5c179a6b9c170b136632deb13be106821fb6dad5 | [] | no_license | Minard-NG/finalyear | 3902320fae7c9e786d6dd8327b10dc98a1828a64 | f3481ebccdf8e72d91a9fefb6a953fe4a105cc1f | refs/heads/master | 2022-10-08T21:51:26.229241 | 2020-06-08T20:00:56 | 2020-06-08T20:00:56 | 270,780,591 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 151 | py | from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
| [
"michael4sure20@gmail.com"
] | michael4sure20@gmail.com |
15871357f103326ade70ff1294562689ef8c5375 | 38dc0477ba472146f4fabe109826198705144d03 | /fastai/layer_optimizer.py | 1791659fe6e1b601fc2ebaac8a96eab91c43d304 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | permissive | dana-kelley/DeOldify | ad54a3a44e4a8d90f00ef3d7ee20e56b14683f47 | fa186f251b8a7dbc120d8a5901fdd0d065c60eec | refs/heads/master | 2020-05-17T04:52:54.795176 | 2019-12-11T05:53:01 | 2019-12-11T05:53:01 | 183,519,547 | 68 | 10 | MIT | 2020-02-18T15:44:14 | 2019-04-25T22:41:00 | Python | UTF-8 | Python | false | false | 3,313 | py | from .imports import *
from .torch_imports import *
from .core import *
def opt_params(parm, lr, wd):
return {'params': chain_params(parm), 'lr':lr, 'weight_decay':wd}
class LayerOptimizer():
def __init__(self, opt_fn, layer_groups, lrs, wds=None):
if not isinstance(layer_groups, (list,tuple)): layer_groups=[layer_groups]
if not isinstance(lrs, Iterable): lrs=[lrs]
if len(lrs)==1: lrs=lrs*len(layer_groups)
if wds is None: wds=0.
if not isinstance(wds, Iterable): wds=[wds]
if len(wds)==1: wds=wds*len(layer_groups)
self.layer_groups,self.lrs,self.wds = layer_groups,lrs,wds
self.opt = opt_fn(self.opt_params())
def opt_params(self):
assert(len(self.layer_groups) == len(self.lrs))
assert(len(self.layer_groups) == len(self.wds))
params = list(zip(self.layer_groups,self.lrs,self.wds))
return [opt_params(*p) for p in params]
@property
def lr(self): return self.lrs[-1]
@property
def mom(self):
if 'betas' in self.opt.param_groups[0]:
return self.opt.param_groups[0]['betas'][0]
else:
return self.opt.param_groups[0]['momentum']
def set_lrs(self, lrs):
if not isinstance(lrs, Iterable): lrs=[lrs]
if len(lrs)==1: lrs=lrs*len(self.layer_groups)
set_lrs(self.opt, lrs)
self.lrs=lrs
def set_wds_out(self, wds):
if not isinstance(wds, Iterable): wds=[wds]
if len(wds)==1: wds=wds*len(self.layer_groups)
set_wds_out(self.opt, wds)
set_wds(self.opt, [0] * len(self.layer_groups))
self.wds=wds
def set_wds(self, wds):
if not isinstance(wds, Iterable): wds=[wds]
if len(wds)==1: wds=wds*len(self.layer_groups)
set_wds(self.opt, wds)
set_wds_out(self.opt, [0] * len(self.layer_groups))
self.wds=wds
def set_mom(self,momentum):
if 'betas' in self.opt.param_groups[0]:
for pg in self.opt.param_groups: pg['betas'] = (momentum, pg['betas'][1])
else:
for pg in self.opt.param_groups: pg['momentum'] = momentum
def set_beta(self,beta):
if 'betas' in self.opt.param_groups[0]:
for pg in self.opt.param_groups: pg['betas'] = (pg['betas'][0],beta)
elif 'alpha' in self.opt.param_groups[0]:
for pg in self.opt.param_groups: pg['alpha'] = beta
def set_opt_fn(self, opt_fn):
if type(self.opt) != type(opt_fn(self.opt_params())):
self.opt = opt_fn(self.opt_params())
def zip_strict_(l, r):
assert(len(l) == len(r))
return zip(l, r)
def set_lrs(opt, lrs):
if not isinstance(lrs, Iterable): lrs=[lrs]
if len(lrs)==1: lrs=lrs*len(opt.param_groups)
for pg,lr in zip_strict_(opt.param_groups,lrs): pg['lr'] = lr
def set_wds_out(opt, wds):
if not isinstance(wds, Iterable): wds=[wds]
if len(wds)==1: wds=wds*len(opt.param_groups)
assert(len(opt.param_groups) == len(wds))
for pg,wd in zip_strict_(opt.param_groups,wds): pg['wd'] = wd
def set_wds(opt, wds):
if not isinstance(wds, Iterable): wds=[wds]
if len(wds)==1: wds=wds*len(opt.param_groups)
assert(len(opt.param_groups) == len(wds))
for pg,wd in zip_strict_(opt.param_groups,wds): pg['weight_decay'] = wd
| [
"jsa169@gmail.com"
] | jsa169@gmail.com |
609fcd0adf68d5900ff33d517a1b36069f8c7cae | 0405ab9b91d3eacf6de40de2b7cdeb8589487f77 | /movie.py | 1f5f10c327627949ca82d0321afbb8496513c729 | [] | no_license | miaomiaogamer/assignment-2---movies-2-miaomiaogamer-master | 13188e9b6a5a7df9b7913daa4bb0d307b2e3b577 | f076733cc9d05465eabef465fa6a4935243d7e56 | refs/heads/master | 2023-02-26T05:23:37.876591 | 2021-01-23T10:51:56 | 2021-01-23T10:51:56 | 332,184,490 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,333 | py | """..."""
# TODO: Create your Movie class in this file
class Movie:
"""creat a Movie class"""
def __init__(self, title='', year=0, category='', is_watched=False):
self.title = title
self.category = category
self.year = year
self.is_watched = is_watched
def __str__(self):
"""Return movie info"""
watch_check = 'watched' \
if self.is_watched \
else 'unwatched'
return '{} - {} ({}) ({})'.format(self.title, self.year, self.category, watch_check)
#def list_movies(movies):
i = 0
Movieswatched = 0
while i < len(movies):
if movies[i][3] == "n":
print("{:2}. * {:35} - {:4} ({})".format(i, movies[i][0], movies[i][1], movies[i][2]))
Movieswatched = Movieswatched + 1
else:
print("{:2}. {:35} - {:4} ({})".format(i, movies[i][0], movies[i][1], movies[i][2]))
i = i + 1
movies_watched = len(movies) - Movieswatched
print("{} movies watched, {} movies still to watch".format(movies_watched, Movieswatched))
def mark_watched(self):
"""Changing movie to watched"""
self.is_watched = True
def mark_unwatched(self):
"""Changing movie to unwatched"""
self.is_watched = False | [
"344013468@qq.com"
] | 344013468@qq.com |
f5e5d39f21c2d2fa02284f4c70aec47a57b0fd5c | 7cc5b4b583028a777eb3617774cdb78ddf017c73 | /game.py | 0b4a14ef3bcb4652251e953219a6ba327d6c0819 | [] | no_license | b0bsky/Tic-Tac-Toe-AI | 7fd517e202d1e489c718cd1b910a17961e1ed235 | add423efb0cc43aa15a00c6b2d682a4dbc5c0ea1 | refs/heads/master | 2020-05-01T03:21:49.172390 | 2019-03-23T04:17:27 | 2019-03-23T04:17:27 | 177,243,069 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,682 | py | # TIC TAC TOE GAME
# Board variables
BOARD_WIDTH = 3
BOARD_HEIGHT = 3
# Variables
current_player = 0
is_running = True
# Function that creates a new empty 3 x 3 board
def new_board():
board = []
# Loop that makes the board filling each tile with None Type
for row in range(0, BOARD_WIDTH):
columns = []
for column in range(0, BOARD_HEIGHT):
columns.append(None)
board.append(columns)
return(board)
# Renders the board and prints out each tile respective to its current state
def render_board(board):
print(" 0 1 2")
row_num = 0
rows = []
# Makes a new array holding each individual row
for y in range(0, BOARD_HEIGHT):
row = []
for x in range(0, BOARD_WIDTH):
row.append(board[x][y])
rows.append(row)
# Printing out each row, filling in all none type objects with spaces
for row in rows:
output_tile = ''
for tile in row:
if tile is None:
output_tile += ' '
else:
output_tile += tile
# Prints out rows and columns including numbering
print("%d|%s|" % (row_num, ' '.join(output_tile)))
row_num += 1
print("--------")
#def win_test():
# #TO-DO: test for all possibilities of wins
# # output winner and stop running game
#
#def full_board():
# # TO-DO: check for full board and act accordingly
# Main loop
def main():
board = new_board()
board[0][1] = "X"
board[1][2] = "O"
render_board(board)
# get_turns()
# win_test()
if __name__ == "__main__":
main()
| [
"noreply@github.com"
] | b0bsky.noreply@github.com |
137d4b277d94a0dcf6824e72ce219e46b22536b7 | 44413721791e00e5e0d728d2063cce9d072680bc | /ate/__init__.py | d1e7384f8b2b29c065f18f9b536d3bfbe07a1f8f | [] | no_license | andriyka/term-extraction-and-ontology-learning | 5174ba52db93bc3dd22b75a41c998c5e23a3bcd5 | 2fa478f1f6f28949d461331f6e8348f86bd344e1 | refs/heads/master | 2020-03-21T19:05:07.755413 | 2018-07-09T16:46:58 | 2018-07-09T16:46:58 | 138,929,875 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 19,309 | py | import PyPDF2
import nltk
import textract
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
from nltk.stem import WordNetLemmatizer
import numpy as np
from os import listdir
from os.path import isdir
from os.path import isfile
from os.path import join
import pandas as pd
import random
import re
import scipy
from sklearn.feature_extraction.text import CountVectorizer
import textract
# noun adj prep + ? ( ) * |
class POSSequenceDetector:
def __init__(self, _pattern):
self.pattern = str(_pattern).lower()
#self.lemmatizer = WordNetLemmatizer()
self.rule = re.compile(r'\W')
tokens = []
i = 0
ptlen = len(self.pattern)
while i < ptlen:
#print i, self.pattern[i:]
if self.pattern[i:].startswith(' '):
i = i + 1
elif self.pattern[i:].startswith('noun'):
tokens.append('N') # noun
i = i + 4
elif self.pattern[i:].startswith('prep'):
tokens.append('P') # preposition
i = i + 4
elif self.pattern[i:].startswith('adj'):
tokens.append('A') #
i = i + 3
elif self.pattern[i:].startswith('+'):
tokens.append('+')
i = i + 1
elif self.pattern[i:].startswith('?'):
tokens.append('?')
i = i + 1
elif self.pattern[i:].startswith('|'):
tokens.append('|')
i = i + 1
elif self.pattern[i:].startswith('*'):
tokens.append('*')
i = i + 1
elif self.pattern[i:].startswith('('):
tokens.append('(')
i = i + 1
elif self.pattern[i:].startswith(')'):
tokens.append(')')
i = i + 1
elif self.pattern[i:].startswith('['):
tokens.append('[')
i = i + 1
elif self.pattern[i:].startswith(']'):
tokens.append(']')
i = i + 1
else:
raise ValueError('Unknown symbol in pattern ' + self.pattern + ' at position ' + i)
# print(tokens)
self.pattern = ''.join(tokens)
# print self.pattern
self.prog = re.compile(self.pattern)
self.map = {
'$':'-', # dollar / $ -$ --$ A$ C$ HK$ M$ NZ$ S$ U.S.$ US$
"''":'-', # closing quotation mark / ' ''
'(':'-', # opening parenthesis / ( [ {
')':'-', # closing parenthesis / ) ] }
',':'-', # comma / ,
'--':'-', # dash / --
'.':'-', # sentence terminator / . ! ?
':':'-', # colon or ellipsis / : ; ...
'``':'-', #': opening quotation mark ` `
'CD':'9', # numeral, cardinal / mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025 fifteen 271,124 dozen quintillion DM2,000 ...
'JJ':'A', # adjective or numeral, ordinal / third ill-mannered pre-war regrettable oiled calamitous first separable ectoplasmic battery-powered participatory fourth still-to-be-named multilingual multi-disciplinary ...
'JJR':'A', # adjective, comparative / bleaker braver breezier briefer brighter brisker broader bumper busier calmer cheaper choosier cleaner clearer closer colder commoner costlier cozier creamier crunchier cuter ...
'JJS':'A', # adjective, superlative / calmest cheapest choicest classiest cleanest clearest closest commonest corniest costliest crassest creepiest crudest cutest darkest deadliest dearest deepest densest dinkiest ...
'RB':'B', # adverb / occasionally unabatingly maddeningly adventurously professedly stirringly prominently technologically magisterially predominately swiftly fiscally pitilessly ...
'RBR':'B', # adverb, comparative / further gloomier grander graver greater grimmer harder harsher healthier heavier higher however larger later leaner lengthier less-perfectly lesser lonelier longer louder lower more ...
'RBS':'B', # adverb, superlative / best biggest bluntest earliest farthest first furthest hardest heartiest highest largest least less most nearest second tightest worst
'CC':'C', # conjunction, coordinating / & 'n and both but either et for less minus neither nor or plus so therefore times v. versus vs. whether yet
'DT':'D', # determiner / all an another any both del each either every half la many much nary neither no some such that the them these this those
'EX':'E', # existential there / there
'FW':'F', # foreign word / gemeinschaft hund ich jeux habeas Haementeria Herr K'ang-si vous lutihaw alai je jour objets salutaris fille quibusdam pas trop Monte terram fiche oui corporis ...
'POS':'G', # genitive marker / ' 's
'RP':'I', # particle / aboard about across along apart around aside at away back before behind by crop down ever fast for forth from go high i.e. in into just later low more off on open out over per pie raising start teeth that through under unto up up-pp upon whole with you
'LS':'-', # list item marker / A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005 SP-44007 Second Third Three Two * a b c d first five four one six three two
'MD':'M', # modal auxiliary / can cannot could couldn't dare may might must need ought shall should shouldn't will would
'NN':'N', # noun, common, singular or mass / common-carrier cabbage knuckle-duster Casino afghan shed thermostat investment slide humour falloff slick wind hyena override subhumanity machinist ...
'NNP':'N', # noun, proper, singular / Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA Shannon A.K.C. Meltex Liverpool ...
'NNPS':'N', # noun, proper, plural / Americans Americas Amharas Amityvilles Amusements Anarcho-Syndicalists Andalusians Andes Andruses Angels Animals Anthony Antilles Antiques Apache Apaches Apocrypha ...
'NNS':'N', # noun, common, plural / undergraduates scotches bric-a-brac products bodyguards facets coasts divestitures storehouses designs clubs fragrances averages subjectivists apprehensions muses factory-jobs ...
'TO':'O', # "to" as preposition or infinitive marker / to
'IN':'P', # preposition or conjunction, subordinating / astride among uppon whether out inside pro despite on by throughout below within for towards near behind atop around if like until below next into if beside ...
'PRP':'R', # pronoun, personal / hers herself him himself hisself it itself me myself one oneself ours ourselves ownself self she thee theirs them themselves they thou thy us
'PRP$':'R', # pronoun, possessive / her his mine my our ours their thy your
'PDT':'T', # pre-determiner / all both half many quite such sure this
'UH':'U', # interjection / Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly man baby diddle hush sonuvabitch ...
'VB':'V', # verb, base form / ask assemble assess assign assume atone attention avoid bake balkanize bank begin behold believe bend benefit bevel beware bless boil bomb boost brace break bring broil brush build ...
'VBD':'V', # verb, past tense / dipped pleaded swiped regummed soaked tidied convened halted registered cushioned exacted snubbed strode aimed adopted belied figgered speculated wore appreciated contemplated ...
'VBG':'V', # verb, present participle or gerund / telegraphing stirring focusing angering judging stalling lactating hankerin' alleging veering capping approaching traveling besieging encrypting interrupting erasing wincing ...
'VBN':'V', # verb, past participle / multihulled dilapidated aerosolized chaired languished panelized used experimented flourished imitated reunifed factored condensed sheared unsettled primed dubbed desired ...
'VBP':'V', # verb, present tense, not 3rd person singular / predominate wrap resort sue twist spill cure lengthen brush terminate appear tend stray glisten obtain comprise detest tease attract emphasize mold postpone sever return wag ...
'VBZ':'V', # verb, present tense, 3rd person singular / bases reconstructs marks mixes displeases seals carps weaves snatches slumps stretches authorizes smolders pictures emerges stockpiles seduces fizzes uses bolsters slaps speaks pleads ...
'WDT':'W', # WH-determiner / that what whatever which whichever
'WP':'W', # WH-pronoun / that what whatever whatsoever which who whom whosoever
'WP$':'W', # WH-pronoun, possessive / whose
'WRB':'W', # Wh-adverb / how however whence whenever where whereby whereever wherein whereof why
'SYM':'-' # symbol / % & ' '' ''. ) ). * + ,. < = > @ A[fj] U.S U.S.S.R * ** ***
}
def encode(self, symbol):
return self.map[symbol] if symbol in self.map else '?'
def detect(self, pos_tagged_sequence):
terms = []
pos_tagged_sequence_encoded = ''.join([self.encode(m[1]) for m in pos_tagged_sequence])
#print pos_tagged_sequence_encoded
pos = 0
m = self.prog.search(pos_tagged_sequence_encoded, pos)
while m:
seq = [self.rule.sub('', t[0].lower()) for t in pos_tagged_sequence[m.start():m.end()]]
last_index = len(seq)-1
# seq[last_index]=self.lemmatizer.lemmatize(seq[last_index])
terms.append(seq)
pos = m.end()
m = self.prog.search(pos_tagged_sequence_encoded, pos)
return terms
class StopWordsDetector:
def __init__(self, _stopwords):
self.stopwords = set(_stopwords)
#print self.stopwords
def detect(self, lst):
if isinstance(lst, basestring):
if lst in self.stopwords:
return [lst]
else:
return []
try:
return [e for e in lst if e in self.stopwords]
except TypeError:
s = str(lst)
print s in self.stopwords
if s in self.stopwords:
return [s]
else:
return []
#fp = open(doc_file, "r")
#doc_txt = fp.read()
#fp.close()
#doc_txt = unicode(doc_txt, "utf-8", errors='ignore')
#doc_txt = re.sub(r'et +al\.', 'et al', doc_txt)
#doc_txt = re.split(r'[\r\n]', doc_txt)
#
#
#term_extractor = ate.TermExtractor(stopwords=stopwords, term_patterns=term_patterns, min_term_words=min_term_words, min_term_length=min_term_length)
#terms = term_extractor.extract_terms(doc_txt)
#c_values = term_extractor.c_values(terms, trace=True)
class TermExtractor:
def __init__(self, stopwords=[], term_patterns=[], min_term_length=3, min_term_words=2):
#StopWordsDetector
self.stopwords = set(stopwords)
self.min_term_length = min_term_length
self.term_patterns = term_patterns
self.min_term_words = min_term_words
self.detectors = []
for tp in term_patterns:
self.detectors.append(POSSequenceDetector(tp))
self.swd = StopWordsDetector(self.stopwords)
def extract_terms(self, doc_txt):
sent_tokenize_list = filter(lambda x: len(x) > 0, map(lambda s: nltk.tokenize.sent_tokenize(s), doc_txt))
sentences = []
_ = [sentences.extend(lst) for lst in sent_tokenize_list]
terms = [] #pd.DataFrame(columns=['term'])
#sentences = sentences[:30]
i = 1
filter_fn = lambda x: len(x) >= self.min_term_length
max_i = len(sentences)
for s in sentences:
text = nltk.word_tokenize(s)
#sent_pos_tags=nltk.pos_tag(text, tagset='universal')
sent_pos_tags = nltk.pos_tag(text)
sentence_terms = set()
for fsa1 in self.detectors:
stn = filter(filter_fn, [' '.join(t) for t in fsa1.detect(sent_pos_tags) if len(t) >= self.min_term_words and len(self.swd.detect(t)) == 0])
sentence_terms.update(stn)
terms.extend(sentence_terms)
#print i, '/', max_i, s
i = i + 1
return terms
def c_values(self, terms, trace=False):
def c_vals_helper(i):
for j in range(i + 1, n_terms):
if scipy.spatial.distance.cosine(t_i[i].toarray(), term_vectors[j].toarray()) < 1:
if term_series[j].find(t_i) >= 0:
is_part_of.append((t_i, term_series[j], 1))
terms_df = pd.DataFrame(terms, columns=['term'])
terms_df['w'] = 1
terms_df['len'] = len(terms_df['term'])
term_stats = terms_df.groupby(['term'])['w'].agg([np.sum])
term_stats['len'] = list(pd.Series(term_stats.index).apply(lambda x:len(x)))
term_stats.sort_values(by=['len'], ascending=True, inplace=True)
term_series = list(term_stats.index)
vectorizer = CountVectorizer(analyzer='word')
vectorizer.fit(term_series)
term_vectors = vectorizer.transform(term_series)
n_terms = len(term_series)
is_part_of = []
for i in range(0, n_terms):
for j in range(i + 1, n_terms):
if scipy.spatial.distance.cosine(term_vectors[i].toarray(), term_vectors[j].toarray()) < 1:
if term_series[j].find(term_vectors[i]) >= 0:
is_part_of.append((term_vectors[i], term_series[j], 1))
subterms = pd.DataFrame(is_part_of, columns=['term', 'part_of', 'w']).set_index(['term', 'part_of'])
c_values = []
# term_series=['time']
for t in term_series:
# print t
current_term = term_stats.loc[t]
# average frequency of the superterms
c_value = 0
if t in subterms.index:
subterm_of = list(subterms.loc[t].index)
for st in subterm_of:
c_value -= term_stats.loc[st]['sum']
c_value /= float(len(subterm_of))
# add current term frequency
c_value += current_term['sum']
# multiply to log(term length)
c_value = c_value * np.log(current_term['len'])
c_values.append(c_value)
# break
return sorted(zip(term_series, c_values), key=lambda x: x[1], reverse=True)
'''
'''
def pdf_to_text_textract(pdf_file_path):
page_text = textract.process(pdf_file_path) #, encoding='ascii'
return page_text
def pdf_to_text_pypdf(_pdf_file_path):
pdf_content = PyPDF2.PdfFileReader(file(_pdf_file_path, "rb"))
# 'Rb' Opens a file for reading only in binary format.
# The file pointer is placed at the beginning of the file
text_extracted = "" # A variable to store the text extracted from the entire PDF
for x in range(0, pdf_content.getNumPages()): # text is extracted page wise
pdf_text = "" # A variable to store text extracted from a page
pdf_text = pdf_text + pdf_content.getPage(x).extractText()
# Text is extracted from page 'x'
text_extracted = text_extracted + "".join(i for i in pdf_text if ord(i) < 128) + "\n\n\n"
# Non-Ascii characters are eliminated and text from each page is separated
return text_extracted
def compose_datasets(txt_file_dir, dataset_file_dir, increment_size=1, increment_strategy='time-asc'):
# read txt files
txt_files = sorted([join(txt_file_dir, f) for f in listdir(txt_file_dir) if isfile(join(txt_file_dir, f)) and f.lower().endswith(".txt")])
# print txt_files
# compose file lists
if increment_strategy == 'time-asc':
cnt = 0
n_dataset = 0
dataset = ''
for i in range(0, len(txt_files)):
fl = open(txt_files[i], 'r')
dataset += fl.read()
fl.close()
cnt += 1
if cnt % increment_size == 0:
n_dataset += 1
fnm = join(dataset_file_dir, 'D' + (('0000000000000000000000000000000000' + str(n_dataset))[-10:]) + '.txt')
print n_dataset, fnm
fl = open(fnm, 'w')
fl.write(dataset)
fl.close()
if increment_strategy == 'time-desc':
txt_files = txt_files[::-1]
cnt = 0
n_dataset = 0
dataset = ''
for i in range(0, len(txt_files)):
fl = open(txt_files[i], 'r')
dataset += fl.read()
fl.close()
cnt += 1
if cnt % increment_size == 0:
n_dataset += 1
fnm = join(dataset_file_dir, 'D' + (('0000000000000000000000000000000000' + str(n_dataset))[-10:]) + '.txt')
fl = open(fnm, 'w')
fl.write(dataset)
fl.close()
if increment_strategy == 'random':
#txt_files =
random.shuffle(txt_files)
cnt = 0
n_dataset = 0
dataset = ''
for i in range(0, len(txt_files)):
fl = open(txt_files[i], 'r')
dataset += fl.read()
fl.close()
cnt += 1
if cnt % increment_size == 0:
n_dataset += 1
fnm = join(dataset_file_dir, 'D' + (('0000000000000000000000000000000000' + str(n_dataset))[-10:]) + '.txt')
fl = open(fnm, 'w')
fl.write(dataset)
fl.close()
if increment_strategy == 'time-bidir':
cnt = 0
n_dataset = 0
dataset = ''
n_files = len(txt_files)
i_max = int(len(txt_files) / 2)
for i1 in range(0, i_max):
fl = open(txt_files[i1], 'r')
dataset += fl.read()
fl.close()
i2 = n_files-i1-1
fl = open(txt_files[i2], 'r')
dataset += fl.read()
fl.close()
cnt += 2
if cnt % increment_size == 0:
n_dataset += 1
fnm = join(dataset_file_dir, 'D' + (('0000000000000000000000000000000000' + str(n_dataset))[-10:]) + '.txt')
fl = open(fnm, 'w')
fl.write(dataset)
fl.close()
# http://icteri.org/icteri-2018/pv1/10000003.pdf
# T1,T2 - the bags of terms
# Each term T1.term
# is accompanied with its
# T.n-score. T1, T2 are sorted in the descending order of T.n-score.
# inputs are two lists of tuples (term, score)
def thd(_T1, _T2):
get_n_score = lambda x: x[1]
T1 = sorted(_T1, reverse=True, key=get_n_score)
T2 = sorted(_T2, reverse=True, key=get_n_score)
_sum = 0
_thd = 0
for k in range(0, len(T2)):
_sum += T2[k][1]
_found = False
for m in range(0, len(T1)):
if T2[k][0] == T1[m][0]:
_thd += abs(T2[k][1]-T1[m][1])
_found = True
if not _found:
_thd += T2[k][1]
_thdr = _thd/_sum
return (_thd, _thdr)
| [
"ankus@ciklum.com"
] | ankus@ciklum.com |
e0e7a32b985f115ea142a2f9d8d27e73ded0f0a2 | 306522802c5d5341647da6cdd2813ba68218334b | /Python3/120_Triangle.py | b5fa97cb0f88f1ca8d37c0a07c2f2c4558739659 | [] | no_license | Darion888/LeetCode | 9521bafedc61ea0eb268ce882efa639706dc230d | 78cba3fdca21097b567b10e0e0b9020e852ba87b | refs/heads/master | 2020-06-18T12:00:19.752769 | 2019-08-05T03:48:50 | 2019-08-05T03:48:50 | 196,297,529 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,868 | py | # Time: O(sum(N))
# Space: O(1)
# N: 三角形每一行宽度
"""
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
·Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
例如,给定三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
说明:
·如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。
"""
from typing import List
class Solution:
# @return an integer
# 思路: 动态回归
def minimumTotal(self, triangle: List[List[int]]) -> int:
if not triangle:
return 0
if len(triangle) == 1:
return triangle[0][0]
for i in range(1, len(triangle)):
triangle[i][0] += triangle[i-1][0]
for j in range(1, len(triangle[i])-1):
triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j])
triangle[i][-1] += triangle[i-1][-1]
return min(triangle[-1])
if __name__ == "__main__":
result = Solution().minimumTotal([
[2],
[3,4],
[6,5,7],
[4,1,8,3]
])
print(result) | [
"noreply@github.com"
] | Darion888.noreply@github.com |
9a749daa1bbdbdc8e0f1d1bcbd849c2e4b405074 | 8cfcebd3c5961472e0edba46bf0b7b3230ce8c55 | /src/python/complex_linear_system.py | 7dc22cad6beeb902740f9623e088f3d655cca90b | [] | no_license | caiuamelo/helmholtz-solver | 1f8648f7bc5b3907a80d337d11e9b56ba8b4b936 | 309cfcfae7aed10234f594a81fbbd5449eca4d05 | refs/heads/master | 2022-09-09T15:05:02.435935 | 2020-05-31T22:36:27 | 2020-05-31T22:36:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,697 | py | from scipy.sparse.coo import coo_matrix
import globals as g
import numpy as np
import _fwi_ls
def _build_extended_A(A_row, A_col, A_data, n_rows, n_cols):
big_A_coo_i = [None] * (4 * len(A_row))
big_A_coo_j = [None] * (4 * len(A_row))
big_A_coo_data = [None] * (4 * len(A_row))
for idx, (i, j, data) in enumerate(zip(A_row, A_col, A_data)):
big_A_coo_i[4 * idx] = i
big_A_coo_j[4 * idx] = j
big_A_coo_data[4 * idx] = data.real
big_A_coo_i[4 * idx + 1] = i + n_rows
big_A_coo_j[4 * idx + 1] = j
big_A_coo_data[4 * idx + 1] = data.imag
big_A_coo_i[4 * idx + 2] = i
big_A_coo_j[4 * idx + 2] = j + n_cols
big_A_coo_data[4 * idx + 2] = -data.imag
big_A_coo_i[4 * idx + 3] = i + n_rows
big_A_coo_j[4 * idx + 3] = j + n_cols
big_A_coo_data[4 * idx + 3] = data.real
return big_A_coo_i, big_A_coo_j, big_A_coo_data
def convert_complex_linear_system_to_real(A, b):
build_extended_A = g.choose_impl(_fwi_ls.build_extended_A, _build_extended_A)
big_A_coo_i, big_A_coo_j, big_A_coo_data = build_extended_A(
A.row, A.col, A.data, A.shape[0], A.shape[1],
)
big_A = coo_matrix(
(big_A_coo_data, (big_A_coo_i, big_A_coo_j)),
shape=(2 * A.shape[0], 2 * A.shape[1]),
dtype=np.float,
)
# b vector is not sparse
big_b = np.zeros(shape=(2 * len(b), 1))
big_b[0 : len(b)] = b.real
big_b[len(b) : 2 * len(b)] = b.imag
return big_A, big_b
def extract_complex_solution(big_x):
x = np.zeros(shape=(len(big_x) // 2,), dtype=np.complex)
x.real = big_x[0 : len(x)]
x.imag = big_x[len(x) : 2 * len(x)]
return x
| [
"tarcisio.fischer.cco@gmail.com"
] | tarcisio.fischer.cco@gmail.com |
98203090674573513d470db819e8b86ba0d02a67 | 4bd5667e90a2fef582bfb1537d6755b5b4a9e0f8 | /Python_Files/Immune_Experiment_Run.py | 00de8dee6ca1c38ca7ba22a26a59a54261ff3aeb | [] | no_license | JMMaroulis/MVP2 | 483ebcb8b24f31af6a94c0a3e5e9ae2d7d618dba | 3196816c45137fe89bd0e70143b564504744eeef | refs/heads/master | 2021-07-05T01:26:37.139206 | 2017-09-30T14:07:13 | 2017-09-30T14:07:13 | 105,374,006 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,979 | py | import Methods
import Measurements
import numpy
import random
import sys
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import gc
import cProfile
import time
import copy
gc.disable()
# SIRS
# S = 0
# I = 1
# R = 2
# IMMUNE = 3
# p1 = p(S -> I)
# p2 = p(I -> R)
# p3 = p(R -> S)
width = int(sys.argv[1])
height = int(sys.argv[2])
p1 = float(sys.argv[3])
p2 = float(sys.argv[4])
p3 = float(sys.argv[5])
equilibration_time = int(sys.argv[6])
num_readings_per_instance = int(sys.argv[7])
correlation_buffer = int(sys.argv[8])
visualisation = int(sys.argv[9])
increment = float(sys.argv[10])
p_immune = float(sys.argv[11])
# VARIOUS P1 P2 P3 SETTINGS
# WAVES SETTING:
# 0.8 0.1 0.01
# DYNAMIC EQUILIBRIUM SETTING:
# 0.5 0.5 0.5
# ABSORBING STATE:
# 0.5 0.5 0.01
# TIME-BASED RANDOM SEED
random.seed()
# INITIALISE GRIDS
# define two n by m grids;
# 'current' for storing current state,
# 'next' for storing changes during parallel updates
# passing stuff into Methods
Methods.set_things(width, height)
# NOTE: HAVING TO GENERATE THE INITIAL GRID FORM ALL FOUR STATES TO GET AUTOMATIC COLOUR
# SETTING OF PLOT TO WORK PROPERLY
# As it happens the very first one dies off anyway, so given a reasonable equilibration period, it makes no difference
# to the recorded data. I don't like it, and I'm not going to pretend it's good practice,
# but it works.
numbers = [0, 1, 2]
current_state = numpy.array([[random.choice(numbers) for a in range(height)] for b in range(width)])
#Methods.set_cell(current_state, 0, 0, 3)
Methods.vaccinate(current_state, p_immune)
next_state = copy.deepcopy(current_state)
# Measurement list
infected_fraction_list = list()
average_infection_fraction_list = list()
p1_list = list()
p_immune_list = list()
infected_fraction_variance_list = list()
sweep_count = 0
num_readings = 0
p1_changes = 0
p3_changes = 0
# ANIMATION ATTEMPT
"""
# uses parallel updates
def generate_data_SIRS():
global current_state, next_state, p1, p2, p3, sweep_count, num_readings
print(sweep_count, equilibration_time)
# give system time to equilibrate
if sweep_count <= equilibration_time:
Methods.sweep_fully_parallel(current_state, next_state, p1, p2, p3)
# updates/measurements after equilibration
if sweep_count > equilibration_time:
# correlation buffer
for p in range(0, correlation_buffer):
Methods.sweep_fully_parallel(current_state, next_state, p1, p2, p3)
# take measurement
infected_fraction_list.append(Measurements.infected_fraction(current_state))
num_readings += 1
print('num_readings', num_readings)
# increment p1 after sufficient readings; reset sweep_count
if num_readings == num_readings_per_instance:
num_readings = 0
sweep_count = 0
p1 += 0.05
print(p1, p3)
# randomise state
next_state = numpy.array([[random.choice(numbers) for a in range(height)] for b in range(width)])
# increment p3 after sufficient p1 increments; reset p1
if p1 > 1.0:
p1 = 0.05
p3 += 0.05
print(p1, p3)
# randomise state
next_state = numpy.array([[random.choice(numbers) for a in range(height)] for b in range(width)])
current_state = copy.deepcopy(next_state)
sweep_count += 1
return current_state
"""
# uses monte-carlo updates
def generate_data_SIRS():
global current_state, p1, p2, p3, p_immune, sweep_count, num_readings
# define conditional return statement
def ret():
if visualisation == 1:
return current_state
else:
return
# CONDITIONAL EXITS
# increment p1 after sufficient readings; reset sweep_count
if num_readings == num_readings_per_instance:
num_readings = 0
sweep_count = 0
if p1 <= 1.0 and p_immune <= 1.0:
p1_list.append(p1)
p_immune_list.append(p_immune)
p1 += increment
print(p1, p_immune)
# randomise state
current_state = numpy.array([[random.choice(numbers) for a in range(height)] for b in range(width)])
# vaccinate
Methods.vaccinate(current_state, p_immune)
return ret()
# increment p3 after sufficient p1 increments; reset p1, reset sweep count
if p1 > 1.0:
if p1 <= 1.0 and p_immune <= 1.0:
p1_list.append(p1)
p_immune_list.append(p_immune)
p1 = increment
p_immune += increment
infected_fraction_list.append(' ')
p1_list.append(' ')
p_immune_list.append(' ')
print(p1, p_immune)
# randomise state
current_state = numpy.array([[random.choice(numbers) for a in range(height)] for b in range(width)])
# vaccinate
Methods.vaccinate(current_state, p_immune)
return ret()
# escape if <I> = 0, should save a lot of time
if Measurements.infected_fraction(current_state) == 0.0:
print('KILL')
while num_readings != num_readings_per_instance:
# pretend to do sweeps
infected_fraction_list.append(0.0)
num_readings += 1
return ret()
# END OF CONDITIONAL EXITS
# BEGINNING OF ACTUAL PROCESS
# give system time to equilibrate
if sweep_count <= equilibration_time:
Methods.sweep_n2_cells(current_state, p1, p2, p3)
sweep_count += 1
return ret()
# updates/measurements after equilibration
if sweep_count > equilibration_time:
# correlation buffer
for p in range(0, correlation_buffer):
Methods.sweep_n2_cells(current_state, p1, p2, p3)
# take measurement
infected_fraction_list.append(Measurements.infected_fraction(current_state))
num_readings += 1
return ret()
# keeps animation happy
def update(state):
mat.set_data(state)
return mat
# generator to keep animation happy
def data_gen_SIRS():
while True:
yield generate_data_SIRS()
# either visualise whilst taking measurements:
if visualisation == 1:
# code animates happily until visualisation stopped manually
fig, ax = plt.subplots()
mat = ax.matshow(generate_data_SIRS())
plt.colorbar(mat)
ani = animation.FuncAnimation(fig, update, data_gen_SIRS, interval=50)
plt.show()
# or don't visualise whilst taking measurements
elif visualisation == 0:
while p_immune <= 1.0:
generate_data_SIRS()
else:
print("choose to visualise or not, please.")
sys.exit()
gc.enable()
Measurements.generate_stats(infected_fraction_list, average_infection_fraction_list, infected_fraction_variance_list,
num_readings_per_instance)
print('FINISHED')
print(len(average_infection_fraction_list))
print(len(p1_list))
print(len(p_immune_list))
Measurements.write_all_to_file(p1_list, p_immune_list, average_infection_fraction_list, infected_fraction_variance_list, p1, p2, p3, 1)
| [
"jamesmmaroulis@hotmail.com"
] | jamesmmaroulis@hotmail.com |
5bf84538a7388fbd2a9cc1ddcea0626ca3650cca | 75c3a5e1ec4b2e5b4c2fc876b1515e15d077e20d | /Preprocessing part/11.02.1.py | 0696ded4b18042091c43c9a02141e1e402d9451a | [] | no_license | William0111/Speech-separation | 1a2b2c2c0115ee7e054999e1c79dadaafb710413 | c60b37fd978624ac13a7ec55a303644d559e51ca | refs/heads/master | 2020-05-01T08:51:14.331098 | 2019-05-10T20:39:32 | 2019-05-10T20:39:32 | 177,387,174 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,109 | py | # CNN first try
from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
return result
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
# strides =1 , y move=1, x move =1
# must have stride[4]=0=stride[0]
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2X2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],
padding='SAME')
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784]) / 255. # 28x28
ys = tf.placeholder(tf.float32, [None, 10]) # 输出为10个数字
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])
print(x_image.shape) # [n_sample, 28,28,1]
##conv1 layer##
W_conv1 = weight_variable([5, 5, 1, 32]) # 5x5是patch的大小,insize=1,outsize=32,高度是32
b_conv1 = bias_variable([32]) # 32个
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # h_conv1的outputsize 28x28x32,长和宽没变,高度变成了32
h_pool1 = max_pool_2X2(h_conv1) # h_pool1的outputsize 14x14x32,高度没变没变,长和宽除以二
##conv2 layer##
W_conv2 = weight_variable([5, 5, 32, 64]) # 32是输入,64是输出
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # 14x14x64
h_pool2 = max_pool_2X2(h_conv2) # 7x7x64
##fun1 layter##
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
# 把它变成一维
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
##fun2 layter##
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# the loss
cross_entropy = tf.placeholder(tf.float32, [None, 1])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(100):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
if i % 5 == 0:
print(compute_accuracy(
mnist.test.images[:1000], mnist.test.labels[:1000]))
#print(sess.run(cross_entropy, feed_dict={xs: batch_xs, ys: batch_ys}))
| [
"44120449+William0111@users.noreply.github.com"
] | 44120449+William0111@users.noreply.github.com |
59070bc627dbf76d9d3ed807c63fd1a985c43649 | a0d02fbdc04c0b4cd24622b9eeddefe9bcacdda3 | /src/add_member.py | ed498d25acc37494f5c65eafdd96477fa6df8de1 | [] | no_license | jiayu520/lg5-selenium2 | 950227d4f80c9b94d992cbc9253d3f67e8e33443 | 46b2984d895d2720ae651f64d05d0ac70ee03a5a | refs/heads/master | 2023-02-23T12:45:45.321072 | 2021-01-22T02:51:28 | 2021-01-22T02:51:28 | 331,817,964 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 515 | py | from selenium.webdriver.common.by import By
from src.base_page import BasePage
from src.contact import Contact
class AddMember(BasePage):
def add_member(self):
'''输入成员信息,点击保存'''
self.find(By.ID,"username").send_keys('皮4')
self.find(By.ID,"memberAdd_acctid").send_keys('71899973')
self.find(By.CSS_SELECTOR,".ww_telInput_mainNumber").send_keys('13959245677')
self.find(By.CSS_SELECTOR,".js_btn_save").click()
return Contact(self.driver)
| [
"jiayu520000@outtlook.com"
] | jiayu520000@outtlook.com |
cac02f47d1ecfbce494b5b3cccba8632db18a064 | 802770deb5a98e8e644e9aaf5a6fabc851e6eae1 | /quiz_test/migrations/0018_auto_20180704_1623.py | 3d78f9b8dbeb5d59fae13e7a420f414c4ff58225 | [] | no_license | Subhash1998/quiz | 1eaf7fe0338eee092f6a5af52d57718c61738930 | da4c11c4f9271200c63970ab1f90c240f5a10598 | refs/heads/master | 2022-12-12T17:34:04.450562 | 2018-07-12T19:41:52 | 2018-07-12T19:41:52 | 140,757,317 | 0 | 0 | null | 2021-06-10T20:33:39 | 2018-07-12T19:39:52 | Python | UTF-8 | Python | false | false | 802 | py | # Generated by Django 2.0.5 on 2018-07-04 16:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('quiz_test', '0017_category_test'),
]
operations = [
migrations.RenameField(
model_name='test',
old_name='question_amount',
new_name='amount',
),
migrations.RenameField(
model_name='test',
old_name='question_category',
new_name='category',
),
migrations.RenameField(
model_name='test',
old_name='question_level',
new_name='level',
),
migrations.RenameField(
model_name='test',
old_name='question_type',
new_name='q_type',
),
]
| [
"you@example.com"
] | you@example.com |
69ed49a41a2c6a4900604a92d2418f53858f8de8 | f555d440fefc1c15653e28ce8e5b53b4c6ece4d3 | /genericdelegates.py | 5c3d9bfeb8841d0d002ebf0ac4ca12281945a59b | [] | no_license | amithreddy/ground-control-tool | 6f56f819760da7b70d43e0eaea0354453dd31b63 | b8fe11b643da6495aab6f770c6fe5a978d781e52 | refs/heads/master | 2021-01-11T17:53:58.509019 | 2017-01-24T00:42:33 | 2017-01-24T00:42:33 | 79,864,893 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,434 | py | #!/usr/bin/env python
# Copyright (c) 2007-8 Qtrac Ltd. All rights reserved.
# This program or module 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
# version 3 of the License, or (at your option) any later version. It is
# provided for educational purposes and 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.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import reg
#import richtextlineedit
class GenericDelegate(QItemDelegate):
def __init__(self, parent=None):
super(GenericDelegate, self).__init__(parent)
self.delegates = {}
def insertColumnDelegate(self, column, delegate):
delegate.setParent(self)
self.delegates[column] = delegate
def paint(self, painter, option, index):
delegate = self.delegates.get(index.column())
if delegate is not None:
delegate.paint(painter, option, index)
else:
QItemDelegate.paint(self, painter, option, index)
def createEditor(self, parent, option, index):
delegate = self.delegates.get(index.column())
if delegate is not None:
return delegate.createEditor(parent, option, index)
else:
return QItemDelegate.createEditor(self, parent, option,index)
def editorEvent(self, event, model, option, index):
delegate = self.delegates.get(index.column())
if delegate is not None:
return delegate.editorEvent( event, model, option, index)
else:
return QItemDelegate.editorEvent(self, event, model, option, index)
def setEditorData(self, editor, index):
delegate = self.delegates.get(index.column())
if delegate is not None:
delegate.setEditorData(editor, index)
else:
QItemDelegate.setEditorData(self, editor, index)
def setModelData(self, editor, model, index):
delegate = self.delegates.get(index.column())
if delegate is not None:
delegate.setModelData(editor, model, index)
else:
QItemDelegate.setModelData(self, editor, model, index)
def setDelegates(self, delegates):
for index, delegate in enumerate(delegates):
if delegate == "num":
self.insertColumnDelegate(index, NumDelegate())
elif delegate == "checkbox":
self.insertColumnDelegate(index, CheckBoxDelegate())
else:
#raise an error
assert False
class NumDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super(NumDelegate,self).__init__(parent)
def createEditor(self,parent,option,index):
lineEdit= QLineEdit(parent)
lineEdit.setFrame(False)
regExp =reg.match_one_num
validator = QRegExpValidator(regExp)
lineEdit.setValidator(validator)
return lineEdit
def setEditorData(self,editor,index):
value = index.model().data(index,Qt.UserRole)
if editor is not None:
editor.setText(value)
def setModelData(self, editor, model,index):
if not editor.isModified():
return
text = editor.text()
validator = editor.validator()
if validator is not None:
state, text =validator.validate(text,0)
if state == QValidator.Acceptable:
color = '#ffffff' #white
model.setData(index, editor.text())
class IntegerColumnDelegate(QItemDelegate):
def __init__(self, minimum=0, maximum=100, parent=None):
super(IntegerColumnDelegate, self).__init__(parent)
self.minimum = minimum
self.maximum = maximum
def createEditor(self, parent, option, index):
spinbox = QSpinBox(parent)
spinbox.setRange(self.minimum, self.maximum)
spinbox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
return spinbox
def setEditorData(self, editor, index):
value = index.model().data(index, Qt.DisplayRole).toInt()[0]
editor.setValue(value)
def setModelData(self, editor, model, index):
editor.interpretText()
model.setData(index, QVariant(editor.value()))
class CheckBoxDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super(CheckBoxDelegate, self).__init__(parent)
def createEditor(self,parent,option, index):
"""important, other wise an editor is created if the user clicks in this cell."""
return None
def paint(self, painter, option, index):
checked = index.data().toBool()
check_box_style_option= QStyleOptionButton()
if (index.flags() & Qt.ItemIsEditable) > 0:
check_box_style_option.state |= QStyle.State_Enabled
else:
check_box_style_option.state |= QStyle.State_ReadOnly
if checked:
check_box_style_option.state |= QStyle.State_On
else:
check_box_style_option.state |= QStyle.State_Off
check_box_style_option.rect = self.getCheckBoxRect(option)
check_box_style_option.state |= QStyle.State_Enabled
QApplication.style().drawControl(QStyle.CE_CheckBox, check_box_style_option, painter)
def editorEvent(self, event, model, option, index):
if not (index.flags() & Qt.ItemIsEditable) > 0:
return False
if event.type() == QEvent.MouseButtonPress \
or event.type() == QEvent.MouseMove:
return False
if event.type() == QEvent.MouseButtonRelease \
or event.type() == QEvent.MouseButtonDblClick:
if event.button() != Qt.LeftButton :
return False
if event.type() == QEvent.MouseButtonDblClick \
and event.button() is Qt.LeftButton:
print "double click"
return True # why are we returning true, how to we go to the bottom of the code?
elif event.type() == QEvent.KeyPress:
if event.key() != Qt.Key_Space \
and event.key() != Qt.Key_Select:
return False
else:
return False
print event.type(), 'button',event.button()
self.setModelData(None, model,index)
return True
def setModelData(self, editor, model, index):
newValue = not(index.model().data(index, Qt.DisplayRole) == True)
model.setData(index, newValue, Qt.EditRole)
def getCheckBoxRect(self, option):
check_box_style_option = QStyleOptionButton()
check_box_rect= QApplication.style().subElementRect(QStyle.SE_CheckBoxIndicator, check_box_style_option, None)
check_box_point = QPoint(option.rect.x() +
option.rect.width() /2 -
check_box_rect.width() / 2,
option.rect.y() +
option.rect.height() /2 -
check_box_rect.height() /2)
return QRect(check_box_point, check_box_rect.size())
class DateColumnDelegate(QItemDelegate):
def __init__(self, minimum=QDate(), maximum=QDate.currentDate(),
format="yyyy-MM-dd", parent=None):
super(DateColumnDelegate, self).__init__(parent)
self.minimum = minimum
self.maximum = maximum
self.format = QString(format)
def createEditor(self, parent, option, index):
dateedit = QDateEdit(parent)
dateedit.setDateRange(self.minimum, self.maximum)
dateedit.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
dateedit.setDisplayFormat(self.format)
dateedit.setCalendarPopup(True)
return dateedit
def setEditorData(self, editor, index):
value = index.model().data(index, Qt.DisplayRole).toDate()
editor.setDate(value)
def setModelData(self, editor, model, index):
model.setData(index, QVariant(editor.date()))
class PlainTextColumnDelegate(QItemDelegate):
def __init__(self, parent=None):
super(PlainTextColumnDelegate, self).__init__(parent)
def createEditor(self, parent, option, index):
lineedit = QLineEdit(parent)
return lineedit
def setEditorData(self, editor, index):
value = index.model().data(index, Qt.DisplayRole).toString()
editor.setText(value)
def setModelData(self, editor, model, index):
model.setData(index, QVariant(editor.text()))
class RichTextColumnDelegate(QItemDelegate):
def __init__(self, parent=None):
super(RichTextColumnDelegate, self).__init__(parent)
def paint(self, painter, option, index):
text = index.model().data(index, Qt.DisplayRole).toString()
palette = QApplication.palette()
document = QTextDocument()
document.setDefaultFont(option.font)
if option.state & QStyle.State_Selected:
document.setHtml(QString("<font color=%1>%2</font>") \
.arg(palette.highlightedText().color().name()) \
.arg(text))
else:
document.setHtml(text)
painter.save()
color = palette.highlight().color() \
if option.state & QStyle.State_Selected \
else QColor(index.model().data(index,
Qt.BackgroundColorRole))
painter.fillRect(option.rect, color)
painter.translate(option.rect.x(), option.rect.y())
document.drawContents(painter)
painter.restore()
def sizeHint(self, option, index):
text = index.model().data(index).toString()
document = QTextDocument()
document.setDefaultFont(option.font)
document.setHtml(text)
return QSize(document.idealWidth() + 5,
option.fontMetrics.height())
def createEditor(self, parent, option, index):
#lineedit = richtextlineedit.RichTextLineEdit(parent)
lineedit
return lineedit
def setEditorData(self, editor, index):
value = index.model().data(index, Qt.DisplayRole).toString()
editor.setHtml(value)
def setModelData(self, editor, model, index):
model.setData(index, QVariant(editor.toSimpleHtml()))
| [
"amithmreddy@gmail.com"
] | amithmreddy@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.